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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/commonMain/kotlin/data/items/LightbringerWristguards.kt
|
marisa-ashkandi
| 332,658,265
| false
| null |
package `data`.items
import `data`.Constants
import `data`.buffs.Buffs
import `data`.itemsets.ItemSets
import `data`.model.Color
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import `data`.socketbonus.SocketBonuses
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class LightbringerWristguards : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 34433
public override var name: String = "Lightbringer Wristguards"
public override var itemLevel: Int = 154
public override var quality: Int = 4
public override var icon: String = "inv_bracer_14.jpg"
public override var inventorySlot: Int = 9
public override var itemSet: ItemSet? = ItemSets.byId(679)
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.PLATE
public override var allowableClasses: Array<Constants.AllowableClass>? = arrayOf(
Constants.AllowableClass.PALADIN
)
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
stamina = 49,
armor = 841,
defenseRating = 20.0,
blockRating = 15.0,
dodgeRating = 22.0
)
public override var sockets: Array<Socket> = arrayOf(
Socket(Color.BLUE)
)
public override var socketBonus: SocketBonus? = SocketBonuses.byId(3153)
public override var phase: Int = 5
public override val buffs: List<Buff> by lazy {
listOfNotNull(
Buffs.byIdOrName(15715, "Increase Spell Dam 25", this)
)}
}
| 21
| null |
11
| 25
|
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
| 1,917
|
tbcsim
|
MIT License
|
library/src/test/java/com/friendoye/recyclerxray/RecyclerXRayTest.kt
|
friendoye
| 266,419,873
| false
|
{"Kotlin": 194671, "Shell": 819}
|
package com.friendoye.recyclerxray
import com.friendoye.recyclerxray.internal.RecyclerXRayApi
import io.mockk.Called
import io.mockk.mockk
import io.mockk.verify
import org.junit.After
import org.junit.Assert
import org.junit.Test
class RecyclerXRayTest {
@After
fun teardown() {
XRayInitializer.reset()
}
@Test
fun `By default use xRayApi from XRayInitializer`() {
val mockXRayApi = mockk<RecyclerXRayApi>()
XRayInitializer.init { mockXRayApi }
val result = LocalRecyclerXRay()
Assert.assertEquals(result.xRayApi, mockXRayApi)
}
@Test
fun `Do not use xRayApi provider during construction 1`() {
val mockProvider = mockk<() -> RecyclerXRayApi>()
XRayInitializer.init(mockProvider)
LocalRecyclerXRay()
verify { mockProvider wasNot Called }
}
@Test
fun `Do not use xRayApi provider during construction 2`() {
val mockProvider = mockk<() -> RecyclerXRayApi>()
LocalRecyclerXRay(mockProvider)
verify { mockProvider wasNot Called }
}
@Test(expected = RecyclerXRayIsNotInitializedException::class)
fun `Throw exception if RecyclerXRay was used without initialization`() {
val result = LocalRecyclerXRay()
result.toggleSecrets()
}
}
| 15
|
Kotlin
|
1
| 13
|
dfac034f9a2e728a2f2d055a0cf105737a95f678
| 1,311
|
RecyclerXRay
|
MIT License
|
libraries/tools/kotlin-gradle-plugin/src/functionalTest/kotlin/org/jetbrains/kotlin/gradle/dependencyResolutionTests/SourceSetDependenciesResolution.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-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.dependencyResolutionTests
import org.gradle.api.Project
import org.gradle.api.internal.project.ProjectInternal
import org.jetbrains.kotlin.gradle.dsl.kotlinExtension
import org.jetbrains.kotlin.gradle.dsl.platformTargets
import org.jetbrains.kotlin.gradle.plugin.mpp.resolvableMetadataConfiguration
import org.jetbrains.kotlin.gradle.plugin.sources.internal
import org.jetbrains.kotlin.gradle.util.*
import org.jetbrains.kotlin.gradle.utils.targets
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.junit.Rule
import org.junit.rules.TemporaryFolder
abstract class SourceSetDependenciesResolution {
@get:Rule
val tempFolder = TemporaryFolder()
class SourceSetDependenciesDsl(
private val project: Project
) {
val mavenRepositoryMock = MavenRepositoryMock()
fun mavenRepositoryMock(code: MavenRepositoryMockDsl.() -> Unit) =
MavenRepositoryMockDsl(mavenRepositoryMock).run(code)
fun api(sourceSetName: String, name: String, version: String): Unit =
api(sourceSetName, "test:$name:$version")
fun mockedDependency(name: String, version: String): String {
return mavenRepositoryMock.module("test", name, version).asMavenNotation
}
fun api(sourceSetName: String, dependencyNotation: String): Unit = project
.kotlinExtension
.sourceSets
.getByName(sourceSetName)
.dependencies { api(mockedDependency(dependencyNotation)) }
fun mockedDependency(dependencyNotation: String): String {
mavenRepositoryMock.module(dependencyNotation)
return dependencyNotation
}
}
/**
* If [withProject] is not null then dependencies of source sets in this projects will be verified against [expectedFilePath]
*
*/
fun assertSourceSetDependenciesResolution(
expectedFilePath: String,
withProject: ProjectInternal? = null,
sanitize: String.() -> String = { this },
configure: SourceSetDependenciesDsl.(Project) -> Unit
) {
val repoRoot = tempFolder.newFolder()
val project = withProject ?: buildProject {
// Disable stdlib and kotlin-dom-api for default tests, as they just pollute dependencies dumps
enableDefaultStdlibDependency(false)
enableDefaultJsDomApiDependency(false)
configureRepositoriesForTests()
applyMultiplatformPlugin()
}
val dsl = SourceSetDependenciesDsl(project)
dsl.configure(project)
dsl.mavenRepositoryMock.applyToProject(project, repoRoot)
project.evaluate()
val actualResult = project.resolveAllSourceSetDependencies().sanitize()
val expectedFile = resourcesRoot
.resolve("dependenciesResolution")
.resolve(this.javaClass.simpleName)
.resolve(expectedFilePath)
KotlinTestUtils.assertEqualsToFile(expectedFile.toFile(), actualResult) {
// remove comment lines
it.replace("""\s+//.+""".toRegex(), "")
}
}
private fun Project.resolveAllSourceSetDependencies(): String {
val allSourceSets = kotlinExtension.sourceSets.toSet()
val platformSpecificSourceSets = kotlinExtension
.targets
.platformTargets
.flatMap { it.compilations }
.associate { it.defaultSourceSet to configurations.getByName(it.compileDependencyConfigurationName) }
val commonSourceSetsWithoutMetadataCompilation = allSourceSets
.minus(platformSpecificSourceSets.keys)
.associateWith { it.internal.resolvableMetadataConfiguration }
val actual = (platformSpecificSourceSets + commonSourceSetsWithoutMetadataCompilation).mapValues { (_, configuration) ->
configuration.dumpResolvedDependencies().prependIndent(" ")
}.entries.sortedBy { (sourceSet, _) -> sourceSet.name }.joinToString("\n") {
it.key.name + "\n" + it.value
}
return actual
}
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 4,304
|
kotlin
|
Apache License 2.0
|
app/src/main/java/edumate/app/navigation/ClassDetailsNavHost.kt
|
mubashirpa
| 605,945,315
| false
|
{"Kotlin": 833094}
|
package edumate.app.navigation
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import edumate.app.core.utils.enumValueOf
import edumate.app.domain.model.course_work.CourseWorkType
import edumate.app.presentation.class_details.ClassDetailsUiEvent
import edumate.app.presentation.class_details.ClassDetailsUiState
import edumate.app.presentation.class_details.UserType
import edumate.app.presentation.classwork.ClassworkViewModel
import edumate.app.presentation.classwork.screen.ClassworkScreen
import edumate.app.presentation.create_announcement.CreateAnnouncementViewModel
import edumate.app.presentation.create_announcement.screen.CreateAnnouncementScreen
import edumate.app.presentation.create_classwork.CreateClassworkViewModel
import edumate.app.presentation.create_classwork.screen.CreateClassworkScreen
import edumate.app.presentation.meet.MeetViewModel
import edumate.app.presentation.meet.screen.MeetScreen
import edumate.app.presentation.people.screen.PeopleScreen
import edumate.app.presentation.stream.StreamViewModel
import edumate.app.presentation.stream.screen.StreamScreen
import edumate.app.presentation.view_classwork.ViewClassworkViewModel
import edumate.app.presentation.view_classwork.screen.ViewClassworkScreen
import edumate.app.presentation.view_student_work.ViewStudentWorkViewModel
import edumate.app.presentation.view_student_work.screen.ViewStudentWorkScreen
@Composable
fun ClassDetailsNavHost(
navController: NavHostController,
modifier: Modifier = Modifier,
snackbarHostState: SnackbarHostState,
uiState: ClassDetailsUiState,
onEvent: (ClassDetailsUiEvent) -> Unit,
onLeaveClass: () -> Unit,
onBackPressed: () -> Unit
) {
val course = uiState.course!!
NavHost(
navController = navController,
startDestination = Screen.StreamScreen.route,
modifier = modifier
) {
composable(
route = Screen.StreamScreen.route,
arguments = listOf(
navArgument(Routes.Args.STREAM_SCREEN_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
}
)
) {
val viewModel: StreamViewModel = hiltViewModel()
StreamScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
snackbarHostState = snackbarHostState,
course = course,
navigateToCreateAnnouncement = { courseId ->
navController.navigate(Screen.CreateAnnouncementScreen.withArgs(courseId, null))
},
navigateToEditAnnouncement = { courseId, announcementId ->
navController.navigate(
Screen.CreateAnnouncementScreen.withArgs(
courseId,
announcementId
)
)
},
navigateToViewAnnouncement = { _, _ -> /*TODO*/ },
onBackPressed = onBackPressed
)
}
composable(
route = Screen.ClassworkScreen.route,
arguments = listOf(
navArgument(Routes.Args.CLASSWORK_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
}
)
) {
val viewModel: ClassworkViewModel = hiltViewModel()
ClassworkScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
snackbarHostState = snackbarHostState,
course = course,
navigateToCreateClasswork = { courseId, workType ->
navController.navigate(
Screen.CreateClassworkScreen.withArgs(
courseId,
null,
workType.toString()
)
)
},
navigateToEditClasswork = { courseId, classworkId, workType ->
navController.navigate(
Screen.CreateClassworkScreen.withArgs(
courseId,
classworkId,
workType.toString()
)
)
},
navigateToViewClasswork = { courseId, classworkId, workType, userType ->
navController.navigate(
Screen.ViewClassworkScreen.withArgs(
courseId,
classworkId,
workType.toString(),
userType.toString()
)
)
},
onBackPressed = onBackPressed
)
}
composable(
route = Screen.PeopleScreen.route,
arguments = listOf(
navArgument(Routes.Args.PEOPLE_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
},
navArgument(Routes.Args.PEOPLE_COURSE_OWNER_ID) {
type = NavType.StringType
defaultValue = course.ownerId
}
)
) {
PeopleScreen(
snackbarHostState = snackbarHostState,
course = course,
onLeaveClass = onLeaveClass,
onBackPressed = onBackPressed
)
}
composable(
route = "${Screen.CreateClassworkScreen.route}${Routes.Args.CREATE_CLASSWORK_SCREEN}",
arguments = listOf(
navArgument(Routes.Args.CREATE_CLASSWORK_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
},
navArgument(Routes.Args.CREATE_CLASSWORK_ID) { type = NavType.StringType },
navArgument(Routes.Args.CREATE_CLASSWORK_TYPE) { type = NavType.StringType }
)
) {
val viewModel: CreateClassworkViewModel = hiltViewModel()
CreateClassworkScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
createClassworkResults = viewModel.createClassworkResults,
snackbarHostState = snackbarHostState,
className = course.name,
onCreateClassworkSuccess = { navController.navigateUp() },
onBackPressed = { navController.navigateUp() }
)
}
composable(
route = "${Screen.ViewClassworkScreen.route}${Routes.Args.VIEW_CLASSWORK_SCREEN}",
arguments = listOf(
navArgument(Routes.Args.VIEW_CLASSWORK_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
},
navArgument(Routes.Args.VIEW_CLASSWORK_ID) { type = NavType.StringType },
navArgument(Routes.Args.VIEW_CLASSWORK_TYPE) { type = NavType.StringType },
navArgument(Routes.Args.VIEW_CLASSWORK_USER_TYPE) { type = NavType.StringType }
)
) { backStackEntry ->
val viewModel: ViewClassworkViewModel = hiltViewModel()
val classworkType: CourseWorkType =
backStackEntry.arguments?.getString(Routes.Args.VIEW_CLASSWORK_TYPE).orEmpty()
.enumValueOf(CourseWorkType.COURSE_WORK_TYPE_UNSPECIFIED)!!
val currentUserType: UserType =
backStackEntry.arguments?.getString(Routes.Args.VIEW_CLASSWORK_USER_TYPE).orEmpty()
.enumValueOf(UserType.STUDENT)!!
ViewClassworkScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
snackbarHostState = snackbarHostState,
classworkType = classworkType,
currentUserType = currentUserType,
navigateToViewStudentWork = { courseWork, studentWorkId, assignedStudent ->
onEvent(
ClassDetailsUiEvent.OnNavigateToViewStudentWork(
courseWork,
assignedStudent
)
)
navController.navigate(
Screen.ViewStudentWorkScreen.withArgs(
courseWork.courseId,
courseWork.id,
studentWorkId
)
)
},
onBackPressed = { navController.navigateUp() }
)
}
composable(
route = "${Screen.ViewStudentWorkScreen.route}${Routes.Args.VIEW_STUDENT_WORK_SCREEN}",
arguments = listOf(
navArgument(Routes.Args.VIEW_STUDENT_WORK_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
},
navArgument(Routes.Args.VIEW_STUDENT_WORK_COURSE_WORK_ID) {
type = NavType.StringType
},
navArgument(Routes.Args.VIEW_STUDENT_WORK_ID) { type = NavType.StringType }
)
) {
val viewModel: ViewStudentWorkViewModel = hiltViewModel()
ViewStudentWorkScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
snackbarHostState = snackbarHostState,
courseWork = uiState.courseWork!!,
assignedStudent = uiState.courseWorkAssignedStudent!!,
onBackPressed = { navController.navigateUp() }
)
}
composable(
route = "${Screen.CreateAnnouncementScreen.route}${Routes.Args.CREATE_ANNOUNCEMENT_SCREEN}",
arguments = listOf(
navArgument(Routes.Args.CREATE_ANNOUNCEMENT_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
},
navArgument(Routes.Args.CREATE_ANNOUNCEMENT_ID) { type = NavType.StringType }
)
) {
val viewModel: CreateAnnouncementViewModel = hiltViewModel()
CreateAnnouncementScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
snackbarHostState = snackbarHostState,
createAnnouncementResults = viewModel.createAnnouncementResults,
className = course.name,
onCreateAnnouncementSuccess = { navController.navigateUp() },
onBackPressed = { navController.navigateUp() }
)
}
composable(
route = Screen.MeetScreen.route,
arguments = listOf(
navArgument(Routes.Args.MEET_SCREEN_COURSE_ID) {
type = NavType.StringType
defaultValue = course.id
}
)
) {
val viewModel: MeetViewModel = hiltViewModel()
MeetScreen(
uiState = viewModel.uiState,
onEvent = viewModel::onEvent,
snackbarHostState = snackbarHostState,
course = course,
onBackPressed = onBackPressed
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1bc4506163dc73821d790822de66460b603836f8
| 11,843
|
Edumate
|
Apache License 2.0
|
kotlin/ktor/pokedex/src/main/kotlin/com/pradyotprkshpokedex/domain/modal/Platinum.kt
|
pradyotprksh
| 385,586,594
| false
| null |
package com.example.myapplication.data.remote.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Platinum(
@SerialName("back_default") val backDefault: String?,
@SerialName("back_female") val backFemale: String?,
@SerialName("back_shiny") val backShiny: String?,
@SerialName("back_shiny_female") val backShinyFemale: String?,
@SerialName("front_default") val frontDefault: String?,
@SerialName("front_female") val frontFemale: String?,
@SerialName("front_shiny") val frontShiny: String?,
@SerialName("front_shiny_female") val frontShinyFemale: String?
)
| 0
| null |
11
| 24
|
da2054de505260bdfa5ffa6d67674f0fa5ba8d3c
| 647
|
development_learning
|
MIT License
|
android/app/src/main/java/hu/sztomek/wheresmybuddy/presentation/common/ListData.kt
|
sztomek
| 126,842,323
| false
|
{"Markdown": 4, "Ignore List": 4, "Gradle": 3, "XML": 82, "Java Properties": 1, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 224, "Java": 1, "JSON with Comments": 2, "JSON": 2, "JavaScript": 1}
|
package hu.sztomek.wheresmybuddy.presentation.common
interface ListData<out T: Any> {
val results: List<T>
}
| 0
|
Kotlin
|
0
| 1
|
9cf2842a4ad380c9b5d1f6524cf7893c6eb27946
| 115
|
buddyfinder
|
Apache License 2.0
|
src/main/kotlin/dev/voqal/assistant/tool/text/BackspaceTool.kt
|
voqal
| 716,228,492
| false
|
{"Kotlin": 1209055, "Java": 493485, "JavaScript": 13007, "Go": 10765, "Python": 9638, "TypeScript": 828, "Groovy": 568, "PHP": 315, "Rust": 308}
|
package dev.voqal.assistant.tool.text
import com.aallam.openai.api.chat.Tool
import com.aallam.openai.api.core.Parameters
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import dev.voqal.assistant.VoqalDirective
import dev.voqal.assistant.focus.DetectedIntent
import dev.voqal.assistant.focus.SpokenTranscript
import dev.voqal.assistant.tool.VoqalTool
import dev.voqal.services.VoqalStatusService
import dev.voqal.services.getVoqalLogger
import io.vertx.core.json.JsonObject
import java.awt.Robot
import java.awt.event.KeyEvent.VK_BACK_SPACE
class BackspaceTool : VoqalTool() {
companion object {
const val NAME = "backspace"
}
override val name = NAME
override suspend fun actionPerformed(args: JsonObject, directive: VoqalDirective) {
val project = directive.project
val log = project.getVoqalLogger(this::class)
log.debug("Triggering backspace")
//todo: not robot
Robot().keyPress(VK_BACK_SPACE)
Robot().keyRelease(VK_BACK_SPACE)
project.service<VoqalStatusService>().updateText("Backspace")
}
override suspend fun getTranscriptIntent(project: Project, transcript: SpokenTranscript): DetectedIntent? {
return attemptIntentExtract(transcript.cleanTranscript)?.let { (intent, args) ->
DetectedIntent(intent, args, transcript, this)
}
}
fun attemptIntentExtract(rawString: String): Pair<String, Map<String, String>>? {
return if (rawString == "backspace") {
Pair(NAME, mapOf())
} else {
null
}
}
override fun isVisible(directive: VoqalDirective): Boolean = false
override fun asTool(directive: VoqalDirective) = Tool.function(
name = NAME,
description = "Press the backspace key.",
parameters = Parameters.Empty
)
}
| 1
|
Kotlin
|
8
| 90
|
1a4eac0c4907c44a88288d6af6a686b97b003583
| 1,881
|
coder
|
Apache License 2.0
|
plugins/kotlinx-serialization/kotlinx-serialization.k2/src/org/jetbrains/kotlinx/serialization/compiler/fir/services/FirSerializablePropertiesProvider.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* 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.kotlinx.serialization.compiler.fir.services
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.primaryConstructorSymbol
import org.jetbrains.kotlin.fir.caches.FirCache
import org.jetbrains.kotlin.fir.caches.createCache
import org.jetbrains.kotlin.fir.caches.firCachesFactory
import org.jetbrains.kotlin.fir.caches.getValue
import org.jetbrains.kotlin.fir.declarations.utils.correspondingValueParameterFromPrimaryConstructor
import org.jetbrains.kotlin.fir.declarations.utils.isEnumClass
import org.jetbrains.kotlin.fir.declarations.utils.visibility
import org.jetbrains.kotlin.fir.extensions.FirDeclarationPredicateRegistrar
import org.jetbrains.kotlin.fir.extensions.FirExtensionSessionComponent
import org.jetbrains.kotlin.fir.scopes.impl.declaredMemberScope
import org.jetbrains.kotlin.fir.scopes.processAllProperties
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlinx.serialization.compiler.fir.*
import org.jetbrains.kotlinx.serialization.compiler.fir.checkers.superClassNotAny
import org.jetbrains.kotlinx.serialization.compiler.resolve.ISerializableProperty
class FirSerializablePropertiesProvider(session: FirSession) : FirExtensionSessionComponent(session) {
private val cache: FirCache<FirClassSymbol<*>, FirSerializableProperties, Nothing?> =
session.firCachesFactory.createCache(this::createSerializableProperties)
fun getSerializablePropertiesForClass(classSymbol: FirClassSymbol<*>): FirSerializableProperties {
return cache.getValue(classSymbol)
}
override fun FirDeclarationPredicateRegistrar.registerPredicates() {
register(FirSerializationPredicates.hasMetaAnnotation)
}
private fun createSerializableProperties(classSymbol: FirClassSymbol<*>): FirSerializableProperties {
val allPropertySymbols = buildList {
classSymbol
.declaredMemberScope(session, memberRequiredPhase = null)
.processAllProperties {
addIfNotNull(it as? FirPropertySymbol)
}
}
val primaryConstructorProperties = allPropertySymbols.mapNotNull {
val parameterSymbol = it.correspondingValueParameterFromPrimaryConstructor ?: return@mapNotNull null
it to parameterSymbol.hasDefaultValue
}.toMap().withDefault { false }
val shouldHaveGeneratedMethods = classSymbol.shouldHaveGeneratedMethods(session)
fun isPropertySerializable(propertySymbol: FirPropertySymbol): Boolean {
return when {
shouldHaveGeneratedMethods -> !propertySymbol.hasSerialTransient(session)
propertySymbol.visibility == Visibilities.Private -> false
else -> (propertySymbol.isVar && propertySymbol.hasSerialTransient(session)) || propertySymbol in primaryConstructorProperties
}
}
val serializableProperties: List<FirSerializableProperty> = allPropertySymbols.asSequence()
.filter { isPropertySerializable(it) }
.map { FirSerializableProperty(session, it, it.declaresDefaultValue()) }
.filterNot { it.transient }
.partition { it.propertySymbol in primaryConstructorProperties }
.let { (fromConstructor, standalone) ->
val superClassSymbol = classSymbol.superClassNotAny(session)
buildList {
if (superClassSymbol != null && superClassSymbol.shouldHaveInternalSerializer(session)) {
addAll(getSerializablePropertiesForClass(superClassSymbol).serializableProperties)
}
addAll(fromConstructor)
addAll(standalone)
}
}
.let { restoreCorrectOrderFromClassProtoExtension(classSymbol, it) }
val isExternallySerializable = classSymbol.isEnumClass ||
primaryConstructorProperties.size == (classSymbol.primaryConstructorSymbol(session)?.valueParameterSymbols?.size ?: 0)
val (serializableConstructorProperties, serializableStandaloneProperties) = serializableProperties.partition { it.propertySymbol in primaryConstructorProperties }
return FirSerializableProperties(
serializableProperties, isExternallySerializable, serializableConstructorProperties, serializableStandaloneProperties
)
}
}
val FirSession.serializablePropertiesProvider: FirSerializablePropertiesProvider by FirSession.sessionComponentAccessor()
fun FirPropertySymbol.declaresDefaultValue(): Boolean {
if (hasInitializer) return true
// TODO: handle deserialized properties
return false
}
@Suppress("UNUSED_PARAMETER")
fun <P : ISerializableProperty> restoreCorrectOrderFromClassProtoExtension(classSymbol: FirClassSymbol<*>, props: List<P>): List<P> {
// TODO: handle deserialized properties
return props
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 5,327
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/levels/kafka/Producer.kt
|
karlazzampersonal
| 456,272,157
| false
|
{"Kotlin": 9291}
|
package com.levels.kafka
import org.apache.kafka.clients.producer.KafkaProducer
import java.util.*
class Producer {
fun <K, V> createProducer(props: Properties): KafkaProducer<K, V> {
return KafkaProducer(props)
}
}
| 0
|
Kotlin
|
0
| 0
|
1cc018d936b894d94dce480424c94d3404e35772
| 234
|
ktor-kafka
|
Apache License 2.0
|
jvm-common/src/main/kotlin/org/digma/intellij/plugin/idea/execution/handlers/OpenLibertyServerRunConfigurationInstrumentationHandler.kt
|
digma-ai
| 472,408,329
| false
|
{"Kotlin": 1290991, "Java": 542977, "C#": 115880, "HTML": 15494, "FreeMarker": 13547, "Shell": 6494}
|
package org.digma.intellij.plugin.idea.execution.handlers
import com.intellij.openapi.components.service
import org.digma.intellij.plugin.execution.RunConfigurationInstrumentationService
import org.digma.intellij.plugin.idea.execution.services.OpenLibertyRunConfigurationInstrumentationService
class OpenLibertyServerRunConfigurationInstrumentationHandler : BaseRunConfigurationInstrumentationHandler() {
override fun getService(): RunConfigurationInstrumentationService {
return service<OpenLibertyRunConfigurationInstrumentationService>()
}
override fun getOrder(): Int {
return 200
}
}
| 427
|
Kotlin
|
7
| 22
|
8995a81e2ede5d60ec5979319a876a1a9026b922
| 625
|
digma-intellij-plugin
|
MIT License
|
src/client/kotlin/z3roco01/meowclient/module/modules/LeftStatusEffectsModule.kt
|
z3roco01
| 782,233,287
| false
|
{"Kotlin": 13825, "Java": 9891}
|
package z3roco01.meowclient.module.modules
import z3roco01.meowclient.module.Module
// Moves status effect overlay to the left
class LeftStatusEffectsModule : Module("l_effect")
| 0
|
Kotlin
|
0
| 0
|
26761a7d1bb253284904b5d576ce36b91a6ff2f9
| 179
|
meow-client
|
The Unlicense
|
plugin/src/main/kotlin/io/ktor/plugin/features/Docker.kt
|
ktorio
| 478,869,199
| false
| null |
package io.ktor.plugin.features
import com.google.cloud.tools.jib.gradle.JibExtension
import com.google.cloud.tools.jib.gradle.JibPlugin
import com.google.cloud.tools.jib.gradle.JibTask
import com.google.cloud.tools.jib.gradle.TargetImageParameters
import org.gradle.api.*
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.process.ExecOperations
import javax.inject.Inject
enum class JreVersion(val javaVersion: JavaVersion) {
JRE_1_8(JavaVersion.VERSION_1_8),
JRE_11(JavaVersion.VERSION_11),
JRE_17(JavaVersion.VERSION_17);
val majorVersion = javaVersion.majorVersion.toInt()
}
enum class DockerPortMappingProtocol {
TCP, UDP
}
data class DockerPortMapping(
val outsideDocker: Int,
val insideDocker: Int = outsideDocker,
val protocol: DockerPortMappingProtocol = DockerPortMappingProtocol.TCP
)
@Suppress("MemberVisibilityCanBePrivate") // Provides a public API
abstract class DockerExtension(project: Project) {
private companion object {
private fun Provider<String>.zipWithTag(tag: Provider<String>): Provider<String> =
zip(tag) { imageName, imageTag ->
"$imageName:$imageTag"
}
}
/**
* Specifies the JRE version to use in the image. Defaults to [JreVersion.JRE_17].
*/
val jreVersion = project.property(defaultValue = JreVersion.JRE_17)
/**
* Specifies a tag to use in the image. Defaults to `"latest"`.
*/
val imageTag = project.property(defaultValue = "latest")
/**
* Specifies an image name for local builds. Defaults to `"ktor-docker-image"`.
*/
val localImageName = project.property(defaultValue = "ktor-docker-image")
/**
* Specifies an external registry to push the image into. Default is not set.
*/
val externalRegistry = project.property<DockerImageRegistry>(defaultValue = null)
/**
* Specifies an image name in form `"imageName:tag"` for a local registry.
*/
val fullLocalImageName = localImageName.zipWithTag(imageTag)
/**
* Specifies an image name in form `"imageName:tag"` for an external registry.
*/
val fullExternalImageName = externalRegistry.flatMap { it.toImage }.zipWithTag(imageTag)
/**
* Specifies port mappings for a `runDocker` command.
*/
val portMappings: ListProperty<DockerPortMapping> = project.objects.listProperty(DockerPortMapping::class.java)
.convention(listOf(DockerPortMapping(8080, 8080, DockerPortMappingProtocol.TCP)))
}
interface DockerImageRegistry {
/**
* Specifies a link for [JibExtension.to.image][TargetImageParameters.image].
*/
val toImage: Provider<String>
/**
* Specifies a username for a given registry.
*/
val username: Provider<String>
/**
* Specifies a password for a given registry.
*/
val password: Provider<String>
companion object {
/**
* Creates a [DockerImageRegistry] for [DockerHub](https://hub.docker.com/)
* from a given [appName], [username] and [password].
*/
@Suppress("unused")
fun dockerHub(
appName: Provider<String>,
username: Provider<String>,
password: Provider<String>
): DockerImageRegistry = DockerHubRegistry(appName, username, password)
/**
* Creates a [DockerImageRegistry] for [Google Container Registry](https://cloud.google.com/container-registry)
* from a given [appName] and [username].
*/
@Suppress("unused")
fun googleContainerRegistry(
projectName: Provider<String>,
appName: Provider<String>,
username: Provider<String>,
password: Provider<String>
): DockerImageRegistry = GoogleContainerRegistry(projectName, appName, username, password)
}
}
private class DockerHubRegistry(
appName: Provider<String>,
override val username: Provider<String>,
override val password: Provider<String>
) : DockerImageRegistry {
override val toImage: Provider<String> = username.zip(appName) { user, app -> "$user/$app" }
}
private class GoogleContainerRegistry(
projectName: Provider<String>,
appName: Provider<String>,
override val username: Provider<String>,
override val password: Provider<String>
) : DockerImageRegistry {
override val toImage: Provider<String> = projectName.zip(appName) { project, app -> "gcr.io/$project/$app" }
}
private const val DOCKER_EXTENSION_NAME = "docker"
// JIB related tasks
private const val JIB_BUILD_INTO_LOCAL_DOCKER_TASK_NAME = JibPlugin.BUILD_DOCKER_TASK_NAME
private const val JIB_BUILD_INTO_TAR_TASK_NAME = JibPlugin.BUILD_TAR_TASK_NAME
private const val JIB_BUILD_IMAGE_AND_PUBLISH_TASK_NAME = JibPlugin.BUILD_IMAGE_TASK_NAME
// Ktor related tasks
const val PUBLISH_IMAGE_TO_LOCAL_REGISTRY_TASK_NAME = "publishImageToLocalRegistry"
const val PUBLISH_IMAGE_TO_EXTERNAL_REGISTRY_TASK_NAME = "publishImage"
const val BUILD_IMAGE_TASK_NAME = "buildImage"
const val RUN_DOCKER_TASK_NAME = "runDocker"
// Ktor configuration tasks
private const val SETUP_JIB_LOCAL_TASK_NAME = "setupJibLocal"
private const val SETUP_JIB_EXTERNAL_TASK_NAME = "setupJibExternal"
private fun markJibTaskNotCompatible(task: Task) = task.markNotCompatibleWithConfigurationCache(
"JIB plugin is not compatible with the configuration cache. " +
"See https://github.com/GoogleContainerTools/jib/issues/3132"
)
private abstract class ConfigureJibTaskBase(@get:Input val isExternal: Boolean) : DefaultTask() {
init {
@Suppress("LeakingThis")
markJibTaskNotCompatible(this)
}
@TaskAction
fun execute() {
val jibExtension = project.extensions.getByType(JibExtension::class.java)
val dockerExtension = project.getKtorExtension<DockerExtension>()
jibExtension.from.setImage(dockerExtension.jreVersion.map { "eclipse-temurin:${it.majorVersion}-jre" })
if (isExternal) {
val externalRegistry = dockerExtension.externalRegistry
jibExtension.to.setImage(dockerExtension.fullExternalImageName)
jibExtension.to.auth.setUsername(externalRegistry.flatMap { it.username })
jibExtension.to.auth.setPassword(externalRegistry.flatMap { it.password })
} else {
jibExtension.to.setImage(dockerExtension.fullLocalImageName)
}
val projectJava = project.javaVersion
val imageJava = dockerExtension.jreVersion.get().javaVersion
if (imageJava < projectJava) {
throw GradleException(
"You're trying to build an image with JRE $imageJava while your project's JDK or 'java.targetCompatibility' is $projectJava. " +
"Please use a higher version of an image JRE through the 'ktor.docker.jreVersion' extension in the build file, " +
"or set the 'java.targetCompatibility' property to a lower version."
)
}
}
}
private abstract class ConfigureJibLocalTask : ConfigureJibTaskBase(isExternal = false)
private abstract class ConfigureJibExternalTask : ConfigureJibTaskBase(isExternal = true)
private abstract class RunDockerTask : DefaultTask() {
@get:Inject
abstract val execOperations: ExecOperations
@get:Input
abstract val fullImageName: Property<String>
@TaskAction
fun execute() {
val dockerExtension = project.getKtorExtension<DockerExtension>()
execOperations.exec {
it.commandLine(buildList {
add("docker")
add("run")
for (portMapping in dockerExtension.portMappings.get()) {
add("-p")
with(portMapping) {
add("${outsideDocker}:${insideDocker}/${protocol.name.lowercase()}")
}
}
add(fullImageName.get())
})
}
}
}
fun configureDocker(project: Project) {
project.plugins.apply(JibPlugin::class.java)
val dockerExtension = project.createKtorExtension<DockerExtension>(DOCKER_EXTENSION_NAME)
val tasks = project.tasks
tasks.withType(JibTask::class.java).configureEach { markJibTaskNotCompatible(it) }
val configureJibLocalTask = tasks.register(SETUP_JIB_LOCAL_TASK_NAME, ConfigureJibLocalTask::class.java)
val configureJibExternalTask = tasks.register(SETUP_JIB_EXTERNAL_TASK_NAME, ConfigureJibExternalTask::class.java)
val configureJibTasks = arrayOf(configureJibLocalTask, configureJibExternalTask)
val jibBuildIntoLocalDockerTask = tasks.named(JIB_BUILD_INTO_LOCAL_DOCKER_TASK_NAME)
val jibBuildIntoTarTask = tasks.named(JIB_BUILD_INTO_TAR_TASK_NAME)
val jibBuildImageAndPublishTask = tasks.named(JIB_BUILD_IMAGE_AND_PUBLISH_TASK_NAME)
val jibTasks = arrayOf(jibBuildIntoLocalDockerTask, jibBuildIntoTarTask, jibBuildImageAndPublishTask)
for (jibTask in jibTasks) {
jibTask.configure {
it.mustRunAfter(*configureJibTasks)
}
}
tasks.registerKtorTask<RunDockerTask>(
RUN_DOCKER_TASK_NAME,
"Builds a project's image to a Docker daemon and runs it."
) {
fullImageName.set(dockerExtension.fullLocalImageName)
dependsOn(
configureJibLocalTask,
jibBuildIntoLocalDockerTask
)
}
tasks.registerKtorTask(
PUBLISH_IMAGE_TO_LOCAL_REGISTRY_TASK_NAME,
"Builds and publishes a project's Docker image to a local registry."
) {
dependsOn(
configureJibLocalTask,
jibBuildIntoLocalDockerTask
)
}
tasks.registerKtorTask(
PUBLISH_IMAGE_TO_EXTERNAL_REGISTRY_TASK_NAME,
"Builds and publishes a project's Docker image to an external registry."
) {
dependsOn(
configureJibExternalTask,
jibBuildImageAndPublishTask
)
}
tasks.registerKtorTask(
BUILD_IMAGE_TASK_NAME,
"Builds a project's Docker image to a tarball."
) {
dependsOn(
configureJibLocalTask,
jibBuildIntoTarTask
)
}
}
| 9
| null |
8
| 58
|
a0c22edecc8d430842b0534b123ad5231f32d4a1
| 10,324
|
ktor-build-plugins
|
Apache License 2.0
|
app/src/main/java/com/manoj/dlt/ui/TutorialUtil.kt
|
ManojMadanmohan
| 52,667,086
| false
| null |
package com.manoj.dlt.ui
import android.app.Activity
import android.view.View
import com.getkeepsafe.taptargetview.TapTarget
import com.getkeepsafe.taptargetview.TapTargetSequence
import com.manoj.dlt.R
object TutorialUtil{
@JvmStatic
fun showTutorial(activity: Activity, onboardingInput: View, onboardingLaunch: View, onboardingHistory: View, listener: TapTargetSequence.Listener)
{
TapTargetSequence(activity)
.targets(TapTarget.forView(onboardingInput, activity.getString(R.string.onboarding_input_title))
.dimColor(android.R.color.black)
.outerCircleColor(R.color.SlateGray)
.targetCircleColor(R.color.fabColorNormal)
.tintTarget(false),
TapTarget.forView(onboardingLaunch, activity.getString(R.string.onboarding_launch_title))
.dimColor(android.R.color.black)
.outerCircleColor(R.color.SlateGray)
.targetCircleColor(R.color.fabColorNormal)
.tintTarget(false),
TapTarget.forView(onboardingHistory, activity.getString(R.string.onboarding_history_title))
.dimColor(android.R.color.black)
.outerCircleColor(R.color.SlateGray)
.targetCircleColor(R.color.fabColorNormal)
.tintTarget(false))
.listener(listener)
.start()
}
}
| 2
| null |
1
| 19
|
d8688cdb280290fa0c8e32ba6eb1164c020563fb
| 1,598
|
dlt
|
MIT License
|
src/main/kotlin/com/dzirbel/kotify/network/model/SpotifyTimeInterval.kt
|
dzirbel
| 211,595,180
| false
| null |
package com.dzirbel.kotify.network.model
import kotlinx.serialization.Serializable
@Serializable
data class SpotifyTimeInterval(
/** The starting point (in seconds) of the time interval. */
val start: Float,
/** The duration (in seconds) of the time interval. */
val duration: Float,
/** The confidence, from 0.0 to 1.0, of the reliability of the interval. */
val confidence: Float
)
| 0
| null |
0
| 9
|
2f8879a43f5741d42811ef90cf12f07581599ed9
| 412
|
kotify
|
MIT License
|
server/src/main/kotlin/org/reckful/archive/twitter/server/dto/MediaDTO.kt
|
ReckfulArchive
| 632,190,129
| false
| null |
package org.reckful.archive.twitter.server.dto
import io.swagger.v3.oas.annotations.media.Schema
@Schema(
name = "Media",
description = "Media file information."
)
class MediaDTO(
@Schema(description = "Pre-defined type of media.", allowableValues = ["photo", "gif", "video"])
val type: String,
@Schema(
description = "URL at which this media file can be accessed. " +
"The URL is static and can be used by a user-facing frontend.",
example = "https://reckfularchive.github.io/twitter/media/byron/photos/1261622132540420096-0.png"
)
val url: String
) {
constructor(type: Type, url: String) : this(type.serializableName, url)
enum class Type { // NOTE: this is serialized by name as is
PHOTO, GIF, VIDEO;
internal val serializableName: String = name.lowercase()
}
}
| 8
|
Kotlin
|
0
| 0
|
10e5ab61116a0864b47c37f2e3ff9860d22976e4
| 858
|
twitter-server
|
MIT License
|
app/src/main/java/io/kotlinthree/extension/KThread.kt
|
KotlinThree
| 48,309,064
| false
| null |
package io.kotlinthree.extension
/**
* Created by jameson on 12/19/15.
*/
import android.os.Handler
import android.os.Looper
fun runAsync(action: () -> Unit) {
Thread(Runnable(action)).start()
}
fun runOnUiThread(action: () -> Unit) {
Handler(Looper.getMainLooper()).post(Runnable(action))
}
fun runDelayed(delayMillis: Long, action: () -> Unit) {
Handler().postDelayed(Runnable(action), delayMillis)
}
fun runDelayedOnUiThread(delayMillis: Long, action: () -> Unit) {
Handler(Looper.getMainLooper()).postDelayed(Runnable(action), delayMillis)
}
| 1
| null |
1
| 6
|
506d4a1782e506fa3adc4f1bc31560c6b0f128b9
| 569
|
kotlin_zhihu
|
Apache License 2.0
|
app/src/main/java/com/ruben/epicworld/data/repository/GamesRepositoryImpl.kt
|
rubenquadros
| 391,401,374
| false
| null |
package com.ruben.epicworld.data.repository
import com.ruben.epicworld.data.DataSource
import com.ruben.epicworld.data.mapper.ErrorMapper
import com.ruben.epicworld.data.mapper.GamesMapper
import com.ruben.epicworld.domain.entity.base.Record
import com.ruben.epicworld.domain.entity.gamedetails.GameDetailsEntity
import com.ruben.epicworld.domain.entity.games.GamesEntity
import com.ruben.epicworld.domain.entity.gamevideos.GameVideosEntity
import com.ruben.epicworld.domain.repository.GamesRepository
import com.ruben.epicworld.remote.RemoteException
import com.ruben.epicworld.remote.model.request.GetAllGamesRequest
import com.ruben.epicworld.remote.model.request.GetGameDetailsRequest
import com.ruben.epicworld.remote.model.request.GetGameVideosRequest
import com.ruben.epicworld.remote.model.request.SearchGamesRequest
import javax.inject.Inject
/**
* Created by <NAME> on 01/08/21
**/
class GamesRepositoryImpl @Inject constructor(private val dataSource: DataSource): GamesRepository {
private val gamesMapper = GamesMapper()
private val errorMapper = ErrorMapper()
override suspend fun getAllGames(nextPage: Int): Record<GamesEntity> {
return try {
dataSource.api().restApi().getAllGames(GetAllGamesRequest(nextPage)).run {
gamesMapper.mapGamesResponse(this)
}
} catch (e: RemoteException) {
errorMapper.mapErrorRecord(e)
}
}
override suspend fun getGameDetails(gameId: Int): Record<GameDetailsEntity> {
return try {
dataSource.api().restApi().getGameDetails(GetGameDetailsRequest(gameId)).run {
gamesMapper.mapGameDetailsResponse(this)
}
} catch (e: RemoteException) {
errorMapper.mapErrorRecord(e)
}
}
override suspend fun getGameVideos(gameId: Int): Record<GameVideosEntity> {
return try {
dataSource.api().restApi().getGameVideos(GetGameVideosRequest((gameId))).run {
gamesMapper.mapGameVideosResponse(this)
}
} catch (e: RemoteException) {
errorMapper.mapErrorRecord(e)
}
}
override suspend fun searchGames(query: String): Record<GamesEntity> {
return try {
dataSource.api().restApi().searchGames(SearchGamesRequest(query)).run {
gamesMapper.mapSearchGamesResponse(this)
}
} catch (e: RemoteException) {
errorMapper.mapErrorRecord(e)
}
}
}
| 1
|
Kotlin
|
9
| 81
|
215317852936a0c0849b6434e030d0ecb9be8546
| 2,505
|
Jetpack-Compose-Video-Games-Example
|
Apache License 2.0
|
device-server/src/main/kotlin/com/badoo/automation/deviceserver/controllers/DevicesController.kt
|
badoo
| 133,063,088
| false
| null |
package com.badoo.automation.deviceserver.controllers
import com.badoo.automation.deviceserver.EmptyMap
import com.badoo.automation.deviceserver.JsonMapper
import com.badoo.automation.deviceserver.data.*
import com.badoo.automation.deviceserver.host.management.DeviceManager
import com.fasterxml.jackson.databind.JsonNode
import io.ktor.auth.UserIdPrincipal
class DevicesController(private val deviceManager: DeviceManager) {
private val happy = emptyMap<Unit, Unit>()
fun getDeviceRefs(): List<DeviceDTO> {
return deviceManager.getDeviceRefs()
}
fun createDevice(desiredCapabilities: DesiredCapabilities, user: UserIdPrincipal?): DeviceDTO {
return deviceManager.createDeviceAsync(desiredCapabilities, user?.name)
}
fun getDeviceContactDetails(ref: DeviceRef): DeviceDTO {
return deviceManager.getGetDeviceDTO(ref)
}
fun controlDevice(ref: DeviceRef, jsonContent: JsonNode): EmptyMap {
val action = jsonContent["action"]?.asText()
when (action) {
"reset" -> deviceManager.resetAsyncDevice(ref)
"clear_safari_cookies" -> deviceManager.clearSafariCookies(ref)
"shake" -> deviceManager.shake(ref)
else -> throw IllegalArgumentException("Unknown action $action")
}
return happy
}
fun deleteReleaseDevice(ref: DeviceRef): EmptyMap {
deviceManager.deleteReleaseDevice(ref, "httpRequest")
return happy
}
fun releaseDevices(user: UserIdPrincipal) {
deviceManager.releaseUserDevices(user.name, "httpRequest")
}
fun setAccessToCameraAndThings(ref: DeviceRef, jsonContent: JsonNode): EmptyMap {
jsonContent.elements().forEach { deviceManager.approveAccess(ref, it["bundle_id"].textValue()) }
return happy
}
fun setPermissions(ref: DeviceRef, json: JsonNode): EmptyMap {
if (json.isArray) {
return setAccessToCameraAndThings(ref, json)
}
val permissions = JsonMapper().fromJson<AppPermissionsDto>(json)
deviceManager.setPermissions(ref, permissions)
return happy
}
fun getEndpointFor(ref: DeviceRef, port: Int): Map<String, String> {
return mapOf("endpoint" to deviceManager.getEndpointFor(ref, port).toString())
}
fun crashLogs(ref: DeviceRef, pastMinutes: Long?): List<Map<String, String>> {
var logs = deviceManager.crashLogs(ref, pastMinutes)
return logs.map {
mapOf("filename" to it.filename, "content" to it.content)
}
}
fun deleteCrashLogs(ref: DeviceRef): Boolean {
return deviceManager.deleteCrashLogs(ref)
}
fun getLastCrashLog(ref: DeviceRef): Map<String, String> {
val log = deviceManager.getLastCrashLog(ref)
return mapOf("filename" to log.filename, "content" to log.content)
}
fun startStopVideo(ref: DeviceRef, jsonContent: JsonNode): EmptyMap {
val start = jsonContent["start"]
if (start.isBoolean) {
when (start.asBoolean()) {
true -> deviceManager.startVideo(ref)
false -> deviceManager.stopVideo(ref)
}
} else {
throw IllegalArgumentException("Parameter start should be boolean true or false")
}
return happy
}
fun getVideo(ref: DeviceRef): ByteArray {
return deviceManager.getVideo(ref)
}
fun deleteVideo(ref: DeviceRef): EmptyMap {
deviceManager.deleteVideo(ref)
return happy
}
fun resetMedia(ref: DeviceRef): EmptyMap {
deviceManager.resetMedia(ref)
return happy
}
fun getDiagnostic(ref: DeviceRef, type: String, query: DiagnosticQuery): Diagnostic {
val diagnosticType = DiagnosticType.fromString(type)
return deviceManager.getDiagnostic(ref, diagnosticType, query)
}
fun resetDiagnostic(ref: DeviceRef, type: String) {
val diagnosticType = DiagnosticType.fromString(type)
deviceManager.resetDiagnostic(ref, diagnosticType)
}
fun getDeviceState(ref: DeviceRef): SimulatorStatusDTO {
return deviceManager.getDeviceState(ref)
}
fun getTotalCapacity(desiredCapabilities: DesiredCapabilities): Map<String, Int> {
return deviceManager.getTotalCapacity(desiredCapabilities)
}
fun listFiles(ref: DeviceRef, dataPath: DataPath): List<String> {
return deviceManager.listFiles(ref, dataPath)
}
fun pullFile(ref: DeviceRef, dataPath: DataPath): ByteArray {
return deviceManager.pullFile(ref, dataPath)
}
fun uninstallApplication(ref: DeviceRef, bundleId: String): EmptyMap {
deviceManager.uninstallApplication(ref, bundleId)
return happy
}
fun setEnvironmentVariables(ref: DeviceRef, environmentVariables: Map<String, String>): EmptyMap {
deviceManager.setEnvironmentVariables(ref, environmentVariables)
return happy
}
}
| 2
| null |
11
| 39
|
2569119e7d074356a320f5440470f74e1f41e4f3
| 4,956
|
ios-device-server
|
MIT License
|
mobilesecurity/src/main/java/android/thakur/com/mobilesecurity/services/jobs/JobsReciever.kt
|
ankitthakur
| 150,006,488
| false
| null |
@file:Suppress("NAME_SHADOWING")
package android.thakur.com.mobilesecurity.services.jobs
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.thakur.com.mobilesecurity.loggerUtil.Logger
import android.thakur.com.mobilesecurity.services.MSServices
internal class JobsReciever:BroadcastReceiver() {
private lateinit var logger:Logger
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == "android.intent.action.BOOT_COMPLETED") {
logger = Logger(context!!)
logger.log("recieved broadcast")
// this will call BackgroundService onHandle fun
MSServices.sharedInstance.startJob(context, null)
}
}
}
| 0
|
Kotlin
|
1
| 0
|
7e6f09d6dc867dab7cc0e88557ed65db5ba74497
| 768
|
MobileSecurity-Android
|
MIT License
|
platform/lang-impl/src/com/intellij/platform/backend/documentation/impl/DocumentationRequest.kt
|
ingokegel
| 72,937,917
| true
| null |
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.backend.documentation.impl
import com.intellij.model.Pointer
import com.intellij.platform.backend.documentation.DocumentationTarget
import com.intellij.platform.backend.presentation.TargetPresentation
class DocumentationRequest(
val targetPointer: Pointer<out DocumentationTarget>,
val presentation: TargetPresentation,
)
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 479
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/example/taskmangamentapp/MainActivity.kt
|
ravinduiddamalgoda
| 799,694,674
| false
|
{"Kotlin": 10416}
|
package me.sunera.taskSet
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.sunera.taskSet.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var db: TaskDatabase
private lateinit var tasksAdapter: TasksAdapter
private val scope = CoroutineScope(Dispatchers.Main + Job())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
tasksAdapter = TasksAdapter(mutableListOf(),this)
db = TaskDatabase.getDatabase(this)
binding.notesRecyclerView.layoutManager = LinearLayoutManager(this)
binding.notesRecyclerView.adapter = tasksAdapter
scope.launch {
val tasks = withContext(Dispatchers.IO) { db.taskDao().getAllTasks() }
tasksAdapter.refreshData(tasks)
}
binding.addButton.setOnClickListener {
val intent = Intent(this, AddTaskActivity::class.java)
startActivity(intent)
}
}
override fun onResume() {
super.onResume()
val taskDao = db.taskDao()
scope.launch {
val tasks = withContext(Dispatchers.IO) { db.taskDao().getAllTasks() }
tasksAdapter.refreshData(tasks)
}
}
override fun onDestroy() {
super.onDestroy()
scope.cancel()
}
}
| 0
|
Kotlin
|
0
| 0
|
092861e03c7c5874be7291d721f9e43c4eddbfe7
| 1,822
|
MAD_IT22925336
|
MIT License
|
statistics/src/main/java/com/duckduckgo/app/statistics/AtbInitializer.kt
|
duckduckgo
| 78,869,127
| false
| null |
/*
* Copyright (c) 2019 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.statistics
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.duckduckgo.app.di.AppCoroutineScope
import com.duckduckgo.app.statistics.api.StatisticsUpdater
import com.duckduckgo.app.statistics.store.StatisticsDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import timber.log.Timber
interface AtbInitializerListener {
/** This method will be called before initializing the ATB */
suspend fun beforeAtbInit()
/** @return the timeout in milliseconds after which [beforeAtbInit] will be stopped */
fun beforeAtbInitTimeoutMillis(): Long
}
class AtbInitializer(
@AppCoroutineScope private val appCoroutineScope: CoroutineScope,
private val statisticsDataStore: StatisticsDataStore,
private val statisticsUpdater: StatisticsUpdater,
private val listeners: Set<AtbInitializerListener>
) : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
appCoroutineScope.launch { initialize() }
}
@VisibleForTesting
suspend fun initialize() {
Timber.v("Initialize ATB")
listeners.forEach {
withTimeoutOrNull(it.beforeAtbInitTimeoutMillis()) { it.beforeAtbInit() }
}
initializeAtb()
}
private fun initializeAtb() {
if (statisticsDataStore.hasInstallationStatistics) {
statisticsUpdater.refreshAppRetentionAtb()
} else {
statisticsUpdater.initializeAtb()
}
}
}
| 62
| null |
870
| 3,310
|
5dd3f5de3013e80ddf045ff2d539773bb73cdeee
| 2,235
|
Android
|
Apache License 2.0
|
clevertap-core/src/main/java/com/clevertap/android/sdk/db/CtDatabase.kt
|
CleverTap
| 42,078,482
| false
|
{"Java": 1804916, "Kotlin": 1661309, "HTML": 10233}
|
package com.clevertap.android.sdk.db
import android.annotation.SuppressLint
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.clevertap.android.sdk.CleverTapInstanceConfig
import com.clevertap.android.sdk.Constants
import com.clevertap.android.sdk.Constants.COMMAND_ADD
import com.clevertap.android.sdk.Constants.COMMAND_SET
import com.clevertap.android.sdk.Constants.DATE_PREFIX
import com.clevertap.android.sdk.Logger
import com.clevertap.android.sdk.StorageHelper
import com.clevertap.android.sdk.db.Table.EVENTS
import com.clevertap.android.sdk.db.Table.INBOX_MESSAGES
import com.clevertap.android.sdk.db.Table.PROFILE_EVENTS
import com.clevertap.android.sdk.db.Table.PUSH_NOTIFICATIONS
import com.clevertap.android.sdk.db.Table.PUSH_NOTIFICATION_VIEWED
import com.clevertap.android.sdk.db.Table.UNINSTALL_TS
import com.clevertap.android.sdk.db.Table.USER_PROFILES
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import kotlin.math.max
class DatabaseHelper internal constructor(val context: Context, val config: CleverTapInstanceConfig, dbName: String?, private val logger: Logger) :
SQLiteOpenHelper(context, dbName, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_VERSION = 4
private const val DB_LIMIT = 20 * 1024 * 1024 //20mb
}
private val databaseFile: File
init {
databaseFile = context.getDatabasePath(dbName)
}
override fun onCreate(db: SQLiteDatabase) {
logger.verbose("Creating CleverTap DB")
executeStatement(db, CREATE_EVENTS_TABLE)
executeStatement(db, CREATE_PROFILE_EVENTS_TABLE)
executeStatement(db, CREATE_USER_PROFILES_TABLE)
executeStatement(db, CREATE_INBOX_MESSAGES_TABLE)
executeStatement(db, CREATE_PUSH_NOTIFICATIONS_TABLE)
executeStatement(db, CREATE_UNINSTALL_TS_TABLE)
executeStatement(db, CREATE_NOTIFICATION_VIEWED_TABLE)
executeStatement(db, EVENTS_TIME_INDEX)
executeStatement(db, PROFILE_EVENTS_TIME_INDEX)
executeStatement(db, UNINSTALL_TS_INDEX)
executeStatement(db, PUSH_NOTIFICATIONS_TIME_INDEX)
executeStatement(db, INBOX_MESSAGES_COMP_ID_USERID_INDEX)
executeStatement(db, NOTIFICATION_VIEWED_INDEX)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
logger.verbose("Upgrading CleverTap DB to version $newVersion")
when (oldVersion) {
1 -> {
// For DB Version 2, just adding Push Notifications, Uninstall TS and Inbox Messages tables and related indices and migrating userProfiles table
executeStatement(db, DROP_TABLE_UNINSTALL_TS)
executeStatement(db, DROP_TABLE_INBOX_MESSAGES)
executeStatement(db, DROP_TABLE_PUSH_NOTIFICATION_VIEWED)
executeStatement(db, CREATE_INBOX_MESSAGES_TABLE)
executeStatement(db, CREATE_PUSH_NOTIFICATIONS_TABLE)
executeStatement(db, CREATE_UNINSTALL_TS_TABLE)
executeStatement(db, CREATE_NOTIFICATION_VIEWED_TABLE)
executeStatement(db, UNINSTALL_TS_INDEX)
executeStatement(db, PUSH_NOTIFICATIONS_TIME_INDEX)
executeStatement(db, INBOX_MESSAGES_COMP_ID_USERID_INDEX)
executeStatement(db, NOTIFICATION_VIEWED_INDEX)
migrateUserProfilesTable(db)
}
2 -> {
// For DB Version 3, just adding Push Notification Viewed table and index and migrating userProfiles table
executeStatement(db, DROP_TABLE_PUSH_NOTIFICATION_VIEWED)
executeStatement(db, CREATE_NOTIFICATION_VIEWED_TABLE)
executeStatement(db, NOTIFICATION_VIEWED_INDEX)
migrateUserProfilesTable(db)
}
3 -> {
// For DB Version 4, just migrate userProfiles table
migrateUserProfilesTable(db)
}
}
}
private fun getDeviceIdForAccountIdFromPrefs(accountId: String): String {
val baseKey = Constants.DEVICE_ID_TAG + ":" + accountId
val fallbackKey = Constants.FALLBACK_ID_TAG + ":" + accountId
return StorageHelper.getString(context, baseKey, null)
?: if (config.isDefaultInstance) StorageHelper.getString(context, baseKey, null) else null
?: StorageHelper.getString(context, fallbackKey, "")
}
/**
* This function migrates the userProfiles table to a new schema with a composite primary key of _id + deviceId
* The older schema only had _id as the primary key
* While migrating, the deviceId is back-filled and also the data string is corrected in format
*
* @param db
*/
private fun migrateUserProfilesTable(db: SQLiteDatabase) {
executeStatement(db, CREATE_TEMP_USER_PROFILES_TABLE)
val deviceId = getDeviceIdForAccountIdFromPrefs(config.accountId)
// Query to select all data from the old user profiles table
val selectQuery = "SELECT ${Column.ID}, ${Column.DATA} FROM ${USER_PROFILES.tableName};"
val cursor = db.rawQuery(selectQuery, null)
cursor.use {
if (cursor.moveToFirst()) {
val id = cursor.getString(cursor.getColumnIndexOrThrow(Column.ID))
val dataString = cursor.getString(cursor.getColumnIndexOrThrow(Column.DATA))
val updatedDataString = migrateDataString(dataString)
// Insert the modified data into the temporary table
val insertQuery =
"""INSERT INTO temp_${USER_PROFILES.tableName} (${Column.ID}, ${Column.DEVICE_ID}, ${Column.DATA})
VALUES ('$id', '$deviceId', '$updatedDataString');"""
executeStatement(db, insertQuery)
}
}
executeStatement(db, DROP_USER_PROFILES_TABLE)
executeStatement(db, RENAME_USER_PROFILES_TABLE)
}
/**
* This function migrates the data column for the userProfiles table
* Removes the "$D_" prefix from date related property values
* Removes the "$set" and "$add" key from incorrectly stored multi-valued properties
*/
private fun migrateDataString(dataString: String): String {
return try {
val jsonObject = JSONObject(dataString)
val keys = jsonObject.keys()
while (keys.hasNext()) {
val key = keys.next()
var value = jsonObject.get(key)
if (value is String && value.startsWith(DATE_PREFIX)) {
value = (value.removePrefix(DATE_PREFIX)).toLong()
jsonObject.put(key, value)
}
if (value is JSONObject) {
if (value.has(COMMAND_SET))
jsonObject.put(key, value.getJSONArray(COMMAND_SET))
else if (value.has(COMMAND_ADD))
jsonObject.put(key, value.getJSONArray(COMMAND_ADD))
}
}
jsonObject.toString()
} catch (e: JSONException) {
// Return the original string if an error occurs
logger.verbose("Error while migrating data column for userProfiles table for data = $dataString", e)
dataString
}
}
@SuppressLint("UsableSpace")
fun belowMemThreshold(): Boolean {
return if (databaseFile.exists()) {
max(databaseFile.usableSpace, DB_LIMIT.toLong()) >= databaseFile.length()
} else {
true
}
}
fun deleteDatabase() {
close()
if (!databaseFile.delete()) {
logger.debug("Could not delete database")
}
}
private fun executeStatement(db: SQLiteDatabase, statement: String) {
val sqLiteStatement = db.compileStatement(statement)
logger.verbose("Executing - $statement")
sqLiteStatement.execute()
}
}
enum class Table(val tableName: String) {
EVENTS("events"),
PROFILE_EVENTS("profileEvents"),
USER_PROFILES("userProfiles"),
INBOX_MESSAGES("inboxMessages"),
PUSH_NOTIFICATIONS("pushNotifications"),
UNINSTALL_TS("uninstallTimestamp"),
PUSH_NOTIFICATION_VIEWED("notificationViewed")
}
object Column {
const val ID = "_id"
const val DATA = "data"
const val CREATED_AT = "created_at"
const val IS_READ = "isRead"
const val EXPIRES = "expires"
const val TAGS = "tags"
const val USER_ID = "messageUser"
const val CAMPAIGN = "campaignId"
const val WZRKPARAMS = "wzrkParams"
const val DEVICE_ID = "deviceID"
}
private val CREATE_EVENTS_TABLE = """
CREATE TABLE ${EVENTS.tableName} (
${Column.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Column.DATA} STRING NOT NULL,
${Column.CREATED_AT} INTEGER NOT NULL
);
"""
private val CREATE_PROFILE_EVENTS_TABLE = """
CREATE TABLE ${PROFILE_EVENTS.tableName} (
${Column.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Column.DATA} STRING NOT NULL,
${Column.CREATED_AT} INTEGER NOT NULL
);
"""
private val CREATE_INBOX_MESSAGES_TABLE = """
CREATE TABLE ${INBOX_MESSAGES.tableName} (
${Column.ID} STRING NOT NULL,
${Column.DATA} TEXT NOT NULL,
${Column.WZRKPARAMS} TEXT NOT NULL,
${Column.CAMPAIGN} STRING NOT NULL,
${Column.TAGS} TEXT NOT NULL,
${Column.IS_READ} INTEGER NOT NULL DEFAULT 0,
${Column.EXPIRES} INTEGER NOT NULL,
${Column.CREATED_AT} INTEGER NOT NULL,
${Column.USER_ID} STRING NOT NULL
);
"""
private val INBOX_MESSAGES_COMP_ID_USERID_INDEX = """
CREATE UNIQUE INDEX IF NOT EXISTS userid_id_idx ON ${INBOX_MESSAGES.tableName} (
${Column.USER_ID},
${Column.ID}
);
"""
private val EVENTS_TIME_INDEX = """
CREATE INDEX IF NOT EXISTS time_idx ON ${EVENTS.tableName} (${Column.CREATED_AT});
"""
private val PROFILE_EVENTS_TIME_INDEX = """
CREATE INDEX IF NOT EXISTS time_idx ON ${PROFILE_EVENTS.tableName} ( ${Column.CREATED_AT});
"""
private val CREATE_PUSH_NOTIFICATIONS_TABLE = """
CREATE TABLE ${PUSH_NOTIFICATIONS.tableName} (
${Column.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Column.DATA} STRING NOT NULL,
${Column.CREATED_AT} INTEGER NOT NULL,
${Column.IS_READ} INTEGER NOT NULL
);
"""
private val PUSH_NOTIFICATIONS_TIME_INDEX = """
CREATE INDEX IF NOT EXISTS time_idx ON ${PUSH_NOTIFICATIONS.tableName} (${Column.CREATED_AT});
"""
private val CREATE_UNINSTALL_TS_TABLE = """
CREATE TABLE ${UNINSTALL_TS.tableName} (
${Column.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Column.CREATED_AT} INTEGER NOT NULL
);
"""
private val UNINSTALL_TS_INDEX = """
CREATE INDEX IF NOT EXISTS time_idx ON ${UNINSTALL_TS.tableName} (${Column.CREATED_AT});
"""
private val CREATE_NOTIFICATION_VIEWED_TABLE = """
CREATE TABLE ${PUSH_NOTIFICATION_VIEWED.tableName} (
${Column.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Column.DATA} STRING NOT NULL,
${Column.CREATED_AT} INTEGER NOT NULL
);
"""
private val NOTIFICATION_VIEWED_INDEX = """
CREATE INDEX IF NOT EXISTS time_idx ON ${PUSH_NOTIFICATION_VIEWED.tableName} (${Column.CREATED_AT});
"""
private val DROP_TABLE_UNINSTALL_TS = "DROP TABLE IF EXISTS ${UNINSTALL_TS.tableName}"
private val DROP_TABLE_INBOX_MESSAGES = "DROP TABLE IF EXISTS ${INBOX_MESSAGES.tableName}"
private val DROP_TABLE_PUSH_NOTIFICATION_VIEWED = "DROP TABLE IF EXISTS ${PUSH_NOTIFICATION_VIEWED.tableName}"
private val CREATE_USER_PROFILES_TABLE = """
CREATE TABLE ${USER_PROFILES.tableName} (
${Column.DEVICE_ID} STRING NOT NULL,
${Column.ID} STRING NOT NULL,
${Column.DATA} STRING NOT NULL,
PRIMARY KEY (${Column.ID}, ${Column.DEVICE_ID})
);
"""
private val CREATE_TEMP_USER_PROFILES_TABLE = """
CREATE TABLE temp_${USER_PROFILES.tableName} (
${Column.ID} STRING NOT NULL,
${Column.DEVICE_ID} STRING NOT NULL,
${Column.DATA} STRING NOT NULL,
PRIMARY KEY (${Column.ID}, ${Column.DEVICE_ID})
);
"""
private val DROP_USER_PROFILES_TABLE = """
DROP TABLE ${USER_PROFILES.tableName};
"""
private val RENAME_USER_PROFILES_TABLE = """
ALTER TABLE temp_${USER_PROFILES.tableName} RENAME TO ${USER_PROFILES.tableName};
"""
| 6
|
Java
|
74
| 80
|
4b1ea7577e14f9abb68492ad09b36cf01c3b7c48
| 12,508
|
clevertap-android-sdk
|
MIT License
|
increase-kotlin-core/src/main/kotlin/com/increase/api/services/async/simulations/PhysicalCardServiceAsync.kt
|
Increase
| 614,596,742
| false
| null |
@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102
package com.increase.api.services.async.simulations
import com.increase.api.core.RequestOptions
import com.increase.api.models.PhysicalCard
import com.increase.api.models.SimulationPhysicalCardShipmentAdvanceParams
interface PhysicalCardServiceAsync {
/**
* This endpoint allows you to simulate advancing the shipment status of a Physical Card, to
* simulate e.g., that a physical card was attempted shipped but then failed delivery.
*/
suspend fun shipmentAdvance(
params: SimulationPhysicalCardShipmentAdvanceParams,
requestOptions: RequestOptions = RequestOptions.none()
): PhysicalCard
}
| 1
| null |
0
| 5
|
dc1361d08cb41ff45817c2e7638f53356f15cf8e
| 730
|
increase-kotlin
|
Apache License 2.0
|
plugins/space/src/main/kotlin/com/intellij/space/vcs/review/SpaceReviewToolwindowEmptyComponent.kt
|
Ret-Mode
| 346,431,027
| 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.space.vcs.review
import com.intellij.openapi.project.Project
import com.intellij.space.components.SpaceWorkspaceComponent
import com.intellij.space.messages.SpaceBundle
import com.intellij.space.settings.SpaceSettingsPanel
import com.intellij.space.vcs.SpaceProjectContext
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.UIUtil
import libraries.coroutines.extra.Lifetime
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import runtime.reactive.Property
import runtime.reactive.isLoading
import runtime.reactive.property.map
import javax.swing.JPanel
internal class SpaceReviewToolwindowEmptyComponent(project: Project, lifetime: Lifetime) : JPanel() {
private val workspaceComponent = SpaceWorkspaceComponent.getInstance()
private val projectContext = SpaceProjectContext.getInstance(project)
private val emptyState: Property<EmptyState> = lifetime.map(workspaceComponent.workspace, projectContext.context) { workspace, context ->
when {
workspace == null -> EmptyState.NOT_LOGGED_IN
context.isLoading -> EmptyState.CONNECTING_TO_REPOS
else -> EmptyState.NOT_ASSOCIATED
}
}
init {
background = UIUtil.getListBackground()
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fill())
val loginLabel = ActionLink(SpaceBundle.message("action.com.intellij.space.actions.SpaceLoginAction.text")) {
SpaceSettingsPanel.openSettings(null)
}
val connectingToReposLabel = JBLabel(SpaceBundle.message("review.toolwindow.empty.connecting.to.repositories.label")).apply {
foreground = UIUtil.getContextHelpForeground()
}
val isNotAssociatedLabel = JBLabel(SpaceBundle.message("review.toolwindow.empty.is.not.associated.label")).apply {
foreground = UIUtil.getContextHelpForeground()
}
emptyState.forEach(lifetime) {
removeAll()
val component = when (it) {
EmptyState.NOT_LOGGED_IN -> loginLabel
EmptyState.CONNECTING_TO_REPOS -> connectingToReposLabel
EmptyState.NOT_ASSOCIATED -> isNotAssociatedLabel
}
add(component, CC().alignX("center").alignY("center"))
revalidate()
repaint()
}
}
private enum class EmptyState {
NOT_LOGGED_IN,
CONNECTING_TO_REPOS,
NOT_ASSOCIATED
}
}
| 1
| null |
1
| 1
|
8dc0867bcc8101279cba2f54f6c009e1cfa2eb50
| 2,587
|
intellij-community
|
Apache License 2.0
|
spring-bukkit-serialization/src/main/kotlin/kr/summitsystems/springbukkit/serialization/ConfigurationSerializableRegistry.kt
|
summit-systems
| 728,399,361
| false
|
{"Kotlin": 150498}
|
package kr.summitsystems.springbukkit.serialization
import org.bukkit.configuration.serialization.ConfigurationSerializable
interface ConfigurationSerializableRegistry {
fun <T : ConfigurationSerializable> register(clazz: Class<T>, alias: String)
fun findRegisteredAll(): Map<String, Class<out ConfigurationSerializable>>
}
| 0
|
Kotlin
|
0
| 12
|
fc7b86e7842b1378b67f9bf069cfa46f317a21ce
| 334
|
spring-bukkit
|
Apache License 2.0
|
app/src/main/kotlin/com/babelia/fansyn/navigation/AlbumsScreenType.kt
|
Babelia13
| 551,891,953
| false
|
{"Kotlin": 309398, "Shell": 3830}
|
/*
* Copyright 2022 Babelia
*
* 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.babelia.fansyn.navigation
import android.os.Bundle
import androidx.navigation.NavType
import com.babelia.fansyn.audiostation.ui.AlbumBasicData
import com.babelia.fansyn.utils.extensions.fromJson
import com.babelia.fansyn.utils.extensions.toJson
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
@Suppress("UndocumentedPublicClass")
sealed class AlbumsScreenType : ScreenType {
object Albums : AlbumsScreenType() {
override val route = "albumsList"
}
object AlbumDetails : AlbumsScreenType() {
const val ALBUM_DATA_ARG = "albumData"
override val route = "${Albums.route}/"
override val routeDefinition = "$route{$ALBUM_DATA_ARG}"
@Suppress("UndocumentedPublicFunction")
fun getRouteFor(moshi: Moshi, albumData: AlbumBasicData) = "$route${moshi.toJson(albumData)}"
}
}
/**
* [NavType] used to send the album basic data as an argument in the navigation graph.
*/
@Suppress("ExpressionBodySyntax")
class AlbumDataNavType : NavType<AlbumBasicData>(isNullableAllowed = false) {
override fun get(bundle: Bundle, key: String): AlbumBasicData? {
return bundle.getParcelable(key)
}
override fun parseValue(value: String): AlbumBasicData {
val moshi: Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val fromJson: AlbumBasicData? = moshi.fromJson(value)
return fromJson!!
}
override fun put(bundle: Bundle, key: String, value: AlbumBasicData) {
bundle.putParcelable(key, value)
}
}
| 0
|
Kotlin
|
0
| 0
|
0fe3a5c9c84a6bad85a1c999b6fb66d4c2cbb478
| 2,189
|
FancySynologyAudioPlayer
|
Apache License 2.0
|
app/src/main/java/com/ali_sajjadi/daneshjooyarapp/mvp/view/ViewVideosFragment.kt
|
alisajjadi751
| 847,226,122
| false
|
{"Kotlin": 62083}
|
package com.ali_sajjadi.daneshjooyarapp.mvp.view
import DataListVideo
import android.content.Context
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ali_sajjadi.daneshjooyarapp.adapter.recycler.CourseVideosRecyclerAdapter
import com.ali_sajjadi.daneshjooyarapp.databinding.FragmentVideosBinding
class ViewVideosFragment(
private val context: Context
) {
val binding = FragmentVideosBinding.inflate(LayoutInflater.from(context))
fun setCourseRecycler(dataList: ArrayList<DataListVideo>) {
binding.recyclerVideos.layoutManager =
LinearLayoutManager(context, RecyclerView.VERTICAL, false)
binding.recyclerVideos.adapter = CourseVideosRecyclerAdapter(context, dataList)
}
}
| 0
|
Kotlin
|
0
| 0
|
9516991e9bd9527c7ad940a21c48e0deb8e3b154
| 826
|
daneshjooyar-App
|
MIT License
|
jcv-db-mongo/src/main/kotlin/com/ekino/oss/jcv/db/mongo/config/DBMongoValidators.kt
|
ekino
| 217,051,634
| false
| null |
package com.ekino.oss.jcv.db.mongo.config
import com.ekino.oss.jcv.core.comparator.RegexComparator
import com.ekino.oss.jcv.core.validator.validators
import com.ekino.oss.jcv.db.config.DBValidators
object DBMongoValidators {
private const val mongoDefaultIdRegex = "^[a-f\\d]{24}$"
@JvmStatic
fun defaultDBValidators() = validators {
+DBValidators.defaultDBValidators()
+templatedValidator("mongo_id", RegexComparator(mongoDefaultIdRegex.toRegex().toPattern()))
}
}
| 6
| null |
1
| 6
|
6723320f89d28781f92f652ea25e51d30c495870
| 502
|
jcv-db
|
MIT License
|
jvm/jvm-analysis-tests/src/com/intellij/codeInspection/tests/test/junit/JUnitMixedFrameworkInspectionTestBase.kt
|
ingokegel
| 72,937,917
| false
| null |
package com.intellij.codeInspection.tests.test.junit
import com.intellij.codeInspection.test.junit.JUnitMixedFrameworkInspection
import com.intellij.codeInspection.tests.UastInspectionTestBase
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.LightProjectDescriptor
abstract class JUnitMixedFrameworkInspectionTestBase : UastInspectionTestBase() {
override val inspection = JUnitMixedFrameworkInspection()
protected open class JUnitProjectDescriptor(languageLevel: LanguageLevel) : ProjectDescriptor(languageLevel) {
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
super.configureModule(module, model, contentEntry)
model.addJUnit3Library()
model.addJUnit4Library()
model.addJUnit5Library()
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = JUnitProjectDescriptor(sdkLevel)
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 1,060
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/alex/morgan/bearlist/BearListFragment.kt
|
axemorgan
| 115,024,266
| false
|
{"Gradle": 5, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 21, "Kotlin": 28, "Java Properties": 1}
|
package com.alex.morgan.bearlist
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.alex.morgan.bearlist.list.BearAdapter
import com.alex.morgan.bearlist.list.BearListActivity
import com.alex.morgan.bearlist.list.BearListContract
import com.google.android.material.snackbar.Snackbar
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.fragment_bear_list.*
import javax.inject.Inject
class BearListFragment : Fragment(), BearListContract.View, SwipeRefreshLayout.OnRefreshListener {
@Inject
lateinit var presenter: BearListContract.Presenter
private lateinit var bearAdapter: BearAdapter
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_bear_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bearAdapter = BearAdapter {
presenter.onShowBearDetail(it)
}
bear_recycler.layoutManager = LinearLayoutManager(view.context)
bear_recycler.adapter = bearAdapter
bear_recycler.addItemDecoration(
DividerItemDecoration(
view.context,
DividerItemDecoration.VERTICAL
)
)
swipe_refresher.setOnRefreshListener(this)
presenter.attachView(this)
}
override fun onDestroyView() {
super.onDestroyView()
presenter.detachView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.main, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.rube_goldberg -> {
presenter.onActivateRubeGoldbergMachine()
true
}
else -> {
super.onOptionsItemSelected(item)
}
}
}
override fun showBears(bears: Collection<Bear>) {
bear_recycler.visibility = View.VISIBLE
loading_view.visibility = View.GONE
bearAdapter.setBears(bears)
swipe_refresher.isRefreshing = false
}
override fun showLoading(text: String) {
bear_recycler.visibility = View.GONE
loading_view.visibility = View.VISIBLE
loading_text.text = text
}
override fun navigateToBearDetail(bear: Bear) {
(requireActivity() as BearListActivity).showBearDetail(bear)
}
override fun showError() {
swipe_refresher.isRefreshing = false
Snackbar.make(bear_recycler, "Uh oh... Something broke!", Snackbar.LENGTH_SHORT).show()
}
override fun showMessage(message: String) {
Snackbar.make(bear_recycler, message, Snackbar.LENGTH_SHORT).show()
}
override fun onRefresh() {
presenter.onRefreshBears()
}
}
| 0
|
Kotlin
|
0
| 0
|
b506d2417f192e02bf460fa66cdcbdc960230661
| 3,539
|
UnBearable
|
Apache License 2.0
|
FishBun/src/main/java/com/sangcomz/fishbun/ui/picker/model/PickerMenuViewData.kt
|
sangcomz
| 45,672,765
| false
| null |
package com.sangcomz.fishbun.ui.picker.model
import android.graphics.drawable.Drawable
data class PickerMenuViewData(
val drawableDoneButton: Drawable?,
val drawableAllDoneButton: Drawable?,
val strDoneMenu: String?,
val colorTextMenu: Int,
val strAllDoneMenu:String?,
val isUseAllDoneButton: Boolean
)
| 49
| null |
2
| 644
|
128187b62072720f5ec46e0824cb642fec488aac
| 329
|
FishBun
|
Apache License 2.0
|
presentation/src/main/java/org/lotka/xenon/presentation/screen/auth/login/LoginScreen.kt
|
armanqanih
| 860,856,530
| false
|
{"Kotlin": 281646}
|
package org.lotka.xenon.presentation.screen.auth.login
import android.content.Context
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.ButtonColors
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import org.lotka.xenon.domain.util.Constants.SpaceLarge
import org.lotka.xenon.domain.util.Constants.SpaceMedium
import org.lotka.xenon.domain.util.Constants.SpaceSmall
import org.lotka.xenon.domain.util.error.AuthError
import org.lotka.xenon.presentation.R
import org.lotka.xenon.presentation.compose.StandardTextField
import org.lotka.xenon.presentation.ui.navigation.ScreensNavigation
import org.lotka.xenon.presentation.util.UiEvent
@Composable
fun LoginScreen(
onNavigateTo: (String) -> Unit = {},
onNavigateUp: () -> Unit = {},
viewModel: LoginViewModel = hiltViewModel(),
) {
val passwordState = viewModel.passwordState.collectAsState().value
val emailState = viewModel.emailState.collectAsState().value
val state = viewModel.state.collectAsState().value
val scaffoldState = rememberScaffoldState()
val sharedPreferences = LocalContext.current.getSharedPreferences(
"your_app_preferences", Context.MODE_PRIVATE)
val isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false)
val scope = rememberCoroutineScope()
LaunchedEffect(key1 = true) {
if (viewModel.isUserLoggedIn()) {
onNavigateTo(ScreensNavigation.ExploreScreen.route)
} else {
viewModel.eventFlow.collect { event ->
when (event) {
is UiEvent.ShowSnakeBar -> {
scaffoldState.snackbarHostState.showSnackbar(message = event.message)
}
is UiEvent.Navigate -> {
viewModel.saveLoginStatus(true)
onNavigateTo(ScreensNavigation.ExploreScreen.route)
}
UiEvent.onNavigateUp -> onNavigateUp()
}
}
}
}
androidx.compose.material.Scaffold(
modifier = Modifier.fillMaxSize()
,scaffoldState = scaffoldState
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(it)
.padding(
start = SpaceLarge.dp,
end = SpaceLarge.dp,
top = SpaceLarge.dp,
bottom = 50.dp
)
) {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.align(Alignment.Center)
) {
Text(
text = stringResource(R.string.login),
style = MaterialTheme.typography.body1,
color = Color.White
)
Spacer(modifier = Modifier.height(SpaceMedium.dp))
StandardTextField(
modifier = Modifier.clip(
shape = RoundedCornerShape(SpaceSmall.dp)),
value = emailState.text,
hint = stringResource(R.string.enter_user_email),
onValueChange = {
viewModel.onEvent(LoginEvent.EnterEmail(it))
},
singleLine = true,
keyboardType = KeyboardType.Email,
error = when(emailState.error){
is AuthError.FieldEmpty -> {
stringResource(R.string.this_field_cant_be_empty)
}
null -> ""
else -> {""}
}
)
Spacer(modifier = Modifier.height(SpaceMedium.dp))
StandardTextField(
modifier = Modifier.clip(
shape = RoundedCornerShape(SpaceSmall.dp)),
value = passwordState.text,
hint = stringResource(R.string.Password),
onValueChange = {
viewModel.onEvent(LoginEvent.EnterPassword(it))
},
singleLine = true,
keyboardType = KeyboardType.Password,
error = when(passwordState.error){
is AuthError.FieldEmpty -> {
stringResource(R.string.this_field_cant_be_empty)
}
else -> ""
},
isPasswordVisible = passwordState.isPasswordVisible,
onPasswordToggleClick = {
viewModel.onEvent(LoginEvent.IsPasswordVisibility)
}
)
Spacer(modifier = Modifier.height(SpaceMedium.dp))
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.primary
),
onClick = {
viewModel.onEvent(LoginEvent.Login)
},
modifier = Modifier
.height(50.dp)
.width(120.dp)
.align(Alignment.End)
.clip(shape = RoundedCornerShape(8.dp))
.background(MaterialTheme.colors.primary),
enabled = emailState.text.isNotEmpty() &&
passwordState.text.isNotEmpty()
) {
val textColor = if (emailState.text.isNotEmpty() && passwordState.text.isNotEmpty()) {
Color.White
} else {
Color.White
}
Text(
text = stringResource(R.string.Login),
style = MaterialTheme.typography.body1,
fontWeight = FontWeight.Bold,
color = textColor
)
}
if (state.isLoading) {
CircularProgressIndicator(modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(SpaceMedium.dp)
)
}
Spacer(modifier = Modifier.height(SpaceLarge.dp))
}
val annotatedText = buildAnnotatedString {
withStyle(
style = SpanStyle(
color = Color.Black,
)
) {
append("Don't you have an account? ")
}
pushStringAnnotation(tag = "REGISTER", annotation = "register")
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
color = MaterialTheme.colors.primary, // optional, for underlining the text
)
) {
append("Register")
}
pop()
}
ClickableText(
text = annotatedText,
onClick = { offset ->
annotatedText.getStringAnnotations(tag = "REGISTER", start = offset, end = offset)
.firstOrNull()?.let {
onNavigateTo(ScreensNavigation.RegisterScreen.route)
}
},
style = MaterialTheme.typography.body1,
modifier = Modifier.align(Alignment.BottomCenter)
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
894b4ba5b113d951ee4975c66cbbe3115f3239b2
| 9,324
|
ModernNews
|
Apache License 2.0
|
bin/main/com/jahnelgroup/controller/GlobalModelAttributes.kt
|
JahnelGroup
| 168,455,772
| false
|
{"HTML": 130381, "Kotlin": 99201, "JavaScript": 23425, "TSQL": 17712, "CSS": 5254, "Dockerfile": 544}
|
package com.jahnelgroup.controller
import com.jahnelgroup.domain.context.UserContextService
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ModelAttribute
@ControllerAdvice
class ModelControllerAdvice(var userContextService: UserContextService){
@ModelAttribute("userContextService")
fun userContextService() = userContextService
@ModelAttribute("currentUser")
fun currentUser() = userContextService.currentUser()
}
| 0
|
HTML
|
2
| 1
|
d97822fd4a348d83a984c031a55b2b0b523f2f04
| 499
|
thymeleaf-starter
|
MIT License
|
samples/kotlin-sample/src/main/java/com/apollographql/apollo/kotlinsample/data/ApolloWatcherService.kt
|
zhuhaow
| 256,031,598
| true
|
{"Java": 1935643, "Kotlin": 1244793, "ANTLR": 3780, "Shell": 868}
|
package com.apollographql.apollo.kotlinsample.data
import android.util.Log
import com.apollographql.apollo.ApolloCall
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.exception.ApolloException
import com.apollographql.apollo.fetcher.ApolloResponseFetchers
import com.apollographql.apollo.kotlinsample.GithubRepositoriesQuery
import com.apollographql.apollo.kotlinsample.GithubRepositoryCommitsQuery
import com.apollographql.apollo.kotlinsample.GithubRepositoryDetailQuery
import com.apollographql.apollo.kotlinsample.type.OrderDirection
import com.apollographql.apollo.kotlinsample.type.PullRequestState
import com.apollographql.apollo.kotlinsample.type.RepositoryOrderField
/**
* An implementation of a [GitHubDataSource] that shows how to fetch data using callbacks.
*/
class ApolloWatcherService(apolloClient: ApolloClient) : GitHubDataSource(apolloClient) {
override fun fetchRepositories() {
val repositoriesQuery = GithubRepositoriesQuery.builder()
.repositoriesCount(50)
.orderBy(RepositoryOrderField.UPDATED_AT)
.orderDirection(OrderDirection.DESC)
.build()
val callback = createCallback<GithubRepositoriesQuery.Data> {
repositoriesSubject.onNext(mapRepositoriesResponseToRepositories(it))
}
apolloClient
.query(repositoriesQuery)
.responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK)
.watcher()
.enqueueAndWatch(callback)
}
override fun fetchRepositoryDetail(repositoryName: String) {
val repositoryDetailQuery = GithubRepositoryDetailQuery.builder()
.name(repositoryName)
.pullRequestStates(listOf(PullRequestState.OPEN))
.build()
val callback = createCallback<GithubRepositoryDetailQuery.Data> {
repositoryDetailSubject.onNext(it)
}
apolloClient
.query(repositoryDetailQuery)
.responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK)
.watcher()
.enqueueAndWatch(callback)
}
override fun fetchCommits(repositoryName: String) {
val commitsQuery = GithubRepositoryCommitsQuery.builder()
.name(repositoryName)
.build()
val callback = createCallback<GithubRepositoryCommitsQuery.Data> { response ->
val headCommit = response.data?.viewer()?.repository()?.ref()?.target() as? GithubRepositoryCommitsQuery.AsCommit
val commits = headCommit?.history()?.edges().orEmpty()
commitsSubject.onNext(commits)
}
apolloClient
.query(commitsQuery)
.responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK)
.watcher()
.enqueueAndWatch(callback)
}
private fun <T : Operation.Data> createCallback(onResponse: (response: Response<T>) -> Unit) =
object : ApolloCall.Callback<T>() {
override fun onResponse(response: Response<T>) = onResponse(response)
override fun onFailure(e: ApolloException) {
exceptionSubject.onNext(e)
}
override fun onStatusEvent(event: ApolloCall.StatusEvent) {
Log.d("ApolloWatcherService", "Apollo Status Event: $event")
}
}
override fun cancelFetching() {
//TODO: Determine how to cancel this when there's callbacks
}
}
| 5
| null |
0
| 0
|
2c1870bf0186064e50ad5f676aee05f53f12b85f
| 3,317
|
apollo-android
|
MIT License
|
app/src/main/java/com/nivs/all/viewmodeleg/MainViewModelmodel.kt
|
niva-cu
| 715,053,095
| false
|
{"Kotlin": 178887, "Java": 2596}
|
package com.nivs.all.viewmodeleg
import androidx.lifecycle.ViewModel
class MainViewModelmodel: ViewModel() {
var count : Int = 0
fun changeData(){
count++
}
}
| 0
|
Kotlin
|
0
| 0
|
7cef99bf38c66469ff21deca686c7ca9018e08fd
| 181
|
alltopics
|
Apache License 2.0
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Edit2.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Edit2: ImageVector
get() {
if (_edit2 != null) {
return _edit2!!
}
_edit2 = Builder(name = "Edit2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.54f, 19.5201f)
curveTo(4.93f, 19.5201f, 4.36f, 19.31f, 3.95f, 18.92f)
curveTo(3.43f, 18.43f, 3.18f, 17.69f, 3.27f, 16.89f)
lineTo(3.64f, 13.65f)
curveTo(3.71f, 13.04f, 4.08f, 12.23f, 4.51f, 11.79f)
lineTo(12.72f, 3.1f)
curveTo(14.77f, 0.93f, 16.91f, 0.87f, 19.08f, 2.92f)
curveTo(21.25f, 4.97f, 21.31f, 7.1101f, 19.26f, 9.2801f)
lineTo(11.05f, 17.97f)
curveTo(10.63f, 18.42f, 9.85f, 18.84f, 9.24f, 18.9401f)
lineTo(6.02f, 19.49f)
curveTo(5.85f, 19.5f, 5.7f, 19.5201f, 5.54f, 19.5201f)
close()
moveTo(15.93f, 2.91f)
curveTo(15.16f, 2.91f, 14.49f, 3.39f, 13.81f, 4.1101f)
lineTo(5.6f, 12.8101f)
curveTo(5.4f, 13.0201f, 5.17f, 13.5201f, 5.13f, 13.8101f)
lineTo(4.76f, 17.05f)
curveTo(4.72f, 17.38f, 4.8f, 17.65f, 4.98f, 17.82f)
curveTo(5.16f, 17.99f, 5.43f, 18.05f, 5.76f, 18.0f)
lineTo(8.98f, 17.4501f)
curveTo(9.27f, 17.4001f, 9.75f, 17.14f, 9.95f, 16.93f)
lineTo(18.16f, 8.2401f)
curveTo(19.4f, 6.9201f, 19.85f, 5.7f, 18.04f, 4.0001f)
curveTo(17.24f, 3.2301f, 16.55f, 2.91f, 15.93f, 2.91f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.3404f, 10.9498f)
curveTo(17.3204f, 10.9498f, 17.2904f, 10.9498f, 17.2704f, 10.9498f)
curveTo(14.1504f, 10.6398f, 11.6404f, 8.2698f, 11.1604f, 5.1698f)
curveTo(11.1004f, 4.7599f, 11.3804f, 4.3798f, 11.7904f, 4.3099f)
curveTo(12.2004f, 4.2498f, 12.5804f, 4.5299f, 12.6504f, 4.9398f)
curveTo(13.0304f, 7.3598f, 14.9904f, 9.2198f, 17.4304f, 9.4599f)
curveTo(17.8404f, 9.4999f, 18.1404f, 9.8699f, 18.1004f, 10.2798f)
curveTo(18.0504f, 10.6598f, 17.7204f, 10.9498f, 17.3404f, 10.9498f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 22.75f)
horizontalLineTo(3.0f)
curveTo(2.59f, 22.75f, 2.25f, 22.41f, 2.25f, 22.0f)
curveTo(2.25f, 21.59f, 2.59f, 21.25f, 3.0f, 21.25f)
horizontalLineTo(21.0f)
curveTo(21.41f, 21.25f, 21.75f, 21.59f, 21.75f, 22.0f)
curveTo(21.75f, 22.41f, 21.41f, 22.75f, 21.0f, 22.75f)
close()
}
}
.build()
return _edit2!!
}
private var _edit2: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 4,333
|
VuesaxIcons
|
MIT License
|
app/src/main/java/com/kcteam/features/stockAddCurrentStock/interface/ShowStockOnClick.kt
|
DebashisINT
| 558,234,039
| false
|
{"Kotlin": 11332958, "Java": 966929}
|
package com.kcteam.features.stockAddCurrentStock.`interface`
interface ShowStockOnClick {
fun stockListOnClick(stockID:String)
}
| 0
|
Kotlin
|
1
| 1
|
a9aabcf48662c76db18bcece75cae9ac961da1ed
| 133
|
KidCity
|
Apache License 2.0
|
data/src/main/java/cat/helm/basearchitecture/data/entity/TvShowDataEntity.kt
|
jstr14
| 158,037,824
| false
| null |
package cat.helm.basearchitecture.data.entity
import cat.helm.basearchitecture.data.repository.datasource.Identifiable
/**
* Created by Borja on 1/6/17.
*/
data class TvShowDataEntity(val popularity: Float, val id: Int, val name: String, val backdrop_path: String, val overview: String) : Identifiable<Int> {
override fun getKey(): Int = id
}
| 0
|
Kotlin
|
0
| 0
|
63c7035dfb077c6585a274be7469be9685ea1cc2
| 351
|
SuperDragonBallHeroes
|
Apache License 2.0
|
app/src/main/java/com/zj/play/profile/rank/user/UserRankActivity.kt
|
zhangjing123
| 319,567,001
| true
|
{"Kotlin": 298820}
|
package com.zj.play.profile.rank.user
import android.content.Context
import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import com.zj.play.R
import com.zj.play.base.BaseListActivity
import kotlinx.android.synthetic.main.activity_base_list.*
class UserRankActivity : BaseListActivity() {
private val viewModel by lazy { ViewModelProvider(this).get(UserRankViewModel::class.java) }
private lateinit var rankAdapter: UserRankAdapter
override fun initData() {
super.initData()
setDataStatus(viewModel.dataLiveData) {
if (page == 1 && viewModel.dataList.size > 0) {
viewModel.dataList.clear()
}
viewModel.dataList.addAll(it.datas)
rankAdapter.notifyDataSetChanged()
}
}
override fun initView() {
super.initView()
rankAdapter = UserRankAdapter(this, R.layout.adapter_rank, viewModel.dataList)
baseListToTop.setAdapter(rankAdapter)
baseListTitleBar.setTitle(getString(R.string.mine_points))
}
override fun isStaggeredGrid(): Boolean {
return false
}
override fun getDataList() {
if (viewModel.dataList.size <= 0) startLoading()
viewModel.getDataList(page)
}
companion object {
fun actionStart(context: Context) {
val intent = Intent(context, UserRankActivity::class.java)
context.startActivity(intent)
}
}
}
| 0
| null |
0
| 0
|
fe7a4cf901e69648875b0e76586bfaee3c6ab561
| 1,466
|
PlayAndroid
|
MIT License
|
app/src/main/java/ss/team16/nthulostfound/domain/usecase/DeleteItemUseCase.kt
|
NTHULostFound
| 503,250,151
| false
| null |
package ss.team16.nthulostfound.domain.usecase
import ss.team16.nthulostfound.domain.model.ItemData
import ss.team16.nthulostfound.domain.repository.ItemRepository
class DeleteItemUseCase(
private val itemRepository: ItemRepository
) {
suspend operator fun invoke(item: ItemData): Result<ItemData> {
return itemRepository.deleteItem(item)
}
}
| 0
|
Kotlin
|
0
| 2
|
5b4b880abb320e5ebd2b03c3cc1da4a94012abcc
| 364
|
NTHULostFound
|
MIT License
|
src/main/kotlin/com/networkedassets/gherkin/runner/report/data/LogEntry.kt
|
NetworkedAssets
| 120,890,153
| false
| null |
package com.networkedassets.gherkin.runner.report.data
data class LogEntry(val message: String, val indent: Int)
| 3
| null |
4
| 7
|
b57d6f90acd5183511aa988040d4f33ddcba5bdb
| 113
|
gherkin-runner
|
Apache License 2.0
|
src/commonMain/kotlin/dev/zxilly/notify/sdk/entity/MessageOption.kt
|
ZNotify
| 500,846,735
| false
|
{"Kotlin": 17115, "JavaScript": 425}
|
package dev.zxilly.notify.sdk.entity
data class MessageOption(
val content: String,
val title: String = "Notification",
val long: String = "",
val priority: Priority = Priority.Normal
)
| 3
|
Kotlin
|
1
| 0
|
d5284403ab2daddd38f83be267760b502fb3d17e
| 202
|
kt-sdk
|
Apache License 2.0
|
src/main/kotlin/xyz/hetula/viola/ViolaMusicPlayer.kt
|
hetula
| 105,060,567
| false
| null |
/*
* MIT License
*
* Copyright (c) 2017 <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 xyz.hetula.viola
import xyz.hetula.viola.backend.Player
import xyz.hetula.viola.model.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* @author <NAME>
* @version 27.9.2017.
*/
class ViolaMusicPlayer(private val playerImpl: Player,
private val executor: ExecutorService = Executors.newSingleThreadExecutor()) {
private val syncLock = Object()
private val playedSongs = PlayedSongs()
private var playbackStartedList = ArrayList<Song>()
private var playback: Playback = NoopPlayback()
var playbackMode: PlaybackMode = PlaybackMode.NORMAL
private set
var nowPlaying: Song? = null
private set
fun initialize() = sync {
playerImpl.create()
}
fun destroy() = sync {
executor.shutdown()
try {
executor.awaitTermination(5, TimeUnit.SECONDS)
} catch (ex: InterruptedException) {
ex.printStackTrace()
}
executor.shutdownNow()
playerImpl.destroy()
}
fun isPaused() = sync {
playerImpl.isPaused()
}
fun isPlaying() = sync {
nowPlaying != null && playerImpl.isPlaying()
}
fun queryDuration() = sync {
playerImpl.queryDuration()
}
fun queryPosition() = sync {
playerImpl.queryPosition()
}
fun getDevice() = playerImpl.getDevice()
fun getDevices() = playerImpl.getDevices()
fun getVolume() = sync {
playerImpl.getVolume()
}
fun setPlayback(playbackMode: PlaybackMode) = runInBackground {
this.playbackMode = playbackMode
val song = nowPlaying ?: return@runInBackground
playback = playbackMode(playbackStartedList, song)
}
fun play(song: Song, playContext: List<Song> = ArrayList()) = runInBackground {
playbackStartedList.clear()
playbackStartedList.addAll(playContext)
playback = playbackMode(playContext, song)
playInternal(song)
}
fun next() = runInBackground {
if (playedSongs.moveBack()) {
playInternal(playedSongs(), false)
} else if (playback.moveToNext()) {
playInternal(playback())
}
}
fun previous() = runInBackground {
if (playedSongs.isNotEmpty() && playedSongs.moveToPrevious()) {
playInternal(playedSongs(), false)
}
}
fun pause() = runInBackground {
playerImpl.pause()
}
fun resume() = runInBackground {
playerImpl.resume()
}
fun seekTo(position: Long) = runInBackground {
playerImpl.seekTo(position)
}
fun setVolume(volume: Int) = runInBackground {
playerImpl.setVolume(volume)
}
fun setMuted(muted: Boolean) = runInBackground {
playerImpl.setMuted(muted)
}
fun setDevice(deviceIndex: Int) = runInBackground {
playerImpl.setDevice(deviceIndex)
}
private fun playInternal(song: Song, addToPlayed: Boolean = true) = sync {
this.nowPlaying = song
if (addToPlayed) {
playedSongs(song)
}
playerImpl.play(song.uri, song.localFile)
}
private inline fun runInBackground(crossinline execute: () -> Unit) = executor.execute { execute() }
private inline fun <R> sync(runInSync: () -> R) = synchronized(syncLock) { runInSync() }
}
| 0
|
Kotlin
|
0
| 0
|
eceaef948c49cd47afbc91967f1bb458fad6a8e6
| 4,533
|
viola-core
|
MIT License
|
buildSrc/src/main/kotlin/dependencies.kt
|
ohyooo
| 449,932,064
| false
| null |
object Ext {
const val applicationId = "com.ohyooo.qrscan"
const val compileSdk = 32
const val buildToolsVersion = "32.0.0"
const val minSdk = 21
const val targetSdk = 32
const val versionCode = 5
const val versionName = "2.3"
}
object Libs {
private const val kotlin_version = "1.6.10"
object Plugin {
const val AGP = "com.android.tools.build:gradle:7.3.0-alpha02"
const val KGP = "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
object Kotlin {
const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
const val coroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0"
}
object Google {
const val material = "com.google.android.material:material:1.6.0-alpha02"
const val barcode = "com.google.mlkit:barcode-scanning:17.0.2"
private const val accompanistVersion = "0.24.1-alpha"
const val pager = "com.google.accompanist:accompanist-pager:$accompanistVersion"
const val indicators = "com.google.accompanist:accompanist-pager-indicators:$accompanistVersion"
}
object AndroidX {
const val coreKtx = "androidx.core:core-ktx:1.8.0-alpha04"
const val datastore = "androidx.datastore:datastore:1.0.0"
private const val activityVersion = "1.5.0-alpha02"
const val activity_compose = "androidx.activity:activity-compose:$activityVersion"
const val fragment = "androidx.fragment:fragment-ktx:1.5.0-alpha02"
const val lifecycle = "androidx.lifecycle:lifecycle-viewmodel-compose:2.5.0-alpha02"
}
object Navigation {
const val compose = "androidx.navigation:navigation-compose:2.5.0-alpha02"
}
object Compose {
const val composeVersion = "1.2.0-alpha03"
const val animation = "androidx.compose.animation:animation:$composeVersion"
const val compiler = "androidx.compose.compiler:compiler:$composeVersion"
const val foundation = "androidx.compose.foundation:foundation:$composeVersion"
const val layout = "androidx.compose.foundation:foundation-layout:$composeVersion"
const val livedata = "androidx.compose.runtime:runtime-livedata:$composeVersion"
const val material = "androidx.compose.material:material:$composeVersion"
const val materialIconsExtended = "androidx.compose.material:material-icons-extended:$composeVersion"
const val runtime = "androidx.compose.runtime:runtime:$composeVersion"
const val tooling = "androidx.compose.ui:ui-tooling:$composeVersion"
const val ui = "androidx.compose.ui:ui:$composeVersion"
}
object Camera {
private const val camerax_version = "1.1.0-alpha11"
const val camera2 = "androidx.camera:camera-camera2:${camerax_version}"
const val lifecycle = "androidx.camera:camera-lifecycle:${camerax_version}"
const val view = "androidx.camera:camera-view:1.1.0-beta01"
}
val plugins = listOf(Plugin.AGP, Plugin.KGP)
val composes = listOf(Compose.animation, Compose.compiler, Compose.foundation, Compose.layout, Compose.livedata, Compose.material, Compose.materialIconsExtended, Compose.runtime, Compose.tooling, Compose.ui)
val implementations = listOf(
AndroidX.activity_compose,
AndroidX.coreKtx,
AndroidX.datastore,
AndroidX.fragment,
AndroidX.lifecycle,
Camera.camera2,
Camera.lifecycle,
Camera.view,
Google.barcode,
Google.material,
Google.pager,
Google.indicators,
Kotlin.coroutines,
Kotlin.stdlib,
Navigation.compose,
)
val deps: List<String> = mutableListOf<String>().apply {
addAll(plugins)
addAll(composes)
add(Navigation.compose)
addAll(implementations)
}
}
| 0
|
Kotlin
|
0
| 0
|
883a51a16db6594efbc0ef6fdfe4a29ace4f5388
| 3,859
|
QRScan
|
Apache License 2.0
|
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/refactorings/rename/KotlinRenameParticipant.kt
|
bvfalcon
| 263,980,575
| false
| null |
/*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.refactorings.rename
import org.eclipse.ltk.core.refactoring.participants.RenameParticipant
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext
import org.eclipse.ltk.core.refactoring.RefactoringStatus
import org.eclipse.ltk.core.refactoring.Change
import kotlin.properties.Delegates
import org.eclipse.jdt.core.IType
import java.util.ArrayList
import org.eclipse.ltk.core.refactoring.CompositeChange
import org.jetbrains.kotlin.ui.search.KotlinQueryParticipant
import org.eclipse.search.ui.text.Match
import org.eclipse.jdt.ui.search.ElementQuerySpecification
import org.eclipse.jdt.core.search.IJavaSearchConstants
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory
import org.jetbrains.kotlin.ui.search.KotlinElementMatch
import org.jetbrains.kotlin.core.builder.KotlinPsiManager
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.eclipse.ltk.core.refactoring.TextFileChange
import org.jetbrains.kotlin.eclipse.ui.utils.getTextDocumentOffset
import org.eclipse.text.edits.ReplaceEdit
import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor
import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments
import org.eclipse.ltk.core.refactoring.participants.RenameArguments
import org.eclipse.text.edits.TextEdit
import org.eclipse.core.resources.IFile
import org.eclipse.jdt.internal.corext.refactoring.changes.TextChangeCompatibility
import org.eclipse.jdt.core.IJavaElement
import org.eclipse.jdt.ui.search.QuerySpecification
open class KotlinRenameParticipant : RenameParticipant() {
lateinit var element: Any
lateinit var newName: String
override fun initialize(element: Any): Boolean {
this.element = element
return true
}
override fun initialize(processor: RefactoringProcessor?, element: Any?, arguments: RefactoringArguments): Boolean {
if (arguments is RenameArguments) {
newName = arguments.getNewName()
}
return super.initialize(processor, element, arguments)
}
override fun checkConditions(pm: IProgressMonitor?, context: CheckConditionsContext?): RefactoringStatus? {
return RefactoringStatus() // TODO: add corresponding refactoring status
}
override fun getName() = "Kotlin Type Rename Participant"
override fun createChange(pm: IProgressMonitor?): Change {
val kotlinQueryParticipant = KotlinQueryParticipant()
val matches = arrayListOf<Match>()
val querySpecification = createSearchQuery()
kotlinQueryParticipant.search({ matches.add(it) }, querySpecification, pm)
val groupedEdits = matches
.map { createTextChange(it) }
.filterNotNull()
.groupBy { it.file }
val changes = arrayListOf<Change>()
for ((file, edits) in groupedEdits) {
val fileChange = TextFileChange("Kotlin change", file)
edits.forEach { TextChangeCompatibility.addTextEdit(fileChange, "Kotlin change", it.edit) }
changes.add(fileChange)
}
return CompositeChange("Changes in Kotlin", changes.toTypedArray())
}
protected open fun createSearchQuery(): QuerySpecification {
val factory = JavaSearchScopeFactory.getInstance()
return ElementQuerySpecification(
obtainOriginElement(element as IJavaElement),
IJavaSearchConstants.ALL_OCCURRENCES,
factory.createWorkspaceScope(false),
factory.getWorkspaceScopeDescription(false))
}
private fun createTextChange(match: Match): FileEdit? {
if (match !is KotlinElementMatch) return null
val jetElement = match.jetElement
val eclipseFile = KotlinPsiManager.getEclipseFile(jetElement.getContainingKtFile())
if (eclipseFile == null) return null
val document = EditorUtil.getDocument(eclipseFile) // TODO: make workaround here later
val textLength = getLengthOfIdentifier(jetElement)
return if (textLength != null) {
FileEdit(
eclipseFile,
ReplaceEdit(jetElement.getTextDocumentOffset(document), textLength, newName))
} else {
null
}
}
private fun obtainOriginElement(javaElement: IJavaElement): IJavaElement {
return when (javaElement) {
is KotlinLightType -> javaElement.originElement
is KotlinLightFunction -> javaElement.originMethod
else -> javaElement
}
}
}
data class FileEdit(val file: IFile, val edit: TextEdit)
| 6
| null |
7
| 43
|
e6360b023e1e377325f1d10bda5755e3fc3af591
| 5,544
|
kotlin-eclipse
|
Apache License 2.0
|
fns-hl7-pipeline/fn-structure-validator/src/test/kotlin/gov/cdc/dex/ValidatorFunction.kt
|
CDCgov
| 510,836,864
| false
| null |
package gov.cdc.dex.validation.structure
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.microsoft.azure.functions.*
import com.microsoft.azure.functions.annotation.*
import gov.cdc.dex.azure.EventHubMetadata
import gov.cdc.dex.azure.EventHubSender
import gov.cdc.dex.metadata.Problem
import gov.cdc.dex.metadata.SummaryInfo
import gov.cdc.dex.model.StructureValidatorProcessMetadata
import gov.cdc.dex.util.DateHelper.toIsoString
import gov.cdc.dex.util.JsonHelper
import gov.cdc.dex.util.JsonHelper.addArrayElement
import gov.cdc.dex.util.JsonHelper.toJsonElement
import gov.cdc.hl7.HL7StaticParser
import gov.cdc.nist.validator.NistReport
import gov.cdc.nist.validator.ProfileManager
import gov.cdc.nist.validator.ResourceFileFetcher
import org.slf4j.LoggerFactory
import java.util.*
private fun buildHttpResponse(message:String, status: HttpStatus, request: HttpRequestMessage<Optional<String>>) : HttpResponseMessage {
return request
.createResponseBuilder(status)
.header("Content-Type", "application/json")
.body(message)
.build()
}
| 119
|
Kotlin
|
14
| 9
|
f164d66658c54e145c7fa932c3151857fcf2b7d0
| 1,174
|
data-exchange-hl7
|
Apache License 2.0
|
core/src/commonMain/kotlin/maryk/core/processors/datastore/writeMapToStorage.kt
|
marykdb
| 290,454,412
| false
|
{"Kotlin": 3292459, "JavaScript": 1004}
|
package maryk.core.processors.datastore
import maryk.core.extensions.bytes.calculateVarByteLength
import maryk.core.extensions.bytes.writeVarBytes
import maryk.core.processors.datastore.StorageTypeEnum.MapSize
import maryk.core.properties.definitions.IsMapDefinition
import maryk.core.properties.definitions.IsPropertyDefinition
import maryk.core.properties.definitions.IsSubDefinition
/** Write a complete [map] defined by [definition] with [qualifierWriter] of [qualifierLength] to storage with [valueWriter]. */
@Suppress("UNCHECKED_CAST")
fun <T : IsPropertyDefinition<*>, K : Any, V : Any> writeMapToStorage(
qualifierLength: Int,
qualifierWriter: QualifierWriter?,
valueWriter: ValueWriter<T>,
definition: T,
map: Map<K, V>
) {
// Process Map Count
valueWriter(
MapSize as StorageTypeEnum<T>,
writeQualifier(qualifierLength, qualifierWriter),
definition,
map.size
)
// Process Map Values
val mapDefinition = (definition as IsMapDefinition<in Any, *, *>)
for ((key, mapValue) in map) {
val keyByteSize = mapDefinition.keyDefinition.calculateStorageByteLength(key)
val keyByteCountSize = keyByteSize.calculateVarByteLength()
val mapValueQualifierWriter: QualifierWriter = { writer ->
qualifierWriter?.invoke(writer)
keyByteSize.writeVarBytes(writer)
mapDefinition.keyDefinition.writeStorageBytes(key, writer)
}
val mapValueQualifierLength = qualifierLength + keyByteSize + keyByteCountSize
writeValue(
null, mapValueQualifierLength, mapValueQualifierWriter,
mapDefinition.valueDefinition,
mapValue,
valueWriter as ValueWriter<IsSubDefinition<*, *>>
)
}
}
| 1
|
Kotlin
|
1
| 8
|
a1e2e988c61067d3fecc952e417e80b4a775ad9c
| 1,784
|
maryk
|
Apache License 2.0
|
Compose/BasicswithCompose/PracticeComposeBasics/WaterMe/src/main/java/com/example/waterme/data/AppContainer.kt
|
pherasymchuk
| 723,622,473
| false
| null |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.waterme.data
import android.content.Context
interface AppContainer {
val waterRepository : WaterRepository
}
class DefaultAppContainer(context: Context) : AppContainer {
override val waterRepository = WorkManagerWaterRepository(context)
}
| 0
| null |
0
| 1
|
ce3c4db10bbd40adf4bc2aa5d455608a69f02727
| 917
|
GoogleCodelabsApps
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/animations/CompositeOperation.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6149909}
|
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.animations
// language=JavaScript
@JsName("""(/*union*/{accumulate: 'accumulate', add: 'add', replace: 'replace'}/*union*/)""")
sealed external interface CompositeOperation {
companion object {
val accumulate: CompositeOperation
val add: CompositeOperation
val replace: CompositeOperation
}
}
| 0
|
Kotlin
|
6
| 26
|
3fcfd2c61da8774151cf121596e656cc123b37db
| 479
|
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/jikgong/history_bottom_sheet_dialogFragment.kt
|
KT-Beak-Ho
| 738,021,615
| false
|
{"Kotlin": 10475}
|
package com.example.jikgong
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class history_bottom_sheet_dialogFragment : BottomSheetDialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_history_bottom_sheet_dialog, container, false)
}
}
| 0
|
Kotlin
|
3
| 0
|
2cb1f9051eba23ebfe1b3aea49c2cdaa76dcefe0
| 764
|
JikGong_co.
|
MIT License
|
src/main/kotlin/io/github/isning/gradle/plugins/cmake/targets/HostTarget.kt
|
ISNing
| 743,468,322
| false
|
{"Kotlin": 243373}
|
/*
* Copyright 2024 ISNing
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.isning.gradle.plugins.cmake.targets
import io.github.isning.gradle.plugins.cmake.CMakeConfiguration
import io.github.isning.gradle.plugins.cmake.CMakeTargetImpl
import io.github.isning.gradle.plugins.cmake.params.ModifiableCMakeBuildParams
import io.github.isning.gradle.plugins.cmake.params.ModifiableCMakeBuildParamsImpl
import io.github.isning.gradle.plugins.cmake.params.entries.platform.ModifiableHostEntries
import io.github.isning.gradle.plugins.cmake.params.platform.ModifiableHostParams
import io.github.isning.gradle.plugins.cmake.params.platform.ModifiableHostParamsImpl
import org.gradle.api.Project
class HostTarget(
project: Project,
name: String,
inheritedParents: List<CMakeConfiguration>,
inheritedNames: List<String>
) :
CMakeTargetImpl<ModifiableHostParams<ModifiableHostEntries>, ModifiableCMakeBuildParams>(
project,
name,
inheritedParents,
inheritedNames,
{
ModifiableHostParamsImpl()
}, {
ModifiableCMakeBuildParamsImpl()
})
| 0
|
Kotlin
|
0
| 1
|
f78bd444798d3f33fb2a6259c1e89be298881835
| 1,643
|
CMakePlugin
|
Apache License 1.1
|
UnicornFilePicker/src/main/java/abhishekti7/unicorn/filepicker/FilePicker.kt
|
ditacristianionut
| 330,927,875
| true
|
{"Java": 23509, "Kotlin": 15648}
|
package abhishekti7.unicorn.filepicker
import abhishekti7.unicorn.filepicker.models.Config
import abhishekti7.unicorn.filepicker.ui.FilePickerActivity
import android.app.Activity
import android.content.Intent
import androidx.fragment.app.Fragment
import java.lang.ref.WeakReference
class FilePicker private constructor() {
private lateinit var _activity: WeakReference<Activity>
private lateinit var _context: WeakReference<Fragment>
private constructor(activity: Activity): this() {
_activity = WeakReference(activity)
_context = WeakReference(null)
}
private constructor(fragment: Fragment): this() {
_activity = WeakReference(null)
_context = WeakReference(fragment)
}
private constructor(activity: Activity, fragment: Fragment): this() {
_activity = WeakReference(activity)
_context = WeakReference(fragment)
}
/**
* Start FilePicker activity and wait for result
* @param requestCode Integer identity for Activity or Fragment request
*/
fun forResult(requestCode: Int) {
Config.getInstance().reqCode = requestCode
val activity = _activity.get()
activity ?: return
val intent = Intent(activity, FilePickerActivity::class.java)
val fragment = _context.get()
if (fragment == null) {
activity.startActivityForResult(intent, requestCode)
} else {
fragment.startActivityForResult(intent, requestCode)
}
}
fun addConfigBuilder() = ConfigBuilder(this)
companion object {
/**
* Start UnicornFilePicker from an activity
*
* @param activity Activity instance
* @return UnicornFilePicker instance
*/
fun from(activity: Activity): FilePicker {
return FilePicker(activity)
}
/**
* Start UnicornFilePicker from a fragment
*
* @param fragment Fragment instance
* @return UnicornFilePicker instance
*/
fun from(fragment: Fragment): FilePicker {
return FilePicker(fragment)
}
}
}
| 0
|
Java
|
0
| 1
|
cbe9d5864486efdebb9dba76f455de9f823a0875
| 1,879
|
UnicornFilePicker
|
Apache License 2.0
|
app/src/jvmMain/kotlin/ru/ivk1800/diff/feature/repositoryview/domain/CommitsRepository.kt
|
ivk1800
| 577,871,072
| false
|
{"Kotlin": 377020}
|
package ru.ivk1800.diff.feature.repositoryview.domain
import ru.ivk1800.vcs.api.Vcs
import ru.ivk1800.vcs.api.VcsChangeType
import ru.ivk1800.vcs.api.VcsCommit
import ru.ivk1800.vcs.api.command.GetCommitCommand
import ru.ivk1800.vcs.api.command.GetCommitFilesCommand
import ru.ivk1800.vcs.api.command.GetCommitsCommand
import java.io.File
import java.time.Instant
class CommitsRepository(
private val repoDirectory: File,
private val vcs: Vcs,
) {
suspend fun getCommit(hash: String): Commit =
vcs.getCommitCommand(repoDirectory.toPath(), GetCommitCommand.Options(hash)).run().toCommit()
suspend fun getCommits(branchName: String, limit: Int, afterCommit: String?): List<Commit> =
vcs.getCommitsCommand(
repoDirectory.toPath(),
GetCommitsCommand.Options(
branchName = branchName,
limit = limit,
afterCommit = afterCommit,
),
)
.run()
.map { it.toCommit() }
suspend fun getCommitFiles(commitHash: String): List<CommitFile> =
vcs.getCommitFilesCommand(
repoDirectory.toPath(),
GetCommitFilesCommand.Options(commitHash),
)
.run()
.map { file ->
CommitFile(
name = file.name,
changeType = file.changeType.toChangeType(),
)
}
private fun VcsCommit.toCommit(): Commit =
Commit(
hash = CommitHash(value = hash, abbreviated = abbreviatedHash),
parents = parents,
authorName = authorName,
authorEmail = authorEmail,
authorDate = Instant.ofEpochSecond(authorDate.toLong()),
commiterName = commiterName,
commiterEmail = commiterEmail,
commiterDate = Instant.ofEpochSecond(commiterDate.toLong()),
message = message,
refNames = refNames.map(::RefName),
)
private fun VcsChangeType.toChangeType(): ChangeType =
when (this) {
VcsChangeType.Add -> ChangeType.Add
VcsChangeType.Modify -> ChangeType.Modify
VcsChangeType.Delete -> ChangeType.Delete
VcsChangeType.Rename -> ChangeType.Rename
VcsChangeType.Copy -> ChangeType.Copy
}
}
| 0
|
Kotlin
|
1
| 0
|
c4721d7f90b4eaed9634d7855847cdd42a58be3d
| 2,341
|
diff-compose
|
MIT License
|
app/src/main/java/com/example/take_my_money/presentation/interfaces/IOnClickFavorite.kt
|
ozielguimaraes
| 494,566,896
| false
|
{"Kotlin": 47595}
|
package com.example.take_my_money.presentation.interfaces
import com.example.take_my_money.data.dao.CoinEntity
interface IOnClickFavorite {
fun onClickFavorite(coinFavorite: CoinEntity)
}
| 2
|
Kotlin
|
2
| 1
|
a09df3749ac565e30721a3c80b8000c90afd701c
| 195
|
take-my-money
|
MIT License
|
user/src/main/java/org/the_chance/honeymart/ui/feature/authentication/signup/authentication/AuthScreen.kt
|
TheChance101
| 647,400,117
| false
|
{"Kotlin": 1218713}
|
package org.the_chance.honeymart.ui.feature.authentication.signup.authentication
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import org.the_chance.design_system.R
import org.the_chance.honeymart.ui.composables.EventHandler
import org.the_chance.honeymart.ui.feature.authentication.login.navigateToLogin
import org.the_chance.honeymart.ui.feature.authentication.signup.SignupUiEffect
import org.the_chance.honeymart.ui.feature.authentication.signup.SignupViewModel
import org.the_chance.honeymart.ui.feature.authentication.signup.navigateToSignupScreen
import org.the_chance.honymart.ui.composables.HoneyAuthFooter
import org.the_chance.honymart.ui.composables.HoneyFilledButton
import org.the_chance.honymart.ui.theme.Typography
import org.the_chance.honymart.ui.theme.black37
import org.the_chance.honymart.ui.theme.dimens
@Composable
fun AuthScreen(
viewModel: SignupViewModel = hiltViewModel(),
) {
EventHandler(
effects = viewModel.effect,
handleEffect = { effect, navController ->
when(effect) {
SignupUiEffect.ClickLoginEffect -> navController.navigateToLogin()
SignupUiEffect.ClickOnboardingSignupEffect -> navController.navigateToSignupScreen()
else -> {}
}
})
AuthContent(listener = viewModel)
}
@Composable
fun AuthContent(
listener: AuthenticationInteractionListener,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.background(MaterialTheme.colorScheme.background)
.verticalScroll(
enabled = true,
state = rememberScrollState()
)
) {
Image(
modifier = Modifier.fillMaxWidth(),
painter = painterResource(R.drawable.background_frame_auth),
contentDescription = "",
contentScale = ContentScale.Crop
)
Text(
text = stringResource(R.string.welcome_to_honey_mart),
modifier = Modifier.padding(top = MaterialTheme.dimens.space16),
style = Typography.displayMedium.copy(black37)
)
Text(
text = stringResource(R.string.get_ready_to_a_shopping_experience_like_no_other),
modifier = Modifier.padding(
horizontal = MaterialTheme.dimens.space16,
vertical = MaterialTheme.dimens.space16
),
style = Typography.bodySmall.copy(black37),
textAlign = TextAlign.Center
)
HoneyFilledButton(
label = stringResource(id = R.string.sign_up),
modifier = Modifier.padding(
horizontal = MaterialTheme.dimens.space16,
vertical = MaterialTheme.dimens.space40
),
onClick = listener::onClickOnBoardingSignUp
)
HoneyAuthFooter(
text = stringResource(R.string.already_have_account),
textButtonText = stringResource(R.string.log_in),
onTextButtonClicked = listener::onClickOnBoardingLogin,
modifier = Modifier.Companion.align(Alignment.CenterHorizontally)
)
}
}
@Preview(device = "id:3.2in HVGA slider (ADP1)")
@Composable
fun AuthScreenPreview() {
AuthContent(listener = object : AuthenticationInteractionListener {
override fun onClickOnBoardingSignUp() {
}
override fun onClickOnBoardingLogin() {
}
})
}
@Preview
@Composable
fun AuthScreenPreview2() {
AuthContent(listener = object : AuthenticationInteractionListener {
override fun onClickOnBoardingSignUp() {
}
override fun onClickOnBoardingLogin() {
}
})
}
| 3
|
Kotlin
|
7
| 21
|
50200e0ec0802cdadc282b09074a19c96df3220c
| 4,614
|
Honey-Mart-Android-Client
|
Apache License 2.0
|
src/main/kotlin/no/nav/brukerdialog/ytelse/pleiepengersyktbarn/søknad/api/domene/arbeid/Arbeidsforhold.kt
|
navikt
| 585,578,757
| false
|
{"Kotlin": 1442549, "Handlebars": 126943, "Dockerfile": 98}
|
package no.nav.brukerdialog.ytelse.pleiepengersyktbarn.søknad.api.domene.arbeid
import jakarta.validation.Valid
import no.nav.k9.søknad.felles.type.Periode
import no.nav.k9.søknad.ytelse.psb.v1.arbeidstid.ArbeidstidInfo
import no.nav.k9.søknad.ytelse.psb.v1.arbeidstid.ArbeidstidPeriodeInfo
import no.nav.brukerdialog.utils.DateUtils.ikkeErHelg
import java.time.LocalDate
import java.util.*
import kotlin.time.toJavaDuration
import kotlin.time.toKotlinDuration
data class Arbeidsforhold(
val normalarbeidstid: NormalArbeidstid,
@field:Valid val arbeidIPeriode: ArbeidIPeriode
) {
companion object {
internal fun k9ArbeidstidInfoMedNullTimer(fraOgMed: LocalDate, tilOgMed: LocalDate) = ArbeidstidInfo()
.medPerioder(
mapOf(
Periode(fraOgMed, tilOgMed) to ArbeidstidPeriodeInfo()
.medFaktiskArbeidTimerPerDag(NULL_TIMER)
.medJobberNormaltTimerPerDag(NULL_TIMER)
)
)
}
fun tilK9ArbeidstidInfo(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
return when (arbeidIPeriode.type) {
ArbeidIPeriodeType.ARBEIDER_VANLIG -> arbeiderVanlig(fraOgMed, tilOgMed)
ArbeidIPeriodeType.ARBEIDER_IKKE -> arbeiderIkke(fraOgMed, tilOgMed)
ArbeidIPeriodeType.ARBEIDER_REDUSERT -> arbeiderRedusert(fraOgMed, tilOgMed)
}
}
fun arbeiderRedusert(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
return when (arbeidIPeriode.redusertArbeid.type) {
RedusertArbeidstidType.PROSENT_AV_NORMALT -> arbeiderProsentAvNormalt(fraOgMed, tilOgMed)
RedusertArbeidstidType.TIMER_I_SNITT_PER_UKE -> arbeiderTimerISnittPerUke(fraOgMed, tilOgMed)
RedusertArbeidstidType.ULIKE_UKER_TIMER -> arbeidsukerUlikeTimer(fraOgMed, tilOgMed)
}
}
private fun arbeiderVanlig(fraOgMed: LocalDate, tilOgMed: LocalDate) =
arbeiderVanligMedNormaltimerSomSnitt(fraOgMed, tilOgMed)
private fun arbeiderVanligMedNormaltimerSomSnitt(
fraOgMed: LocalDate,
tilOgMed: LocalDate,
): ArbeidstidInfo {
val arbeidstidInfo = ArbeidstidInfo()
arbeidstidInfo.medPerioder(
mapOf(
Periode(fraOgMed, tilOgMed) to ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normalarbeidstid.timerPerDagFraSnitt())
.medFaktiskArbeidTimerPerDag(normalarbeidstid.timerPerDagFraSnitt())
)
)
return arbeidstidInfo
}
private fun arbeiderIkke(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
val arbeidstidInfo = ArbeidstidInfo()
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normalarbeidstid.timerPerDagFraSnitt())
.medFaktiskArbeidTimerPerDag(NULL_TIMER)
arbeidstidInfo.medPerioder(
mapOf(Periode(fraOgMed, tilOgMed) to arbeidstidPeriodeInfo)
)
return arbeidstidInfo
}
private fun arbeiderProsentAvNormalt(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
requireNotNull(arbeidIPeriode.redusertArbeid.prosentAvNormalt) { "For å regne ut arbeid fra prosentAvNormalt må den være satt." }
val normaltTimerPerdag = normalarbeidstid.timerPerDagFraSnitt()
val faktiskTimerPerDag = normaltTimerPerdag.toKotlinDuration()
.div(100)
.times(arbeidIPeriode.redusertArbeid.prosentAvNormalt)
.toJavaDuration()
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normaltTimerPerdag)
.medFaktiskArbeidTimerPerDag(faktiskTimerPerDag)
return ArbeidstidInfo().medPerioder(
mapOf(Periode(fraOgMed, tilOgMed) to arbeidstidPeriodeInfo)
)
}
private fun arbeiderTimerISnittPerUke(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
requireNotNull(arbeidIPeriode.redusertArbeid.timerPerUke) { "For å regne ut arbeid fra timerPerUke må den være satt." }
val normaltTimerPerDag = normalarbeidstid.timerPerDagFraSnitt()
val faktiskTimerPerDag = arbeidIPeriode.redusertArbeid.timerPerUke.dividedBy(DAGER_PER_UKE)
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normaltTimerPerDag)
.medFaktiskArbeidTimerPerDag(faktiskTimerPerDag)
return ArbeidstidInfo().medPerioder(
mapOf(Periode(fraOgMed, tilOgMed) to arbeidstidPeriodeInfo)
)
}
internal fun arbeidsukerUlikeTimer(
fraOgMed: LocalDate,
tilOgMed: LocalDate,
): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
requireNotNull(arbeidIPeriode.redusertArbeid.arbeidsuker) { "For å regne ut arbeid fra arbeidsuker må den være satt." }
val arbeidstidInfo = ArbeidstidInfo()
arbeidIPeriode.redusertArbeid.arbeidsuker.map { arbeidsuke: ArbeidsUke ->
requireNotNull(normalarbeidstid.timerPerUkeISnitt) { "normalarbeidstid.timerPerUkeISnitt må være satt." }
val periodeUtenHelg: SortedSet<LocalDate> = arbeidsuke.periodeUtenHelg()
val k9Periode = Periode(periodeUtenHelg.first(), periodeUtenHelg.last())
val normaltArbeidstimerPerDag = normalarbeidstid.timerPerUkeISnitt.dividedBy(DAGER_PER_UKE)
val ukedager = periodeUtenHelg.size.toLong()
val faktiskArbeidstimerPerDag = arbeidsuke.timer.dividedBy(ukedager)
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normaltArbeidstimerPerDag)
.medFaktiskArbeidTimerPerDag(faktiskArbeidstimerPerDag)
Pair(k9Periode, arbeidstidPeriodeInfo)
}
.forEach { (periode, arbeidstidPeriodeInfo) ->
//Tar høyde for at enkeltdager kan være utenfor fraOgMed/tilOgMed som kan være justert pga start/slutt innenfor søknadsperioden
if (periode.fraOgMed.erInnenforPerioden(fraOgMed, tilOgMed)) {
arbeidstidInfo.leggeTilPeriode(periode, arbeidstidPeriodeInfo)
}
}
return arbeidstidInfo
}
private fun ArbeidsUke.periodeUtenHelg(): SortedSet<LocalDate> {
return periode.fraOgMed.datesUntil(periode.tilOgMed.plusDays(1))
.filter { it.ikkeErHelg() }
.toList()
.toSortedSet()
}
private fun LocalDate.erInnenforPerioden(fraOgMed: LocalDate, tilOgMed: LocalDate) =
this.isEqual(fraOgMed) || this.isEqual(tilOgMed) || (this.isAfter(fraOgMed) && this.isBefore(tilOgMed))
}
| 4
|
Kotlin
|
0
| 0
|
402a0658544afc0f238f3a3c7babd0addad556b0
| 7,096
|
k9-brukerdialog-prosessering
|
MIT License
|
src/main/kotlin/no/nav/brukerdialog/ytelse/pleiepengersyktbarn/søknad/api/domene/arbeid/Arbeidsforhold.kt
|
navikt
| 585,578,757
| false
|
{"Kotlin": 1442549, "Handlebars": 126943, "Dockerfile": 98}
|
package no.nav.brukerdialog.ytelse.pleiepengersyktbarn.søknad.api.domene.arbeid
import jakarta.validation.Valid
import no.nav.k9.søknad.felles.type.Periode
import no.nav.k9.søknad.ytelse.psb.v1.arbeidstid.ArbeidstidInfo
import no.nav.k9.søknad.ytelse.psb.v1.arbeidstid.ArbeidstidPeriodeInfo
import no.nav.brukerdialog.utils.DateUtils.ikkeErHelg
import java.time.LocalDate
import java.util.*
import kotlin.time.toJavaDuration
import kotlin.time.toKotlinDuration
data class Arbeidsforhold(
val normalarbeidstid: NormalArbeidstid,
@field:Valid val arbeidIPeriode: ArbeidIPeriode
) {
companion object {
internal fun k9ArbeidstidInfoMedNullTimer(fraOgMed: LocalDate, tilOgMed: LocalDate) = ArbeidstidInfo()
.medPerioder(
mapOf(
Periode(fraOgMed, tilOgMed) to ArbeidstidPeriodeInfo()
.medFaktiskArbeidTimerPerDag(NULL_TIMER)
.medJobberNormaltTimerPerDag(NULL_TIMER)
)
)
}
fun tilK9ArbeidstidInfo(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
return when (arbeidIPeriode.type) {
ArbeidIPeriodeType.ARBEIDER_VANLIG -> arbeiderVanlig(fraOgMed, tilOgMed)
ArbeidIPeriodeType.ARBEIDER_IKKE -> arbeiderIkke(fraOgMed, tilOgMed)
ArbeidIPeriodeType.ARBEIDER_REDUSERT -> arbeiderRedusert(fraOgMed, tilOgMed)
}
}
fun arbeiderRedusert(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
return when (arbeidIPeriode.redusertArbeid.type) {
RedusertArbeidstidType.PROSENT_AV_NORMALT -> arbeiderProsentAvNormalt(fraOgMed, tilOgMed)
RedusertArbeidstidType.TIMER_I_SNITT_PER_UKE -> arbeiderTimerISnittPerUke(fraOgMed, tilOgMed)
RedusertArbeidstidType.ULIKE_UKER_TIMER -> arbeidsukerUlikeTimer(fraOgMed, tilOgMed)
}
}
private fun arbeiderVanlig(fraOgMed: LocalDate, tilOgMed: LocalDate) =
arbeiderVanligMedNormaltimerSomSnitt(fraOgMed, tilOgMed)
private fun arbeiderVanligMedNormaltimerSomSnitt(
fraOgMed: LocalDate,
tilOgMed: LocalDate,
): ArbeidstidInfo {
val arbeidstidInfo = ArbeidstidInfo()
arbeidstidInfo.medPerioder(
mapOf(
Periode(fraOgMed, tilOgMed) to ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normalarbeidstid.timerPerDagFraSnitt())
.medFaktiskArbeidTimerPerDag(normalarbeidstid.timerPerDagFraSnitt())
)
)
return arbeidstidInfo
}
private fun arbeiderIkke(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
val arbeidstidInfo = ArbeidstidInfo()
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normalarbeidstid.timerPerDagFraSnitt())
.medFaktiskArbeidTimerPerDag(NULL_TIMER)
arbeidstidInfo.medPerioder(
mapOf(Periode(fraOgMed, tilOgMed) to arbeidstidPeriodeInfo)
)
return arbeidstidInfo
}
private fun arbeiderProsentAvNormalt(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
requireNotNull(arbeidIPeriode.redusertArbeid.prosentAvNormalt) { "For å regne ut arbeid fra prosentAvNormalt må den være satt." }
val normaltTimerPerdag = normalarbeidstid.timerPerDagFraSnitt()
val faktiskTimerPerDag = normaltTimerPerdag.toKotlinDuration()
.div(100)
.times(arbeidIPeriode.redusertArbeid.prosentAvNormalt)
.toJavaDuration()
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normaltTimerPerdag)
.medFaktiskArbeidTimerPerDag(faktiskTimerPerDag)
return ArbeidstidInfo().medPerioder(
mapOf(Periode(fraOgMed, tilOgMed) to arbeidstidPeriodeInfo)
)
}
private fun arbeiderTimerISnittPerUke(fraOgMed: LocalDate, tilOgMed: LocalDate): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
requireNotNull(arbeidIPeriode.redusertArbeid.timerPerUke) { "For å regne ut arbeid fra timerPerUke må den være satt." }
val normaltTimerPerDag = normalarbeidstid.timerPerDagFraSnitt()
val faktiskTimerPerDag = arbeidIPeriode.redusertArbeid.timerPerUke.dividedBy(DAGER_PER_UKE)
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normaltTimerPerDag)
.medFaktiskArbeidTimerPerDag(faktiskTimerPerDag)
return ArbeidstidInfo().medPerioder(
mapOf(Periode(fraOgMed, tilOgMed) to arbeidstidPeriodeInfo)
)
}
internal fun arbeidsukerUlikeTimer(
fraOgMed: LocalDate,
tilOgMed: LocalDate,
): ArbeidstidInfo {
requireNotNull(arbeidIPeriode.redusertArbeid) { "For å regne ut redusert arbeid må den være satt." }
requireNotNull(arbeidIPeriode.redusertArbeid.arbeidsuker) { "For å regne ut arbeid fra arbeidsuker må den være satt." }
val arbeidstidInfo = ArbeidstidInfo()
arbeidIPeriode.redusertArbeid.arbeidsuker.map { arbeidsuke: ArbeidsUke ->
requireNotNull(normalarbeidstid.timerPerUkeISnitt) { "normalarbeidstid.timerPerUkeISnitt må være satt." }
val periodeUtenHelg: SortedSet<LocalDate> = arbeidsuke.periodeUtenHelg()
val k9Periode = Periode(periodeUtenHelg.first(), periodeUtenHelg.last())
val normaltArbeidstimerPerDag = normalarbeidstid.timerPerUkeISnitt.dividedBy(DAGER_PER_UKE)
val ukedager = periodeUtenHelg.size.toLong()
val faktiskArbeidstimerPerDag = arbeidsuke.timer.dividedBy(ukedager)
val arbeidstidPeriodeInfo = ArbeidstidPeriodeInfo()
.medJobberNormaltTimerPerDag(normaltArbeidstimerPerDag)
.medFaktiskArbeidTimerPerDag(faktiskArbeidstimerPerDag)
Pair(k9Periode, arbeidstidPeriodeInfo)
}
.forEach { (periode, arbeidstidPeriodeInfo) ->
//Tar høyde for at enkeltdager kan være utenfor fraOgMed/tilOgMed som kan være justert pga start/slutt innenfor søknadsperioden
if (periode.fraOgMed.erInnenforPerioden(fraOgMed, tilOgMed)) {
arbeidstidInfo.leggeTilPeriode(periode, arbeidstidPeriodeInfo)
}
}
return arbeidstidInfo
}
private fun ArbeidsUke.periodeUtenHelg(): SortedSet<LocalDate> {
return periode.fraOgMed.datesUntil(periode.tilOgMed.plusDays(1))
.filter { it.ikkeErHelg() }
.toList()
.toSortedSet()
}
private fun LocalDate.erInnenforPerioden(fraOgMed: LocalDate, tilOgMed: LocalDate) =
this.isEqual(fraOgMed) || this.isEqual(tilOgMed) || (this.isAfter(fraOgMed) && this.isBefore(tilOgMed))
}
| 4
|
Kotlin
|
0
| 0
|
402a0658544afc0f238f3a3c7babd0addad556b0
| 7,096
|
k9-brukerdialog-prosessering
|
MIT License
|
src/commonTest/kotlin/fr/acinq/lightning/channel/states/SyncingTestsCommon.kt
|
ACINQ
| 243,326,972
| false
| null |
package fr.acinq.lightning.channel.states
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.ScriptFlags
import fr.acinq.bitcoin.Transaction
import fr.acinq.lightning.Feature
import fr.acinq.lightning.blockchain.BITCOIN_FUNDING_SPENT
import fr.acinq.lightning.blockchain.WatchConfirmed
import fr.acinq.lightning.blockchain.WatchEventSpent
import fr.acinq.lightning.channel.*
import fr.acinq.lightning.channel.TestsHelper.processEx
import fr.acinq.lightning.channel.TestsHelper.reachNormal
import fr.acinq.lightning.tests.TestConstants
import fr.acinq.lightning.tests.utils.LightningTestSuite
import fr.acinq.lightning.utils.msat
import fr.acinq.lightning.wire.ChannelReestablish
import fr.acinq.lightning.wire.Error
import fr.acinq.lightning.wire.Init
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SyncingTestsCommon : LightningTestSuite() {
@Test
fun `detect that a remote commit tx was published`() {
val (alice, bob, _) = run {
val (alice, bob) = init()
disconnect(alice, bob)
}
val aliceCommitTx = alice.state.commitments.localCommit.publishableTxs.commitTx.tx
val (bob1, actions) = bob.processEx(ChannelEvent.WatchReceived(WatchEventSpent(bob.state.channelId, BITCOIN_FUNDING_SPENT, aliceCommitTx)))
assertTrue(bob1 is Closing)
// we published a tx to claim our main output
val claimTx = actions.filterIsInstance<ChannelAction.Blockchain.PublishTx>().map { it.tx }.first()
Transaction.correctlySpends(claimTx, alice.state.commitments.localCommit.publishableTxs.commitTx.tx, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS)
val watches = actions.findWatches<WatchConfirmed>()
assertEquals(watches.map { it.txId }.toSet(), setOf(aliceCommitTx.txid, claimTx.txid))
}
@Test
fun `detect that a revoked commit tx was published`() {
val (_, bob, revokedTx) = run {
val (alice, bob) = init()
val (nodes, _, _) = TestsHelper.addHtlc(10_000_000.msat, payer = alice, payee = bob)
val (alice1, bob1) = nodes
val (alice2, bob2) = TestsHelper.crossSign(alice1, bob1)
alice2 as Normal
bob2 as Normal
val (alice3, bob3, _) = disconnect(alice2, bob2)
Triple(alice3, bob3, alice.commitments.localCommit.publishableTxs.commitTx.tx)
}
val (bob1, actions) = bob.processEx(ChannelEvent.WatchReceived(WatchEventSpent(bob.state.channelId, BITCOIN_FUNDING_SPENT, revokedTx)))
assertTrue(bob1 is Closing)
val claimTxs = actions.filterIsInstance<ChannelAction.Blockchain.PublishTx>().map { it.tx }
assertEquals(claimTxs.size, 2)
claimTxs.forEach { Transaction.correctlySpends(it, revokedTx, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) }
val watches = actions.findWatches<WatchConfirmed>()
// we watch the revoked tx and our "claim main output tx"
assertEquals(watches.map { it.txId }.toSet(), setOf(revokedTx.txid, bob1.revokedCommitPublished.first().claimMainOutputTx!!.tx.txid))
}
@Test
fun `recv CMD_FORCECLOSE`() {
val (alice, _, _) = run {
val (alice, bob) = init()
disconnect(alice, bob)
}
val (alice1, actions1) = alice.process(ChannelEvent.ExecuteCommand(CMD_FORCECLOSE))
assertTrue(alice1 is Closing)
actions1.hasOutgoingMessage<Error>()
}
companion object {
fun init(): Pair<Normal, Normal> {
// NB: we disable channel backups to ensure Bob sends his channel_reestablish on reconnection.
return reachNormal(bobFeatures = TestConstants.Bob.nodeParams.features.remove(Feature.ChannelBackupClient))
}
fun disconnect(alice: Normal, bob: Normal): Triple<Syncing, Syncing, Pair<ChannelReestablish, ChannelReestablish>> {
val (alice1, _) = alice.processEx(ChannelEvent.Disconnected)
val (bob1, _) = bob.processEx(ChannelEvent.Disconnected)
assertTrue(alice1 is Offline)
assertTrue(bob1 is Offline)
val aliceInit = Init(ByteVector(alice1.state.commitments.localParams.features.toByteArray()))
val bobInit = Init(ByteVector(bob1.state.commitments.localParams.features.toByteArray()))
val (alice2, actions) = alice1.processEx(ChannelEvent.Connected(aliceInit, bobInit))
assertTrue(alice2 is Syncing)
val channelReestablishA = actions.findOutgoingMessage<ChannelReestablish>()
val (bob2, actions1) = bob1.processEx(ChannelEvent.Connected(bobInit, aliceInit))
assertTrue(bob2 is Syncing)
val channelReestablishB = actions1.findOutgoingMessage<ChannelReestablish>()
return Triple(alice2, bob2, Pair(channelReestablishA, channelReestablishB))
}
}
}
| 18
|
Kotlin
|
3
| 38
|
57af9b447df16b7a0b537d054bf6112e6d9c13c5
| 4,877
|
lightning-kmp
|
Apache License 2.0
|
src/main/kotlin/io/github/dockyardmc/extentions/ExtendedByteBuf.kt
|
DockyardMC
| 650,731,309
| false
| null |
package io.github.dockyardmc.extentions
import io.github.dockyardmc.item.ItemStack
import io.github.dockyardmc.item.writeItemStack
import io.github.dockyardmc.scroll.Component
import io.github.dockyardmc.scroll.extensions.toComponent
import io.github.dockyardmc.utils.MathUtils
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.handler.codec.DecoderException
import org.jglrxavpok.hephaistos.nbt.*
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.time.Instant
import java.util.*
import kotlin.experimental.inv
private const val SEGMENT_BITS: Byte = 0x7F
private const val CONTINUE_BIT = 0x80
fun ByteBuf.writeOptional(item: Any?, unit: (ByteBuf) -> Unit) {
val isPresent = item != null
this.writeBoolean(isPresent)
if(isPresent) {
unit.invoke(this)
}
}
fun ByteBuf.writeTextComponent(component: Component) {
component.italic = false
this.writeNBT(component.toNBT())
}
fun ByteBuf.writeTextComponent(text: String) {
this.writeTextComponent(text.toComponent())
}
fun ByteBuf.writeItemStackList(list: Collection<ItemStack>) {
this.writeVarInt(list.size)
list.forEach {
this.writeItemStack(it)
}
}
fun ByteBuf.readUUID(): UUID {
val most = this.readLong()
val least = this.readLong()
return UUID(most, least)
}
fun ByteBuf.writeUUID(uuid: UUID) {
this.writeLong(uuid.mostSignificantBits)
this.writeLong(uuid.leastSignificantBits)
}
fun ByteBuf.writeUUIDArray(uuids: List<UUID>) {
this.writeVarInt(uuids.size)
uuids.forEach { this.writeUUID(it) }
}
fun ByteBuf.writeByteArray(bs: ByteArray) {
this.writeVarInt(bs.size)
this.writeBytes(bs)
}
fun ByteBuf.writeVarIntArray(array: List<Int>) {
this.writeVarInt(array.size)
array.forEach { this.writeVarInt(it) }
}
fun ByteBuf.writeLongArray(array: LongArray) {
this.writeLongArray(array.toList())
}
fun ByteBuf.writeLongArray(array: List<Long>) {
this.writeVarInt(array.size)
array.forEach { this.writeLong(it) }
}
fun ByteBuf.readByteArray(): ByteArray {
val len = this.readVarInt()
return readBytes(len).toByteArraySafe()
}
fun ByteBuf.readNBT(): NBT {
val buffer = this
val nbtReader = NBTReader(object : InputStream() {
override fun read(): Int = buffer.readByte().toInt() and 0xFF
override fun available(): Int = buffer.readableBytes()
}, CompressedProcesser.NONE)
return try {
val tagId: Byte = buffer.readByte()
if (tagId.toInt() == NBTType.TAG_End.ordinal) NBTEnd else nbtReader.readRaw(tagId.toInt())
} catch (e: IOException) {
throw java.lang.RuntimeException(e)
} catch (e: NBTException) {
throw java.lang.RuntimeException(e)
}
}
fun ByteBuf.writeNBT(nbt: NBT, truncateRootTag: Boolean = true) {
val outputStream = ByteArrayOutputStream()
try {
val writer = NBTWriter(outputStream, CompressedProcesser.NONE)
writer.writeNamed("", nbt)
writer.close()
} finally {
if (truncateRootTag) {
var outData = outputStream.toByteArray()
// Since 1.20.2 (Protocol 764) NBT sent over the network has been updated to exclude the name from the root TAG_COMPOUND
// ┌───────────┬────────┬────────────────┬──────────────┬───────────┐
// │ Version │ TypeID │ Length of Name │ Name │ Payload │
// ├───────────┼────────┼────────────────┼──────────────┼───────────┤
// │ < 1.20.2 │ 0x0a │ 0x00 0x00 │ Empty String │ 0x02 0x09 │
// │ >= 1.20.2 │ 0x0a │ N/A │ N/A │ 0x02 0x09 │
// └───────────┴────────┴────────────────┴──────────────┴───────────┘
// Thanks to Kev (kev_dev) for pointing this out because I think I would have gone mad otherwise
val list = outData.toMutableList()
list.removeAt(1)
list.removeAt(1)
outData = list.toByteArray()
writeBytes(outData)
} else {
writeBytes(outputStream.toByteArray())
}
}
}
fun ByteBuf.readFixedBitSet(i: Int): BitSet {
val bs = ByteArray(MathUtils.positiveCeilDiv(i, 8))
this.readBytes(bs)
return BitSet.valueOf(bs)
}
fun ByteBuf.readInstant(): Instant = Instant.ofEpochMilli(this.readLong())
fun ByteBuf.writeVarLong(long: Long): ByteBuf {
var modLong = long
while (true) {
if (modLong and -0x80L == 0L) {
this.writeByte(modLong.toInt())
}
this.writeByte((modLong and 0x7FL).toInt() or 0x80)
modLong = modLong ushr 7
}
}
fun ByteBuf.readVarLong(): Long {
var b: Byte
var long = 0L
var iteration = 0
do {
b = this.readByte()
long = long or ((b.toInt() and 0x7F).toLong() shl iteration++ * 7)
if (iteration <= 10) continue
throw RuntimeException("VarLong too big")
} while (hasContinuationBit(b))
return long
}
fun hasContinuationBit(byte: Byte): Boolean = byte.toInt() and 0x80 == 128
inline fun <reified T : Enum<T>> ByteBuf.readVarIntEnum(): T = T::class.java.enumConstants[readVarInt()]
inline fun <reified T : Enum<T>> ByteBuf.readByteEnum(): T = T::class.java.enumConstants[readByte().toInt()]
inline fun <reified T : Enum<T>> ByteBuf.writeVarIntEnum(value: T) {
this.writeVarInt(value.ordinal)
}
fun <T : Enum<T>> ByteBuf.writeByteEnum(value: T) {
this.writeByte(value.ordinal)
}
fun ByteBuf.readVarInt(): Int {
var value = 0
var position = 0
var currentByte: Byte
while (this.isReadable) {
currentByte = readByte()
value = value or (currentByte.toInt() and SEGMENT_BITS.toInt() shl position)
if (currentByte.toInt() and CONTINUE_BIT == 0) break
position += 7
if (position >= 32) throw java.lang.RuntimeException("VarInt is too big")
}
return value
}
fun ByteBuf.writeStringArray(list: Collection<String>) {
writeVarInt(list.size)
list.forEach { writeUtf(it) }
}
fun ByteBuf.writeVarInt(int: Int) {
var value = int
while (true) {
if (value and SEGMENT_BITS.inv().toInt() == 0) {
writeByte(value)
return
}
writeByte(value and SEGMENT_BITS.toInt() or CONTINUE_BIT)
value = value ushr 7
}
}
fun ByteBuf.readString() = readString(Short.MAX_VALUE.toInt())
fun ByteBuf.readUtfAndLength() = readUtfAndLength(Short.MAX_VALUE.toInt())
fun ByteBuf.readString(i: Int): String {
val maxSize = i * 3
val size = this.readVarInt()
if (size > maxSize) throw DecoderException("The received string was longer than the allowed $maxSize ($size > $maxSize)")
if (size < 0) throw DecoderException("The received string's length was smaller than 0")
val string = this.toString(this.readerIndex(), size, StandardCharsets.UTF_8)
this.readerIndex(this.readerIndex() + size)
if (string.length > i) throw DecoderException("The received string was longer than the allowed (${string.length} > $i)")
return string
}
fun ByteBuf.readUtfAndLength(i: Int): Pair<String, Int> {
val maxSize = i * 3
val size = this.readVarInt()
if (size > maxSize) throw DecoderException("The received string was longer than the allowed $maxSize ($size > $maxSize)")
if (size < 0) throw DecoderException("The received string's length was smaller than 0")
val string = this.toString(this.readerIndex(), size, StandardCharsets.UTF_8)
this.readerIndex(this.readerIndex() + size)
if (string.length > i) throw DecoderException("The received string was longer than the allowed (${string.length} > $i)")
return string to size
}
fun ByteBuf.writeUtf(text: String) {
val utf8Bytes = text.toByteArray(StandardCharsets.UTF_8)
val length = utf8Bytes.size
this.writeVarInt(length)
this.writeBytes(utf8Bytes)
}
fun ByteBuf.toByteArraySafe(): ByteArray {
if (this.hasArray()) {
return this.array()
}
val bytes = ByteArray(this.readableBytes())
this.getBytes(this.readerIndex(), bytes)
return bytes
}
fun ByteArray.toByteBuf(): ByteBuf = Unpooled.copiedBuffer(this)
| 9
| null |
7
| 55
|
9a0eb8f3184123b79b835356ddde526d9eb6df65
| 8,203
|
Dockyard
|
MIT License
|
Edu-Cpp/testSrc/com/jetbrains/edu/cpp/CppUtilTest.kt
|
kirillSenchov
| 283,726,841
| true
|
{"Kotlin": 2674430, "Java": 578303, "HTML": 132288, "CSS": 12844, "Python": 3994, "JavaScript": 315}
|
package com.jetbrains.edu.cpp
import com.jetbrains.cmake.CMakeListsFileType
import com.jetbrains.edu.learning.EduTestCase
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
import org.junit.Assert.assertThat
class CppUtilTest : EduTestCase() {
fun `test find CMake command - project`() = checkCMakeCommand("""
|#some text
|
|project(name)
|
|# some text
""", "project")
fun `test find CMake command - ProJEct`() = checkCMakeCommand("""
| #some text
|
| ProJEct(name)
""", "project")
fun `test find CMake command - inline call`() = checkCMakeCommand("""
| message("Hi!") project(name) message("By!")
""", "project")
fun `test find CMake command - no command`() = checkCMakeCommand("""
| #some text
| message("empty me )=")
| # no text ;)
""", "project", shouldFind = false)
private fun checkCMakeCommand(text: String, commandName: String, shouldFind: Boolean = true) {
val file = myFixture.configureByText(CMakeListsFileType.FILE_NAME, text.trimMargin())
val result = file.findCMakeCommand(commandName)
if (shouldFind) {
check(result != null)
assertThat(result.name, IsEqualIgnoringCase(commandName))
}
else {
assertNull(result)
}
}
}
// BACKCOMPAT: 2019.3. Use `org.hamcrest.text.IsEqualIgnoringCase` instead
private class IsEqualIgnoringCase(private val string: String) : TypeSafeMatcher<String>() {
override fun matchesSafely(item: String): Boolean {
return string.equals(item, ignoreCase = true)
}
override fun describeMismatchSafely(item: String, mismatchDescription: Description) {
mismatchDescription.appendText("was $item")
}
override fun describeTo(description: Description) {
description.appendText("equalToIgnoringCase($string)")
}
}
| 0
| null |
0
| 0
|
1fd0576070c07a273dbc25ec0ab3f72fac5caebd
| 1,807
|
educational-plugin
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/NoteSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/NoteSharp")
package mui.icons.material
@JsName("default")
external val NoteSharp: SvgIconComponent
| 12
|
Kotlin
|
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 182
|
kotlin-wrappers
|
Apache License 2.0
|
androidx-fetcher/src/main/kotlin/land/sungbin/androidx/fetcher/Logger.kt
|
jisungbin
| 829,412,179
| false
|
{"Kotlin": 71964}
|
/*
* Developed by <NAME> 2024.
*
* Licensed under the MIT.
* Please see full license: https://github.com/jisungbin/androidx-aosp-viewer/blob/trunk/LICENSE
*/
package land.sungbin.androidx.fetcher
import java.util.logging.Level
import java.util.logging.Logger as JavaLogger
// Timber is an Android library, so we can't use it.
public open class Logger {
protected open val logger: JavaLogger by lazy {
JavaLogger.getLogger(Logger::class.qualifiedName!!).apply {
level = Level.ALL
}
}
public open fun debug(lazyMessage: () -> String) {
if (logger.isLoggable(Level.INFO)) {
logger.info(lazyMessage())
}
}
public open fun warn(lazyMessage: () -> String) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning(lazyMessage())
}
}
public open fun error(lazyMessage: () -> String) {
if (logger.isLoggable(Level.SEVERE)) {
logger.severe(lazyMessage())
}
}
public companion object Default : Logger() {
override fun toString(): String = "DefaultLogger"
}
}
| 1
|
Kotlin
|
0
| 3
|
5242291f54d8d11e44ab85cb1d8a0eec7117b070
| 1,040
|
androidx-aosp-viewer
|
MIT License
|
src/main/kotlin/com/grubhub/kotlin/Main.kt
|
wakingrufus
| 107,727,970
| false
|
{"Gradle": 1, "Text": 1, "Ignore List": 1, "Java": 4, "Kotlin": 23}
|
package com.grubhub.kotlin
fun main(args: Array<String>) {
System.out.println("OOP: ")
val runner = FizzBuzzRunnerOop(System.out)
runner.fizzBuzz(limit = 15)
System.out.println("Functional: ")
fizzBuzzFunctional(limit = 15)
System.out.println("Functional (isolated): ")
fizzBuzzFunctionIsolated(limit = 15)
}
| 0
|
Kotlin
|
0
| 0
|
b79169c095b570e20df63affd4dd25caed8fe40b
| 340
|
writing-testable-functional-kotlin
|
MIT License
|
gdownload/src/main/java/com/tanodxyz/gdownload/CallbacksHandler.kt
|
tanoDxyz
| 490,427,660
| false
| null |
package com.tanodxyz.gdownload
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.tanodxyz.gdownload.executors.BackgroundExecutor
import java.util.*
/**
*The [CallbacksHandler] is used to run the callbacks based on flag [callbackThreadMain].
*It will run the callbacks on main thread or background thread.
*
* if [Lifecycle] object is provided - [CallbacksHandler] will behave in the following manner.
*
* if current state of [Lifecycle] object is [Lifecycle.State.RESUMED]
* -all callbacks provided via [runOnSelectedThread] will be immediately executed.
* else if callbacks are provided but current state was other then [Lifecycle.State.RESUMED]
* then all callbacks will accumulate in the list un till [Lifecycle] = [Lifecycle.State.RESUMED]
*
*/
open class CallbacksHandler(
internal val callbackThreadMain: Boolean = false,
internal val executor: BackgroundExecutor?,
lifecycle: Lifecycle? = null
) {
protected val mainThreadHandler = Handler(Looper.getMainLooper())
private val internalHandler = InternalHandler(lifecycle)
fun Runnable.runOnSelectedThread() {
internalHandler.handleCallback(this)
}
open fun clean() {
executor?.shutDown()
mainThreadHandler.removeCallbacksAndMessages(null)
internalHandler.destroy()
}
private inner class InternalHandler(val lifecycle: Lifecycle?) : DefaultLifecycleObserver {
private val callbacksList = Collections.synchronizedList(mutableListOf<Runnable>())
init {
lifecycle?.addObserver(this)
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
Runnable {
callbacksList.forEach { callback ->
callback.run()
}
callbacksList.clear()
}.runOn()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
destroy()
}
fun destroy() {
callbacksList.clear()
}
fun handleCallback(runnable: Runnable) {
if (lifecycle == null) {
runnable.runOn()
} else {
if (lifecycle.currentState == Lifecycle.State.RESUMED) {
runnable.runOn()
} else if (lifecycle.currentState != Lifecycle.State.DESTROYED) {
callbacksList.add(runnable)
}
}
}
private fun Runnable.runOn() {
if (callbackThreadMain) mainThreadHandler.post(this)
else if (!isMainThread()) this.run() else executor?.execute(this)
}
}
}
| 0
|
Kotlin
|
0
| 8
|
35fccc0fafb63c26639a30ab9bc4199e5dfe53e6
| 2,808
|
GDownload
|
Apache License 2.0
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CameraSpark.kt
|
walter-juan
| 868,046,028
| false
| null |
package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.CameraSpark: ImageVector
get() {
if (_cameraSpark != null) {
return _cameraSpark!!
}
_cameraSpark = Builder(name = "CameraSpark", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.5f, 20.0f)
horizontalLineToRelative(-6.5f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f)
verticalLineToRelative(-9.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, -2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
horizontalLineToRelative(6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, 2.0f)
horizontalLineToRelative(1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
verticalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 13.0f)
arcToRelative(3.0f, 3.0f, 0.0f, true, false, 6.0f, 0.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, -6.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(19.0f, 22.5f)
arcToRelative(4.75f, 4.75f, 0.0f, false, true, 3.5f, -3.5f)
arcToRelative(4.75f, 4.75f, 0.0f, false, true, -3.5f, -3.5f)
arcToRelative(4.75f, 4.75f, 0.0f, false, true, -3.5f, 3.5f)
arcToRelative(4.75f, 4.75f, 0.0f, false, true, 3.5f, 3.5f)
}
}
.build()
return _cameraSpark!!
}
private var _cameraSpark: ImageVector? = null
| 0
| null |
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 3,356
|
compose-icon-collections
|
MIT License
|
core/src/main/java/se/ltu/emapal/compute/ComputeLogEntry.kt
|
emanuelpalm
| 57,034,203
| false
| null |
package se.ltu.emapal.compute
import se.ltu.emapal.compute.util.Result
import se.ltu.emapal.compute.util.time.UnixTime
import se.ltu.emapal.compute.util.media.MediaDecoder
import se.ltu.emapal.compute.util.media.MediaEncodable
import se.ltu.emapal.compute.util.media.MediaEncoder
import se.ltu.emapal.compute.util.media.schema.MediaSchema
import se.ltu.emapal.compute.util.media.schema.MediaSchemaException
/**
* A compute log entry.
*
* @param timestamp Date and time at which the log entry was generated.
* @param lambdaId Identifies lambda executed when entry was logged.
* @param batchId Identifies batch processed when entry was logged.
* @param message Logged message.
*/
data class ComputeLogEntry(
val timestamp: UnixTime,
val lambdaId: Int,
val batchId: Int,
val message: String
) : MediaEncodable {
/** Creates new log entry with the current time as timestamp. */
constructor(
lambdaId: Int,
batchId: Int,
message: String
) : this(UnixTime.now(), lambdaId, batchId, message)
override val encodable: (MediaEncoder) -> Unit
get() = {
it.encodeMap {
it
.add("tim", timestamp.toMilliseconds())
.add("lid", lambdaId)
.add("bid", batchId)
.add("msg", message)
}
}
companion object {
private val decoderSchema = MediaSchema.typeMap()
.schemaEntry("tim", MediaSchema.typeNumber())
.schemaEntry("lid", MediaSchema.typeNumber())
.schemaEntry("bid", MediaSchema.typeNumber())
.schemaEntry("msg", MediaSchema.typeText())
/** Attempts to produce [ComputeLambda] using provided decoder. */
fun decode(decoder: MediaDecoder): Result<ComputeLogEntry, MediaSchemaException> {
return decoderSchema.verify(decoder)
.map {
val decoderMap = it.toMap()
ComputeLogEntry(
UnixTime.ofMilliseconds(decoderMap["tim"]!!.toLong()),
decoderMap["lid"]!!.toInt(),
decoderMap["bid"]!!.toInt(),
decoderMap["msg"]!!.toText()
)
}
}
}
}
| 1
| null |
1
| 1
|
5a8903ef4fd96867dbb6a8d4bdf5f6c54d5a6827
| 2,414
|
palm-compute
|
MIT License
|
seouling/src/main/java/mobile/seouling/com/application/add_spot/SearchByTagResultFragment.kt
|
seouling
| 202,506,383
| false
| null |
package mobile.seouling.com.application.add_spot
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.frag_search_by_tag.*
import mobile.seouling.com.BaseConstant
import mobile.seouling.com.R
import mobile.seouling.com.application.BaseViewModelFragment
import mobile.seouling.com.application.Injection
import mobile.seouling.com.application.SearchViewModel
import mobile.seouling.com.application.common.custom_view.BaseToast
import mobile.seouling.com.application.data.vo.Spot
import mobile.seouling.com.application.data_provider.BasePreference
import mobile.seouling.com.application.events.FragmentBackPressEvent
import mobile.seouling.com.application.events.ShowSpotDetailEvent
import mobile.seouling.com.base_android.doOnClick
import mobile.seouling.com.framework.BaseEventBus
import mobile.seouling.com.framework.rx.kt.observeOnMain
import mobile.seouling.com.framework.rx.kt.subscribeWithErrorConsumer
class SearchByTagResultFragment : BaseViewModelFragment() {
private val modifySection by lazy { arguments?.getString(BaseConstant.BundleKey.EXTRA_MODIFY_SCHEDULE_SECTION) ?: ""}
private val tagIdList: String by lazy { arguments?.getString(BaseConstant.BundleKey.EXTRA_TAG_LIST) ?: "" }
private val guIdList: String by lazy { arguments?.getString(BaseConstant.BundleKey.EXTRA_GU_LIST) ?: "" }
private lateinit var searchViewModel: SearchViewModel
private lateinit var searchByTagAdapter: SearchByTagAdapter
override fun onAttach(context: Context?) {
super.onAttach(context)
if (tagIdList.isEmpty()) {
BaseToast.show(R.string.wrong_path)
BaseEventBus.getInstance().post(FragmentBackPressEvent())
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
searchViewModel = ViewModelProviders.of(this, Injection.provideSearchViewModelFactory()).get(SearchViewModel::class.java)
searchByTagAdapter = SearchByTagAdapter(requireContext(), ::handleOnClickSpot, ::handleOnLongClickSpot)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.frag_search_by_tag, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
searchRecycler.adapter = searchByTagAdapter
complete.doOnClick {
if (searchByTagAdapter.checkedSpotList.isEmpty()) {
BaseToast.show(R.string.add_spot_least_one)
return@doOnClick
}
searchByTagAdapter.checkedSpotList
.forEach {
when (modifySection) {
"morning" -> BasePreference.insertSpotToMorning(it)
"lunch" -> BasePreference.insertSpotToLunch(it)
"night" -> BasePreference.insertSpotToNight(it)
else -> return@forEach
}
}
BaseEventBus.getInstance().post(FragmentBackPressEvent())
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
searchViewModel.apply {
searchTag(tagIdList, guIdList)
.observeOnMain()
.subscribeWithErrorConsumer {
searchByTagAdapter.submitList(it)
}
.addToDisposables()
}
}
private fun handleOnClickSpot(spot: Spot) {
}
private fun handleOnLongClickSpot(spotId: Int) {
BaseEventBus.getInstance().post(ShowSpotDetailEvent(spotId))
}
}
| 0
|
Kotlin
|
2
| 0
|
2b87bc5949b66f584b5e66919d09fca11d0c7b92
| 3,940
|
seouling-android
|
Apache License 2.0
|
features/obfuscationregionselection/src/main/java/com/kape/obfuscationregionselection/ui/ShadowsocksRegionSelectionScreen.kt
|
pia-foss
| 808,533,574
| false
|
{"Kotlin": 1249493}
|
package com.kape.obfuscationregionselection.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.os.ConfigurationCompat
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.kape.appbar.view.mobile.AppBar
import com.kape.appbar.viewmodel.AppBarViewModel
import com.kape.obfuscationregionselection.ui.vm.ShadowsocksRegionSelectionViewModel
import com.kape.obfuscationregionselection.util.ItemType
import com.kape.ui.R
import com.kape.ui.mobile.elements.Screen
import com.kape.ui.mobile.elements.Search
import com.kape.ui.mobile.text.MenuText
import com.kape.ui.utils.LocalColors
import org.koin.androidx.compose.koinViewModel
@Composable
fun ShadowsocksRegionSelectionScreen() = Screen {
val locale = ConfigurationCompat.getLocales(LocalConfiguration.current)[0]?.language
val isLoading = remember { mutableStateOf(false) }
val viewModel: ShadowsocksRegionSelectionViewModel =
koinViewModel<ShadowsocksRegionSelectionViewModel>().apply {
LaunchedEffect(Unit) {
locale?.let {
getShadowsocksRegions()
}
}
}
val appBarViewModel: AppBarViewModel = koinViewModel<AppBarViewModel>().apply {
appBarText(stringResource(id = R.string.location_selection_title))
}
val isSearchEnabled = remember { mutableStateOf(false) }
Column(
modifier = Modifier
.background(LocalColors.current.surfaceVariant)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
AppBar(appBarViewModel, onLeftIconClick = { viewModel.navigateBack() })
Column(modifier = Modifier.widthIn(max = 520.dp)) {
Search(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
viewModel.filterByName(it, isSearchEnabled)
}
SwipeRefresh(
state = rememberSwipeRefreshState(isLoading.value),
onRefresh = {
locale?.let {
viewModel.fetchShadowsocksRegions(locale, isLoading)
}
},
) {
LazyColumn {
val items = if (isSearchEnabled.value) {
viewModel.sorted.value
} else {
viewModel.servers.value
}
items(items.size) { index ->
val item = items[index]
when (item.type) {
is ItemType.Content -> {
LocationPickerItem(
server = item.type.server,
isFavorite = item.type.isFavorite,
enableFavorite = item.type.enableFavorite,
onClick = { viewModel.onShadowsocksRegionSelected(it) },
onFavoriteShadowsocksClick = {
viewModel.onFavoriteShadowsocksClicked(
it,
)
},
)
}
ItemType.HeadingAll -> {
MenuText(
content = stringResource(id = R.string.all_locations),
modifier = Modifier.padding(16.dp),
)
}
ItemType.HeadingFavorites -> {
MenuText(
content = stringResource(id = R.string.favorites),
modifier = Modifier.padding(16.dp),
)
}
}
}
}
}
}
}
}
| 3
|
Kotlin
|
0
| 4
|
151ea781036e280fcbfecfcb5716c7881fc802c1
| 4,830
|
mobile-android
|
MIT License
|
src/main/kotlin/other/mvvm/activity/src/app_package/mvvmAcitivityKt.kt
|
funaihui
| 531,447,396
| false
|
{"Kotlin": 19854}
|
package other.mvvm.activity.src.app_package
import other.mvvm.util.layoutName2Binding
/**
* Copyright (c) 2022, Lollitech
* All rights reserved
* author: <EMAIL>
* describe: 生成Activity模板代码
**/
fun mvvmActivityKt(activityClass: String, packageName: String, layoutName: String) = """
package $packageName
import android.os.Bundle
class ${activityClass}Activity : BaseActivity<${layoutName2Binding(layoutName)}Binding>() {
override fun initView(savedInstanceState: Bundle?) {
}
}
"""
| 0
|
Kotlin
|
0
| 0
|
3e9ec4564101d8df10d9f102e3891790d973ffed
| 508
|
lollitech-android
|
Apache License 2.0
|
app/src/main/java/com/skydoves/waterdays/ui/activities/settings/NFCActivity.kt
|
skydoves
| 100,711,724
| false
| null |
/*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.pani.ui.activities.settings
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.skydoves.pani.R
import kotlinx.android.synthetic.main.activity_nfc.*
import java.io.IOException
/**
* Created by skydoves on 2016-10-15.
* Updated by skydoves on 2017-08-17.
* Copyright (c) 2017 skydoves rights reserved.
*/
class NFCActivity : AppCompatActivity() {
private var mWriteMode = false
private var mNfcAdapter: NfcAdapter? = null
private var mNfcPendingIntent: PendingIntent? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nfc)
nfc_sticker.startRippleAnimation()
nfc_btn_setnfcdata.setOnClickListener {
if (CheckNFCEnabled()) {
mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
mNfcPendingIntent = PendingIntent.getActivity(this, 0, Intent(this, NFCActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
enableTagWriteMode()
nfc_sticker.visibility = View.VISIBLE
} else {
val setnfc = Intent(Settings.ACTION_NFC_SETTINGS)
startActivity(setnfc)
Toast.makeText(this, getString(R.string.msg_require_nfc), Toast.LENGTH_SHORT).show()
}
}
}
private fun CheckNFCEnabled(): Boolean {
val nfcAdpt = NfcAdapter.getDefaultAdapter(this)
if (nfcAdpt != null) {
if (!nfcAdpt.isEnabled)
return false
}
return true
}
private fun enableTagWriteMode() {
mWriteMode = true
val tagDetected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)
val mWriteTagFilters = arrayOf(tagDetected)
mNfcAdapter!!.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null)
}
private fun disableTagWriteMode() {
mWriteMode = false
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED == intent.action) {
val detectedTag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
val record = NdefRecord.createMime("waterdays_nfc/NFC", nfc_edt01.text.toString().toByteArray())
val message = NdefMessage(arrayOf(record))
// detected tag
if (writeTag(message, detectedTag)) {
disableTagWriteMode()
nfc_sticker.visibility = View.INVISIBLE
Toast.makeText(this, "NFC তথ্য ট্যাগ করুন.", Toast.LENGTH_SHORT).show()
}
}
}
fun writeTag(message: NdefMessage, tag: Tag): Boolean {
val size = message.toByteArray().size
try {
val ndef = Ndef.get(tag)
if (ndef != null) {
ndef.connect()
if (!ndef.isWritable) {
Toast.makeText(applicationContext, "ডাটা ট্যাগ করা যাচ্ছে না.", Toast.LENGTH_SHORT).show()
return false
}
if (ndef.maxSize < size) {
Toast.makeText(applicationContext, "ট্যাগ সাইজ খুবই ছোট.", Toast.LENGTH_SHORT).show()
return false
}
ndef.writeNdefMessage(message)
return true
} else {
val format = NdefFormatable.get(tag)
return if (format != null) {
try {
format.connect()
format.format(message)
true
} catch (e: IOException) {
false
}
} else {
false
}
}
} catch (e: Exception) {
return false
}
}
}
| 1
| null |
23
| 75
|
0196d34d71e11d0466e8e08e5ceab788e9d7fbbb
| 4,364
|
WaterDrink
|
Apache License 2.0
|
src/test/kotlin/com/codeperfection/shipit/controller/TransporterControllerTest.kt
|
codeperfection
| 730,719,882
| false
|
{"Kotlin": 50566, "Dockerfile": 567}
|
package com.codeperfection.shipit.controller
import com.codeperfection.shipit.dto.PageDto
import com.codeperfection.shipit.dto.PaginationFilterDto
import com.codeperfection.shipit.exception.clienterror.NotFoundException
import com.codeperfection.shipit.exception.dto.ErrorType
import com.codeperfection.shipit.fixture.*
import com.codeperfection.shipit.service.TransporterService
import org.hamcrest.Matchers
import org.hamcrest.Matchers.hasSize
import org.json.JSONArray
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.*
class TransporterControllerTest : ControllerTestBase() {
@MockBean
private lateinit var transporterService: TransporterService
@AfterEach
fun tearDown() {
Mockito.verifyNoMoreInteractions(transporterService)
}
private val transporterJson = """
{
"id": "$TRANSPORTER_ID",
"userId": "$USER_ID",
"name": "$TRANSPORTER_NAME",
"capacity": $TRANSPORTER_CAPACITY
}
""".trimIndent()
@Test
@WithMockUser
fun `GIVEN invalid request, WHEN creating transporter, THEN error response is returned`() {
mockMvc.perform(
MockMvcRequestBuilders.post("/api/v1/users/$USER_ID/transporters")
.contentType(MediaType.APPLICATION_JSON)
.content(
"""
{
"name": " ",
"capacity": 0
}
""".trimIndent()
)
)
.andExpect(status().isBadRequest)
.andExpect(jsonPath("errorType", Matchers.`is`(ErrorType.INVALID_REQUEST.name)))
.andExpect(jsonPath("fieldErrors", hasSize<JSONArray>(2)))
}
@Test
@WithMockUser
fun `GIVEN valid request, WHEN creating transporter, THEN created transporter is returned`() {
whenever(transporterService.createTransporter(USER_ID, createTransporterDtoFixture)).thenReturn(
transporterDtoFixture
)
mockMvc.perform(
MockMvcRequestBuilders.post("/api/v1/users/$USER_ID/transporters")
.contentType(MediaType.APPLICATION_JSON)
.content(
"""
{
"name": "$TRANSPORTER_NAME",
"capacity": $TRANSPORTER_CAPACITY
}
""".trimIndent()
)
)
.andExpect(status().isCreated)
.andExpect(content().json(transporterJson))
verify(transporterService).createTransporter(USER_ID, createTransporterDtoFixture)
}
@Test
@WithMockUser
fun `GIVEN invalid request, WHEN getting transporters page, THEN error response is returned`() {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/users/$USER_ID/transporters")
.queryParam("page", "-1")
.queryParam("size", "0")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isBadRequest)
.andExpect(jsonPath("errorType", Matchers.`is`(ErrorType.INVALID_REQUEST.name)))
.andExpect(jsonPath("fieldErrors", hasSize<JSONArray>(2)))
}
@Test
@WithMockUser
fun `GIVEN valid request, WHEN getting transporters page, THEN transporters page is returned`() {
val paginationFilterDto = PaginationFilterDto(page = 0, size = 1)
whenever(transporterService.getTransporters(USER_ID, paginationFilterDto))
.thenReturn(PageDto(totalElements = 1, totalPages = 1, elements = listOf(transporterDtoFixture)))
mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/users/$USER_ID/transporters")
.queryParam("page", "0")
.queryParam("size", "1")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk)
.andExpect(
content().json(
"""
{
"totalElements": 1,
"totalPages": 1,
"elements": [
$transporterJson
]
}
""".trimIndent()
)
)
verify(transporterService).getTransporters(USER_ID, paginationFilterDto)
}
@Test
@WithMockUser
fun `GIVEN request for a transporter that doesn't exist, WHEN getting the transporter, THEN not found is returned`() {
whenever(
transporterService.getTransporter(
USER_ID,
TRANSPORTER_ID
)
).thenThrow(NotFoundException(TRANSPORTER_ID))
mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/users/$USER_ID/transporters/$TRANSPORTER_ID")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isNotFound)
.andExpect(jsonPath("errorType", Matchers.`is`(ErrorType.NOT_FOUND.name)))
verify(transporterService).getTransporter(USER_ID, TRANSPORTER_ID)
}
@Test
@WithMockUser
fun `GIVEN request for a transporter that exists, WHEN getting the transporter, THEN transporter is returned`() {
whenever(transporterService.getTransporter(USER_ID, TRANSPORTER_ID)).thenReturn(transporterDtoFixture)
mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/users/$USER_ID/transporters/$TRANSPORTER_ID")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk)
.andExpect(
content().json(transporterJson)
)
verify(transporterService).getTransporter(USER_ID, TRANSPORTER_ID)
}
@Test
@WithMockUser
fun `GIVEN valid request, WHEN deleting transporter, THEN no content is returned`() {
mockMvc.perform(
MockMvcRequestBuilders.delete("/api/v1/users/$USER_ID/transporters/$TRANSPORTER_ID")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isNoContent)
verify(transporterService).deleteTransporter(USER_ID, TRANSPORTER_ID)
}
}
| 0
|
Kotlin
|
0
| 0
|
fbc1dc3aed31cf83d40fff3f988ca53b4033e0ac
| 6,680
|
ship-it
|
MIT License
|
core/ui/src/main/kotlin/com/t8rin/imagetoolboxlite/core/ui/utils/helper/ActivityUtils.kt
|
T8RIN
| 767,600,774
| false
| null |
/*
* ImageToolbox is an image editor for android
* Copyright (c) 2024 T8RIN (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
* You should have received a copy of the Apache License
* along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package com.t8rin.imagetoolboxlite.core.ui.utils.helper
import android.app.Activity
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ErrorOutline
import androidx.compose.material.icons.rounded.Save
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import com.t8rin.imagetoolboxlite.core.domain.saving.SaveResult
import com.t8rin.imagetoolboxlite.core.resources.R
import com.t8rin.imagetoolboxlite.core.ui.utils.helper.ContextUtils.requestStoragePermission
import com.t8rin.imagetoolboxlite.core.ui.utils.helper.ReviewHandler.showReview
import com.t8rin.imagetoolboxlite.core.ui.widget.other.ToastDuration
import com.t8rin.imagetoolboxlite.core.ui.widget.other.ToastHostState
fun Activity.failedToSaveImages(
scope: CoroutineScope,
results: List<SaveResult>,
toastHostState: ToastHostState,
savingPathString: String,
isOverwritten: Boolean,
showConfetti: () -> Unit
) {
val failed = results.count { it is SaveResult.Error }
val done = results.count { it is SaveResult.Success }
if (results.any { it == SaveResult.Error.MissingPermissions }) requestStoragePermission()
else if (failed == 0) {
if (done == 1) {
scope.launch {
toastHostState.showToast(
(results.first() as? SaveResult.Success)?.message ?: getString(
R.string.saved_to_without_filename,
savingPathString
),
Icons.Rounded.Save
)
}
} else {
if (isOverwritten) {
scope.launch {
toastHostState.showToast(
getString(R.string.images_overwritten),
Icons.Rounded.Save
)
}
} else {
scope.launch {
toastHostState.showToast(
getString(
R.string.saved_to_without_filename,
savingPathString
),
Icons.Rounded.Save
)
}
}
showReview(this)
showConfetti()
}
showReview(this)
showConfetti()
} else if (failed < done) {
scope.launch {
showConfetti()
toastHostState.showToast(
(results.first { it is SaveResult.Success } as SaveResult.Success).message
?: getString(
R.string.saved_to_without_filename,
savingPathString
),
Icons.Rounded.Save
)
toastHostState.showToast(
getString(R.string.failed_to_save, failed),
Icons.Rounded.ErrorOutline,
ToastDuration.Long
)
}
} else {
scope.launch {
toastHostState.showToast(
getString(R.string.failed_to_save, failed),
Icons.Rounded.ErrorOutline,
ToastDuration.Long
)
}
}
}
| 5
| null |
84
| 8
|
f8fe322c2bde32544e207b49a01cfeac92c187ce
| 3,893
|
ImageToolboxLite
|
Apache License 2.0
|
compose/src/main/java/de/jensklingenberg/jetpackcomposeplayground/ui/samples/common/Vectors.kt
|
ravishankarsingh1996
| 223,398,680
| true
|
{"Kotlin": 274603, "Shell": 5712, "Java": 1172}
|
/*
* 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.example.jetnews.ui
import androidx.annotation.DrawableRes
import androidx.compose.Composable
import androidx.compose.unaryPlus
import androidx.ui.core.WithDensity
import androidx.ui.foundation.Clickable
import androidx.ui.graphics.Color
import androidx.ui.graphics.vector.DrawVector
import androidx.ui.layout.Container
import androidx.ui.material.ripple.Ripple
import androidx.ui.res.vectorResource
@Composable
fun VectorImageButton(@DrawableRes id: Int, onClick: () -> Unit) {
Ripple(bounded = false) {
Clickable(onClick = onClick) {
VectorImage(id)
}
}
}
@Composable
fun VectorImage(@DrawableRes id: Int, tint: Color = Color.Transparent) {
val vector = +vectorResource(id)
WithDensity {
Container(
width = vector.defaultWidth.toDp(),
height = vector.defaultHeight.toDp()
) {
DrawVector(vector, tint)
}
}
}
| 1
| null |
1
| 4
|
2d87fa9dbdd7f89b0d0e3e97f143910e5a3a9e54
| 1,528
|
Jetpack-Compose-Playground
|
MIT License
|
common-server/src/commonMain/kotlin/com/toxicbakery/game/dungeon/machine/authentication/AuthenticationMachine.kt
|
ToxicBakery
| 224,311,645
| false
| null |
package com.toxicbakery.game.dungeon.machine.authentication
import com.toxicbakery.game.dungeon.exception.AuthenticationException
import com.toxicbakery.game.dungeon.exception.NoPlayerWithUsernameException
import com.toxicbakery.game.dungeon.machine.Machine
import com.toxicbakery.game.dungeon.machine.command.CommandMachine
import com.toxicbakery.game.dungeon.machine.command.processor.ProcessorLook
import com.toxicbakery.game.dungeon.manager.AuthenticationManager
import com.toxicbakery.game.dungeon.model.auth.Credentials
import com.toxicbakery.game.dungeon.model.client.ExpectedResponseType
import com.toxicbakery.game.dungeon.model.session.GameSession
import org.kodein.di.Kodein
import org.kodein.di.erased.bind
import org.kodein.di.erased.instance
import org.kodein.di.erased.provider
private class AuthenticationMachineImpl(
private val authenticationManager: AuthenticationManager,
private val commandMachine: CommandMachine,
private val authMachineState: AuthMachineState = AuthMachineState()
) : AuthenticationMachine {
override val currentState: AuthenticationState = authMachineState.state
override val name: String = "AuthenticationMachine"
override suspend fun acceptMessage(
gameSession: GameSession,
message: String
): Machine<*> = gameSession.cycle(message).let { nextState ->
when (nextState.state) {
AuthenticationState.Authenticated -> commandMachine.acceptMessage(gameSession, ProcessorLook.COMMAND)
else -> AuthenticationMachineImpl(
authenticationManager = authenticationManager,
commandMachine = commandMachine,
authMachineState = nextState
)
}
}
override suspend fun initMachine(gameSession: GameSession) = when (currentState) {
AuthenticationState.Init -> AuthenticationMachineImpl(
authenticationManager = authenticationManager,
commandMachine = commandMachine,
authMachineState = gameSession.cycle()
)
else -> this
}
private suspend fun GameSession.cycle(message: String = ""): AuthMachineState = when (currentState) {
AuthenticationState.Init -> initAuthentication()
AuthenticationState.AwaitingUsername -> takeUsernameAndProceed(message)
AuthenticationState.AwaitingPassword -> takePasswordAndProceed(message)
AuthenticationState.Authenticated -> error("Request to process on end state")
}
private suspend fun GameSession.initAuthentication(): AuthMachineState {
sendMessage("What is your username?")
return authMachineState.copy(
state = AuthenticationState.AwaitingUsername,
credentials = Credentials()
)
}
private suspend fun GameSession.takeUsernameAndProceed(username: String): AuthMachineState {
sendMessage("What is your password?", ExpectedResponseType.Secure)
return authMachineState.copy(
state = AuthenticationState.AwaitingPassword,
credentials = Credentials(username = username)
)
}
private suspend fun GameSession.takePasswordAndProceed(password: String): AuthMachineState = try {
val credentials = authMachineState.credentials.copy(password = <PASSWORD>)
authenticationManager.authenticatePlayer(credentials, this)
sendMessage("Authentication successful! Welcome back ${credentials.username}")
authMachineState.copy(
state = AuthenticationState.Authenticated,
credentials = credentials
)
} catch (e: NoPlayerWithUsernameException) {
sendMessage("User not found, are you sure you have registered?")
close()
initAuthentication()
} catch (e: AuthenticationException) {
sendMessage("Authentication failed, check your password and try again.")
close()
initAuthentication()
}
}
private data class AuthMachineState(
val credentials: Credentials = Credentials(),
val state: AuthenticationState = AuthenticationState.Init
)
interface AuthenticationMachine : Machine<AuthenticationState>
val authenticationMachineModule = Kodein.Module("authenticationMachineModule") {
bind<AuthenticationMachine>() with provider {
AuthenticationMachineImpl(
authenticationManager = instance(),
commandMachine = instance()
)
}
}
| 0
|
Kotlin
|
0
| 0
|
6d796493fb7674d58b5a6029417618b609f972bd
| 4,415
|
dungeon
|
Apache License 2.0
|
src/main/kotlin/thealexhoar/longjoke/HelloWorldIntentHandler.kt
|
thealexhoar
| 138,489,700
| false
|
{"Kotlin": 69704}
|
package thealexhoar.longjoke
import com.amazon.ask.dispatcher.request.handler.HandlerInput
import com.amazon.ask.dispatcher.request.handler.RequestHandler
import com.amazon.ask.model.Response
import com.amazon.ask.request.Predicates.intentName
import java.util.*
class HelloWorldIntentHandler : RequestHandler {
override fun canHandle(input: HandlerInput?): Boolean {
return when (input) {
null -> false
else -> input.matches(intentName("HelloWorldIntent"))
}
}
var count = 1
override fun handle(input: HandlerInput?): Optional<Response> {
val speechText = "Hello world " + count++
return when (input) {
null -> Optional.empty()
else -> input.responseBuilder
.withSpeech(speechText)
.withSimpleCard("LongestJoke", speechText)
.withReprompt("Hello world " + count)
.build()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6613f6fc1de00277be09fe5bc06a965e41f0a3ad
| 954
|
longjoke
|
MIT License
|
FragmentDemo/app/src/main/java/com/renyu/fragmentdemo/fragment/MainFragment1.kt
|
r17171709
| 23,950,456
| false
| null |
package com.renyu.fragmentdemo.fragment
import android.util.Log
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
class MainFragment1(@LayoutRes layoutId: Int): Fragment(layoutId) {
override fun onResume() {
super.onResume()
check()
}
override fun onPause() {
super.onPause()
check()
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
check()
}
private fun check() {
if (isResumed && !isHidden) {
Log.d("TAGTAGTAG", "$this Visible")
} else {
Log.d("TAGTAGTAG", "$this InVisible")
}
}
}
| 8
| null |
333
| 612
|
ee75780c1187355d81bab329e62ecaad985d6832
| 672
|
StudyDemo
|
Apache License 2.0
|
simplified-viewer-audiobook/src/main/java/org/nypl/simplified/viewer/audiobook/AudioBookViewer.kt
|
jonathangreen
| 292,624,474
| true
|
{"Kotlin": 2602716, "Java": 665605, "JavaScript": 10239, "Shell": 5927, "HTML": 557, "CSS": 159}
|
package org.nypl.simplified.viewer.audiobook
import android.app.Activity
import org.nypl.simplified.books.api.Book
import org.nypl.simplified.books.api.BookFormat
import org.nypl.simplified.http.core.HTTP
import org.nypl.simplified.viewer.spi.ViewerPreferences
import org.nypl.simplified.viewer.spi.ViewerProviderType
import org.slf4j.LoggerFactory
/**
* An audio book viewer service.
*/
class AudioBookViewer : ViewerProviderType {
private val logger =
LoggerFactory.getLogger(AudioBookViewer::class.java)
override val name: String =
"org.nypl.simplified.viewer.audiobook.AudioBookViewer"
override fun canSupport(
preferences: ViewerPreferences,
book: Book,
format: BookFormat
): Boolean {
return when (format) {
is BookFormat.BookFormatEPUB,
is BookFormat.BookFormatPDF -> {
this.logger.debug("audio book viewer can only view audio books")
false
}
is BookFormat.BookFormatAudioBook ->
true
}
}
override fun open(
activity: Activity,
preferences: ViewerPreferences,
book: Book,
format: BookFormat
) {
val formatAudio =
format as BookFormat.BookFormatAudioBook
val manifest =
formatAudio.manifest!!
val params =
AudioBookPlayerParameters(
accountID = book.account,
bookID = book.id,
manifestContentType = format.contentType.fullType,
manifestFile = manifest.manifestFile,
manifestURI = manifest.manifestURI,
opdsEntry = book.entry,
userAgent = HTTP.userAgent()
)
AudioBookPlayerActivity.startActivity(activity, params)
}
}
| 0
|
Kotlin
|
0
| 0
|
d832b391188c86858158ef702f308c6b507ddb61
| 1,638
|
Simplified-Android-Core
|
Apache License 2.0
|
app/src/main/java/com/ltu/m7019e/v23/themoviedb/database/Platforms.kt
|
Jovali99
| 639,393,965
| false
| null |
package com.ltu.m7019e.v23.themoviedb.database
import com.ltu.m7019e.v23.themoviedb.model.Platform
import com.ltu.m7019e.v23.themoviedb.model.SpecificPlatform
class Platforms {
var list = mutableListOf<Platform>()
init {
list.add(Platform(SpecificPlatform(name = "PC")))
list.add(Platform(SpecificPlatform(name = "Xbox Series S/X")))
list.add(Platform(SpecificPlatform(name = "PlayStation 5")))
list.add(Platform(SpecificPlatform(name = "PlayStation 4")))
list.add(Platform(SpecificPlatform(name = "PlayStation 3")))
list.add(Platform(SpecificPlatform(name = "Xbox 360")))
list.add(Platform(SpecificPlatform(name = "Xbox One")))
list.add(Platform(SpecificPlatform(name = "Nintendo Switch")))
list.add(Platform(SpecificPlatform(name = "Linux")))
}
}
| 0
|
Kotlin
|
0
| 1
|
c6b7108fe7b912947894ad49043d3ac141e6be26
| 838
|
GameDB
|
MIT License
|
scanner/src/main/kotlin/ru/inforion/lab403/common/scanner/scanner.kt
|
inforion
| 175,944,783
| false
|
{"Kotlin": 551792, "Java": 1271}
|
@file:Suppress("unused")
package ru.inforion.lab403.common.scanner
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner
import org.reflections.util.ClasspathHelper
import org.reflections.util.ConfigurationBuilder
import ru.inforion.lab403.common.extensions.packageName
import kotlin.reflect.KClass
inline fun <reified T : Any> String.scanSubtypesOf(cl: ClassLoader? = null): Set<Class<out T>> {
val url = ClasspathHelper.forPackage(this)
val builder = ConfigurationBuilder().apply {
addUrls(url)
addScanners(SubTypesScanner())
if (cl != null) addClassLoader(cl)
}
return Reflections(builder).getSubTypesOf(T::class.java)
}
inline fun <reified T: Any> Class<T>.scanSubtypesOf(cl: ClassLoader? = null) = name.packageName().scanSubtypesOf<T>(cl)
inline fun <reified T: Any> KClass<T>.scanSubtypesOf(cl: ClassLoader? = null) = java.scanSubtypesOf(cl)
| 1
|
Kotlin
|
1
| 1
|
e42ce78aa5d230025f197b044db4a698736d1630
| 922
|
kotlin-extensions
|
MIT License
|
app/src/main/java/com/oriplastbreezefsm/features/SearchLocation/EditTextAddressTypeModel.kt
|
DebashisINT
| 630,052,678
| false
|
{"Kotlin": 13742367, "Java": 997699}
|
package com.oriplastbreezefsm.features.SearchLocation
/**
* Created by bipradip on 28-11-2016.
*/
class EditTextAddressTypeModel {
var value = ""
}
| 0
|
Kotlin
|
0
| 0
|
01878e357b293a1a67cfa0c2bdd387870736fca9
| 157
|
Oriplast
|
Apache License 2.0
|
common/src/main/kotlin/io/pilgrimdb/common/migrations/operations/Migration.kt
|
pilgrimdbio
| 188,329,665
| false
| null |
package io.pilgrimdb.common.migrations.operations
import io.pilgrimdb.common.model.ProjectState
data class Migration(
val packageName: String,
val migrationName: String,
val operations: MutableList<Operation> = mutableListOf()
) {
fun mutateState(state: ProjectState): ProjectState {
operations.forEach { it.stateForwards(state) }
return state
}
}
| 0
|
Kotlin
|
0
| 3
|
ff815a73eef0a3b83db5c8a50b3f8813f30667cc
| 387
|
pilgrimdb
|
Apache License 2.0
|
components/src/main/java/com/mercadolibre/android/andesui/message/hierarchy/AndesMessageHierarchy.kt
|
jorGonzalez291292
| 296,400,886
| false
| null |
package com.mercadolibre.android.andesui.message.hierarchy
import com.mercadolibre.android.andesui.message.AndesMessage
/**
* Utility class that does two things: Defines the possible styles an [AndesMessage] can take because it's an enum, as you can see.
* But as a bonus it gives you the proper implementation so you don't have to make any mapping.
*
* You ask me with, let's say 'QUIET', and then I'll give you a proper implementation of that style.
*
* @property hierarchy Possible styles that an [AndesMessage] may take.
*/
enum class AndesMessageHierarchy {
QUIET,
LOUD;
companion object {
fun fromString(value: String): AndesMessageHierarchy = valueOf(value.toUpperCase())
}
internal val hierarchy get() = getAndesMessageHierarchy()
private fun getAndesMessageHierarchy(): AndesMessageHierarchyInterface {
return when (this) {
QUIET -> AndesQuietMessageHierarchy
LOUD -> AndesLoudMessageHierarchy
}
}
}
| 0
| null |
0
| 1
|
5b1d7b395cb60073c044365fef9d0c205c8b68cb
| 997
|
fury_andesui-android
|
MIT License
|
app/src/main/java/edu/uwp/appfactory/rusd/data/model/RealmString.kt
|
dakotajd
| 120,720,631
| false
| null |
package edu.uwp.appfactory.rusd.data.model
import io.realm.RealmObject
/**
* Created by dakota on 8/19/17.
*/
open class RealmString() : RealmObject() {
constructor(string: String) : this() {
this.string = string
}
private var string: String = ""
override fun toString(): String {
return string
}
}
| 0
|
Kotlin
|
0
| 0
|
36fa5a7cf85ab9c6a7a005440f17bec2ec904550
| 342
|
Racine-Unified-School-District
|
MIT License
|
network/core/src/main/java/com/yigitozgumus/core/di/ServiceModule.kt
|
yigitozgumus
| 475,998,040
| false
|
{"Kotlin": 49621}
|
/*
* Created by yigitozgumus on 4/2/22, 11:44 AM
* Copyright (c) 2022 . All rights reserved.
* Last modified 4/2/22, 11:44 AM
*/
package com.yigitozgumus.core.di
import com.yigitozgumus.api.services.AllCurrenciesService
import com.yigitozgumus.api.services.MarketSearchService
import com.yigitozgumus.core.service.*
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class ServiceModule {
@Binds
@Singleton
@ServiceTypeCoinBase
abstract fun bindCoinBaseService(impl: CoinBaseService): ServiceCreator
@Binds
@Singleton
@ServiceTypeCoinGecko
abstract fun bindCoinGeckoService(impl: CoinGeckoService): ServiceCreator
companion object {
@Provides
@Singleton
fun provideAllCurrenciesService(factory: CoinBaseService): AllCurrenciesService =
factory.create(AllCurrenciesService::class.java)
@Provides
@Singleton
fun provideMarketSearchService(factory: CoinGeckoService): MarketSearchService =
factory.create(MarketSearchService::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
ca3ff32aaab6fd96fcee9f7c69098f99d10300ed
| 1,238
|
DemoCurrencyApplication
|
MIT License
|
app/src/main/kotlin/dev/soupslurpr/beautyxt/Utils.kt
|
soupslurpr
| 647,066,717
| false
|
{"Kotlin": 341145, "Rust": 40004, "Handlebars": 3740, "AIDL": 1071}
|
package dev.soupslurpr.beautyxt
import java.security.MessageDigest
fun returnHashSha256(byteArray: ByteArray): String {
return MessageDigest
.getInstance("SHA-256")
.digest(byteArray)
.joinToString("") {
"%02x".format(it)
}
}
| 33
|
Kotlin
|
7
| 90
|
58d6e0b0af365ce9f5b964107c1d030be0d7b378
| 276
|
BeauTyXT
|
ISC License
|
src/main/kotlin/no/nav/syfo/util/VeilederAPIAccessPipeline.kt
|
navikt
| 424,518,784
| false
| null |
package no.nav.syfo.behandler.api.access
import io.ktor.application.*
import io.ktor.util.pipeline.*
import no.nav.syfo.client.veiledertilgang.VeilederTilgangskontrollClient
import no.nav.syfo.domain.PersonIdentNumber
import no.nav.syfo.util.getBearerHeader
import no.nav.syfo.util.getCallId
suspend fun PipelineContext<out Unit, ApplicationCall>.validateVeilederAccess(
action: String,
personIdentToAccess: PersonIdentNumber,
veilederTilgangskontrollClient: VeilederTilgangskontrollClient,
requestBlock: suspend () -> Unit,
) {
val callId = getCallId()
val token = getBearerHeader()
?: throw IllegalArgumentException("Failed to complete the following action: $action. No Authorization header supplied")
val hasVeilederAccess = veilederTilgangskontrollClient.hasAccess(
callId = callId,
personIdentNumber = personIdentToAccess,
token = token,
)
if (hasVeilederAccess) {
requestBlock()
} else {
throw ForbiddenAccessVeilederException(
action = action,
)
}
}
class ForbiddenAccessVeilederException(
action: String,
message: String = "Denied NAVIdent access to personIdent: $action",
) : RuntimeException(message)
| 7
|
Kotlin
|
3
| 0
|
dd12b992684acda2da79c73c5364ece6d58f3dbd
| 1,236
|
isoppfolgingstilfelle
|
MIT License
|
app/src/main/java/com/qhy040404/libraryonetap/utils/tools/GPAUtils.kt
|
qhy040404
| 484,416,715
| false
| null |
package com.qhy040404.libraryonetap.utils.tools
import com.qhy040404.libraryonetap.constant.enums.GPAAlgorithm
import com.qhy040404.libraryonetap.data.tools.Grade
import com.qhy040404.libraryonetap.utils.extensions.to2Decimal
object GPAUtils {
fun calculateGPA(grades: List<Grade>, algorithm: GPAAlgorithm): Double {
var totalWeightedGP = 0.0
var totalCredits = grades.sumOf { it.credit }
grades.forEach {
runCatching {
totalWeightedGP += when (algorithm) {
GPAAlgorithm.DLUT -> it.gp * it.credit
GPAAlgorithm.STD5 -> getGpByStandard5(it.grade.toInt()) * it.credit
GPAAlgorithm.STD4 -> getGpByStandard4(it.grade.toInt()) * it.credit
GPAAlgorithm.PK4 -> getGpByPeking4(it.grade.toInt()) * it.credit
}
}.onFailure { _ ->
totalCredits -= it.credit
}
}
return (totalWeightedGP / totalCredits).to2Decimal()
}
private fun getGpByStandard5(score: Int): Double {
return when (score) {
in 95..100 -> 5.0
in 90 until 95 -> 4.5
in 85 until 90 -> 4.0
in 80 until 85 -> 3.5
in 75 until 80 -> 3.0
in 70 until 75 -> 2.5
in 65 until 70 -> 2.0
in 60 until 65 -> 1.0
else -> 0.0
}
}
private fun getGpByStandard4(score: Int): Double {
return when (score) {
in 90..100 -> 4.0
in 80 until 90 -> 3.0
in 70 until 80 -> 2.0
in 60 until 70 -> 1.0
else -> 0.0
}
}
private fun getGpByPeking4(score: Int): Double {
return when (score) {
in 90..100 -> 4.0
in 85 until 90 -> 3.7
in 82 until 85 -> 3.3
in 78 until 82 -> 3.0
in 75 until 78 -> 2.7
in 72 until 75 -> 2.3
in 68 until 72 -> 2.0
in 64 until 68 -> 1.5
in 60 until 64 -> 1.0
else -> 0.0
}
}
}
| 4
|
Kotlin
|
0
| 9
|
db5d2cf858f05a03273c5fe1e06944a713842c71
| 2,098
|
Library-One-Tap-Android
|
Apache License 2.0
|
layout-inspector/testSrc/com/android/tools/idea/layoutinspector/snapshots/LegacySnapshotLoaderTest.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.layoutinspector.snapshots
import com.android.test.testutils.TestUtils
import com.android.tools.idea.concurrency.AndroidCoroutineScope
import com.android.tools.idea.layoutinspector.metrics.statistics.SessionStatisticsImpl
import com.android.tools.idea.layoutinspector.model
import com.android.tools.idea.layoutinspector.model.InspectorModel
import com.android.tools.idea.layoutinspector.model.NotificationModel
import com.android.tools.idea.layoutinspector.util.CheckUtil.ANY_DRAW_ID
import com.android.tools.idea.layoutinspector.util.CheckUtil.assertDrawTreesEqual
import com.android.tools.idea.testing.disposable
import com.google.common.truth.Truth.assertThat
import com.google.wireless.android.sdk.stats.DynamicLayoutInspectorAttachToProcess.ClientType.SNAPSHOT_CLIENT
import com.intellij.testFramework.ProjectRule
import java.nio.file.Files
import javax.imageio.ImageIO
import kotlinx.coroutines.runBlocking
import layoutinspector.snapshots.Metadata
import org.junit.Rule
import org.junit.Test
private const val TEST_DATA_PATH = "tools/adt/idea/layout-inspector/testData"
class LegacySnapshotLoaderTest {
@get:Rule val projectRule = ProjectRule()
private val testDataPath = TestUtils.resolveWorkspacePathUnchecked(TEST_DATA_PATH)
@Test
fun loadV1Snapshot() {
val model = InspectorModel(projectRule.project, AndroidCoroutineScope(projectRule.disposable))
val notificationModel = NotificationModel(projectRule.project)
val stats = SessionStatisticsImpl(SNAPSHOT_CLIENT)
val snapshotMetadata =
LegacySnapshotLoader()
.loadFile(testDataPath.resolve("legacy-snapshot-v1.li"), model, notificationModel, stats)
// We don't get any metadata from V1, so just verify the version
assertThat(snapshotMetadata.snapshotVersion).isEqualTo(ProtocolVersion.Version1)
validateModel(model)
}
@Test
fun loadV3Snapshot() {
val model = InspectorModel(projectRule.project, AndroidCoroutineScope(projectRule.disposable))
val notificationModel = NotificationModel(projectRule.project)
val stats = SessionStatisticsImpl(SNAPSHOT_CLIENT)
val snapshotMetadata =
LegacySnapshotLoader()
.loadFile(testDataPath.resolve("legacy-snapshot-v3.li"), model, notificationModel, stats)
assertThat(snapshotMetadata.snapshotVersion).isEqualTo(ProtocolVersion.Version3)
assertThat(snapshotMetadata.apiLevel).isEqualTo(27)
assertThat(snapshotMetadata.processName).isEqualTo("com.example.myapplication")
assertThat(snapshotMetadata.containsCompose).isFalse()
assertThat(snapshotMetadata.liveDuringCapture).isFalse()
assertThat(snapshotMetadata.source).isEqualTo(Metadata.Source.STUDIO)
assertThat(snapshotMetadata.sourceVersion).isEqualTo("dev build")
validateModel(model)
}
private fun validateModel(model: InspectorModel) {
val window = model.windows.values.single()
runBlocking { window.refreshImages(1.0) }
val expected =
model(projectRule.disposable) {
view(ANY_DRAW_ID) {
Files.newInputStream(testDataPath.resolve("legacy-snapshot.png")).use { imageInput ->
image(ImageIO.read(imageInput))
}
view(ANY_DRAW_ID) {
view(ANY_DRAW_ID)
view(ANY_DRAW_ID) {
view(ANY_DRAW_ID) {
view(ANY_DRAW_ID) { view(ANY_DRAW_ID) { view(ANY_DRAW_ID) } }
view(ANY_DRAW_ID) {
view(ANY_DRAW_ID) {
view(ANY_DRAW_ID)
view(ANY_DRAW_ID)
}
view(ANY_DRAW_ID)
}
}
}
}
view(ANY_DRAW_ID)
view(ANY_DRAW_ID)
}
}
assertDrawTreesEqual(expected.root, model.root)
}
}
| 5
| null |
230
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 4,401
|
android
|
Apache License 2.0
|
vector/src/main/java/im/vector/app/features/analytics/plan/Signup.kt
|
tchapgouv
| 340,329,238
| 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.analytics.plan
import im.vector.app.features.analytics.itf.VectorAnalyticsEvent
// GENERATED FILE, DO NOT EDIT. FOR MORE INFORMATION VISIT
// https://github.com/matrix-org/matrix-analytics-events/
/**
* Triggered once onboarding has completed, but only if the user registered a
* new account.
*/
data class Signup(
/**
* The type of authentication that was used to sign up.
*/
val authenticationType: AuthenticationType,
) : VectorAnalyticsEvent {
enum class AuthenticationType(val rawValue: String) {
/**
* Social login using Apple.
*/
Apple("Apple"),
/**
* Social login using Facebook.
*/
Facebook("Facebook"),
/**
* Social login using GitHub.
*/
GitHub("GitHub"),
/**
* Social login using GitLab.
*/
GitLab("GitLab"),
/**
* Social login using Google.
*/
Google("Google"),
/**
* Registration using some other mechanism such as fallback.
*/
Other("Other"),
/**
* Registration with a username and password.
*/
Password("<PASSWORD>"),
/**
* Registration using another SSO provider.
*/
SSO("SSO"),
}
override fun getName() = "Signup"
override fun getProperties(): Map<String, Any>? {
return mutableMapOf<String, Any>().apply {
put("authenticationType", authenticationType.rawValue)
}.takeIf { it.isNotEmpty() }
}
}
| 86
|
Kotlin
|
8
| 9
|
8781b6bc4c7298ee137571bb574226ff75bd7519
| 2,217
|
tchap-android
|
Apache License 2.0
|
app/src/main/kotlin/dev/katanagari7c1/wolverine/presentation/base/DialogActivity.kt
|
katanagari7c1
| 92,713,057
| false
| null |
package dev.katanagari7c1.wolverine.presentation.base
import android.app.ProgressDialog
import android.content.Context
import android.view.inputmethod.InputMethodManager
import org.jetbrains.anko.indeterminateProgressDialog
abstract class DialogActivity: ToolbarActivity() {
var activeDialog: ProgressDialog? = null
fun showLoading(messageId:Int) {
this.activeDialog = indeterminateProgressDialog(messageId)
this.activeDialog?.show()
}
fun hideLoading() {
this.activeDialog?.dismiss()
this.activeDialog = null
}
override fun onDestroy() {
super.onDestroy()
hideLoading()
}
}
| 1
| null |
1
| 1
|
f7298ad8b7ec7fe326a17ca421e21e3ddd652694
| 601
|
wolverine-comics-kotlin
|
MIT License
|
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/DocBadgePlus.kt
|
alexzhirkevich
| 636,411,288
| false
| null |
/*
* Copyright (c) 2023-2024. Compose Cupertino project and open source contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.alexzhirkevich.cupertino.icons.outlined
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Outlined.DocBadgePlus: ImageVector
get() {
if (_docBadgePlus != null) {
return _docBadgePlus!!
}
_docBadgePlus = Builder(name = "DocBadgePlus", defaultWidth = 24.7148.dp, defaultHeight =
29.543.dp, viewportWidth = 24.7148f, viewportHeight = 29.543f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.0039f, 16.0781f)
curveTo(5.3203f, 16.043f, 5.625f, 16.0195f, 5.9297f, 16.0195f)
curveTo(6.2461f, 16.0195f, 6.5508f, 16.043f, 6.8906f, 16.0781f)
lineTo(6.8906f, 5.918f)
curveTo(6.8906f, 4.7578f, 7.5117f, 4.0898f, 8.7305f, 4.0898f)
lineTo(13.9453f, 4.0898f)
lineTo(13.9453f, 10.8984f)
curveTo(13.9453f, 12.375f, 14.6836f, 13.1016f, 16.1484f, 13.1016f)
lineTo(22.8281f, 13.1016f)
lineTo(22.8281f, 23.625f)
curveTo(22.8281f, 24.7969f, 22.207f, 25.4414f, 20.9883f, 25.4414f)
lineTo(13.2422f, 25.4414f)
curveTo(13.0898f, 26.1094f, 12.832f, 26.7539f, 12.4922f, 27.3281f)
lineTo(21.082f, 27.3281f)
curveTo(23.5078f, 27.3281f, 24.7148f, 26.0977f, 24.7148f, 23.6602f)
lineTo(24.7148f, 13.0195f)
curveTo(24.7148f, 11.5078f, 24.5391f, 10.8516f, 23.6016f, 9.8906f)
lineTo(17.1445f, 3.3164f)
curveTo(16.2539f, 2.4023f, 15.5156f, 2.2031f, 14.2031f, 2.2031f)
lineTo(8.6367f, 2.2031f)
curveTo(6.2227f, 2.2031f, 5.0039f, 3.4453f, 5.0039f, 5.8828f)
close()
moveTo(15.7148f, 10.6758f)
lineTo(15.7148f, 4.4531f)
lineTo(22.4648f, 11.332f)
lineTo(16.3594f, 11.332f)
curveTo(15.8906f, 11.332f, 15.7148f, 11.1445f, 15.7148f, 10.6758f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.9531f, 29.543f)
curveTo(9.1758f, 29.543f, 11.9062f, 26.8359f, 11.9062f, 23.5898f)
curveTo(11.9062f, 20.3203f, 9.2227f, 17.6367f, 5.9531f, 17.6367f)
curveTo(2.6836f, 17.6367f, 0.0f, 20.3203f, 0.0f, 23.5898f)
curveTo(0.0f, 26.8594f, 2.6836f, 29.543f, 5.9531f, 29.543f)
close()
moveTo(5.9531f, 27.3164f)
curveTo(5.5195f, 27.3164f, 5.2383f, 27.0234f, 5.2383f, 26.6016f)
lineTo(5.2383f, 24.3047f)
lineTo(2.9414f, 24.3047f)
curveTo(2.5195f, 24.3047f, 2.2266f, 24.0234f, 2.2266f, 23.5898f)
curveTo(2.2266f, 23.1562f, 2.5195f, 22.8633f, 2.9414f, 22.8633f)
lineTo(5.2383f, 22.8633f)
lineTo(5.2383f, 20.5781f)
curveTo(5.2383f, 20.1562f, 5.5195f, 19.8633f, 5.9531f, 19.8633f)
curveTo(6.3867f, 19.8633f, 6.668f, 20.1562f, 6.668f, 20.5781f)
lineTo(6.668f, 22.8633f)
lineTo(8.9531f, 22.8633f)
curveTo(9.3867f, 22.8633f, 9.6797f, 23.1562f, 9.6797f, 23.5898f)
curveTo(9.6797f, 24.0234f, 9.3867f, 24.3047f, 8.9531f, 24.3047f)
lineTo(6.668f, 24.3047f)
lineTo(6.668f, 26.6016f)
curveTo(6.668f, 27.0234f, 6.3867f, 27.3164f, 5.9531f, 27.3164f)
close()
}
}
.build()
return _docBadgePlus!!
}
private var _docBadgePlus: ImageVector? = null
| 18
| null |
31
| 848
|
54bfbb58f6b36248c5947de343567903298ee308
| 5,347
|
compose-cupertino
|
Apache License 2.0
|
app/src/main/java/moe/feng/danmaqua/ui/settings/list/LicenseItemViewDelegate.kt
|
danmaqua
| 237,640,502
| false
| null |
package moe.feng.danmaqua.ui.settings.list
import android.view.View
import androidx.content.launchViewUrl
import moe.feng.danmaqua.R
import moe.feng.danmaqua.databinding.LicensesItemLayoutBinding
import moe.feng.danmaqua.model.LicenseItem
import moe.feng.danmaqua.ui.common.list.*
class LicenseItemViewDelegate
: ItemBasedSimpleViewBinder<LicenseItem, LicenseItemViewDelegate.ViewHolder>() {
override val viewHolderCreator: ViewHolderCreator<ViewHolder>
= dataBindingViewHolderCreatorOf(R.layout.licenses_item_layout)
class ViewHolder(dataBinding: LicensesItemLayoutBinding) :
DataBindingViewHolder<LicenseItem, LicensesItemLayoutBinding>(dataBinding) {
fun onCardClick(view: View) {
context.launchViewUrl(data.url)
}
}
}
| 1
|
Kotlin
|
9
| 137
|
68694b9f1e575af8541680afe96e2a3108338828
| 788
|
danmaqua-android
|
Apache License 2.0
|
app/src/main/java/ro/alexmamo/firestorecleanarchitecture/presentation/books/components/BooksContent.kt
|
alexmamo
| 413,736,186
| false
| null |
package eif.viko.books_feature.presentation.books.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import eif.viko.books_feature.domain.repository.Books
@Composable
fun BooksContent(
padding: PaddingValues,
books: Books,
deleteBook: (bookId: String) -> Unit
) {
LazyColumn(
modifier = Modifier.fillMaxSize().padding(padding)
) {
items(
items = books
) { book ->
BookCard(
book = book,
deleteBook = {
book.id?.let { bookId ->
deleteBook(bookId)
}
}
)
}
}
}
| 0
| null |
31
| 98
|
354d33ad5811aae9d3b791386111c47452b4207b
| 959
|
FirestoreCleanArchitectureApp
|
Apache License 2.0
|
src/test/kotlin/dev/shtanko/algorithms/leetcode/PacificAtlanticWaterFlowTest.kt
|
ashtanko
| 203,993,092
| false
| null |
/*
* Copyright 2021 Oleksii Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.stream.Stream
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class PacificAtlanticWaterFlowTest<out T : PacificAtlanticWaterFlow>(private val strategy: T) {
private class InputArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
arrayOf(
intArrayOf(1, 2, 2, 3, 5),
intArrayOf(3, 2, 3, 4, 4),
intArrayOf(2, 4, 5, 3, 1),
intArrayOf(6, 7, 1, 4, 5),
intArrayOf(5, 1, 1, 2, 4),
),
listOf(
listOf(0, 4),
listOf(1, 3),
listOf(1, 4),
listOf(2, 2),
listOf(3, 0),
listOf(3, 1),
listOf(4, 0),
),
),
)
}
@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `pacific atlantic test`(matrix: Array<IntArray>, expected: List<List<Int>>) {
val actual = strategy.perform(matrix)
assertThat(actual).isEqualTo(expected)
}
}
class PacificAtlanticBFSTest : PacificAtlanticWaterFlowTest<PacificAtlanticBFS>(PacificAtlanticBFS())
class PacificAtlanticDFSTest : PacificAtlanticWaterFlowTest<PacificAtlanticDFS>(PacificAtlanticDFS())
| 4
| null |
0
| 19
|
5bfa4b0dd30d515117d112b5d061e9235e444d13
| 2,351
|
kotlab
|
Apache License 2.0
|
app/src/main/java/cn/cqautotest/sunnybeach/app/AppApplication.kt
|
anjiemo
| 378,095,612
| false
| null |
package cn.cqautotest.sunnybeach.app
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.res.Resources
import android.net.ConnectivityManager
import android.net.Network
import android.os.Build
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.work.Configuration
import androidx.work.Constraints
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import cn.cqautotest.sunnybeach.R
import cn.cqautotest.sunnybeach.aop.Log
import cn.cqautotest.sunnybeach.db.CookieRoomDatabase
import cn.cqautotest.sunnybeach.db.CookieRoomDatabase.Companion.getDatabase
import cn.cqautotest.sunnybeach.http.glide.GlideApp
import cn.cqautotest.sunnybeach.http.interceptor.accountInterceptor
import cn.cqautotest.sunnybeach.http.model.RequestHandler
import cn.cqautotest.sunnybeach.http.model.RequestServer
import cn.cqautotest.sunnybeach.ktx.resetConfiguration
import cn.cqautotest.sunnybeach.manager.ActivityManager
import cn.cqautotest.sunnybeach.other.*
import cn.cqautotest.sunnybeach.util.PushHelper
import cn.cqautotest.sunnybeach.work.CacheCleanupWorker
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonToken
import com.hjq.bar.TitleBar
import com.hjq.gson.factory.GsonFactory
import com.hjq.http.EasyConfig
import com.hjq.http.config.IRequestApi
import com.hjq.http.model.HttpHeaders
import com.hjq.http.model.HttpParams
import com.hjq.toast.ToastUtils
import com.hjq.umeng.UmengClient
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import dagger.hilt.android.HiltAndroidApp
import okhttp3.OkHttpClient
import timber.log.Timber
import java.io.InputStream
import java.util.concurrent.TimeUnit
/**
* author : Android 轮子哥 & A Lonely Cat
* github : https://github.com/getActivity/AndroidProject-Kotlin
* time : 2018/10/18
* desc : 应用入口
*/
@HiltAndroidApp
class AppApplication : Application(), Configuration.Provider {
@Log("启动耗时")
override fun onCreate() {
super.onCreate()
mApp = this
initSdk(this)
}
override fun onLowMemory() {
super.onLowMemory()
// 清理所有图片内存缓存
GlideApp.get(this).onLowMemory()
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
// 根据手机内存剩余情况清理图片内存缓存
GlideApp.get(this).onTrimMemory(level)
}
override fun getWorkManagerConfiguration(): Configuration = Configuration.Builder().also {
if (AppConfig.isDebug()) {
it.setMinimumLoggingLevel(android.util.Log.INFO)
}
}.build()
override fun getResources(): Resources = super.getResources().apply {
resetConfiguration()
}
companion object {
private lateinit var mApp: AppApplication
private lateinit var database: CookieRoomDatabase
private const val sWeatherApiToken = "7xoSm4k7GIK8X8E1"
fun getInstance() = mApp
fun getDatabase() = database
fun getWeatherApiToken(): String {
return sWeatherApiToken
}
/**
* 初始化一些第三方框架
*/
fun initSdk(application: Application) {
// 设置标题栏初始化器
TitleBar.setDefaultStyle(TitleBarStyle())
// 设置全局的 Header 构建器
SmartRefreshLayout.setDefaultRefreshHeaderCreator { context: Context, _: RefreshLayout ->
ClassicsHeader(context)
}
// 设置全局的 Footer 构建器
SmartRefreshLayout.setDefaultRefreshFooterCreator { context: Context, _: RefreshLayout ->
SmartBallPulseFooter(context)
}
// 设置全局初始化器
SmartRefreshLayout.setDefaultRefreshInitializer { _: Context, layout: RefreshLayout ->
// 刷新头部是否跟随内容偏移
layout.setEnableHeaderTranslationContent(true)
// 刷新尾部是否跟随内容偏移
.setEnableFooterTranslationContent(true)
// 加载更多是否跟随内容偏移
.setEnableFooterFollowWhenNoMoreData(true)
// 内容不满一页时是否可以上拉加载更多
.setEnableLoadMoreWhenContentNotFull(false)
// 仿苹果越界效果开关
.setEnableOverScrollDrag(false)
}
// 初始化吐司
ToastUtils.init(application, ToastStyle())
// 设置调试模式
ToastUtils.setDebugMode(AppConfig.isDebug())
// 设置 Toast 拦截器
ToastUtils.setInterceptor(ToastLogInterceptor())
// 本地异常捕捉
CrashHandler.register(application)
// 友盟统计、登录、分享 SDK
UmengClient.init(application, AppConfig.isLogEnable())
// Bugly 异常捕捉
CrashReport.initCrashReport(application, AppConfig.getBuglyId(), AppConfig.isDebug())
// Activity 栈管理初始化
ActivityManager.getInstance().init(application)
// MMKV 初始化
MMKV.initialize(application)
// 网络请求框架初始化
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(accountInterceptor)
.build()
EasyConfig.with(okHttpClient)
// 是否打印日志
.setLogEnabled(AppConfig.isLogEnable())
// 设置服务器配置
.setServer(RequestServer())
// 设置请求处理策略
.setHandler(RequestHandler(application))
// 设置请求重试次数
.setRetryCount(1)
.setInterceptor { _: IRequestApi, _: HttpParams, headers: HttpHeaders ->
// 添加全局请求头
// headers.put("token", "66666666666")
headers.put("deviceOaid", UmengClient.getDeviceOaid())
headers.put("versionName", AppConfig.getVersionName())
headers.put("versionCode", AppConfig.getVersionCode().toString())
}
.into()
// 设置 Json 解析容错监听
GsonFactory.setJsonCallback { typeToken: TypeToken<*>, fieldName: String?, jsonToken: JsonToken ->
// 上报到 Bugly 错误列表
CrashReport.postCatchedException(IllegalArgumentException("类型解析异常:$typeToken#$fieldName,后台返回的类型为:$jsonToken"))
}
// 初始化日志打印
if (AppConfig.isLogEnable()) {
Timber.plant(DebugLoggerTree())
}
// MiPush 初始化
PushHelper.init(application)
// 注册网络状态变化监听
val connectivityManager: ConnectivityManager? = ContextCompat.getSystemService(application, ConnectivityManager::class.java)
if (connectivityManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
val topActivity: Activity? = ActivityManager.getInstance().getTopActivity()
if (topActivity !is LifecycleOwner) {
return
}
val lifecycleOwner: LifecycleOwner = topActivity
if (lifecycleOwner.lifecycle.currentState != Lifecycle.State.RESUMED) {
return
}
ToastUtils.show(R.string.common_network_error)
}
})
}
// 初始化 Room 数据库
database = getDatabase(application)
// 初始化 Glide 的 Cookie 管理
Glide.get(application)
.registry
.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(okHttpClient))
initCacheCleanWork(application)
}
/**
* 初始化 缓存清理工作
*
* @param application Application
*/
private fun initCacheCleanWork(application: Application) {
// 构造工作执行的约束条件
val builder = Constraints.Builder() // 电池电量不低
.setRequiresBatteryNotLow(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 设备处于空闲状态
builder.setRequiresDeviceIdle(true)
}
val constraints = builder.build()
// 定期工作请求(间隔三天工作一次)
val workRequest = PeriodicWorkRequest.Builder(CacheCleanupWorker::class.java, 3, TimeUnit.DAYS) // 设置约束条件
.setConstraints(constraints) // 符合约束条件后,延迟1分钟执行
.setInitialDelay(0, TimeUnit.MINUTES)
.build()
val wm = WorkManager.getInstance(application)
// 将工作加入队列中
wm.enqueue(workRequest)
}
}
}
| 1
| null |
26
| 95
|
a2402da1cb6af963c829a69d9783053f15d866b5
| 9,105
|
SunnyBeach
|
Apache License 2.0
|
core/src/main/java/com/aidventory/core/common/designsystem/component/dialogs/AppDialog.kt
|
yuriikonovalov
| 615,443,609
| false
| null |
package com.aidventory.core.common.designsystem.component.dialogs
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@Composable
fun AppDialog(
open: Boolean,
title: @Composable () -> Unit,
content: @Composable ColumnScope.() -> Unit,
negativeButtonText: String,
onNegativeButtonClick: () -> Unit,
modifier: Modifier = Modifier,
onDismiss: () -> Unit = onNegativeButtonClick,
positiveButtonText: String = "",
onPositiveButtonClick: (() -> Unit)? = null,
secondPositiveButtonText: String = "",
onSecondPositiveButtonClick: (() -> Unit)? = null,
properties: DialogProperties = DialogProperties()
) {
if (open)
Dialog(onDismissRequest = onDismiss, properties = properties) {
Surface(
modifier = modifier,
shape = MaterialTheme.shapes.large,
border = BorderStroke(0.5.dp, Color.DarkGray)
) {
Column {
title()
Column(modifier = Modifier.padding(bottom = 16.dp)) {
content()
}
Divider(modifier = Modifier.fillMaxWidth(), thickness = 0.5.dp)
when {
onPositiveButtonClick != null && onSecondPositiveButtonClick != null -> {
DoublePositiveButton(
firstPositiveButtonText = positiveButtonText,
onFirstPositiveButtonClick = onPositiveButtonClick,
secondPositiveButtonText = secondPositiveButtonText,
onSecondPositiveButtonClick = onSecondPositiveButtonClick,
negativeButtonText = negativeButtonText,
onNegativeButtonClick = onNegativeButtonClick
)
}
onPositiveButtonClick != null -> {
SinglePositiveButton(
firstPositiveButtonText = positiveButtonText,
onFirstPositiveButtonClick = onPositiveButtonClick,
negativeButtonText = negativeButtonText,
onNegativeButtonClick = onNegativeButtonClick
)
}
else -> {
NegativeButton(
modifier = Modifier.fillMaxWidth(),
text = negativeButtonText,
onClick = onNegativeButtonClick
)
}
}
}
}
}
}
@Composable
fun DoublePositiveButton(
firstPositiveButtonText: String,
onFirstPositiveButtonClick: () -> Unit,
secondPositiveButtonText: String,
onSecondPositiveButtonClick: (() -> Unit),
negativeButtonText: String,
onNegativeButtonClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Column(modifier = modifier) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
) {
PositiveButton(
modifier = Modifier.weight(1f),
text = firstPositiveButtonText,
onClick = onFirstPositiveButtonClick
)
Box(
modifier = Modifier
.fillMaxHeight()
.width(0.5.dp)
.background(Color.Gray)
)
PositiveButton(
modifier = Modifier.weight(1f),
text = secondPositiveButtonText,
onClick = onSecondPositiveButtonClick
)
}
Divider(modifier = Modifier.fillMaxWidth(), thickness = 0.5.dp)
NegativeButton(
modifier = Modifier.fillMaxWidth(),
text = negativeButtonText,
onClick = onNegativeButtonClick
)
}
}
@Composable
fun SinglePositiveButton(
firstPositiveButtonText: String,
onFirstPositiveButtonClick: () -> Unit,
negativeButtonText: String,
onNegativeButtonClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
) {
NegativeButton(
modifier = Modifier.weight(1f),
text = negativeButtonText,
onClick = onNegativeButtonClick
)
Box(
modifier = Modifier
.fillMaxHeight()
.width(0.5.dp)
.background(Color.Gray)
)
PositiveButton(
modifier = Modifier.weight(1f),
text = firstPositiveButtonText,
onClick = onFirstPositiveButtonClick
)
}
}
@Composable
fun AppDialogTitle(
text: String,
modifier: Modifier = Modifier
) {
Text(
modifier = modifier.padding(16.dp),
text = text,
style = MaterialTheme.typography.titleMedium
)
}
@Composable
fun AppDialogMessageContent(
text: String,
modifier: Modifier = Modifier
) {
Text(
modifier = modifier.padding(horizontal = 16.dp),
text = text,
style = MaterialTheme.typography.bodyMedium
)
}
@Composable
private fun PositiveButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
TextButton(
modifier = modifier,
onClick = onClick,
) {
Text(text = text)
}
}
@Composable
private fun NegativeButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
TextButton(
modifier = modifier,
onClick = onClick,
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error),
) {
Text(text = text)
}
}
| 0
|
Kotlin
|
0
| 0
|
f6605489ce47b35b75e0628e6be64372eb5518e6
| 7,032
|
aidventory
|
MIT License
|
src/main/kotlin/com/exactpro/th2/codec/util/DebugUtil.kt
|
th2-net
| 315,864,047
| false
| null |
/*
* Copyright 2020-2020 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.th2.codec.util
import com.google.protobuf.GeneratedMessageV3
import com.google.protobuf.util.JsonFormat
fun GeneratedMessageV3.toDebugString(): String {
return JsonFormat.printer().omittingInsignificantWhitespace().includingDefaultValueFields().print(this)
}
| 1
|
Kotlin
|
2
| 0
|
a263ee3f95e4bd98fc79df0c368311e17fbc6764
| 920
|
th2-codec
|
Apache License 2.0
|
feature/welcome/src/main/java/org/expenny/feature/welcome/WelcomeViewModel.kt
|
expenny-application
| 712,607,222
| false
|
{"Kotlin": 1159524}
|
package org.expenny.feature.welcome
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import org.expenny.core.ui.base.ExpennyViewModel
import org.expenny.feature.welcome.contract.WelcomeAction
import org.expenny.feature.welcome.contract.WelcomeEvent
import javax.inject.Inject
@HiltViewModel
internal class WelcomeViewModel @Inject constructor() : ExpennyViewModel<WelcomeAction>() {
private val _event = MutableSharedFlow<WelcomeEvent>()
val event: SharedFlow<WelcomeEvent> = _event.asSharedFlow()
override fun onAction(action: WelcomeAction) {
when (action) {
is WelcomeAction.OnCtaClick -> handleOnCtaClick()
}
}
private fun handleOnCtaClick() {
viewModelScope.launch {
_event.emit(WelcomeEvent.NavigateToProfileSetup)
}
}
}
| 0
|
Kotlin
|
3
| 42
|
7e4b8e1a5dfacf5799d5ace2e72cd21f002d6311
| 1,022
|
expenny-android
|
Apache License 2.0
|
app/src/main/java/com/krygodev/singlesplanet/profile/ProfileEvent.kt
|
krygo-dev
| 419,788,067
| false
|
{"Kotlin": 155940}
|
package com.krygodev.singlesplanet.profile
import android.net.Uri
sealed class ProfileEvent {
data class UpdateInterestedGender(val value: String): ProfileEvent()
data class UpdateBio(val value: String): ProfileEvent()
data class UpdatePhoto(val value: Uri): ProfileEvent()
data class UpdateSearchDistance(val value: Float): ProfileEvent()
data class UpdateSearchAge(val value: List<Float>): ProfileEvent()
object UpdateUserData: ProfileEvent()
object SignOut: ProfileEvent()
object GetUserData: ProfileEvent()
}
| 0
|
Kotlin
|
0
| 0
|
7c4383045a9cf6f6b13aeaa5f016ae714d5dcf1c
| 547
|
Singles-Planet-Dating-Mobile-App
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.