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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/configurationImplementations.kt
|
drewhannay
| 285,109,025
| true
|
{"Kotlin": 1180486, "CSS": 20670, "JavaScript": 14795, "TypeScript": 7384, "Java": 1484}
|
@file:Suppress("FunctionName")
package org.jetbrains.dokka.gradle
import com.android.build.gradle.api.AndroidSourceSet
import com.fasterxml.jackson.annotation.JsonIgnore
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.gradle.util.ConfigureUtil
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.DokkaConfiguration.*
import org.jetbrains.dokka.DokkaDefaults
import org.jetbrains.dokka.DokkaSourceSetID
import org.jetbrains.dokka.Platform
import java.io.File
import java.net.URL
import java.util.concurrent.Callable
import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.memberProperties
import org.gradle.api.tasks.SourceSet as GradleSourceSet
import org.jetbrains.kotlin.gradle.model.SourceSet as KotlinSourceSet
class GradleSourceRootImpl : SourceRoot {
override var path: String = ""
set(value) {
field = File(value).absolutePath
}
override fun toString(): String = path
}
open class GradleDokkaSourceSet constructor(
@get:JsonIgnore @Transient @get:Input val name: String,
@get:JsonIgnore @Transient @get:Internal internal val project: Project
) : DokkaSourceSet {
@Input
@Optional
override var classpath: List<String> = emptyList()
@Input
override var moduleDisplayName: String = ""
@Input
override var displayName: String = ""
@get:Internal
override val sourceSetID: DokkaSourceSetID = DokkaSourceSetID(project, name)
@Input
override var sourceRoots: MutableList<SourceRoot> = mutableListOf()
@Input
override var dependentSourceSets: MutableSet<DokkaSourceSetID> = mutableSetOf()
@Input
override var samples: List<String> = emptyList()
@Input
override var includes: List<String> = emptyList()
@Input
override var includeNonPublic: Boolean = DokkaDefaults.includeNonPublic
@Input
override var includeRootPackage: Boolean = DokkaDefaults.includeRootPackage
@Input
override var reportUndocumented: Boolean = DokkaDefaults.reportUndocumented
@Input
override var skipEmptyPackages: Boolean = DokkaDefaults.skipEmptyPackages
@Input
override var skipDeprecated: Boolean = DokkaDefaults.skipDeprecated
@Input
override var jdkVersion: Int = DokkaDefaults.jdkVersion
@Input
override var sourceLinks: MutableList<SourceLinkDefinition> = mutableListOf()
@Input
override var perPackageOptions: MutableList<PackageOptions> = mutableListOf()
@Input
override var externalDocumentationLinks: MutableList<ExternalDocumentationLink> = mutableListOf()
@Input
@Optional
override var languageVersion: String? = null
@Input
@Optional
override var apiVersion: String? = null
@Input
override var noStdlibLink: Boolean = DokkaDefaults.noStdlibLink
@Input
override var noJdkLink: Boolean = DokkaDefaults.noJdkLink
@Input
var noAndroidSdkLink: Boolean = false
@Input
override var suppressedFiles: List<String> = emptyList()
@Input
override var analysisPlatform: Platform = DokkaDefaults.analysisPlatform
@Input
@Optional
var platform: String? = null
@JsonIgnore
@Internal
@Transient
var collectKotlinTasks: (() -> List<Any?>?)? = null
fun DokkaSourceSetID(sourceSetName: String): DokkaSourceSetID {
return DokkaSourceSetID(project, sourceSetName)
}
fun dependsOn(sourceSet: GradleSourceSet) {
dependsOn(DokkaSourceSetID(sourceSet.name))
}
fun dependsOn(sourceSet: DokkaSourceSet) {
dependsOn(sourceSet.sourceSetID)
}
fun dependsOn(sourceSetName: String) {
dependsOn(DokkaSourceSetID(sourceSetName))
}
fun dependsOn(sourceSetID: DokkaSourceSetID) {
dependentSourceSets.add(sourceSetID)
}
fun kotlinTasks(taskSupplier: Callable<List<Any>>) {
collectKotlinTasks = { taskSupplier.call() }
}
fun kotlinTasks(closure: Closure<Any?>) {
collectKotlinTasks = { closure.call() as? List<Any?> }
}
fun sourceRoot(c: Closure<Unit>) {
val configured = ConfigureUtil.configure(c, GradleSourceRootImpl())
sourceRoots.add(configured)
}
fun sourceRoot(action: Action<in GradleSourceRootImpl>) {
val sourceRoot = GradleSourceRootImpl()
action.execute(sourceRoot)
sourceRoots.add(sourceRoot)
}
fun sourceLink(c: Closure<Unit>) {
val configured = ConfigureUtil.configure(c, GradleSourceLinkDefinitionImpl())
sourceLinks.add(configured)
}
fun sourceLink(action: Action<in GradleSourceLinkDefinitionImpl>) {
val sourceLink = GradleSourceLinkDefinitionImpl()
action.execute(sourceLink)
sourceLinks.add(sourceLink)
}
fun perPackageOption(c: Closure<Unit>) {
val configured = ConfigureUtil.configure(c, GradlePackageOptionsImpl())
perPackageOptions.add(configured)
}
fun perPackageOption(action: Action<in GradlePackageOptionsImpl>) {
val option = GradlePackageOptionsImpl()
action.execute(option)
perPackageOptions.add(option)
}
fun externalDocumentationLink(c: Closure<Unit>) {
val link = ConfigureUtil.configure(c, GradleExternalDocumentationLinkImpl())
externalDocumentationLinks.add(ExternalDocumentationLink.Builder(link.url, link.packageListUrl).build())
}
fun externalDocumentationLink(action: Action<in GradleExternalDocumentationLinkImpl>) {
val link = GradleExternalDocumentationLinkImpl()
action.execute(link)
externalDocumentationLinks.add(ExternalDocumentationLink.Builder(link.url, link.packageListUrl).build())
}
}
fun GradleDokkaSourceSet.dependsOn(sourceSet: KotlinSourceSet) {
dependsOn(DokkaSourceSetID(sourceSet.name))
}
fun GradleDokkaSourceSet.dependsOn(sourceSet: org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet) {
dependsOn(DokkaSourceSetID(sourceSet.name))
}
fun GradleDokkaSourceSet.dependsOn(sourceSet: AndroidSourceSet) {
dependsOn(DokkaSourceSetID(sourceSet.name))
}
class GradleSourceLinkDefinitionImpl : SourceLinkDefinition {
override var path: String = ""
override var url: String = ""
override var lineSuffix: String? = null
}
class GradleExternalDocumentationLinkImpl : ExternalDocumentationLink {
override var url: URL = URL("http://")
override var packageListUrl: URL = URL("http://")
}
class GradleDokkaModuleDescription : DokkaModuleDescription {
override var name: String = ""
override var path: String = ""
override var docFile: String = ""
}
class GradleDokkaConfigurationImpl : DokkaConfiguration {
override var outputDir: String = ""
override var cacheRoot: String? = DokkaDefaults.cacheRoot
override var offlineMode: Boolean = DokkaDefaults.offlineMode
override var failOnWarning: Boolean = DokkaDefaults.failOnWarning
override var sourceSets: List<GradleDokkaSourceSet> = emptyList()
override var pluginsClasspath: List<File> = emptyList()
override var pluginsConfiguration: Map<String, String> = mutableMapOf()
override var modules: List<GradleDokkaModuleDescription> = emptyList()
}
class GradlePackageOptionsImpl : PackageOptions {
override var prefix: String = ""
override var includeNonPublic: Boolean = DokkaDefaults.includeNonPublic
override var reportUndocumented: Boolean = DokkaDefaults.reportUndocumented
override var skipDeprecated: Boolean = DokkaDefaults.skipDeprecated
override var suppress: Boolean = DokkaDefaults.suppress
}
internal fun GradleDokkaSourceSet.copy(): GradleDokkaSourceSet {
val newObj = GradleDokkaSourceSet(this.name, this.project)
this::class.memberProperties.forEach { field ->
if (field is KMutableProperty<*>) {
when (val value = field.getter.call(this)) {
is List<*> -> field.setter.call(newObj, value.toMutableList())
is Set<*> -> field.setter.call(newObj, value.toMutableSet())
else -> field.setter.call(newObj, field.getter.call(this))
}
}
}
return newObj
}
| 0
| null |
0
| 0
|
299d5ce889242cd352d4305b622cfe39c4e2f67d
| 8,259
|
dokka
|
Apache License 2.0
|
example/src/main/java/io/y2k/replexample/MainActivity.kt
|
y2k
| 166,288,356
| false
| null |
package io.y2k.replexample
import android.app.Activity
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.y2k.remoteconnector.Server
import y2k.remoteembederepl.Repl
import java.io.Closeable
class MainActivity : Activity() {
private lateinit var server: Closeable
override fun onStart() {
super.onStart()
server = Server.start(Repl::eval)
if (false)
NotificationManagerCompat
.from(App.instance!!)
.notify(
1,
NotificationCompat.Builder(App.instance!!, "default")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle("Hello")
.setContentText("World")
// .setContentIntent(
// PendingIntent.getActivity(
// App.instance!!,
// 1,
// Intent(Intent.ACTION_VIEW, Uri.parse("https://youtu.be/dQw4w9WgXcQ")),
// PendingIntent.FLAG_UPDATE_CURRENT
// )
// )
.build()
)
}
override fun onStop() {
super.onStop()
server.close()
}
}
class App : Application() {
override fun onCreate() {
super.onCreate()
instance = this
setChannel()
}
private fun setChannel() {
val nm = NotificationManagerCompat.from(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val nc = NotificationChannel("default", "default", NotificationManager.IMPORTANCE_DEFAULT)
nm.createNotificationChannel(nc)
}
}
companion object {
@JvmField
var instance: Application? = null
}
}
| 0
|
Kotlin
|
0
| 0
|
15de83c6aac857f6817a950c2c7e6fb89f76e7b4
| 2,016
|
remote-embeded-repl
|
MIT License
|
src/main/kotlin/juuxel/jay/Deserializer.kt
|
Juuxel
| 165,117,741
| false
| null |
/* This file is a part of the Jay project
* by Juuxel, licensed under the MIT license.
* Full code and license: https://github.com/Juuxel/Jay
*/
package juuxel.jay
interface Deserializer<out T> {
fun deserialize(value: JsonValue): T?
}
| 0
|
Kotlin
|
0
| 0
|
e4e5d7231869b3f49b8d9b6532a2036e53f69169
| 244
|
Jay
|
MIT License
|
app/src/main/kotlin/br/eng/ecarrara/vilibra/book/domain/entity/Book.kt
|
rviannaoliveira
| 143,359,047
| false
|
{"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Ignore List": 3, "YAML": 1, "Proguard": 2, "Kotlin": 43, "Java": 68, "INI": 1, "JSON": 1, "XML": 38}
|
package br.eng.ecarrara.vilibra.book.domain.entity
import br.eng.ecarrara.vilibra.util.DefaultData
data class Book(
val id: Long = DefaultData.NOT_INITIALIZED.getLong(),
val title: String = DefaultData.NOT_INITIALIZED.getString(),
val subtitle: String = DefaultData.NOT_INITIALIZED.getString(),
val authors: List<String> = emptyList(),
val publisher: String = DefaultData.NOT_INITIALIZED.getString(),
val publishedDate: String = DefaultData.NOT_INITIALIZED.getString(),
val pageCount: Int = DefaultData.NOT_INITIALIZED.getInt(),
val isbn10: String = DefaultData.NOT_INITIALIZED.getString(),
val isbn13: String = DefaultData.NOT_INITIALIZED.getString()
) {
companion object {
val NO_BOOK = Book()
}
}
| 1
| null |
1
| 1
|
3c8395740512c575e34ca8c0573550fb62a9f152
| 790
|
vilibra
|
MIT License
|
src/commonTest/kotlin/com/github/andreypfau/raptorq/arraymap/ArrayMapTest.kt
|
andreypfau
| 531,010,252
| false
|
{"Kotlin": 182365}
|
@file:Suppress("OPT_IN_USAGE")
package com.github.andreypfau.raptorq.arraymap
import kotlin.test.Test
import kotlin.test.assertTrue
class ArrayMapTest {
@Test
fun listMap() {
val builder = ImmutableListMapBuilder(10)
builder.add(0u, 1u)
builder.add(3u, 1u)
builder.add(3u, 2u)
val map = builder.build()
assertTrue(map[0].contains(1u))
assertTrue(!map[0].contains(2u))
assertTrue(map[3].contains(1u))
assertTrue(map[3].contains(2u))
assertTrue(!map[3].contains(3u))
assertTrue(!map[2].contains(1u))
}
}
| 0
|
Kotlin
|
0
| 0
|
e0364bfd0ceae46c30993db72424802b7553a02b
| 608
|
raptorq-kotlin
|
Apache License 2.0
|
backend/src/test/kotlin/com/github/davinkevin/podcastserver/entity/TagTest.kt
|
kareemabbas90
| 205,540,089
| true
|
{"HTML": 22707379, "Kotlin": 968949, "TypeScript": 162740, "JavaScript": 95419, "Java": 65945, "CSS": 26945, "Shell": 6240, "Dockerfile": 4258, "Smarty": 328}
|
package com.github.davinkevin.podcastserver.entity
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.util.*
/**
* Created by kevin on 15/06/15 for HackerRank problem
*/
class TagTest {
@Test
fun `should create a tag`() {
val anId = UUID.randomUUID()
val tag = Tag().apply {
name = "Humour"
id = anId
}
assertThat(tag.id).isEqualTo(anId)
assertThat(tag.name).isEqualTo("Humour")
}
@Test
fun `should be equals`() {
/* Given */
val tag = Tag().apply {
name = "Humour"
id = UUID.randomUUID()
}
val notEquals = Tag().apply {
name = "Conférence"
id = UUID.randomUUID()
}
val notATag = Any()
/* When */
val notSameType = tag == notATag
/* Then */
assertThat(tag).isEqualTo(tag)
assertThat(tag).isNotEqualTo(notEquals)
assertThat(tag).isNotEqualTo(notSameType)
assertThat(tag.hashCode()).isEqualTo("Humour".hashCode())
}
}
| 0
|
HTML
|
0
| 0
|
1d94a578cc68654172a70efa40743c112c79cffa
| 1,110
|
Podcast-Server
|
Apache License 2.0
|
commons/ui/src/main/java/es/littledavity/commons/ui/base/rv/AdapterComon.kt
|
Benderinos
| 260,322,264
| false
| null |
/*
* Copyright 2021 dalodev
*/
package es.littledavity.commons.ui.base.rv
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
typealias ListenerBinder<IT> = (IT, RecyclerView.ViewHolder) -> Unit
interface ViewHolderFactory {
fun create(
inflater: LayoutInflater,
parent: ViewGroup,
dependencies: ItemDependencies
): RecyclerView.ViewHolder
}
interface Bindable {
fun bind(
viewHolder: RecyclerView.ViewHolder,
dependencies: ItemDependencies
)
}
interface HasUniqueIdentifier<out T> {
val uniqueIdentifier: T
}
interface HasListeners
interface ItemDependencies
object NoDependencies : ItemDependencies
interface Item<Model : Any, Dependencies : ItemDependencies> : ViewHolderFactory, Bindable {
val model: Model
val itemId: Long
get() = RecyclerView.NO_ID
}
abstract class AbstractItem<
Model : Any,
ViewHolder : RecyclerView.ViewHolder,
Dependencies : ItemDependencies
>(final override val model: Model) : Item<Model, Dependencies> {
@Suppress("unchecked_cast")
final override fun create(
inflater: LayoutInflater,
parent: ViewGroup,
dependencies: ItemDependencies
) = createViewHolder(
inflater = inflater,
parent = parent,
dependencies = dependencies as Dependencies
)
protected abstract fun createViewHolder(
inflater: LayoutInflater,
parent: ViewGroup,
dependencies: Dependencies
): ViewHolder
@Suppress("unchecked_cast")
final override fun bind(viewHolder: RecyclerView.ViewHolder, dependencies: ItemDependencies) {
performBinding(
viewHolder = viewHolder as ViewHolder,
dependencies = dependencies as Dependencies
)
}
protected abstract fun performBinding(viewHolder: ViewHolder, dependencies: Dependencies)
final override fun equals(other: Any?) = model == (other as? Item<*, *>)?.model
final override fun hashCode() = model.hashCode()
final override fun toString() = model.toString()
}
| 0
|
Kotlin
|
0
| 1
|
4f7f9d251c4da8e130a9f2b64879867bfecb44e8
| 2,133
|
ChorboAgenda
|
Apache License 2.0
|
server/zally-server/src/main/kotlin/org/zalando/zally/configuration/WebMvcConfiguration.kt
|
SchweizerischeBundesbahnen
| 272,621,483
| true
|
{"Kotlin": 744050, "JavaScript": 118225, "Go": 76281, "SCSS": 3271, "Pug": 1680, "Shell": 1131, "Dockerfile": 519}
|
package org.zalando.zally.configuration
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import java.util.Arrays
@Configuration
class WebMvcConfiguration : WebMvcConfigurer {
@Autowired
@Qualifier("yamlObjectMapper")
private lateinit var yamlObjectMapper: ObjectMapper
override fun configureContentNegotiation(configurer: ContentNegotiationConfigurer) {
configurer
.favorPathExtension(true)
.favorParameter(false)
.ignoreAcceptHeader(false)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType(MediaType.APPLICATION_JSON.subtype, MediaType.APPLICATION_JSON)
.mediaType(MEDIA_TYPE_TEXT_XYAML.subtype, MEDIA_TYPE_TEXT_XYAML)
.mediaType(MEDIA_TYPE_APP_XYAML.subtype, MEDIA_TYPE_APP_XYAML)
}
override fun extendMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
val yamlConverter = MappingJackson2HttpMessageConverter(yamlObjectMapper)
yamlConverter.supportedMediaTypes = Arrays.asList(MEDIA_TYPE_TEXT_XYAML, MEDIA_TYPE_APP_XYAML)
converters.add(yamlConverter)
}
override fun addCorsMappings(registry: CorsRegistry) {
registry
.addMapping("/**")
.allowedMethods("GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH")
.allowedOrigins("*")
.allowedHeaders("*")
}
companion object {
val MEDIA_TYPE_APP_XYAML: MediaType = MediaType.valueOf("application/x-yaml")
val MEDIA_TYPE_TEXT_XYAML: MediaType = MediaType.valueOf("text/x-yaml")
}
}
| 15
|
Kotlin
|
2
| 3
|
8045c57b346abc79110940971e721b31b1677e2c
| 2,203
|
zally
|
MIT License
|
module_travel_policy/src/main/java/com/noble/module_travel_policy/bean/reqbean/PolicyDetailReqBean.kt
|
NobleXL
| 514,568,667
| false
|
{"Kotlin": 69212}
|
package com.noble.module_travel_policy.bean.reqbean
import com.noble.module_travel_policy.bean.enum.RiskLevelEnum
/**
* @author:HQL
* @desc:政策详细信息
*/
class PolicyDetailReqBean {
var province_id: String? = null
var city_id: String? = null
var city_name: String? = null
var health_code_desc: String? = null
var health_code_gid: String? = null
var health_code_name: String? = null
var health_code_picture: String? = null
var health_code_style: String? = null
var high_in_desc: String? = null
var low_in_desc: String? = null
var out_desc: String? = null
var province_name: String? = null
var risk_level: String? = null
val isLowRisk: Boolean
get() {
risk_level?.let {
if (it == "0" || it == "1") {
return true
}
}
return false
}
val riskLevelDesc: String
get() {
risk_level?.let {
return RiskLevelEnum.getRiskLevelDesc(it)
}
return "未知"
}
}
| 0
|
Kotlin
|
0
| 0
|
1ef6f67f43fe122154adcb3b9793e4bbd2eea0f8
| 1,073
|
TravelPrevention
|
Apache License 2.0
|
wear-app/src/main/java/ee/schimke/wmp/ui/settings/SettingsScreen.kt
|
yschimke
| 514,614,213
| false
| null |
/*
* Copyright 2022 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 ee.schimke.wmp.ui.settings
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.res.stringResource
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyListState
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.ToggleChip
import androidx.wear.compose.material.ToggleChipDefaults
import com.google.android.horologist.compose.layout.StateUtils.rememberStateWithLifecycle
import com.google.android.horologist.compose.navscaffold.scrollableColumn
import ee.schimke.wmp.R
@Composable
fun SettingsScreen(
focusRequester: FocusRequester,
state: ScalingLazyListState,
settingsScreenViewModel: SettingsScreenViewModel,
modifier: Modifier = Modifier,
) {
val uiState by rememberStateWithLifecycle(settingsScreenViewModel.uiState)
ScalingLazyColumn(
modifier = modifier
.fillMaxSize()
.scrollableColumn(focusRequester, state),
state = state
) {
item {
CheckedSetting(
uiState.animated,
stringResource(id = R.string.animated_setting),
enabled = uiState.writable
) {
settingsScreenViewModel.setAnimated(it)
}
}
item {
CheckedSetting(
uiState.showTimeTextInfo,
stringResource(id = R.string.show_info_setting),
enabled = uiState.writable
) {
settingsScreenViewModel.setShowTimeTextInfo(it)
}
}
item {
ActionSetting(stringResource(id = R.string.logout)) {
settingsScreenViewModel.logout()
}
}
}
}
@Composable
private fun ActionSetting(
text: String,
onClick: () -> Unit,
) {
Chip(
onClick = onClick,
label = {
Text(text)
},
modifier = Modifier.fillMaxWidth()
)
}
@Composable
private fun ToggleSetting(
value: Boolean,
text: String,
enabled: Boolean = true,
onCheckedChange: (Boolean) -> Unit,
) {
ToggleChip(
checked = value,
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.radioIcon(checked = value),
contentDescription = if (value) stringResource(id = R.string.toggle_chip_on) else stringResource(
id = R.string.toggle_chip_off
),
)
},
enabled = enabled,
onCheckedChange = onCheckedChange,
label = {
Text(text)
}, modifier = Modifier.fillMaxWidth()
)
}
@Composable
private fun CheckedSetting(
value: Boolean,
text: String,
enabled: Boolean = true,
onCheckedChange: (Boolean) -> Unit,
) {
ToggleChip(
checked = value,
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.checkboxIcon(checked = value),
contentDescription = if (value) stringResource(id = R.string.toggle_chip_on) else stringResource(
id = R.string.toggle_chip_off
),
)
},
enabled = enabled,
onCheckedChange = onCheckedChange,
label = {
Text(text)
}, modifier = Modifier.fillMaxWidth()
)
}
| 1
|
Kotlin
|
0
| 1
|
0d1fec3491c2faa8e6cdce867a835914620c3520
| 4,295
|
wear-media-player
|
Apache License 2.0
|
src/test/kotlin/com/alipay/sofa/koupleless/kouplelessidea/parser/modifier/TransactionManagerBeanReuserTest.kt
|
koupleless
| 783,180,038
| false
|
{"Kotlin": 840464, "Java": 26198, "Shell": 3994}
|
package com.alipay.sofa.koupleless.kouplelessidea.parser.modifier
import com.alipay.sofa.koupleless.kouplelessidea.model.splitmodule.staticparser.DBContext
import com.alipay.sofa.koupleless.kouplelessidea.parser.util.JavaParserUtil
import com.alipay.sofa.koupleless.kouplelessidea.util.MockKUtil
import com.github.javaparser.StaticJavaParser
import com.github.javaparser.ast.CompilationUnit
import io.mockk.every
import io.mockk.mockk
import org.junit.Test
import java.nio.file.Path
import kotlin.test.assertTrue
/**
* @description: TODO
* @author lipeng
* @date 2024/1/5 17:18
*/
class TransactionManagerBeanReuserTest {
private val cu = getCu()
private fun getCu(): CompilationUnit {
return StaticJavaParser.parse("""
package com.example;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
public class MybatisConfiguration {
@Bean("mockTransactionManager")
public DataSourceTransactionManager sourceTransactionManager(DataSource mockDataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(mockDataSource);
return dataSourceTransactionManager;
}
}
""")
}
@Test
fun testDoParse(){
// 准备数据
val managerBeanInfo = MockKUtil.spyBeanInfo("mockTransactionManager",null)
val methodSignature = JavaParserUtil.parseMethodSignature(JavaParserUtil.filterMethodByName(cu.getType(0),"sourceTransactionManager").first())
managerBeanInfo.defineByMethod(methodSignature)
val transactionManager = mockk<DBContext.PlatformTransactionManager>{
every { beanInfo } returns managerBeanInfo
}
// 修改
val modifier = TransactionManagerBeanReuser("mockPath",transactionManager)
modifier.doParse(Path.of("mockPath"),cu,null)
// 校验 method 有 getBean 语句
val method = JavaParserUtil.filterMethodByName(cu.getType(0),"sourceTransactionManager").first()
assertTrue(JavaParserUtil.filterMethodCallStatInMethodBody(method,"getBaseBean").isNotEmpty())
// 验证 method 没有参数
assertTrue(method.parameters.isEmpty())
}
}
| 1
|
Kotlin
|
1
| 2
|
371a738491d60019d9c25a131fab484ad8064fc2
| 2,441
|
koupleless-idea
|
Apache License 2.0
|
sample-compose/src/main/java/com/rubensousa/carioca/android/sample/SampleScreen.kt
|
rubensousa
| 853,775,838
| false
|
{"Kotlin": 336232}
|
/*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rubensousa.carioca.android.sample
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun SampleScreen(
modifier: Modifier = Modifier,
viewModel: SampleViewModel = viewModel<SampleViewModel>(),
) {
SampleScreen(
modifier = modifier,
onButtonClick = {
viewModel.log("Button clicked")
},
onFabClick = {
viewModel.log("Fab clicked")
}
)
}
@Composable
internal fun SampleScreen(
modifier: Modifier,
onButtonClick: () -> Unit,
onFabClick: () -> Unit,
) {
Scaffold(
modifier = modifier,
floatingActionButton = {
ExtendedFloatingActionButton(
onClick = {
onFabClick()
}
) {
Text("FAB")
}
}
) { padding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
ElevatedButton(
modifier = Modifier.align(Alignment.Center),
onClick = {
onButtonClick()
}
) {
Text("Main button")
}
}
}
}
@Composable
@Preview
private fun PreviewSampleScreen() {
SampleScreen(
modifier = Modifier.fillMaxSize(),
onButtonClick = {},
onFabClick = {}
)
}
| 2
|
Kotlin
|
0
| 1
|
bc33dbf0f8b288e1950483c5711eebc1c910f8ac
| 2,516
|
Carioca
|
Apache License 2.0
|
src/main/kotlin/com/meiblorn/kotidgy/engine/generator/Generator.kt
|
meiblorn
| 160,176,578
| false
| null |
package com.meiblorn.kotidgy.engine.generator
import com.meiblorn.kotidgy.domain.generation.sample.Sample
abstract class Generator<T> {
abstract fun process(source: T): Sequence<Sample<*>>
}
| 0
|
Kotlin
|
0
| 3
|
c4e666422151e3e1ff87216190bb2b8ad58e2642
| 198
|
kotidgy
|
MIT License
|
app/src/main/java/io/github/tonnyl/mango/DeepLinkActivity.kt
|
SelvaGaneshM
| 101,606,103
| true
|
{"Kotlin": 256284, "HTML": 27144}
|
package io.github.tonnyl.mango
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.airbnb.deeplinkdispatch.DeepLinkHandler
/**
* Created by lizhaotailang on 2017/7/31.
*
* The activity with the scheme you'd like to handle in your `AndroidManifest.xml` file
* Annotate it with [DeepLinkHandler] and provide a list of [com.airbnb.deeplinkdispatch.DeepLinkModule]
* annotated class(es).
*/
@DeepLinkHandler(MangoDeepLinkModule::class)
class DeepLinkActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// DeepLinkDelegate, MangoDeepLinkModuleLoader is generated at compile-time.
val deepLinkDelegate = DeepLinkDelegate(MangoDeepLinkModuleLoader())
// Delegate the deep link handling to DeepLinkDispatch.
// It will start the correct Activity based on the incoming Intent URI
deepLinkDelegate.dispatchFrom(this)
// Finish this Activity since the correct one has been just started
finish()
}
}
| 0
|
Kotlin
|
1
| 0
|
2c6de8532424dcaa814445a66830e4b9f24d0495
| 1,074
|
Mango
|
MIT License
|
src/test/kotlin/info/mycityreport/api/healthcheck/RouteingTest.kt
|
mycityreport
| 434,082,324
| false
| null |
package info.mycityreport.api.healthcheck
import info.mycityreport.api.module
import io.ktor.application.Application
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.handleRequest
import io.ktor.server.testing.withTestApplication
import kotlin.test.Test
import kotlin.test.assertEquals
internal class RouteingTest {
@Test
fun healthEndpointIsAvailable() {
withTestApplication(Application::module) {
handleRequest(HttpMethod.Get, "/health").apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("{\"status\":200}", response.content)
}
}
}
}
| 6
|
Kotlin
|
0
| 0
|
fe3681410d08466217f7e9f15a74c0e82573e906
| 691
|
mcr-api-server
|
MIT License
|
UICPC/21/nwerc2020all/conteststruggles/submissions/accepted/paul.kt
|
mohammadi-milad-mim
| 457,724,622
| false
|
{"C++": 896197, "Python": 190309, "Java": 61478, "TeX": 26818, "C": 14624, "Kotlin": 1431, "Asymptote": 771, "Shell": 337, "VHDL": 7}
|
private fun readInts() = readLine()!!.split(' ').map { it.toInt() }
fun main() {
val (n, k) = readInts()
val (a, s) = readInts()
val res = (n*a-k*s).toDouble()/(n-k)
println(if (res < 0 || res > 100) "impossible" else res)
}
| 0
|
C++
|
0
| 0
|
9f84a2d2734a5efe0e1fde0062e51782cd5af2c6
| 242
|
Competitive-Programming
|
MIT License
|
core/src/test/kotlin/dev/usbharu/multim/api/NotImplEmojiApiTest.kt
|
multim-dev
| 591,652,793
| false
| null |
package dev.usbharu.multim.api
import dev.usbharu.multim.TestUtil.failOnSuccess
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
@OptIn(ExperimentalCoroutinesApi::class)
class NotImplEmojiApiTest {
@Test
fun get() = runTest {
NotImplEmojiApi.get("dgeB0b").failOnSuccess()
}
@Test
fun findByName() = runTest {
NotImplEmojiApi.findByName("KR4y61").failOnSuccess()
}
}
| 8
|
Kotlin
|
0
| 7
|
daad2d142ae6fa7414acdb6704832a4d477dc41f
| 528
|
multim
|
Apache License 2.0
|
basick/src/main/java/com/mozhimen/basick/elemk/android/view/cons/CSurface.kt
|
mozhimen
| 353,952,154
| false
| null |
package com.mozhimen.kotlin.elemk.android.view.cons
import android.view.Surface
/**
* @ClassName CSurface
* @Description TODO
* @Author Mozhimen / Kolin Zhao
* @Date 2024/1/27 0:20
* @Version 1.0
*/
object CSurface {
const val ROTATION_0 = Surface.ROTATION_0
const val ROTATION_90 = Surface.ROTATION_90
const val ROTATION_180 = Surface.ROTATION_180
const val ROTATION_270 = Surface.ROTATION_270
}
| 1
| null |
14
| 118
|
bbdd6ab9b945f04036c27add35c1cbd70c1b49f7
| 420
|
SwiftKit
|
Apache License 2.0
|
feature-theater/src/main/java/soup/movie/feature/theater/TheaterFilterChip.kt
|
Moop-App
| 113,048,795
| false
| null |
/*
* Copyright 2021 SOUP
*
* 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 soup.movie.feature.theater
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Text
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import soup.metronome.material.chip.ChipDefaults
import soup.metronome.material.chip.FilterChip
import soup.movie.core.designsystem.icon.MovieIcons
import soup.movie.core.designsystem.theme.MovieTheme
import soup.movie.model.TheaterModel
import soup.movie.model.TheaterTypeModel
@OptIn(ExperimentalMaterialApi::class)
@Composable
internal fun TheaterFilterChip(
theater: TheaterModel,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit
) {
when (theater.type) {
TheaterTypeModel.CGV -> CgvFilterChip(
text = theater.name,
checked = checked,
onCheckedChange = onCheckedChange
)
TheaterTypeModel.LOTTE -> LotteFilterChip(
text = theater.name,
checked = checked,
onCheckedChange = onCheckedChange
)
TheaterTypeModel.MEGABOX -> MegaboxFilterChip(
text = theater.name,
checked = checked,
onCheckedChange = onCheckedChange
)
}
}
@ExperimentalMaterialApi
@Composable
private fun CgvFilterChip(
text: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
enabled: Boolean = true
) {
CompositionLocalProvider(LocalRippleTheme provides rippleTheme(Color(0xFFBDBDBD))) {
FilterChip(
checked = checked,
onCheckedChange = onCheckedChange,
chipIcon = {
Image(
MovieIcons.Check,
contentDescription = null,
colorFilter = ColorFilter.tint(
Color.Black.copy(alpha = 0.2f)
),
)
},
checkedIcon = {
Image(
MovieIcons.Check,
contentDescription = null,
colorFilter = ColorFilter.tint(MovieTheme.colors.onCgv),
)
},
enabled = enabled,
border = BorderStroke(width = 1.dp, color = Color(0x229E9E9E)),
colors = ChipDefaults.filterChipColors(
checkedBackgroundColor = MovieTheme.colors.cgv,
checkedContentColor = MovieTheme.colors.onCgv,
uncheckedBackgroundColor = Color(0x55FFFFFF),
uncheckedContentColor = Color(0x66000000)
)
) {
Text(
text = text,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(ChipDefaults.TextPadding)
)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun LotteFilterChip(
text: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
enabled: Boolean = true
) {
CompositionLocalProvider(LocalRippleTheme provides rippleTheme(Color.White)) {
FilterChip(
checked = checked,
onCheckedChange = onCheckedChange,
chipIcon = {
Image(
MovieIcons.Check,
contentDescription = null,
colorFilter = ColorFilter.tint(
MovieTheme.colors.onLotte.copy(alpha = 0.4f)
),
)
},
checkedIcon = {
Image(
MovieIcons.Check,
contentDescription = null,
colorFilter = ColorFilter.tint(MovieTheme.colors.onLotte),
)
},
enabled = enabled,
colors = ChipDefaults.filterChipColors(
checkedBackgroundColor = Color(0xFFED1D24),
checkedContentColor = Color.White,
uncheckedBackgroundColor = Color(0x66ED1D24),
uncheckedContentColor = Color(0x77FFFFFF)
)
) {
Text(
text = text,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(ChipDefaults.TextPadding)
)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun MegaboxFilterChip(
text: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
enabled: Boolean = true
) {
CompositionLocalProvider(LocalRippleTheme provides rippleTheme(Color.White)) {
FilterChip(
checked = checked,
onCheckedChange = onCheckedChange,
chipIcon = {
Image(
MovieIcons.Check,
contentDescription = null,
colorFilter = ColorFilter.tint(
MovieTheme.colors.onMegabox.copy(alpha = 0.4f)
),
)
},
checkedIcon = {
Image(
MovieIcons.Check,
contentDescription = null,
colorFilter = ColorFilter.tint(MovieTheme.colors.onMegabox),
)
},
enabled = enabled,
colors = ChipDefaults.filterChipColors(
checkedBackgroundColor = Color(0xFF352263),
checkedContentColor = Color.White,
uncheckedBackgroundColor = Color(0x77352263),
uncheckedContentColor = Color(0x77FFFFFF)
)
) {
Text(
text = text,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(ChipDefaults.TextPadding)
)
}
}
}
| 5
|
Kotlin
|
17
| 147
|
29693e89bcdfebcb0b5eb2f5c4adfb14d65bd5b5
| 6,700
|
Moop-Android
|
Apache License 2.0
|
java/bc-foundation/src/main/kotlin/io/mike/foundation/service/CrudService.kt
|
fl3xman
| 240,129,869
| false
| null |
/*
* Copyright (c) 2020 <EMAIL>
* All rights reserved.
* 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 io.mike.foundation.service
import io.mike.foundation.mapper.ModelMapperProvider
import io.mike.foundation.repository.CrudRepositoryProvider
import io.mike.foundation.repository.PageResponse
import io.mike.foundation.repository.SearchPageRequestParams
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
interface CrudService<Model, ID, R, Output> : DelegatedCrudService<Output>, CrudRepositoryProvider<Model, ID, R>, ModelMapperProvider where R : JpaRepository<Model, ID>, R : JpaSpecificationExecutor<Model> {
fun <Input> create(input: Input, modelClass: Class<Model>): Output = create(repository, input, modelClass)
fun <Input> update(id: ID, input: Input): Output = update(repository, id, input)
fun delete(id: ID): Unit = delete(repository, id)
fun findOne(id: ID): Output = findOne(repository, id)
fun find(params: SearchPageRequestParams, attributes: Set<String> = emptySet()): PageResponse<Output> = find(repository, params, attributes)
fun findEntity(id: ID): Model = findEntity(repository, id)
fun findEntities(ids: Set<ID>): List<Model> = findEntities(repository, ids)
}
| 12
|
Kotlin
|
0
| 0
|
91c44d43af2a7ce30e3f4909905d39c2c73e578e
| 2,369
|
book-collection
|
MIT License
|
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLInputBotInlineMessageMediaGeo.kt
|
Miha-x64
| 436,587,061
| true
|
{"Kotlin": 3919807, "Java": 75352}
|
package com.github.badoualy.telegram.tl.api
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
/**
* inputBotInlineMessageMediaGeo#96929a85
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
class TLInputBotInlineMessageMediaGeo() : TLAbsInputBotInlineMessage() {
var geoPoint: TLAbsInputGeoPoint = TLInputGeoPointEmpty()
var heading: Int? = null
var period: Int? = null
var proximityNotificationRadius: Int? = null
override var replyMarkup: TLAbsReplyMarkup? = null
private val _constructor: String = "inputBotInlineMessageMediaGeo#96929a85"
override val constructorId: Int = CONSTRUCTOR_ID
constructor(
geoPoint: TLAbsInputGeoPoint,
heading: Int?,
period: Int?,
proximityNotificationRadius: Int?,
replyMarkup: TLAbsReplyMarkup?
) : this() {
this.geoPoint = geoPoint
this.heading = heading
this.period = period
this.proximityNotificationRadius = proximityNotificationRadius
this.replyMarkup = replyMarkup
}
override fun computeFlags() {
_flags = 0
updateFlags(heading, 1)
updateFlags(period, 2)
updateFlags(proximityNotificationRadius, 8)
updateFlags(replyMarkup, 4)
}
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) {
computeFlags()
writeInt(_flags)
writeTLObject(geoPoint)
doIfMask(heading, 1) { writeInt(it) }
doIfMask(period, 2) { writeInt(it) }
doIfMask(proximityNotificationRadius, 8) { writeInt(it) }
doIfMask(replyMarkup, 4) { writeTLObject(it) }
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) {
_flags = readInt()
geoPoint = readTLObject<TLAbsInputGeoPoint>()
heading = readIfMask(1) { readInt() }
period = readIfMask(2) { readInt() }
proximityNotificationRadius = readIfMask(8) { readInt() }
replyMarkup = readIfMask(4) { readTLObject<TLAbsReplyMarkup>() }
}
override fun computeSerializedSize(): Int {
computeFlags()
var size = SIZE_CONSTRUCTOR_ID
size += SIZE_INT32
size += geoPoint.computeSerializedSize()
size += getIntIfMask(heading, 1) { SIZE_INT32 }
size += getIntIfMask(period, 2) { SIZE_INT32 }
size += getIntIfMask(proximityNotificationRadius, 8) { SIZE_INT32 }
size += getIntIfMask(replyMarkup, 4) { it.computeSerializedSize() }
return size
}
override fun toString() = _constructor
override fun equals(other: Any?): Boolean {
if (other !is TLInputBotInlineMessageMediaGeo) return false
if (other === this) return true
return _flags == other._flags
&& geoPoint == other.geoPoint
&& heading == other.heading
&& period == other.period
&& proximityNotificationRadius == other.proximityNotificationRadius
&& replyMarkup == other.replyMarkup
}
companion object {
const val CONSTRUCTOR_ID: Int = 0x96929a85.toInt()
}
}
| 1
|
Kotlin
|
2
| 3
|
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
| 3,534
|
kotlogram-resurrected
|
MIT License
|
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLInputBotInlineMessageMediaGeo.kt
|
Miha-x64
| 436,587,061
| true
|
{"Kotlin": 3919807, "Java": 75352}
|
package com.github.badoualy.telegram.tl.api
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
/**
* inputBotInlineMessageMediaGeo#96929a85
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
class TLInputBotInlineMessageMediaGeo() : TLAbsInputBotInlineMessage() {
var geoPoint: TLAbsInputGeoPoint = TLInputGeoPointEmpty()
var heading: Int? = null
var period: Int? = null
var proximityNotificationRadius: Int? = null
override var replyMarkup: TLAbsReplyMarkup? = null
private val _constructor: String = "inputBotInlineMessageMediaGeo#96929a85"
override val constructorId: Int = CONSTRUCTOR_ID
constructor(
geoPoint: TLAbsInputGeoPoint,
heading: Int?,
period: Int?,
proximityNotificationRadius: Int?,
replyMarkup: TLAbsReplyMarkup?
) : this() {
this.geoPoint = geoPoint
this.heading = heading
this.period = period
this.proximityNotificationRadius = proximityNotificationRadius
this.replyMarkup = replyMarkup
}
override fun computeFlags() {
_flags = 0
updateFlags(heading, 1)
updateFlags(period, 2)
updateFlags(proximityNotificationRadius, 8)
updateFlags(replyMarkup, 4)
}
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) {
computeFlags()
writeInt(_flags)
writeTLObject(geoPoint)
doIfMask(heading, 1) { writeInt(it) }
doIfMask(period, 2) { writeInt(it) }
doIfMask(proximityNotificationRadius, 8) { writeInt(it) }
doIfMask(replyMarkup, 4) { writeTLObject(it) }
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) {
_flags = readInt()
geoPoint = readTLObject<TLAbsInputGeoPoint>()
heading = readIfMask(1) { readInt() }
period = readIfMask(2) { readInt() }
proximityNotificationRadius = readIfMask(8) { readInt() }
replyMarkup = readIfMask(4) { readTLObject<TLAbsReplyMarkup>() }
}
override fun computeSerializedSize(): Int {
computeFlags()
var size = SIZE_CONSTRUCTOR_ID
size += SIZE_INT32
size += geoPoint.computeSerializedSize()
size += getIntIfMask(heading, 1) { SIZE_INT32 }
size += getIntIfMask(period, 2) { SIZE_INT32 }
size += getIntIfMask(proximityNotificationRadius, 8) { SIZE_INT32 }
size += getIntIfMask(replyMarkup, 4) { it.computeSerializedSize() }
return size
}
override fun toString() = _constructor
override fun equals(other: Any?): Boolean {
if (other !is TLInputBotInlineMessageMediaGeo) return false
if (other === this) return true
return _flags == other._flags
&& geoPoint == other.geoPoint
&& heading == other.heading
&& period == other.period
&& proximityNotificationRadius == other.proximityNotificationRadius
&& replyMarkup == other.replyMarkup
}
companion object {
const val CONSTRUCTOR_ID: Int = 0x96929a85.toInt()
}
}
| 1
|
Kotlin
|
2
| 3
|
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
| 3,534
|
kotlogram-resurrected
|
MIT License
|
scraper/src/commonMain/kotlin/kotlinx/scraper/Source.kt
|
mazuninky
| 222,733,264
| false
| null |
package kotlinx.scraper
sealed class Source
data class WebPage(val url: String) : Source()
| 0
|
Kotlin
|
0
| 0
|
f14943fca860873379ab7671ff5b2b1f98b12d8b
| 93
|
kotlinx.scraper
|
MIT License
|
core/data/src/main/java/com/jetapps/jettaskboard/model/common/UrlDataModel.kt
|
pushpalroy
| 535,554,638
| false
|
{"Kotlin": 490124, "Shell": 210}
|
package com.jetapps.jettaskboard.model.common
import com.google.gson.annotations.SerializedName
data class UrlDataModel(
@SerializedName("raw")
val raw: String? = null,
@SerializedName("full")
val full: String? = null,
@SerializedName("regular")
val regular: String? = null,
@SerializedName("small")
val small: String? = null,
@SerializedName("thumb")
val thumb: String? = null,
@SerializedName("small_s3")
val smallS3: String? = null
)
| 1
|
Kotlin
|
4
| 64
|
a2df8dd3e763e5ad4f5d4ba5d3441f47c7c7680c
| 487
|
jetTaskBoard
|
MIT License
|
core/src/main/kotlin/core/vfs/File.kt
|
naotiki
| 585,808,592
| false
| null |
package core.vfs
import core.commands.parser.CommandResult
import core.commands.parser.Executable
import core.commands.parser.SuperArgsParser
import core.user.Group
import core.user.User
import core.vfs.Permission.Companion.Operation
class FileValue<T>(private val file: File, private var internalValue: T) {
fun set(user: User, value: T): Boolean {
if (file.checkPermission(user, Operation.Write)) {
internalValue = value
return true
}
return false
}
fun get(): T {
return internalValue
}
}
class SealedFileValue<T>(private val file: File, private var internalValue: T) {
fun set(user: User, value: T): Boolean {
if (file.checkPermission(user, Operation.Write)) {
internalValue = value
return true
}
return false
}
fun get(user: User): T? {
if (file.checkPermission(user, Operation.Read)) {
return internalValue
}
return null
}
}
fun <T> File.sealedValue(value: T) = SealedFileValue(this, value)
fun <T> File.value(value: T) = FileValue(this, value)
/**
* 仮想的ファイルの抽象クラス
* ディレクトリもファイルとする。
* @param name ファイルの名前
* @param parent 親ディレクトリ、ルートの場合はnull
* @param hidden 属性 [Boolean]をとる
*/
open class File(
var name: String, val parent: Directory? = null, hidden: Boolean, owner: User, group: Group, permission: Permission,
) {
val hidden = value(hidden)
val owner = value(owner)
val ownerGroup = value(group)
val permission = value(permission)
fun getFullPath(): Path {
val path = mutableListOf<String>()
var f: File? = this
while (f?.parent != null) {
path.add(f.name)
f = f.parent
}
return Path(path.reversed().joinToString("/", "/"))
}
}
fun File.toDirectoryOrNull(): Directory? {
return if (this is Directory) {
this
} else null
}
/**
* 表示可能な文字列を持つファイル
* @param [content] 内容
* */
class TextFile(
name: String,
parent: Directory?,
content: String,
owner: User,
group: Group,
permission: Permission,
hidden: Boolean
) : File(name, parent, owner = owner, group = group, hidden = hidden, permission = permission) {
val content = sealedValue(content)
}
class ExecutableFile<R>(
private val executable: Executable<R>, name: String=executable.name, parent: Directory?, owner: User, group: Group, permission:
Permission,
hidden: Boolean
) : File(name, parent, owner = owner, group = group, hidden = hidden, permission = permission) {
val argParser: SuperArgsParser get() = executable.argParser
val description get() = executable.description
fun generateHelpText()=executable.generateHelpText()
fun verbose(args: List<String>) =executable.verbose(args)
suspend fun execute(user: User, args: List<String>): CommandResult<R> {
return if (checkPermission(user, Permission.Companion.Operation.Execute)) {
executable.resolve(user,args)
} else {
executable.out.println("実行権限が不足しています。\nls -lで確認してみましょう。")
CommandResult.Error()
}
}
}
open class Directory(
name: String, parent: Directory?, owner: User, group: Group, permission: Permission,
hidden: Boolean
) : File(
name, parent = parent, owner = owner, group = group, hidden = hidden, permission = permission
) {
open val _children = sealedValue(mutableMapOf<String, File>())
fun getChildren(user: User, includeHidden: Boolean = false): Map<String, File>? {
return _children.get(user)?.filterValues { !it.hidden.get() || includeHidden }?.toMap()
}
fun addChildren(user: User, vararg childDir: File): Boolean {
return _children.get(user)?.putAll(childDir.associateBy { it.name }) != null
}
fun removeChild(user: User, childDir: File): Boolean {
println("削除:${childDir.name}")
return if (checkPermission(user,Operation.Write)) {
println("権限許可:${childDir.name}")
(_children.get(user)?.remove(childDir.name)!= null).also {
if (it) println("成功")
}
}else false
}
}
| 0
|
Kotlin
|
0
| 4
|
e410804e180fe76820544a5eeb3749e0b0270edb
| 4,161
|
EseLinux
|
MIT License
|
app/shared/bitkey-primitives/public/src/commonMain/kotlin/build/wallet/bitkey/inheritance/InheritanceMaterialHash.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
|
package build.wallet.bitkey.inheritance
import build.wallet.bitcoin.BitcoinNetworkType
import build.wallet.bitkey.app.AppSpendingPublicKey
import build.wallet.bitkey.relationships.EndorsedTrustedContact
import kotlin.jvm.JvmInline
@JvmInline
value class InheritanceMaterialHash(val value: Int)
data class InheritanceMaterialHashData(
val networkType: BitcoinNetworkType,
val spendingKey: AppSpendingPublicKey,
val contacts: List<EndorsedTrustedContact>,
) {
val inheritanceMaterialHash = InheritanceMaterialHash(hashCode())
}
| 3
|
C
|
16
| 113
|
694c152387c1fdb2b6be01ba35e0a9c092a81879
| 537
|
bitkey
|
MIT License
|
ui/feature/details/src/main/kotlin/com/houlis/haris/feature/details/ui/DetailsMiddleware.kt
|
HarisHoulis
| 595,512,452
| false
|
{"Kotlin": 74440, "Shell": 135}
|
package com.houlis.haris.feature.details.ui
import com.houlis.haris.core.domain.PicturesRepositoryContract
import com.houlis.haris.feature.details.ui.PicDetailsAction.DetailsFetched
import com.houlis.haris.feature.details.ui.PicDetailsAction.FetchDetailsFor
import com.houlis.haris.pictrfindr.core.coroutines.CloseableCoroutineScope
import com.houlis.haris.pictrfindr.ui.common.mvi.Dispatcher
import com.houlis.haris.pictrfindr.ui.common.mvi.Middleware
internal class DetailsMiddleware(
private val repository: PicturesRepositoryContract,
dispatcher: Dispatcher<PicDetailsAction>,
scope: CloseableCoroutineScope,
) : Middleware<DetailsState, PicDetailsAction>(dispatcher, scope) {
override suspend fun process(state: DetailsState, action: PicDetailsAction) {
when (action) {
is FetchDetailsFor -> dispatch(DetailsFetched(repository.retrieve(action.imageId).image))
else -> {}
}
}
}
| 8
|
Kotlin
|
0
| 0
|
679d1a897048f019c849e828913dcd645174f3ca
| 945
|
PicFind
|
Apache License 2.0
|
purchasely-amazon/android/src/main/java/com/reactnativepurchaselyamazon/PurchaselyAmazonModule.kt
|
Purchasely
| 327,927,099
| false
|
{"Objective-C": 64687, "Kotlin": 51241, "TypeScript": 49231, "Swift": 6513, "Ruby": 5232, "Shell": 2155, "JavaScript": 1195, "Objective-C++": 805}
|
package com.reactnativepurchaselyamazon
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
class PurchaselyAmazonModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return "PurchaselyAmazon"
}
// Example method
// See https://reactnative.dev/docs/native-modules-android
@ReactMethod
fun multiply(a: Int, b: Int, promise: Promise) {
promise.resolve(a * b)
}
}
| 2
|
Objective-C
|
3
| 14
|
af88f9ed057cebede824cd6263c781fcc85b7a98
| 645
|
Purchasely-ReactNative
|
MIT License
|
mobile/src/main/java/de/michelinside/glucodatahandler/preferences/AlarmAdvancedFragment.kt
|
pachi81
| 587,280,747
| false
|
{"Kotlin": 813094, "Java": 1673}
|
package de.michelinside.glucodatahandler.preferences
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import de.michelinside.glucodatahandler.R
import de.michelinside.glucodatahandler.common.Constants
import de.michelinside.glucodatahandler.common.notification.AlarmHandler
import de.michelinside.glucodatahandler.common.notification.Channels
import de.michelinside.glucodatahandler.common.utils.PackageUtils
import de.michelinside.glucodatahandler.common.utils.Utils
class AlarmAdvancedFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
private val LOG_ID = "GDH.AlarmAdvancedFragment"
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
try {
Log.v(LOG_ID, "onCreatePreferences called for key: ${Utils.dumpBundle(this.arguments)}" )
preferenceManager.sharedPreferencesName = Constants.SHARED_PREF_TAG
setPreferencesFromResource(R.xml.alarm_advanced, rootKey)
initPreferences()
} catch (exc: Exception) {
Log.e(LOG_ID, "onCreatePreferences exception: " + exc.toString())
}
}
private fun initPreferences() {
val listPreference = findPreference<ListPreference>(Constants.SHARED_PREF_ALARM_START_DELAY_STRING)
val delayMap = mutableMapOf<String, String>()
for (i in 0 until 3500 step 500) {
delayMap.put(i.toString(), "${(i.toFloat()/1000)} s")
}
listPreference!!.entries = delayMap.values.toTypedArray()
listPreference.entryValues = delayMap.keys.toTypedArray()
}
override fun onResume() {
Log.d(LOG_ID, "onResume called")
try {
preferenceManager.sharedPreferences?.registerOnSharedPreferenceChangeListener(this)
updateEnableStates(preferenceManager.sharedPreferences!!)
update()
super.onResume()
} catch (exc: Exception) {
Log.e(LOG_ID, "onResume exception: " + exc.toString())
}
}
override fun onPause() {
Log.d(LOG_ID, "onPause called")
try {
preferenceManager.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(this)
super.onPause()
} catch (exc: Exception) {
Log.e(LOG_ID, "onPause exception: " + exc.toString())
}
}
fun <T : Preference?> setEnableState(sharedPreferences: SharedPreferences, key: String, enableKey: String, invert: Boolean = false) {
val pref = findPreference<T>(key)
if (pref != null)
pref.isEnabled = invert != sharedPreferences.getBoolean(enableKey, false)
}
fun updateEnableStates(sharedPreferences: SharedPreferences) {
try {
setEnableState<SwitchPreferenceCompat>(sharedPreferences, Constants.SHARED_PREF_ALARM_FORCE_SOUND, Constants.SHARED_PREF_NOTIFICATION_VIBRATE, invert = true)
setEnableState<SwitchPreferenceCompat>(sharedPreferences, Constants.SHARED_PREF_NOTIFICATION_USE_ALARM_SOUND, Constants.SHARED_PREF_NOTIFICATION_VIBRATE, invert = true)
setEnableState<SwitchPreferenceCompat>(sharedPreferences, Constants.SHARED_PREF_ALARM_FULLSCREEN_DISMISS_KEYGUARD, Constants.SHARED_PREF_ALARM_FULLSCREEN_NOTIFICATION_ENABLED)
} catch (exc: Exception) {
Log.e(LOG_ID, "updateEnableStates exception: " + exc.toString())
}
}
private fun update() {
if (!Channels.getNotificationManager(requireContext()).isNotificationPolicyAccessGranted) {
disableSwitch(Constants.SHARED_PREF_ALARM_FORCE_SOUND)
disableSwitch(Constants.SHARED_PREF_ALARM_FORCE_VIBRATION)
}
val aaPref = findPreference<SwitchPreferenceCompat>(Constants.SHARED_PREF_NO_ALARM_NOTIFICATION_AUTO_CONNECTED)
if(aaPref != null) {
aaPref.isEnabled = PackageUtils.isGlucoDataAutoAvailable(requireContext())
if(!aaPref.isEnabled && aaPref.isChecked) {
disableSwitch(Constants.SHARED_PREF_NO_ALARM_NOTIFICATION_AUTO_CONNECTED)
}
}
}
private fun disableSwitch(prefname: String) {
val pref =
findPreference<SwitchPreferenceCompat>(prefname)
if (pref != null && pref.isChecked) {
Log.i(LOG_ID, "Disable preference $prefname as there is no permission!")
pref.isChecked = false
with(preferenceManager.sharedPreferences!!.edit()) {
putBoolean(prefname, false)
apply()
}
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
Log.d(LOG_ID, "onSharedPreferenceChanged called for " + key)
try {
updateEnableStates(sharedPreferences)
if(AlarmHandler.alarmPreferencesToSend.contains(key))
AlarmFragment.settingsChanged = true
when(key) {
Constants.SHARED_PREF_ALARM_FORCE_SOUND -> checkDisablePref(Constants.SHARED_PREF_ALARM_FORCE_SOUND, Constants.SHARED_PREF_ALARM_FORCE_VIBRATION)
Constants.SHARED_PREF_ALARM_FORCE_VIBRATION -> checkDisablePref(Constants.SHARED_PREF_ALARM_FORCE_VIBRATION, Constants.SHARED_PREF_ALARM_FORCE_SOUND)
Constants.SHARED_PREF_ALARM_START_DELAY_STRING -> {
val delayString = sharedPreferences.getString(Constants.SHARED_PREF_ALARM_START_DELAY_STRING, "")
if (!delayString.isNullOrEmpty()) {
val delay = delayString.toInt()
with(sharedPreferences.edit()) {
putInt(Constants.SHARED_PREF_ALARM_START_DELAY, delay)
apply()
}
}
}
}
} catch (exc: Exception) {
Log.e(LOG_ID, "onSharedPreferenceChanged exception: " + exc.toString())
}
}
private fun checkDisablePref(changedPref: String, targetPref: String) {
val changed = findPreference<SwitchPreferenceCompat>(changedPref)
if (changed!!.isChecked) {
if (!Channels.getNotificationManager(requireContext()).isNotificationPolicyAccessGranted) {
requestNotificationPolicyPermission()
} else {
val target = findPreference<SwitchPreferenceCompat>(targetPref)
if (target!!.isChecked) {
target.isChecked = false
with(preferenceManager.sharedPreferences!!.edit()) {
putBoolean(targetPref, false)
apply()
}
}
}
}
}
private fun requestNotificationPolicyPermission() {
if (!Channels.getNotificationManager(requireContext()).isNotificationPolicyAccessGranted) {
val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
startActivity(intent)
}
}
}
| 5
|
Kotlin
|
11
| 56
|
8ca4fcef5277806e557161bf90c830d08513765a
| 7,277
|
GlucoDataHandler
|
MIT License
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ClassifierFunction.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: ClassifierFunction
*
* Full name: System`ClassifierFunction
*
* Usage: ClassifierFunction[…] represents a function generated by Classify that classifies data into classes.
*
* AcceptanceThreshold -> Automatic
* AnomalyDetector -> Automatic
* BatchProcessing -> Automatic
* ClassPriors -> Automatic
* IndeterminateThreshold -> Automatic
* PerformanceGoal -> Automatic
* RandomSeeding -> 1234
* TargetDevice -> CPU
* TieBreakerFunction -> RandomChoice
* Options: UtilityFunction -> Automatic
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/ClassifierFunction
* Documentation: web: http://reference.wolfram.com/language/ref/ClassifierFunction.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun classifierFunction(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("ClassifierFunction", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,537
|
mathemagika
|
Apache License 2.0
|
feature/profile/src/main/java/com/alexereh/profile/component/ProfileComponent.kt
|
AlexEreh
| 680,205,233
| false
|
{"Kotlin": 106073}
|
package com.alexereh.profile.component
import com.alexereh.profile.ProfileStore
import kotlinx.coroutines.flow.StateFlow
interface ProfileComponent {
val state: StateFlow<ProfileStore.State>
fun doBackAction()
fun doLogoutAction()
fun refreshProfile()
}
| 2
|
Kotlin
|
0
| 2
|
c1e9d62fd3eb3f52d1377cce4cb42dd7875d6fb3
| 271
|
CSFBRS
|
MIT License
|
src/main/kotlin/heckerpowered/matrix/common/magics/DecisiveStrikeMagic.kt
|
heckerpowered
| 766,079,408
| false
|
{"Kotlin": 41833, "Java": 2677}
|
package heckerpowered.matrix.common.magics
import heckerpowered.matrix.common.Magic
import heckerpowered.matrix.data.language.MatrixLanguage
import net.minecraft.entity.Entity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.text.Text
class DecisiveStrikeMagic : Magic(MatrixLanguage.magicDecisiveStrike, 6) {
override fun onUse(player: PlayerEntity, target: Entity) {
target.timeUntilRegen = 0
target.damage(target.damageSources.playerAttack(player), 6.0f)
}
override fun getDescription(): List<Text> {
return listOf(
MatrixLanguage.magicDecisiveStrikeDescription1,
MatrixLanguage.magicDecisiveStrikeDescription2,
MatrixLanguage.magicDecisiveStrikeDescription3,
)
}
}
| 0
|
Kotlin
|
0
| 0
|
f29b5c92bb18ec806581160773192883336ee2b5
| 781
|
Matrix
|
Creative Commons Zero v1.0 Universal
|
grammar/testData/grammar/annotations/namePrefixAsUseSiteTargetPrefix/setparam.kt
|
oleksiyp
| 174,851,143
| true
|
{"ANTLR": 52211, "Kotlin": 47868, "JavaScript": 7607, "CSS": 6892, "Shell": 2376}
|
class Foo(@setparamann private val field: Int) {}
class Foo(@`setparamann` private val field: Int) {}
class Foo(@`setparam ` val field: Int) {}
class Foo {
@ann @setparamann var field: Int = 10
}
class Foo(@setparamann @ann protected val field: Int) {}
class Foo {
@ann@setparamann var field: Int = 10
}
class Foo {
@ann@`setparamann` var field: Int = 10
}
class Foo(@`setparam-`@`ann` protected val field: Int) {}
class Foo(@`ann`@`setparam)` protected val field: Int) {}
| 0
|
ANTLR
|
0
| 0
|
7244ab64ec4e820d0023f35e868b52839d240a2b
| 493
|
kotlin-spec
|
Apache License 2.0
|
app/src/main/java/com/example/gokartandroidapplication/activities/GoKartActivity.kt
|
diegowit
| 772,832,343
| false
|
{"Kotlin": 46241}
|
package com.example.gokartandroidapplication.activities
import android.view.Menu
import com.example.gokartandroidapplication.main.MainApp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import com.example.gokartandroidapplication.models.GoKartModel
import com.example.gokartandroidapplication.databinding.ActivityGokartBinding
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import timber.log.Timber.i
import com.example.gokartandroidapplication.R
import com.example.gokartandroidapplication.helpers.showImagePicker
import android.content.Intent
import android.net.Uri
import com.example.gokartandroidapplication.models.Location
import com.squareup.picasso.Picasso
import com.example.gokartandroidapplication.activities.DatePickerFragment
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
class GoKartActivity : AppCompatActivity() {
private lateinit var binding: ActivityGokartBinding
private lateinit var mapIntentLauncher: ActivityResultLauncher<Intent>
private lateinit var imageIntentLauncher: ActivityResultLauncher<Intent>
//private lateinit var searchView: SearchView
//private lateinit var searchList: ArrayList<GoKartModel>
var gokart = GoKartModel()
lateinit var app: MainApp
var edit = false //tracks if we arrived here via an existing placemark
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGokartBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.topAppBar.title = title
setSupportActionBar(binding.topAppBar)
// Initialize the MainApp and other variables
app = application as MainApp
/***** Logging *****/
i(getString(R.string.gokart_activity_started))
// Check if this activity is opened for editing a GoKartModel
if (intent.hasExtra("gokart_edit")) {
edit = true
gokart = intent.extras?.getParcelable("gokart_edit")!!
// Set the existing data to the UI elements
binding.DriverName.setText(gokart.name)
binding.DriverGender.setText(gokart.gender)
binding.CarModel.setText(gokart.carModel)
binding.btnAdd.text = getString(R.string.save_gokart)
// Load the image if it exists
Picasso.get()
.load(gokart.image)
.into(binding.placemarkImage)
// Change the text of chooseImage button if an image is already selected
if (gokart.image != Uri.EMPTY) {
binding.chooseImage.setText(R.string.change_gokart_image)
}
}
// Handle click event of add button
binding.btnAdd.setOnClickListener() {
gokart.name = binding.DriverName.text.toString()
gokart.gender = binding.DriverGender.text.toString()
gokart.carModel = binding.CarModel.text.toString()
if (gokart.name.isNotEmpty()) {
if (edit) {
app.gokarts.update(gokart.copy())
} else {
app.gokarts.create(gokart.copy())
}
setResult(RESULT_OK)
finish()
} else {
Snackbar.make(
it, getString(R.string.enter_gokart_title),
Snackbar.LENGTH_LONG
).show()
}
}
// Handle click event of chooseImage button
binding.chooseImage.setOnClickListener {
showImagePicker(imageIntentLauncher, this)
}
registerImagePickerCallback()
// Handle click event of GokartLocation button
binding.placemarkLocation.setOnClickListener {
val location = Location(52.245696, -7.139102, 15f)
if (gokart.zoom != 0f) {
location.lat = gokart.lat
location.lng = gokart.lng
location.zoom = gokart.zoom
}
val launcherIntent = Intent(this, MapActivity::class.java)
.putExtra("location", location)
mapIntentLauncher.launch(launcherIntent)
}
registerMapCallback()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_gokart, menu)
if (edit) menu.getItem(1).isVisible = true
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.item_cancel -> {
setResult(RESULT_CANCELED)
finish()
}
R.id.item_delete -> {
app.gokarts.delete(gokart)
setResult(99)
finish()
}
}
return super.onOptionsItemSelected(item)
}
// Register callback for image picker result
private fun registerImagePickerCallback() {
imageIntentLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ result ->
when (result.resultCode) {
RESULT_OK -> {
if (result.data != null) {
i("Got Result ${result.data!!.data}")
val image = result.data!!.data!!
contentResolver.takePersistableUriPermission(
image,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
gokart.image = image
Picasso.get()
.load(gokart.image)
.into(binding.placemarkImage)
binding.chooseImage.setText(R.string.change_gokart_image)
} // end of if
}
RESULT_CANCELED -> {}
else -> {}
}
}
}
// Register callback for map activity result
private fun registerMapCallback() {
mapIntentLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ result ->
when (result.resultCode) {
RESULT_OK -> {
if (result.data != null) {
i("Got Location ${result.data.toString()}")
val location =
result.data!!.extras?.getParcelable<Location>("location")!!
i("Location == $location")
gokart.lat = location.lat
gokart.lng = location.lng
gokart.zoom = location.zoom
} // end of if
}
RESULT_CANCELED -> {}
else -> {}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5fdd1ca86045ea8e6a4e74dc3f119dc201a7eb3d
| 7,208
|
GoKartAndroidApplication
|
MIT License
|
src/test/kotlin/com/autonomousapps/internal/advice/AdvisorTest.kt
|
tasomaniac
| 250,905,017
| true
|
{"Kotlin": 316360, "Java": 71861, "ANTLR": 68053, "Groovy": 18464, "Shell": 587}
|
package com.autonomousapps.internal.advice
import com.autonomousapps.Ignore
import com.autonomousapps.Warn
import com.autonomousapps.internal.*
import com.autonomousapps.internal.utils.filterToOrderedSet
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class AdvisorTest {
private val project1 = Dependency(":project1")
private val project2 = Dependency(":project2")
private val project3 = Dependency(":project3")
private val library1 = Dependency("some:lib1", "1")
private val library2 = Dependency("some:lib2", "1")
private val library3 = Dependency("some:lib3", "1")
private val library4 = Dependency("some:lib4", "1", "api")
private val library5 = Dependency("some:lib5", "1", "api")
private val library6 = Dependency("some:lib6", "1", "implementation")
/* ****************************************
* Change advice (incorrect configurations)
* ****************************************
*/
@Test fun changeAdvice() {
// Given
// 4 (api), 5 (api), and 6 (impl) are declared. 3, 4, and 6 are abi. Therefore 6 should be "changed" from impl to
// api, 5 should be changed from api to implementation, and 3 from null to api.
val abiDeps = listOf(library3, library4, library6)
val allDeclaredDeps = listOf(library4, library5, library6)
// a precondition to ensure I don't set up the test incorrectly
assertTrue("No declared deps will have a null configuration") {
allDeclaredDeps.none { it.configurationName == null }
}
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = emptyList(),
abiDeps = abiDeps,
allDeclaredDeps = allDeclaredDeps
)
val computedAdvice = advisor.compute()
val changeAdvice = computedAdvice.advicePrinter().getChangeAdvice()
// Then
assertNotNull(changeAdvice, "Change advice should not be null")
val expected = sortedSetOf(
Advice.change(library5, "implementation"),
Advice.change(library6, "api")
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isChange() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun changeAdviceRespectsIgnoreChangeRule() {
// Given
// 4 (api), 5 (api), and 6 (impl) are declared. 3 is undeclared but should be api. 5 is api but should be impl. 6 is
// impl but should be api.
val abiDeps = listOf(library3, library4, library6)
val allDeclaredDeps = listOf(library4, library5, library6)
// a precondition to ensure I don't set up the test incorrectly
assertTrue("No declared deps will have a null configuration") {
allDeclaredDeps.none { it.configurationName == null }
}
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = emptyList(),
abiDeps = abiDeps,
allDeclaredDeps = allDeclaredDeps
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(incorrectConfigurationsBehavior = Ignore))
val changeAdvice = computedAdvice.advicePrinter().getChangeAdvice()
// Then
assertNull(changeAdvice, "Change advice should be null")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isChange() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun changeAdviceRespectsIgnoreAllRule() {
// Given
val abiDeps = listOf(library3, library4, library6)
val allDeclaredDeps = listOf(library4, library5, library6)
// a precondition to ensure I don't set up the test incorrectly
assertTrue("No declared deps will have a null configuration") {
allDeclaredDeps.none { it.configurationName == null }
}
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = emptyList(),
abiDeps = abiDeps,
allDeclaredDeps = allDeclaredDeps
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(anyBehavior = Ignore))
val changeAdvice = computedAdvice.advicePrinter().getChangeAdvice()
// Then
assertNull(changeAdvice, "Change advice should be null")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices()
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun changeAdviceRespectsIgnoreSomeFromSpecificRule() {
// Given
// 4 (api), 5 (api), and 6 (impl) are declared. 3, 4, and 6 are ABI. 3: null -> api. 4: no change. 5: api -> impl.
// 6: impl -> api
val abiDeps = listOf(library3, library4, library6)
val allDeclaredDeps = listOf(library4, library5, library6)
// a precondition to ensure I don't set up the test incorrectly
assertTrue("No declared deps will have a null configuration") {
allDeclaredDeps.none { it.configurationName == null }
}
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = emptyList(),
abiDeps = abiDeps,
allDeclaredDeps = allDeclaredDeps
)
val computedAdvice = advisor.compute(
filterSpec = FilterSpec(incorrectConfigurationsBehavior = Warn(setOf(library5.identifier)))
)
val changeAdvice = computedAdvice.advicePrinter().getChangeAdvice()
// Then
assertNotNull(changeAdvice, "Change advice should not be null")
val expected = sortedSetOf(Advice.change(library6, "api"))
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isChange() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun changeAdviceRespectsIgnoreSomeFromAnyRule() {
// Given
val abiDeps = listOf(library3, library4, library6)
val allDeclaredDeps = listOf(library4, library5, library6)
// a precondition to ensure I don't set up the test incorrectly
assertTrue("No declared deps will have a null configuration") {
allDeclaredDeps.none { it.configurationName == null }
}
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = emptyList(),
abiDeps = abiDeps,
allDeclaredDeps = allDeclaredDeps
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(anyBehavior = Warn(setOf(library5.identifier))))
val changeAdvice = computedAdvice.advicePrinter().getChangeAdvice()
// Then
assertNotNull(changeAdvice, "Change advice should not be null")
val expected = sortedSetOf(Advice.change(library6, "api"))
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isChange() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun changeAdviceDoesNotAdviseChangingCompileOnlyDependency() {
// Given
val allComponents = listOf(
Component(dependency = library3, isTransitive = true, isCompileOnlyAnnotations = false, classes = emptySet()),
Component(dependency = library4, isTransitive = false, isCompileOnlyAnnotations = false, classes = emptySet()),
// Because this component is a compileOnly candidate, it will not show up in the change advice.
Component(dependency = library6, isTransitive = false, isCompileOnlyAnnotations = true, classes = emptySet())
)
val abiDeps = listOf(library3, library4, library6)
val allDeclaredDeps = listOf(library4, library6)
// a precondition to ensure I don't set up the test incorrectly
assertTrue("No declared deps will have a null configuration") {
allDeclaredDeps.none { it.configurationName == null }
}
// When
val advisor = Advisor(
allComponents = allComponents,
unusedDirectComponents = emptyList(),
usedTransitiveComponents = emptyList(),
abiDeps = abiDeps,
allDeclaredDeps = allDeclaredDeps
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec())
val changeAdvice = computedAdvice.advicePrinter().getChangeAdvice()
// Then
assertNull(changeAdvice, "There should be nothing to change")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isChange() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
/* *****************************************
* Add advice (used transitive dependencies)
* *****************************************
*/
@Test fun addAdvice() {
// Given
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1, project3)
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec())
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNotNull(addAdvice, "Add advice should not be null")
val expected = sortedSetOf(
Advice.add(project1, "api"),
Advice.add(project2, "implementation"),
Advice.add(project3, "api")
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun addAdviceRespectsIgnoreChangeRule() {
// Given
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1, project3)
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(usedTransitivesBehavior = Ignore))
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNull(addAdvice, "Add advice should be null")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun addAdviceRespectsIgnoreAllRule() {
// Given
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1, project3)
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(anyBehavior = Ignore))
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNull(addAdvice, "Add advice should not be null")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun addAdviceRespectsIgnoreSomeFromSpecificRule() {
// Given
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1, project3)
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(usedTransitivesBehavior = Warn(setOf(project1.identifier))))
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNotNull(addAdvice, "Add advice should not be null")
val expected = sortedSetOf(
Advice.add(project2, "implementation"),
Advice.add(project3, "api")
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun addAdviceRespectsIgnoreSomeFromAnyRule() {
// Given
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1, project3)
// When
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(anyBehavior = Warn(setOf(project1.identifier))))
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNotNull(addAdvice, "Add advice should not be null")
val expected = sortedSetOf(
Advice.add(project2, "implementation"),
Advice.add(project3, "api")
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun addAdviceDoesNotAdviseAddingCompileOnlyDependency() {
// Given
val allComponents = listOf(
Component(project1, isTransitive = true, isCompileOnlyAnnotations = false, classes = emptySet()),
Component(project2, isTransitive = true, isCompileOnlyAnnotations = false, classes = emptySet()),
Component(project3, isTransitive = false, isCompileOnlyAnnotations = true, classes = emptySet())
)
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1, project3)
// When
val advisor = Advisor(
allComponents = allComponents,
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec())
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNotNull(addAdvice, "Add advice should not be null")
val expected = sortedSetOf(
Advice.add(project1, "api"),
Advice.add(project2, "implementation")
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun addAdviceDoesNotAdviseAddingTransitiveCompileOnlyDependency() {
// Given
val allComponents = listOf(
Component(project1, isTransitive = true, isCompileOnlyAnnotations = false, classes = emptySet()),
Component(project2, isTransitive = true, isCompileOnlyAnnotations = true, classes = emptySet())
)
val usedTransitiveComponents = listOf(
TransitiveComponent(project1, emptySet()),
TransitiveComponent(project2, emptySet())
)
val abiDeps = listOf(project1)
// When
val advisor = Advisor(
allComponents = allComponents,
unusedDirectComponents = emptyList(),
usedTransitiveComponents = usedTransitiveComponents,
abiDeps = abiDeps,
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec())
val addAdvice = computedAdvice.advicePrinter().getAddAdvice()
// Then
assertNotNull(addAdvice, "Add advice should not be null")
val expected = sortedSetOf(
Advice.add(project1, "api")
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isAdd() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
/* ***********************************
* Remove advice (unused dependencies)
* ***********************************
*/
@Test fun removeAdvice() {
// Given
val unusedDirectComponents = listOf(
UnusedDirectComponent(project1, mutableSetOf(library1)),
UnusedDirectComponent(project2, mutableSetOf(library2)),
UnusedDirectComponent(project3, mutableSetOf())
)
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = unusedDirectComponents,
usedTransitiveComponents = emptyList(),
abiDeps = emptyList(),
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec())
// When
val removeAdvice = computedAdvice.advicePrinter().getRemoveAdvice()
// Then
assertNotNull(removeAdvice, "Remove advice should not be null")
val expected = sortedSetOf(
Advice.remove(project1),
Advice.remove(project2),
Advice.remove(project3)
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isRemove() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun removeAdviceRespectsIgnoreChangeRule() {
// Given
val unusedDirectComponents = listOf(
UnusedDirectComponent(project1, mutableSetOf(library1)),
UnusedDirectComponent(project2, mutableSetOf(library2)),
UnusedDirectComponent(project3, mutableSetOf())
)
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = unusedDirectComponents,
usedTransitiveComponents = emptyList(),
abiDeps = emptyList(),
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(unusedDependenciesBehavior = Ignore))
// When
val removeAdvice = computedAdvice.advicePrinter().getRemoveAdvice()
// Then
assertNull(removeAdvice, "Remove advice should be null")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isRemove() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun removeAdviceRespectsIgnoreAllRule() {
// Given
val unusedDirectComponents = listOf(
UnusedDirectComponent(project1, mutableSetOf(library1)),
UnusedDirectComponent(project2, mutableSetOf(library2)),
UnusedDirectComponent(project3, mutableSetOf())
)
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = unusedDirectComponents,
usedTransitiveComponents = emptyList(),
abiDeps = emptyList(),
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(anyBehavior = Ignore))
// When
val removeAdvice = computedAdvice.advicePrinter().getRemoveAdvice()
// Then
assertNull(removeAdvice, "Remove advice should be null")
val expected = emptySet<Advice>()
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isRemove() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun removeAdviceRespectsIgnoreSomeFromSpecificRule() {
// Given
val unusedDirectComponents = listOf(
UnusedDirectComponent(project1, mutableSetOf(library1)),
UnusedDirectComponent(project2, mutableSetOf(library2)),
UnusedDirectComponent(project3, mutableSetOf())
)
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = unusedDirectComponents,
usedTransitiveComponents = emptyList(),
abiDeps = emptyList(),
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(unusedDependenciesBehavior = Warn(setOf(project1.identifier))))
// When
val removeAdvice = computedAdvice.advicePrinter().getRemoveAdvice()
// Then
assertNotNull(removeAdvice, "Remove advice should not be null")
val expected = sortedSetOf(
Advice.remove(project2),
Advice.remove(project3)
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isRemove() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun removeAdviceRespectsIgnoreSomeFromAnyRule() {
// Given
val unusedDirectComponents = listOf(
UnusedDirectComponent(project1, mutableSetOf(library1)),
UnusedDirectComponent(project2, mutableSetOf(library2)),
UnusedDirectComponent(project3, mutableSetOf())
)
val advisor = Advisor(
allComponents = emptyList(),
unusedDirectComponents = unusedDirectComponents,
usedTransitiveComponents = emptyList(),
abiDeps = emptyList(),
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec(anyBehavior = Warn(setOf(project1.identifier))))
// When
val removeAdvice = computedAdvice.advicePrinter().getRemoveAdvice()
// Then
assertNotNull(removeAdvice, "Remove advice should not be null")
val expected = sortedSetOf(
Advice.remove(project2),
Advice.remove(project3)
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isRemove() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
@Test fun removeAdviceWillNotAdviseRemovingACompileOnlyDependency() {
// Given
val allComponents = listOf(
Component(project1, isTransitive = false, isCompileOnlyAnnotations = true, classes = emptySet()),
Component(project2, isTransitive = false, isCompileOnlyAnnotations = false, classes = emptySet()),
Component(project3, isTransitive = false, isCompileOnlyAnnotations = false, classes = emptySet())
)
val unusedDirectComponents = listOf(
UnusedDirectComponent(project1, mutableSetOf()),
UnusedDirectComponent(project2, mutableSetOf()),
UnusedDirectComponent(project3, mutableSetOf())
)
val advisor = Advisor(
allComponents = allComponents,
unusedDirectComponents = unusedDirectComponents,
usedTransitiveComponents = emptyList(),
abiDeps = emptyList(),
allDeclaredDeps = emptyList()
)
val computedAdvice = advisor.compute(filterSpec = FilterSpec())
// When
val removeAdvice = computedAdvice.advicePrinter().getRemoveAdvice()
// Then
assertNotNull(removeAdvice, "Remove advice should not be null")
val expected = sortedSetOf(
Advice.remove(project2),
Advice.remove(project3)
)
val actual = computedAdvice.getAdvices().filterToOrderedSet { it.isRemove() }
assertEquals(expected, actual, "Expected $expected\nActual $actual\n")
}
}
| 0
| null |
0
| 1
|
866161796c564fc19b6fcca2343f438e8ec9aeff
| 22,865
|
dependency-analysis-android-gradle-plugin
|
Apache License 2.0
|
core/src/main/java/android/core/external/constants/AppConstant.kt
|
tossaro
| 526,498,578
| false
|
{"Kotlin": 31073}
|
package android.core.external.constants
object AppConstant {
}
| 0
|
Kotlin
|
0
| 0
|
210d0531abcb00f82d1da9387fad0da333dfe2af
| 63
|
kotlin-android-core
|
MIT License
|
app/src/main/java/com/eeyan/mymenty/common/loader/AnimatorDialog.kt
|
otsembo
| 436,253,051
| false
|
{"Kotlin": 72165}
|
package com.eeyan.mymenty.common.loader
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.widget.LinearLayout
import com.eeyan.mymenty.R
import com.eeyan.mymenty.databinding.DialogAnimatorBinding
class AnimatorDialog (mCtx: Context) : Dialog(mCtx){
//binding object
private lateinit var binding:DialogAnimatorBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DialogAnimatorBinding.inflate(layoutInflater)
setContentView(binding.root)
window?.let{
it.setLayout(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
it.setBackgroundDrawableResource(R.color.transparent_50)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
9684f230b7bd53f9648fa65ba482bc56835b9290
| 841
|
MyMenty
|
Apache License 2.0
|
services/csm.cloud.api/src/main/kotlin/com/bosch/pt/iot/smartsite/api/security/facade/rest/KeyCloak1SignupController.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2023
*
* ************************************************************************
*/
package com.bosch.pt.iot.smartsite.api.security.facade.rest
import com.bosch.pt.iot.smartsite.api.security.RedirectConstants.REDIRECT_URL_PARAMETER
import com.bosch.pt.iot.smartsite.api.security.config.KeyCloak1Configuration.Companion.KEYCLOAK1
import java.net.URI.create
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpStatus.FOUND
import org.springframework.http.ResponseEntity
import org.springframework.http.ResponseEntity.status
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
import reactor.core.publisher.Mono.just
@Profile(KEYCLOAK1)
@RestController
class KeyCloak1SignupController {
/** Redirects to /login as it is the exact same flow with KEYCLOAK1 (and SingleKeyID). */
@GetMapping("/signup", "/api/signup")
fun signupInternal(
@RequestParam(name = REDIRECT_URL_PARAMETER) redirectUri: String
): Mono<ResponseEntity<Any>> =
just(status(FOUND).location(create("/login?$REDIRECT_URL_PARAMETER=$redirectUri")).build())
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 1,386
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
app/src/main/java/com/smihajlovski/instabackstack/ui/base/BaseActivity.kt
|
kdu0136
| 376,753,829
| true
|
{"Kotlin": 37896, "Java": 1147}
|
package com.smihajlovski.instabackstack.ui.base
import android.content.Intent
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import com.smihajlovski.instabackstack.tmp.PrintLog
import com.smihajlovski.instabackstack.tmp.createDataBinding
abstract class BaseActivity<VB : ViewDataBinding>(@LayoutRes resId: Int) :
AppCompatActivity() {
protected val activityTag = javaClass.simpleName
protected val binding: VB by lazy { createDataBinding(activity = this, resId = resId) }
/**
* page UI setup
*/
abstract fun onSetupUI()
/**
* page view model observe setting
*/
abstract fun observeViewModel()
override fun onCreate(savedInstanceState: Bundle?) {
// PrintLog.d(javaClass.simpleName, "onCreate", activityTag)
super.onCreate(savedInstanceState)
onSetupUI()
observeViewModel()
}
override fun onStart() {
// PrintLog.d(javaClass.simpleName, "onStart", activityTag)
super.onStart()
}
override fun onResume() {
// PrintLog.d(javaClass.simpleName, "onResume", activityTag)
super.onResume()
}
override fun onPause() {
// PrintLog.d(javaClass.simpleName, "onPause", activityTag)
super.onPause()
}
override fun onRestart() {
// PrintLog.d(javaClass.simpleName, "onRestart", activityTag)
super.onRestart()
}
override fun onStop() {
// PrintLog.d(javaClass.simpleName, "onStop", activityTag)
super.onStop()
}
override fun onDestroy() {
// PrintLog.d(javaClass.simpleName, "onDestroy", activityTag)
super.onDestroy()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
PrintLog.d("ActivityResult", "resultCode: $resultCode", activityTag)
PrintLog.d("ActivityResult", "requestCode: $requestCode", activityTag)
}
override fun onSaveInstanceState(outState: Bundle) {
// PrintLog.d(javaClass.simpleName, "onSaveInstanceState", activityTag)
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
// PrintLog.d(javaClass.simpleName, "onRestoreInstanceState", activityTag)
super.onRestoreInstanceState(savedInstanceState)
}
}
| 0
|
Kotlin
|
0
| 0
|
7a0714dac29aae86b1a9f0fed7280d706c462c4e
| 2,470
|
instagram-like-backstack
|
Apache License 2.0
|
numeriko-core/src/main/kotlin/tomasvolker/numeriko/core/operations/reduction/DoubleReductions.kt
|
TomasVolker
| 114,266,369
| false
| null |
package tomasvolker.numeriko.core.operations.reduction
import tomasvolker.numeriko.core.index.All
import tomasvolker.numeriko.core.interfaces.array1d.double.DoubleArray1D
import tomasvolker.numeriko.core.interfaces.array1d.integer.IntArray1D
import tomasvolker.numeriko.core.interfaces.array2d.double.DoubleArray2D
import tomasvolker.numeriko.core.interfaces.array2d.generic.indices0
import tomasvolker.numeriko.core.interfaces.array2d.generic.indices1
import tomasvolker.numeriko.core.interfaces.arraynd.double.DoubleArrayND
import tomasvolker.numeriko.core.interfaces.arraynd.double.unsafeGetView
import tomasvolker.numeriko.core.interfaces.arraynd.generic.indices
import tomasvolker.numeriko.core.interfaces.factory.doubleArray1D
import tomasvolker.numeriko.core.interfaces.factory.doubleArrayND
import tomasvolker.numeriko.core.interfaces.factory.intArray1D
inline fun reduce(
indices: IntProgression,
initial: Double,
combine: (acc: Double, next: Double)->Double,
selector: (Int)->Double
): Double {
var result = initial
for (i in indices) {
result = combine(result, selector(i))
}
return result
}
inline fun DoubleArray1D.reduce(
initial: Double,
combine: (acc: Double, next: Double)->Double
): Double = reduce(indices, initial, combine) { i -> this[i] }
inline fun DoubleArray2D.reduce(
initial: Double,
axis: Int = 0,
combine: (acc: Double, next: Double)->Double
): DoubleArray1D = when(axis) {
0 -> doubleArray1D(shape1) { i1 ->
reduce(indices0, initial, combine) { i0 -> this[i0, i1] }
}
1 -> doubleArray1D(shape0) { i0 ->
reduce(indices1, initial, combine) { i1 -> this[i0, i1] }
}
else -> throw IllegalArgumentException()
}
inline fun DoubleArray2D.reduce(
axis: Int = 0,
reduction: (array: DoubleArray1D)->Double
): DoubleArray1D = when(axis) {
0 -> doubleArray1D(shape1) { i1 ->
reduction(this[All, i1])
}
1 -> doubleArray1D(shape0) { i0 ->
reduction(this[i0, All])
}
else -> throw IllegalArgumentException()
}
inline fun DoubleArrayND.reduce(
initial: Double,
axis: Int = 0,
combine: (acc: Double, next: Double)->Double
): DoubleArrayND =
doubleArrayND(shape.remove(axis)) { indices ->
reduce(this.indices(axis), initial, combine) { ir ->
this[indices.inject(index = axis, value = ir)]
}
}
inline fun DoubleArrayND.reduce(
axis: Int = 0,
reduction: (acc: DoubleArray1D)->Double
): DoubleArrayND =
doubleArrayND(shape.remove(axis)) { indices ->
reduction(
this.unsafeGetView(
*Array<Any>(rank) { a ->
when {
a < axis -> indices[a]
a == axis -> All
else -> indices[a-1]
}
}
).as1D()
)
}
| 8
|
Kotlin
|
1
| 3
|
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
| 3,069
|
numeriko
|
Apache License 2.0
|
src/main/kotlin/kitowashere/boiled_witchcraft/common/world/glyph/type/FireGlyphType.kt
|
AugustoMegener
| 750,093,937
| false
|
{"Kotlin": 62440}
|
package kitowashere.boiled_witchcraft.common.world.glyph.type
import kitowashere.boiled_witchcraft.common.data.glyph.PillarGlyphData
class FireGlyphType : GlyphType.PrimaryGlyphType(listOf(1, 2, 3)) {
override fun newData(): PillarGlyphData = PillarGlyphData()
}
| 0
|
Kotlin
|
0
| 1
|
5952266c28d9593b89be44c601fa9763f937451b
| 268
|
boiled_witchcraft
|
MIT License
|
aareg/src/main/kotlin/no/nav/helse/sparkel/aareg/arbeidsforholdV2/StsRestClient.kt
|
navikt
| 341,650,641
| false
| null |
package no.nav.helse.sparkel.aareg.arbeidsforholdV2
import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.client.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.runBlocking
import no.nav.helse.sparkel.aareg.objectMapper
import no.nav.helse.sparkel.aareg.util.ServiceUser
import java.time.LocalDateTime
/**
* henter jwt fra STS
*/
class StsRestClient(
private val baseUrl: String,
private val serviceUser: ServiceUser,
private val httpClient: HttpClient = HttpClient {
install(HttpTimeout) {
socketTimeoutMillis = 10000
requestTimeoutMillis = 10000
connectTimeoutMillis = 10000
}
}
) {
private var cachedOidcToken: Token = runBlocking { fetchToken() }
suspend fun token(): String {
if (cachedOidcToken.expired) cachedOidcToken = fetchToken()
return cachedOidcToken.access_token
}
private suspend fun fetchToken(): Token = httpClient.get<HttpStatement>(
"$baseUrl/rest/v1/sts/token?grant_type=client_credentials&scope=openid"
) {
header("Authorization", serviceUser.basicAuth)
accept(ContentType.Application.Json)
}.execute { objectMapper.readValue(it.readText()) }
internal data class Token(
internal val access_token: String,
private val token_type: String,
private val expires_in: Long
) {
// expire 10 seconds before actual expiry. for great margins.
private val expirationTime: LocalDateTime = LocalDateTime.now().plusSeconds(expires_in - 10L)
internal val expired get() = expirationTime.isBefore(LocalDateTime.now())
}
}
| 0
|
Kotlin
|
0
| 1
|
1582a5129c10c88fbb2bf4d65492195042661809
| 1,739
|
helse-sparkelapper
|
MIT License
|
src/main/kotlin/io/github/dockyardmc/sounds/Sounds.kt
|
DockyardMC
| 650,731,309
| false
|
{"Kotlin": 1019371}
|
package io.github.dockyardmc.sounds
import io.github.dockyardmc.DockyardServer
import io.github.dockyardmc.extentions.*
import io.github.dockyardmc.location.Location
import io.github.dockyardmc.player.Player
import io.github.dockyardmc.player.PlayerManager
import io.github.dockyardmc.protocol.packets.play.clientbound.ClientboundPlaySoundPacket
import io.github.dockyardmc.protocol.packets.play.clientbound.SoundCategory
import io.github.dockyardmc.world.World
import io.netty.buffer.ByteBuf
class Sound(var identifier: String, var volume: Float = 0.5f, var pitch: Float = 1.0f, var category: SoundCategory = SoundCategory.MASTER) {
init {
if(!identifier.contains(":")) identifier = "minecraft:$identifier"
}
}
fun Player.playSound(sound: Sound, location: Location = this.location) {
val packet = ClientboundPlaySoundPacket(sound, location)
this.sendPacket(packet)
}
fun Player.playSound(identifier: String, location: Location = this.location, volume: Float = 0.5f, pitch: Float = 1.0f, category: SoundCategory = SoundCategory.MASTER) {
val sound = Sound(identifier, volume, pitch, category)
this.playSound(sound, location)
}
fun Player.playSound(identifier: String, volume: Float = 0.5f, pitch: Float = 1.0f, category: SoundCategory = SoundCategory.MASTER) {
val sound = Sound(identifier, volume, pitch, category)
this.playSound(sound, this.location)
}
fun Collection<Player>.playSound(sound: Sound, location: Location? = null) {
this.forEach { it.playSound(sound, location ?: it.location) }
}
fun Collection<Player>.playSound(identifier: String, location: Location? = null, volume: Float = 0.5f, pitch: Float = 1.0f, category: SoundCategory = SoundCategory.MASTER) {
val sound = Sound(identifier, volume, pitch, category)
this.playSound(sound)
}
fun World.playSound(sound: Sound, location: Location? = null) {
this.players.values.playSound(sound, location)
}
fun World.playSound(identifier: String, location: Location? = null, volume: Float = 0.5f, pitch: Float = 1.0f, category: SoundCategory = SoundCategory.MASTER) {
val sound = Sound(identifier, volume, pitch, category)
this.playSound(sound, location)
}
fun DockyardServer.playSound(sound: Sound, location: Location? = null) {
PlayerManager.players.playSound(sound, location)
}
fun DockyardServer.playSound(identifier: String, location: Location? = null, volume: Float = 0.5f, pitch: Float = 1.0f, category: SoundCategory = SoundCategory.MASTER) {
val sound = Sound(identifier, volume, pitch, category)
this.playSound(sound, location)
}
fun ByteBuf.writeSoundEvent(sound: String) {
this.writeVarInt(0)
this.writeUtf(sound)
this.writeBoolean(false)
}
fun ByteBuf.readSoundEvent(): String {
val type = this.readVarInt()
val identifier = this.readString()
val hasFixedRange = this.readBoolean()
if(hasFixedRange) {
val fixedRange = this.readFloat()
}
return identifier
}
| 6
|
Kotlin
|
7
| 55
|
9a0eb8f3184123b79b835356ddde526d9eb6df65
| 2,959
|
Dockyard
|
MIT License
|
src/main/kotlin/com/IceCreamQAQ/SmartWeb/server/WebServer.kt
|
Yu-Works
| 546,741,389
| false
|
{"Kotlin": 78653, "HTML": 191, "Java": 1}
|
package com.IceCreamQAQ.SmartWeb.server
import com.IceCreamQAQ.SmartWeb.http.websocket.WsAction
interface WebServer {
fun createWsAction(path: String, action: WsAction)
}
| 0
|
Kotlin
|
0
| 3
|
428aaafaf98a32d5d44da4d6f12ed01a9a361919
| 182
|
SmartWeb
|
Apache License 2.0
|
word-herd-server/src/main/kotlin/com/tripledip/wordherdserver/AuthenticationChecker.kt
|
benjamin-heasly
| 136,988,497
| false
|
{"Kotlin": 17887, "JavaScript": 9376, "HTML": 1590, "Shell": 1534, "CSS": 711}
|
package com.tripledip.wordherdserver
import org.jboss.logging.Logger
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.security.Principal
@RestController
class AuthenticationChecker {
val log = Logger.getLogger(AuthenticationChecker::class.java)
@GetMapping("/checkAuth")
fun checkAuth(principal: Principal): String {
log.info("checkAuth for ${principal.name}")
return "If you can read this, you are authenticated."
}
}
| 0
|
Kotlin
|
0
| 0
|
9e41e79c0baf007b0bae0929c1d96977ba1f8536
| 537
|
word-herd
|
The Unlicense
|
app/src/main/java/com/msg/gcms/data/remote/dto/club/request/MemberManagementRequest.kt
|
GSM-MSG
| 465,292,111
| false
| null |
package com.msg.gcms.data.remote.dto.club.request
data class MemberManagementRequest(
val q : String,
val type : String,
val userId : String
)
| 4
|
Kotlin
|
0
| 0
|
8239a015cc311b1631e0c6fc5047e231b5a7ec20
| 156
|
GCMS-Android
|
MIT License
|
korge-gradle-plugin-common/src/test/kotlin/com/soywiz/kproject/util/NewKProjectResolverTest.kt
|
korlibs
| 80,095,683
| false
|
{"Kotlin": 4210038, "C": 105670, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 1068, "Shell": 439, "CMake": 202, "Batchfile": 41, "CSS": 33}
|
package com.soywiz.kproject.util
import com.soywiz.kproject.model.*
import kotlin.test.*
class NewKProjectResolverTest {
@Test
fun testResolver() {
val files = MemoryFiles().root
files["demo/kproject.yml"] = """
dependencies:
- ../demo2
""".trimIndent()
files["demo2/kproject.yml"] = """
name: Ademo2
dependencies:
- ../demo3.kproject.yml
- ../demo4
""".trimIndent()
files["demo4/kproject.yml"] = """
name: Ademo4
""".trimIndent()
files["demo3.kproject.yml"] = """
name: Ademo3
dependencies:
- ../demo
""".trimIndent()
val resolver = NewKProjectResolver()
val mainProject = resolver.load(files["demo/kproject.yml"])
assertEquals(
"""
demo
Ademo2
Ademo3
<recursion detected>
Ademo4
""".trimIndent(),
mainProject.dumpDependenciesToString()
)
//println(mainProject)
/*
println("---")
for (dep in mainProject.dependencies) {
println(resolver.getProjectByDependency(dep))
}
println("---")
for (dep in resolver.getProjectByName("Ademo2").project.dependencies) {
println(resolver.getProjectByDependency(dep))
}
println("---")
println(resolver.getAllProjects().values.joinToString("\n"))
*/
assertEquals(listOf("demo", "Ademo2", "Ademo3", "Ademo4"), resolver.getProjectNames().toList())
val paths = resolver.getAllProjects().map {
it.key to ((it.value.dep as? FileRefDependency?)?.path as? MemoryFileRef?)?.path?.fullPath
}.toMap()
assertEquals(mapOf(
"demo" to "/demo/kproject.yml",
"Ademo2" to "/demo2/kproject.yml",
"Ademo3" to "/demo3.kproject.yml",
"Ademo4" to "/demo4/kproject.yml",
), paths)
}
@Test
fun testVersionConflict() {
val files = MemoryFiles().root
files["demo/kproject.yml"] = """
dependencies:
- ../demo2
-"maven::common::org.jetbrains.compose.runtime:runtime:1.4.0"
""".trimIndent()
files["demo2/kproject.yml"] = """
name: Ademo2
dependencies:
- ../demo3
- "maven::common::org.jetbrains.compose.runtime:runtime:1.4.2"
""".trimIndent()
files["demo3/kproject.yml"] = """
name: Ademo3
dependencies:
- "maven::common::org.jetbrains.compose.runtime:runtime:1.4.1"
""".trimIndent()
val resolver = NewKProjectResolver()
val mainProject = resolver.load(files["demo/kproject.yml"])
assertEquals(
"""
demo
Ademo2
Ademo3
org.jetbrains.compose.runtime-runtime:1.4.2
<recursion detected>
<recursion detected>
""".trimIndent(),
mainProject.dumpDependenciesToString()
)
assertEquals(listOf("demo", "Ademo2", "Ademo3"), resolver.getProjectNames().toList())
assertEquals(
listOf(
MavenDependency(group="org.jetbrains.compose.runtime", name="runtime", version="1.4.2".version, target="common")
),
resolver.getAllMavenDependencies().map { it.dep }
)
val out = arrayListOf<String>().also { it ->
for (project in resolver.getAllProjects().values) {
it.add("${project.name}:")
for (dep in project.dependencies) {
it.add(" - ${dep.dep}")
}
}
}
assertEquals(
"""
demo:
- FileRefDependency(path=MemoryFileRef(files=MemoryFiles[3], path=PathInfo(/demo2/kproject.yml)))
- MavenDependency(group=org.jetbrains.compose.runtime, name=runtime, version=1.4.2, target=common)
Ademo2:
- FileRefDependency(path=MemoryFileRef(files=MemoryFiles[3], path=PathInfo(/demo3/kproject.yml)))
- MavenDependency(group=org.jetbrains.compose.runtime, name=runtime, version=1.4.2, target=common)
Ademo3:
- MavenDependency(group=org.jetbrains.compose.runtime, name=runtime, version=1.4.2, target=common)
""".trimIndent(),
out.joinToString("\n")
)
val paths = resolver.getAllProjects().map {
it.key to ((it.value.dep as? FileRefDependency?)?.path as? MemoryFileRef?)?.path?.fullPath
}.toMap()
assertEquals(mapOf(
"demo" to "/demo/kproject.yml",
"Ademo2" to "/demo2/kproject.yml",
"Ademo3" to "/demo3/kproject.yml",
), paths)
}
@Test
fun testResolverWithGit() {
val files = MemoryFiles().root
files["demo/kproject.yml"] = """
dependencies:
- "https://github.com/korlibs/kproject.git/samples/demo2#95696dd942ebc8db4ee9d9f4835ce12d853ff16f"
""".trimIndent()
val resolver = NewKProjectResolver()
val mainProject = resolver.load(files["demo/kproject.yml"])
assertEquals(
"""
demo
Ademo2:95696dd942ebc8db4ee9d9f4835ce12d853ff16f
Ademo3
org.jetbrains.compose.runtime-runtime:1.4.1
""".trimIndent(),
mainProject.dumpDependenciesToString()
)
assertEquals(listOf("demo", "Ademo2", "Ademo3"), resolver.getProjectNames().toList())
val paths = resolver.getAllProjects().map {
it.key to ((it.value.dep as? FileRefDependency?)?.path as? MemoryFileRef?)?.path?.fullPath
}.toMap()
assertEquals(mapOf(
"demo" to "/demo/kproject.yml",
"Ademo2" to null,
"Ademo3" to null,
), paths)
}
}
| 464
|
Kotlin
|
123
| 2,497
|
1a565007ab748e00a4d602fcd78f7d4032afaf0b
| 6,150
|
korge
|
Apache License 2.0
|
app/src/main/java/com/example/pokedex/viewmodel/PokemonViewModelFactory.kt
|
GabrielDaCostaAlves
| 843,550,258
| false
|
{"Kotlin": 15022}
|
package com.example.pokedex.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.pokedex.data.repository.PokemonRepository
class PokemonViewModelFactory(private val repository: PokemonRepository) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(PokemonViewModel::class.java)) {
return PokemonViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 0
|
Kotlin
|
0
| 0
|
de111916016c6b646b104c533a80c1d6a8b51db9
| 593
|
Pokedex
|
MIT License
|
return-to-wild/src/main/kotlin/com/briarcraft/rtw/change/repo/DependencyChanges.kt
|
toddharrison
| 581,553,858
| false
| null |
package com.briarcraft.rtw.change.repo
import org.bukkit.Location
import org.bukkit.World
data class DependencyChanges(
val world: World,
val locations: List<Location>
)
| 0
|
Kotlin
|
1
| 4
|
80528c8dbea16f3f7e3058785351eaba027c23a8
| 179
|
BriarCode
|
MIT License
|
_pending/android-super-hero-app/features/characters/characters-data/src/test/java/com/carlosrd/superhero/data/characters/datasource/remote/CharactersRemoteDataSourceTest.kt
|
luannguyen252
| 371,359,679
| false
| null |
package com.carlosrd.superhero.data.characters.datasource.remote
import com.carlosrd.superhero.data.characters.datasource.remote.model.CharactersDTO
import com.carlosrd.superhero.data.characters.datasource.remote.retrofit.CharactersService
import com.carlosrd.superhero.domain.characters.model.CharacterModel
import com.carlosrd.superhero.domain.either.Either
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import junit.framework.Assert
import junit.framework.Assert.assertEquals
import org.junit.Test
import retrofit2.Call
import retrofit2.Response
import java.io.IOException
class CharactersRemoteDataSourceTest {
private val mockCharacterDTO : CharactersDTO
private val mockCharacterId = 1234L
private val mockCharacterIdError = 4321L
private val mockCharacterIdException = 9999L
private val mockCharacterName = "CharacterName"
private val mockCharacterDescription = "CharacterDescription"
private val mockErrorMessage = "Error"
private val charactersService : CharactersService
private val charactersRemoteDataSource : CharactersRemoteDataSource
init {
val mockThumbnailDTO : CharactersDTO.Data.Results.Thumbnail = mockk {
every { path } returns ""
every { extension } returns ""
}
val mockResultsDTO : CharactersDTO.Data.Results = mockk(){
every { id } returns mockCharacterId
every { name } returns mockCharacterName
every { description } returns mockCharacterDescription
every { thumbnail } returns mockThumbnailDTO
every { comics } returns CharactersDTO.Data.Results.Comics(0,0,"", listOf())
every { series } returns CharactersDTO.Data.Results.Series(0,0,"", listOf())
every { events } returns CharactersDTO.Data.Results.Events(0,0,"", listOf())
every { stories } returns CharactersDTO.Data.Results.Stories(0,0,"", listOf())
}
mockCharacterDTO = mockk(){
every { data.results } returns listOf(mockResultsDTO)
}
val mockResponse : Response<CharactersDTO> = mockk() {
every { body() } returns mockCharacterDTO
every { isSuccessful } returns true
}
val mockResponseError : Response<CharactersDTO> = mockk() {
every { isSuccessful } returns false
}
val mockCall : Call<CharactersDTO> = mockk() {
every { execute() } returns mockResponse
}
val mockCallError : Call<CharactersDTO> = mockk() {
every { execute() } returns mockResponseError
}
val mockCallException : Call<CharactersDTO> = mockk() {
every { execute() } throws IOException()
}
charactersService = mockk() {
every { getCharacterDetails(mockCharacterId, any()) } returns mockCall
every { getCharacterDetails(mockCharacterIdError, any()) } returns mockCallError
every { getCharacterDetails(mockCharacterIdException, any()) } returns mockCallException
}
charactersRemoteDataSource = CharactersRemoteDataSource(charactersService, mockk())
}
@Test
fun `Test getCharacterDetails - Success`(){
val result = charactersRemoteDataSource.getCharacterDetails(mockCharacterId)
verify(exactly = 1) { charactersService.getCharacterDetails(mockCharacterId, any()) }
assert(result is Either.Success<CharactersDTO>)
assertEquals((result as Either.Success<CharactersDTO>).data.data.results[0].name, mockCharacterName)
assertEquals(result.data.data.results[0].id, mockCharacterId)
assertEquals(result.data.data.results[0].description, mockCharacterDescription)
}
@Test
fun `Test getCharacterDetails - Failure`(){
val result = charactersRemoteDataSource.getCharacterDetails(mockCharacterIdError)
verify(exactly = 1) { charactersService.getCharacterDetails(mockCharacterIdError, any()) }
assert(result is Either.Failure<String>)
assertEquals((result as Either.Failure<String>).error,
"Request error.\nPlease try again...")
}
@Test
fun `Test getCharacterDetails - Failure by Exception`(){
val result = charactersRemoteDataSource.getCharacterDetails(mockCharacterIdException)
verify(exactly = 1) { charactersService.getCharacterDetails(mockCharacterIdException, any()) }
assert(result is Either.Failure<String>)
assertEquals((result as Either.Failure<String>).error,
"Request exception error.\nPlease try again...")
}
}
| 0
|
Kotlin
|
0
| 1
|
a9b5aef8662a1808042c820c3dfac02e1efd5800
| 4,618
|
my-android-journey
|
MIT License
|
mvvm_rhine/src/main/java/com/qingmei2/rhine/ext/paging/PagingExt.kt
|
xiaowu55555
| 173,267,488
| true
|
{"Kotlin": 125811}
|
package com.qingmei2.rhine.ext.paging
import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import androidx.paging.RxPagedListBuilder
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
object Paging {
fun <T> buildLiveData(
intPageKeyedDataSource: IntPageKeyedDataSource<T>,
enablePlaceholders: Boolean = false,
pageSize: Int = DEFAULT_PAGE_SIZE,
initialLoadSizeHint: Int = DEFAULT_INITIAL_LOAD_SIZE_HINT,
prefetchDistance: Int = DEFAULT_PREFETCH_DISTANCE
): LiveData<PagedList<T>> =
buildLiveDataPageList(
dataSourceFactory = intPageKeyedDataSource(dataSource = intPageKeyedDataSource),
enablePlaceholders = enablePlaceholders,
pageSize = pageSize,
initialLoadSizeHint = initialLoadSizeHint,
prefetchDistance = prefetchDistance
)
fun <T> buildReactiveStream(
intPageKeyedDataSource: IntPageKeyedDataSource<T>,
enablePlaceholders: Boolean = false,
pageSize: Int = DEFAULT_PAGE_SIZE,
initialLoadSizeHint: Int = DEFAULT_INITIAL_LOAD_SIZE_HINT,
prefetchDistance: Int = DEFAULT_PREFETCH_DISTANCE
): Flowable<PagedList<T>> =
buildRxJavaPagedList(
dataSourceFactory = intPageKeyedDataSource(dataSource = intPageKeyedDataSource),
enablePlaceholders = enablePlaceholders,
pageSize = pageSize,
initialLoadSizeHint = initialLoadSizeHint,
prefetchDistance = prefetchDistance
)
private fun <T> intPageKeyedDataSource(
dataSource: IntPageKeyedDataSource<T>
): DataSource.Factory<Int, T> =
object : DataSource.Factory<Int, T>() {
override fun create(): DataSource<Int, T> = dataSource
}
private fun <T> buildRxJavaPagedList(
dataSourceFactory: DataSource.Factory<Int, T>,
enablePlaceholders: Boolean = false,
pageSize: Int = DEFAULT_PAGE_SIZE,
initialLoadSizeHint: Int = DEFAULT_INITIAL_LOAD_SIZE_HINT,
prefetchDistance: Int = DEFAULT_PREFETCH_DISTANCE
): Flowable<PagedList<T>> =
RxPagedListBuilder<Int, T>(
dataSourceFactory,
PagedList.Config
.Builder()
.setInitialLoadSizeHint(initialLoadSizeHint)
.setPageSize(pageSize)
.setPrefetchDistance(prefetchDistance)
.setEnablePlaceholders(enablePlaceholders)
.build()
).buildFlowable(BackpressureStrategy.LATEST)
private fun <T> buildLiveDataPageList(
dataSourceFactory: DataSource.Factory<Int, T>,
enablePlaceholders: Boolean = false,
pageSize: Int = DEFAULT_PAGE_SIZE,
initialLoadSizeHint: Int = DEFAULT_INITIAL_LOAD_SIZE_HINT,
prefetchDistance: Int = DEFAULT_PREFETCH_DISTANCE
): LiveData<PagedList<T>> =
LivePagedListBuilder<Int, T>(
dataSourceFactory,
PagedList.Config
.Builder()
.setInitialLoadSizeHint(initialLoadSizeHint)
.setPageSize(pageSize)
.setPrefetchDistance(prefetchDistance)
.setEnablePlaceholders(enablePlaceholders)
.build()
).build()
private const val DEFAULT_PAGE_SIZE = 15
private const val DEFAULT_PREFETCH_DISTANCE = DEFAULT_PAGE_SIZE
private const val DEFAULT_INITIAL_LOAD_SIZE_HINT = 30
}
| 0
|
Kotlin
|
0
| 0
|
03c302232ee4ab2d079f0e48a19252933112cf6c
| 3,923
|
MVVM-Rhine
|
Apache License 2.0
|
app/src/main/kotlin/com/kentoapps/ministagram/di/module/ActivityModule.kt
|
kentoapps
| 135,547,461
| false
| null |
package com.kentoapps.ministagram.di.module
import android.arch.lifecycle.ViewModelProvider
import com.kentoapps.ministagram.di.ViewModelFactory
import com.kentoapps.ministagram.ui.AccountActivity
import com.kentoapps.ministagram.ui.MainActivity
import dagger.Binds
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
internal abstract class ActivityModule {
@Binds
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
@ContributesAndroidInjector(modules = [AccountModule::class])
internal abstract fun contributeAccountActivity(): AccountActivity
@ContributesAndroidInjector(modules = [MainModule::class])
internal abstract fun contributeMainActivity(): MainActivity
}
| 0
|
Kotlin
|
7
| 18
|
a40602027fbeb51d50362f21b49fef115c7d50b8
| 758
|
Ministagram
|
Apache License 2.0
|
presentation-core/src/commonMain/kotlin/com.chrynan.presentation/BasePresenterFactory.kt
|
chRyNaN
| 294,552,765
| false
| null |
@file:Suppress("unused")
package com.chrynan.presentation
/**
* An extension on a [PresenterFactory] that returns a [BasePresenter] instead of just a [Presenter].
*/
fun interface BasePresenterFactory<I : Intent, S : State, C : Change> : PresenterFactory<I, S, C> {
override fun invoke(view: View<I, S>): BasePresenter<I, S, C>
companion object
}
| 0
|
Kotlin
|
0
| 4
|
60369f5f8f4cc166bb1bd1dab25198f27eb60771
| 361
|
presentation
|
Apache License 2.0
|
src/Day02.kt
|
greg-burgoon
| 573,074,283
| false
| null |
import java.util.*
fun main() {
val conclusionMap = mapOf(
"A X" to 3,
"A Y" to 6,
"A Z" to 0,
"B X" to 0,
"B Y" to 3,
"B Z" to 6,
"C X" to 6,
"C Y" to 0,
"C Z" to 3
)
val winLoseDrawMap = mapOf(
"A X" to "A Z",
"A Y" to "A X",
"A Z" to "A Y",
"B X" to "B X",
"B Y" to "B Y",
"B Z" to "B Z",
"C X" to "C Y",
"C Y" to "C Z",
"C Z" to "C X"
)
val moveMap = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3
)
fun part1(input: String): Int {
val lines = input.split("\n")
val winValues = lines.stream().map {
val move = it.split(" ").get(1)
conclusionMap.getOrDefault(it, 0).plus(moveMap.getOrDefault(move, 0))
}.toList().sum()
return winValues
}
fun part2(input: String): Int {
val lines = input.split("\n")
val winValues = lines.stream().map {
winLoseDrawMap.getOrDefault(it, "")
}.map {
val move = it.split(" ").get(1)
conclusionMap.getOrDefault(it, 0).plus(moveMap.getOrDefault(move, 0))
}.toList().sum()
return winValues
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 1
|
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
| 1,499
|
aoc-kotlin
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/FileAdd.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.group
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.FileAdd: ImageVector
get() {
if (_fileAdd != null) {
return _fileAdd!!
}
_fileAdd = Builder(name = "FileAdd", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
group {
path(fill = SolidColor(Color(0xFF374957)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.0002f, 16.0f)
curveTo(16.0002f, 16.2652f, 15.8948f, 16.5196f, 15.7073f, 16.7071f)
curveTo(15.5197f, 16.8947f, 15.2654f, 17.0f, 15.0002f, 17.0f)
horizontalLineTo(13.0002f)
verticalLineTo(19.0f)
curveTo(13.0002f, 19.2652f, 12.8948f, 19.5196f, 12.7073f, 19.7071f)
curveTo(12.5197f, 19.8947f, 12.2654f, 20.0f, 12.0002f, 20.0f)
curveTo(11.7349f, 20.0f, 11.4806f, 19.8947f, 11.293f, 19.7071f)
curveTo(11.1055f, 19.5196f, 11.0002f, 19.2652f, 11.0002f, 19.0f)
verticalLineTo(17.0f)
horizontalLineTo(9.0001f)
curveTo(8.7349f, 17.0f, 8.4806f, 16.8947f, 8.293f, 16.7071f)
curveTo(8.1055f, 16.5196f, 8.0001f, 16.2652f, 8.0001f, 16.0f)
curveTo(8.0001f, 15.7348f, 8.1055f, 15.4805f, 8.293f, 15.2929f)
curveTo(8.4806f, 15.1054f, 8.7349f, 15.0f, 9.0001f, 15.0f)
horizontalLineTo(11.0002f)
verticalLineTo(13.0f)
curveTo(11.0002f, 12.7348f, 11.1055f, 12.4805f, 11.293f, 12.2929f)
curveTo(11.4806f, 12.1054f, 11.7349f, 12.0f, 12.0002f, 12.0f)
curveTo(12.2654f, 12.0f, 12.5197f, 12.1054f, 12.7073f, 12.2929f)
curveTo(12.8948f, 12.4805f, 13.0002f, 12.7348f, 13.0002f, 13.0f)
verticalLineTo(15.0f)
horizontalLineTo(15.0002f)
curveTo(15.2654f, 15.0f, 15.5197f, 15.1054f, 15.7073f, 15.2929f)
curveTo(15.8948f, 15.4805f, 16.0002f, 15.7348f, 16.0002f, 16.0f)
close()
moveTo(22.0002f, 10.485f)
verticalLineTo(19.0f)
curveTo(21.9986f, 20.3256f, 21.4713f, 21.5965f, 20.5339f, 22.5338f)
curveTo(19.5966f, 23.4711f, 18.3257f, 23.9984f, 17.0002f, 24.0f)
horizontalLineTo(7.0002f)
curveTo(5.6746f, 23.9984f, 4.4037f, 23.4711f, 3.4664f, 22.5338f)
curveTo(2.529f, 21.5965f, 2.0017f, 20.3256f, 2.0001f, 19.0f)
verticalLineTo(5.0f)
curveTo(2.0017f, 3.6744f, 2.529f, 2.4036f, 3.4664f, 1.4662f)
curveTo(4.4037f, 0.5289f, 5.6746f, 0.0016f, 7.0002f, 0.0f)
horizontalLineTo(11.5152f)
curveTo(12.4348f, -0.0023f, 13.3457f, 0.1776f, 14.1954f, 0.5295f)
curveTo(15.045f, 0.8814f, 15.8165f, 1.3982f, 16.4652f, 2.05f)
lineTo(19.9492f, 5.536f)
curveTo(20.6014f, 6.1843f, 21.1185f, 6.9555f, 21.4706f, 7.805f)
curveTo(21.8226f, 8.6545f, 22.0026f, 9.5654f, 22.0002f, 10.485f)
close()
moveTo(15.0512f, 3.464f)
curveTo(14.7364f, 3.1592f, 14.3831f, 2.897f, 14.0002f, 2.684f)
verticalLineTo(7.0f)
curveTo(14.0002f, 7.2652f, 14.1055f, 7.5196f, 14.293f, 7.7071f)
curveTo(14.4806f, 7.8947f, 14.7349f, 8.0f, 15.0002f, 8.0f)
horizontalLineTo(19.3162f)
curveTo(19.1031f, 7.6172f, 18.8405f, 7.2642f, 18.5352f, 6.95f)
lineTo(15.0512f, 3.464f)
close()
moveTo(20.0002f, 10.485f)
curveTo(20.0002f, 10.32f, 19.9682f, 10.162f, 19.9532f, 10.0f)
horizontalLineTo(15.0002f)
curveTo(14.2045f, 10.0f, 13.4414f, 9.684f, 12.8788f, 9.1213f)
curveTo(12.3162f, 8.5587f, 12.0002f, 7.7957f, 12.0002f, 7.0f)
verticalLineTo(2.047f)
curveTo(11.8382f, 2.032f, 11.6792f, 2.0f, 11.5152f, 2.0f)
horizontalLineTo(7.0002f)
curveTo(6.2045f, 2.0f, 5.4414f, 2.3161f, 4.8788f, 2.8787f)
curveTo(4.3162f, 3.4413f, 4.0002f, 4.2044f, 4.0002f, 5.0f)
verticalLineTo(19.0f)
curveTo(4.0002f, 19.7957f, 4.3162f, 20.5587f, 4.8788f, 21.1213f)
curveTo(5.4414f, 21.684f, 6.2045f, 22.0f, 7.0002f, 22.0f)
horizontalLineTo(17.0002f)
curveTo(17.7958f, 22.0f, 18.5589f, 21.684f, 19.1215f, 21.1213f)
curveTo(19.6841f, 20.5587f, 20.0002f, 19.7957f, 20.0002f, 19.0f)
verticalLineTo(10.485f)
close()
}
}
}
.build()
return _fileAdd!!
}
private var _fileAdd: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,894
|
icons
|
MIT License
|
lib-ui/src/main/java/com/me/lib/ui/recycler/adapter/MuxAdapter.kt
|
pickerX
| 311,518,829
| false
| null |
package com.me.lib.ui.recycler.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.me.lib.ui.recycler.ItemViewCreator
import com.me.lib.ui.recycler.ViewHolder
class MuxAdapter : RecyclerView.Adapter<ViewHolder<*>>() {
private val viewsArray = mutableListOf<ItemViewCreator<*>>()
fun addItem(item: ItemViewCreator<*>) {
viewsArray.add(item)
}
override fun getItemViewType(position: Int): Int {
return viewsArray[position].getItemViewType()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<*> {
val holder = getItemViewCreator(viewType)
val itemView = LayoutInflater.from(parent.context).inflate(holder.layout(), parent, false)
return holder.newViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder<*>, position: Int) {
val type = getItemViewType(position)
val h = getItemViewCreator(type)
h.onBindViewHolder(holder, position)
}
private fun getItemViewCreator(type: Int): ItemViewCreator<*> {
var index = -1
viewsArray.forEachIndexed { i, h ->
if (h.getItemViewType() == type) {
index = i
return@forEachIndexed
}
}
check(index != -1) { "unregister type:$type" }
return viewsArray[index]
}
override fun getItemCount(): Int = viewsArray.size
}
| 0
|
Kotlin
|
0
| 0
|
28df25ec7879b3a4b08da844137fcbc8cde0399a
| 1,487
|
TMDB-collector
|
MIT License
|
core/database/src/main/java/com/hanbikan/nook/core/database/translator/CollectionTranslator.kt
|
hanbikan
| 737,877,468
| false
|
{"Kotlin": 247435}
|
package com.hanbikan.nook.core.database.translator
import com.hanbikan.nook.core.database.entity.FishEntity
import com.hanbikan.nook.core.domain.model.Fish
fun FishEntity.toDomain(): Fish {
return Fish(
id = id,
userId = userId,
name = name,
number = number,
imageUrl = imageUrl,
timesByMonth = timesByMonth,
isCollected = isCollected,
)
}
fun Fish.toData(): FishEntity {
return FishEntity(
id = id,
userId = userId,
name = name,
number = number,
imageUrl = imageUrl,
timesByMonth = timesByMonth,
isCollected = isCollected,
)
}
| 0
|
Kotlin
|
0
| 0
|
c0d9dd3584778d98d39d546858a561343397ea43
| 658
|
Nook
|
Apache License 2.0
|
src/feature_details/src/main/kotlin/com/gabrielbmoro/moviedb/details/ui/widgets/TextUrl.kt
|
gabrielbmoro
| 574,746,759
| false
|
{"Kotlin": 162208}
|
package com.gabrielbmoro.moviedb.details.ui.widgets
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextDecoration
import com.gabrielbmoro.moviedb.core.ui.theme.MovieDBAppTheme
import com.gabrielbmoro.moviedb.core.ui.theme.ThemePreviews
@Composable
fun TextUrl(url: String, modifier: Modifier = Modifier) {
val uriHandler = LocalUriHandler.current
ClickableText(
modifier = modifier,
style = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.tertiary,
fontStyle = FontStyle.Italic,
textDecoration = TextDecoration.Underline
),
text = buildAnnotatedString {
append(url)
},
onClick = {
uriHandler.openUri(url)
}
)
}
@ThemePreviews
@Composable
fun TextUrlPreview() {
MovieDBAppTheme {
TextUrl(url = "https://www.google.com")
}
}
| 3
|
Kotlin
|
2
| 39
|
7c07b093340042b736a5b7ce6b57c1dafe18a6b9
| 1,223
|
MovieDB-Android
|
MIT License
|
client/src/main/java/ru/memebattle/feature/onboarding/page/OnboardingPageFragment.kt
|
MrSwimmer
| 285,444,414
| false
| null |
package ru.memebattle.feature.onboarding.page
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_onboarding_page.*
import ru.memebattle.R
/**
* Фрагмент одной страницы ViewPager'а онбодинга.
*/
class OnboardingPageFragment : Fragment(R.layout.fragment_onboarding_page) {
private lateinit var page: OnboardingPage
private lateinit var onComplete: () -> Unit
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.getString(EXTRA_PAGE_NAME)?.let { pageName ->
page = OnboardingPage.valueOf(pageName)
initPage(page)
}
}
private fun initPage(page: OnboardingPage) {
title.text = getString(page.titleRes)
description.text = getString(page.descriptionRes)
page_banner.setImageResource(page.backgroundRes)
complete_button.isVisible = page.isLastPage
complete_button.setOnClickListener { onComplete.invoke() }
}
companion object {
private const val EXTRA_PAGE_NAME = "extra_page_name"
/** Создаёт инстанс страницы ViewPager'а, соответствующий названию страницы [pageName]. */
fun newInstance(pageName: String, onComplete: () -> Unit): OnboardingPageFragment {
return OnboardingPageFragment().apply {
arguments = Bundle().apply {
putString(EXTRA_PAGE_NAME, pageName)
}
this.onComplete = onComplete
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
ffea058e2ea8ea3f3a862e0639c518645f495578
| 1,641
|
memeapp
|
Apache License 2.0
|
androidApp/src/main/java/com/amc/acieslinski/simplegiftapp/android/ui/scanner/BarCodeAnalyzer.kt
|
acieslinski
| 777,244,363
| false
|
{"Kotlin": 71875, "Swift": 15526}
|
package com.amc.acieslinski.simplegiftapp.android.ui.scanner
import android.annotation.SuppressLint
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
// TODO meant to be in data layer, but not sure how it works with iOs
class BarcodeAnalyzer(
private val callback: (String) -> Unit
) : ImageAnalysis.Analyzer {
private val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS)
.build()
private val scanner = BarcodeScanning.getClient(options)
@SuppressLint("UnsafeOptInUsageError")
override fun analyze(imageProxy: ImageProxy) {
imageProxy.image?.let { image ->
scanner.process(
InputImage.fromMediaImage(
image, imageProxy.imageInfo.rotationDegrees
)
).addOnSuccessListener { barcode ->
barcode?.takeIf { it.isNotEmpty() }
?.mapNotNull { it.rawValue }
?.joinToString(",")
?.let {
callback(it)
}
}.addOnCompleteListener {
imageProxy.close()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b8f62adb8b31d612df1cc222302d787816224cf4
| 1,430
|
simplegiftapp
|
Apache License 2.0
|
library/src/main/kotlin/dev/niltsiar/easycrypt/EasyCryptInitProvider.kt
|
niltsiar
| 188,866,823
| false
| null |
package dev.niltsiar.easycrypt
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.pm.ProviderInfo
import android.database.Cursor
import android.net.Uri
class EasyCryptInitProvider : ContentProvider() {
companion object {
@JvmSynthetic
internal const val EMPTY_APPLICATION_ID_PROVIDER_AUTHORITY = "dev.niltsiar.easycrypt.easycryptinitprovider"
@JvmStatic
lateinit var applicationContext: Context
private set
}
override fun onCreate(): Boolean {
return context?.let {
applicationContext = it
true
} ?: false
}
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun getType(uri: Uri): String? = null
override fun attachInfo(context: Context?, info: ProviderInfo?) {
checkContentProviderAuthority(info)
super.attachInfo(context, info)
}
private fun checkContentProviderAuthority(info: ProviderInfo?) {
checkNotNull(info) { "EasyCryptInitProvider ProviderInfo cannot be null" }
check(EMPTY_APPLICATION_ID_PROVIDER_AUTHORITY != info.authority) {
"Incorrect provider authority in manifest. Most likely due to a missing applicationId variable in application's gradle script"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
18578409841bd3e20cdcc82fc2b64030aa8b39ba
| 1,726
|
easycrypt
|
Apache License 2.0
|
example/src/main/kotlin/com/expedia/graphql/sample/query/ResolverInterfaceQueries.kt
|
tkruener
| 196,866,673
| true
|
{"Kotlin": 324093, "HTML": 20063, "Shell": 2927}
|
package com.expedia.graphql.sample.query
import com.expedia.graphql.sample.resolvers.Query
import com.expedia.graphql.sample.resolvers.Resolver
import org.springframework.stereotype.Component
interface Vehicle<X : Vehicle<X>> : VehicleResolverI<X> {
fun move(meters: Int): String
val color: String
}
interface VehicleResolverI<X : Vehicle<X>> {
fun customResolver(self: X): String = error("Should be implemented by the resolvers")
}
class Sportscar : Vehicle<Sportscar> {
override fun move(meters: Int): String = "Zshshhhh"
override val color: String = "Red"
}
class Truck : Vehicle<Truck> {
override fun move(meters: Int): String = "Tuck tuck"
override val color: String = "Yellow"
}
@Component
class VehicleResolver : Resolver<Vehicle<*>>() {
@Query
fun vehicle(wantATruck: Boolean) = if (wantATruck) Truck() else Sportscar()
fun doStuff() = "qweqwe"
}
@Component
class TruckResolver : Resolver<Truck>(), VehicleResolverI<Truck> {
fun doSomeExtraNoise() = "RATATA"
override fun customResolver(self: Truck): String = "Truck resolver"
}
@Component
class SportscarResolver : Resolver<Sportscar>(), VehicleResolverI<Sportscar> {
override fun customResolver(self: Sportscar): String = "Sportscar resolver"
}
| 0
|
Kotlin
|
0
| 0
|
5197d3245b6d24fbdac3380b9f28e14115eb0377
| 1,234
|
graphql-kotlin
|
Apache License 2.0
|
precompose/src/commonMain/kotlin/moe/tlaster/precompose/lifecycle/LifecycleRegistry.kt
|
Tlaster
| 349,750,473
| false
|
{"Kotlin": 191657}
|
package moe.tlaster.precompose.lifecycle
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
class LifecycleRegistry : Lifecycle {
private var observers: List<LifecycleObserver> = emptyList()
private val _currentStateFlow = MutableStateFlow(Lifecycle.State.Initialized)
override val currentStateFlow: StateFlow<Lifecycle.State> = _currentStateFlow.asStateFlow()
private var _state: Lifecycle.State = _currentStateFlow.value
set(value) {
if (field == Lifecycle.State.Destroyed || value == Lifecycle.State.Initialized) {
observers = emptyList()
return
}
field = value
_currentStateFlow.value = value
dispatchState(value)
}
override val currentState: Lifecycle.State get() = _state
fun updateState(value: Lifecycle.State) {
_state = value
}
private fun dispatchState(value: Lifecycle.State) {
observers.forEach {
it.onStateChanged(value)
}
}
override fun removeObserver(observer: LifecycleObserver) {
observers -= observer
}
override fun addObserver(observer: LifecycleObserver) {
if (observers.contains(observer)) {
return
}
observers += observer
observer.onStateChanged(currentState)
}
override fun hasObserver(): Boolean {
return observers.isNotEmpty()
}
}
| 40
|
Kotlin
|
49
| 849
|
276c933397d94b8dfc60b809942bc38b23d945bd
| 1,510
|
PreCompose
|
MIT License
|
app/src/main/java/com/example/fitpeo/data/repository/local/JsonDataSource.kt
|
Tabishahmad
| 669,515,444
| false
| null |
package com.example.fitpeo.data.repository.local
import android.content.Context
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.fitpeo.common.MAX_PAGE
import com.example.fitpeo.data.repository.model.AlbumDTO
import com.example.fitpeo.domain.model.Album
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import javax.inject.Inject
class JsonDataSource @Inject constructor(private val context: Context, private val fileNames: List<String>
) : PagingSource<Int, Album>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Album> {
val pageNumber = params.key ?: 0
val currentFileName = fileNames.getOrNull(pageNumber)
return try {
currentFileName?.let { fileName ->
val json = loadJsonFromAsset(context, fileName)
val items = parseJson(json)
val prevKey = if (pageNumber > 0) pageNumber - 1 else null
val nextKey = if (pageNumber < fileNames.size - 1) pageNumber + 1 else null
println("pageNumber fileName " +fileName + " pageNumber " + pageNumber )
LoadResult.Page(
data = items,
prevKey = prevKey,
nextKey = nextKey
)
} ?: LoadResult.Error(IllegalArgumentException("Invalid page number: $pageNumber"))
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, Album>): Int? {
return state.anchorPosition?.let {
state.closestPageToPosition(it)?.prevKey?.plus(1)
?: state.closestPageToPosition(it)?.nextKey?.minus(1)
}
}
private fun loadJsonFromAsset(context: Context, fileName: String): String {
println("pageNumber loadJsonFromAsset " +fileName )
return context.assets.open(fileName).bufferedReader().use { it.readText() }
}
private fun parseJson(jsonString: String): List<Album> {
val gson = Gson()
val itemArrayType = object : TypeToken<AlbumDTO>() {}.type
val dto : AlbumDTO = gson.fromJson(jsonString, itemArrayType)
return dto.toAlbum()
}
}
| 0
|
Kotlin
|
0
| 0
|
dde4964584dd2cec066eb0b0272d84c36349ab8c
| 2,248
|
Content-Showcase-App
|
MIT License
|
presentation/src/main/java/com/movingmaker/presentation/util/BindingAdapter.kt
|
Comment-Diary
| 458,682,004
| false
| null |
package com.movingmaker.presentation.util
import android.annotation.SuppressLint
import android.app.Activity
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatButton
import androidx.databinding.BindingAdapter
import androidx.lifecycle.LiveData
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.movingmaker.domain.model.response.Comment
import com.movingmaker.presentation.R
import com.movingmaker.presentation.view.main.mypage.MyCommentListAdapter
import timber.log.Timber
@BindingAdapter("items")
fun setItems(recyclerView: RecyclerView, items: LiveData<List<Comment>>) {
if (recyclerView.adapter == null) {
val adapter = MyCommentListAdapter()
adapter.setHasStableIds(true)
recyclerView.adapter = adapter
}
val diaryListAdapter = recyclerView.adapter as MyCommentListAdapter
diaryListAdapter.submitList(items.value)
}
@BindingAdapter("android:signUpProgress")
fun signUpProgress(view: ProgressBar, currentFragment: LiveData<FRAGMENT_NAME>) {
when (currentFragment.value) {
FRAGMENT_NAME.SIGNUP_TERMS -> {
view.visibility = View.VISIBLE
view.progress = 25
}
FRAGMENT_NAME.SIGNUP_EMAIL -> {
view.visibility = View.VISIBLE
view.progress = 50
}
FRAGMENT_NAME.SIGNUP_CODE -> {
view.visibility = View.VISIBLE
view.progress = 75
}
FRAGMENT_NAME.SIGNUP_PASSWORD -> {
view.visibility = View.VISIBLE
view.progress = 100
}
else -> {
view.visibility = View.GONE
}
}
}
@BindingAdapter("android:checkState")
fun setCheckState(view: ImageView, checkState: LiveData<Boolean>) {
when (checkState.value) {
true -> {
view.setImageResource(R.drawable.ic_check_green)
}
else -> {
view.setImageResource(R.drawable.ic_check)
}
}
}
@BindingAdapter("isCorrectEmail", "noticeEmail")
fun changeEmailNotice(view: TextView, isCorrect: LiveData<Boolean>, text: LiveData<String>) {
when (isCorrect.value) {
false -> {
view.text = view.context.getString(R.string.onboarding_email_incorrect)
}
else -> {
view.text = ""
}
}
if (text.value != "" && text.value != null)
view.text = text.value
}
@BindingAdapter("android:validateFindPasswordEmail")
fun changeFindPasswordEmailNotice(view: TextView, isCorrect: LiveData<Boolean>) {
when (isCorrect.value) {
false -> {
view.visibility = View.VISIBLE
view.text = view.context.getString(R.string.onboarding_email_incorrect)
}
else -> {
view.text = ""
view.visibility = View.GONE
}
}
}
@BindingAdapter("android:visibleEmail")
fun changeVisible(view: TextView, text: LiveData<String>) {
when (text.value) {
KAKAO -> {
view.visibility = View.GONE
}
EMAIL -> {
view.visibility = View.VISIBLE
}
}
}
@BindingAdapter("diaryType", "isExpand", "selectedDate")
fun changeVisibleWithDiaryType(
view: View,
diaryType: LiveData<DIARY_TYPE>,
isExpand: LiveData<Boolean>,
tempSelectedDiaryDate: LiveData<String>
) {
when (isExpand.value) {
true -> {
when (view.id) {
R.id.sendButton, R.id.saveButton -> {
view.visibility = View.INVISIBLE
}
R.id.selectAloneDiaryInRadioButton -> {
when (diaryType.value) {
DIARY_TYPE.COMMENT_DIARY -> {
view.visibility = View.GONE
}
DIARY_TYPE.ALONE_DIARY -> {
view.visibility = View.VISIBLE
}
else -> {}
}
}
R.id.selectCommentDiaryInRadioButton -> {
when (diaryType.value) {
DIARY_TYPE.COMMENT_DIARY -> {
view.visibility = View.VISIBLE
}
DIARY_TYPE.ALONE_DIARY -> {
view.visibility = View.GONE
}
else -> {}
}
}
else -> {}
}
}
else -> {
when (view.id) {
R.id.sendButton -> {
when (diaryType.value) {
DIARY_TYPE.COMMENT_DIARY -> {
view.visibility = View.VISIBLE
}
DIARY_TYPE.ALONE_DIARY -> {
view.visibility = View.INVISIBLE
}
else -> {}
}
}
R.id.saveButton -> {
when (diaryType.value) {
DIARY_TYPE.COMMENT_DIARY -> {
view.visibility = View.INVISIBLE
}
DIARY_TYPE.ALONE_DIARY -> {
view.visibility = View.VISIBLE
}
else -> {}
}
}
R.id.selectCommentDiaryInRadioButton, R.id.selectAloneDiaryInRadioButton -> {
view.visibility = View.GONE
}
else -> {
(view as TextView)
tempSelectedDiaryDate.value?.let {
val selectedDiaryDate = DateConverter.ymdToDate(it)
if (selectedDiaryDate < DateConverter.getCodaToday()) {
view.isEnabled = false
view.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
} else {
view.isEnabled = true
view.setCompoundDrawablesWithIntrinsicBounds(
0,
0,
R.drawable.ic_arrow_down,
0
)
}
}
view.text = when (diaryType.value) {
DIARY_TYPE.COMMENT_DIARY -> view.context.getString(R.string.diary_type_comment)
else -> view.context.getString(R.string.diary_type_alone)
}
}
}
}
}
}
@BindingAdapter("app:nonClickableActivity", "app:nonClickableLoading")
fun setNonClickableLoading(view: ProgressBar, activity: Activity, state: LiveData<Boolean>) {
when (state.value) {
true -> {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
)
view.visibility = View.VISIBLE
}
else -> {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
view.visibility = View.GONE
}
}
}
@BindingAdapter("app:loading")
fun setLoading(view: ProgressBar, state: LiveData<Boolean>) {
view.visibility = when (state.value) {
true -> View.VISIBLE
else -> View.GONE
}
}
@SuppressLint("SetTextI18n")
@BindingAdapter("android:yearMonth")
fun changeYearMonth(view: TextView, text: LiveData<String>) {
try {
val (y, m) = text.value!!.split('.')
view.text = "${y}년 ${m}월"
} catch (e: Exception) {
view.text = "년 월"
Timber.e("changeYearMonth: $e")
}
}
@BindingAdapter("android:buttonState")
fun changeButtonState(view: AppCompatButton, currentFragment: LiveData<FRAGMENT_NAME>) {
when (currentFragment.value) {
FRAGMENT_NAME.LOGIN_BEFORE -> {
view.visibility = View.GONE
}
else -> {
view.visibility = View.VISIBLE
when (currentFragment.value) {
FRAGMENT_NAME.LOGIN, FRAGMENT_NAME.LOGIN_BEFORE -> {
view.text = view.context.getString(R.string.onboarding_login)
}
FRAGMENT_NAME.FIND_PASSWORD -> {
view.text = view.context.getString(R.string.onboarding_find_password)
}
FRAGMENT_NAME.SIGNUP_TERMS -> {
view.text = view.context.getString(R.string.onboarding_sign_up)
}
FRAGMENT_NAME.SIGNUP_PASSWORD -> {
view.text = view.context.getString(R.string.onboarding_coda_start)
}
FRAGMENT_NAME.KAKAO_TERMS -> {
view.text = view.context.getString(R.string.onboarding_coda_start)
}
FRAGMENT_NAME.SIGNUP_EMAIL -> {
view.text = view.context.getString(R.string.onboarding_send_auth)
}
FRAGMENT_NAME.SIGNUP_CODE -> {
view.text = view.context.getString(R.string.onboarding_certify)
}
else -> {}
}
}
}
}
/*
* write diary
* */
@BindingAdapter("app:colorWithDiaryType")
fun TextView.setColorWithDiaryType(diaryType: LiveData<DIARY_TYPE>) {
setTextColor(
when (diaryType.value) {
DIARY_TYPE.COMMENT_DIARY -> context.getColor(R.color.core_green)
else -> context.getColor(R.color.core_orange)
}
)
}
@BindingAdapter("app:sendButtonState")
fun AppCompatButton.setSendButtonState(canSendCommentDiary: LiveData<Boolean>) {
background = when (canSendCommentDiary.value) {
true -> AppCompatResources.getDrawable(context, R.drawable.background_green_radius_10)
else -> AppCompatResources.getDrawable(
context,
R.drawable.background_green_alpha_40_radius_10
)
}
}
@BindingAdapter("app:navigateUp")
fun navigateUp(view: View, dummy: Any?) {
view.setOnClickListener {
view.findNavController().navigateUp()
}
}
| 7
|
Kotlin
|
1
| 2
|
cf9f329970d83181c41a6cfc0470cd2712301f6f
| 10,414
|
CommentDiary-AOS
|
MIT License
|
app/src/main/java/com/mati/automaster/data/MainItemModel.kt
|
mr-mati
| 756,311,850
| false
|
{"Kotlin": 145918}
|
package com.mati.automaster.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class MainItemModel(
val ID: Int,
val title: String,
val image: Int,
) : Parcelable
| 0
|
Kotlin
|
0
| 0
|
6243239a888dd1d85eb5fad23cf06df9003b252d
| 211
|
AutoMaster
|
MIT License
|
app/src/main/java/com/pokemon/go/data/remote/responses/MoveX.kt
|
hdmor
| 757,383,118
| false
|
{"Kotlin": 46545}
|
package com.pokemon.go.data.remote.responses
data class MoveX(
val name: String,
val url: String
)
| 0
|
Kotlin
|
0
| 0
|
575b0a6ba631bb9b2d48f1fa403528af851c85df
| 107
|
pokemon
|
MIT License
|
src/main/kotlin/leetcode/kotlin/tree/102. Binary Tree Level Order Traversal.kt
|
sandeep549
| 251,593,168
| false
| null |
package leetcode.kotlin.tree
import java.util.*
import kotlin.collections.ArrayList
private fun levelOrder(root: TreeNode?): List<List<Int>> {
val res = mutableListOf<MutableList<Int>>()
if (root == null) return res
val q = ArrayDeque<TreeNode>()
q.add(root)
while (!q.isEmpty()) {
var size = q.size
val list = ArrayList<Int>()
while (size > 0) {
val node = q.poll()
list.add(node.`val`)
node.left?.let { q.add(it) }
node.right?.let { q.add(it) }
size--
}
res.add(list)
}
return res
}
// todo: do it with recursion
| 0
|
Kotlin
|
0
| 0
|
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
| 646
|
kotlinmaster
|
Apache License 2.0
|
android/flippertabular/src/main/java/me/haroldmartin/flipper/tabular/FlipperExt.kt
|
hbmartin
| 357,045,056
| false
|
{"TypeScript": 7647, "Kotlin": 6193, "JavaScript": 4054}
|
/**
* Copyright (c) 2021 <NAME>.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package me.haroldmartin.flipper.tabular
import com.facebook.flipper.core.FlipperObject
internal fun Map<String, Any>.toFlipperObject(): FlipperObject =
keys.fold(FlipperObject.Builder()) { b, key -> b.put(key, get(key)) }.build()
| 0
|
TypeScript
|
0
| 1
|
78f2551b499d9c1f4599affb3614d3506a4cfb7b
| 404
|
flipper-plugin-tabular
|
MIT License
|
app/src/main/java/com/example/instagramapplication/Post.kt
|
rdd43
| 553,217,024
| false
| null |
package com.example.instagramapplication
import android.util.Log
import com.parse.ParseClassName
import com.parse.ParseFile
import com.parse.ParseObject
import com.parse.ParseUser
import java.io.File
import java.util.*
//decs, user, file
@ParseClassName("Post")
class Post : ParseObject() {
fun getDescription():String?{
return getString(KEY_DESCRIPTION)
}
fun setDescription(description: String){
put(KEY_DESCRIPTION, description)
}
fun getImage(): ParseFile?{
return getParseFile(KEY_IMAGE)
}
fun setImage(parseFile: ParseFile){
put(KEY_IMAGE, parseFile)
}
fun getUser():ParseUser?{
return getParseUser(KEY_USER)
}
fun setUser(user: ParseUser){
put(KEY_USER, user)
}
fun getDate(): Date? {
Log.i("ROB", "Date is ${getDate(KEY_CREATEDAT)}")
return getDate(KEY_CREATEDAT)
}
companion object{
const val KEY_DESCRIPTION = "description"
const val KEY_USER = "user"
const val KEY_IMAGE = "image"
const val KEY_CREATEDAT = "createdAt"
}
}
| 3
|
Kotlin
|
0
| 0
|
5ef51c573b890dc08edb529bce071fb5abd791ae
| 1,102
|
InstagramApplication
|
Apache License 2.0
|
sisterhood-core/src/commonMain/kotlin/sisterhood/business/commands/CommandProp.kt
|
trinity-library
| 821,523,435
| false
|
{"Kotlin": 49468, "JavaScript": 21486}
|
package sisterhood.business.commands
import sisterhood.domain.PrintFactory
class CommandProp(
val printFactory: PrintFactory
)
| 0
|
Kotlin
|
0
| 0
|
538470b8dfceb920ab6b3546ea144382fd6d5d90
| 133
|
sisterhood
|
MIT License
|
app/src/main/java/com/imnstudios/runningapp/other/SortType.kt
|
imnithish
| 278,848,739
| false
| null |
package com.imnstudios.runningapp.other
enum class SortType {
DATE, RUNNING_TIME, AVG_SPEED, DISTANCE, CALORIES_BURNED
}
| 0
|
Kotlin
|
2
| 9
|
7d1a0da914babeba7a1f794dfcb3404dd51237d2
| 125
|
running_app
|
Apache License 2.0
|
app/src/main/java/com/alexzh/composeplayground/ui/demo/dropdown/DemoDropDownMenu.kt
|
AlexZhukovich
| 363,830,311
| false
| null |
package com.alexzh.composeplayground.ui.demo.dropdown
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import me.saket.cascade.CascadeDropdownMenu
/**
* Jetpack Compose: DropDown menu.
* Example of creating a DropDownMenu in Jetpack Compose.
*
* Note: The preview shows pop-up in a wrong place. Please use a device or emulator for verification.
*
* Read more and check samples: https://alexzh.com/jetpack-compose-dropdownmenu/
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Demo_DropDownMenu() {
val context = LocalContext.current
var expanded by remember { mutableStateOf(false) }
Scaffold(
modifier = Modifier.height(200.dp),
topBar = {
TopAppBar(
title = { },
actions = {
IconButton(onClick = { expanded = !expanded }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "More menu"
)
}
},
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFFE3E3E3)),
)
}
) { paddingValues ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.background(Color(0xFFE3E3E3))
.wrapContentSize(Alignment.TopEnd)
) {
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
DropdownMenuItem(
text = { Text("Load") },
onClick = { Toast.makeText(context, "Load", Toast.LENGTH_SHORT).show() },
leadingIcon = {
Icon(
imageVector = Icons.Default.Image,
contentDescription = "More menu"
)
},
trailingIcon = {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "More menu"
)
}
)
DropdownMenuItem(
text = { Text("Save") },
onClick = { Toast.makeText(context, "Save", Toast.LENGTH_SHORT).show() }
)
}
}
}
}
/**
* Jetpack Compose: DropDown menu.
* Example of creating a ExposedDropdownMenuBox in Jetpack Compose.
*
* Note: The preview didn't work properly. Please use a device or emulator for verification.
*
* Read more and check samples: https://alexzh.com/jetpack-compose-dropdownmenu/#creating-an-exposeddropdownmenubox
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Demo_ExposedDropdownMenuBox() {
val context = LocalContext.current
val coffeeDrinks = arrayOf("Americano", "Cappuccino", "Espresso", "Latte", "Mocha")
var expanded by remember { mutableStateOf(false) }
var selectedText by remember { mutableStateOf(coffeeDrinks[0]) }
Box(
modifier = Modifier
.fillMaxWidth()
.height(400.dp)
.background(Color(0xFFE3E3E3))
.padding(32.dp)
) {
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
}
) {
TextField(
value = selectedText,
onValueChange = {},
readOnly = true,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
modifier = Modifier.menuAnchor()
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
coffeeDrinks.forEach { item ->
DropdownMenuItem(
text = { Text(text = item) },
onClick = {
selectedText = item
expanded = false
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
)
}
}
}
}
}
/**
* Jetpack Compose: DropDown menu.
* Example of creating an ExposedDropdownMenuBox and styling selected item in a list in Jetpack Compose.
*
* Note: The preview didn't work properly. Please use a device or emulator for verification.
*
* Read more and check samples: https://alexzh.com/jetpack-compose-dropdownmenu/#changing-style-of-selected-menu-item
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Demo_ExposedDropdownMenuBox_SelectionStyling() {
val context = LocalContext.current
val coffeeDrinks = arrayOf("Americano", "Cappuccino", "Espresso", "Latte", "Mocha")
var expanded by remember { mutableStateOf(false) }
var selectedItemIndex by remember { mutableStateOf(0) }
Box(
modifier = Modifier
.fillMaxWidth()
.height(400.dp)
.background(Color(0xFFE3E3E3))
.padding(32.dp)
) {
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = { expanded = !expanded },
modifier = Modifier.padding(16.dp),
) {
TextField(
value = coffeeDrinks[selectedItemIndex],
onValueChange = {},
readOnly = true,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
modifier = Modifier.menuAnchor()
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
coffeeDrinks.forEachIndexed { index, item ->
DropdownMenuItem(
text = {
Text(
text = item,
fontWeight = if (index == selectedItemIndex) FontWeight.Bold else null
)
},
onClick = {
selectedItemIndex = index
expanded = false
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
)
}
}
}
}
}
/**
* Jetpack Compose: DropDown menu.
* Example of creating a CascadeDropdownMenu in Jetpack Compose.
*
* Note: The preview didn't work properly. Please use a device or emulator for verification.
*
* Read more and check samples: https://alexzh.com/jetpack-compose-dropdownmenu/#creating-a-cascadedropdownmenu
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Demo_CascadeDropdownMenu() {
val context = LocalContext.current
var expanded by remember { mutableStateOf(false) }
Scaffold(
modifier = Modifier.height(300.dp),
topBar = {
TopAppBar(
title = { },
actions = {
IconButton(onClick = { expanded = !expanded }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "More menu"
)
}
},
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFFE3E3E3)),
)
}
) { paddingValues ->
Box(
modifier = Modifier
.fillMaxWidth()
.background(Color(0xFFE3E3E3))
.padding(paddingValues)
.wrapContentSize(Alignment.TopEnd)
.padding(end = 8.dp)
) {
CascadeDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text(text = "1. Item") },
childrenHeader = {},
children = {
DropdownMenuItem(
text = { Text(text = "1.1. Sub-Item") },
onClick = {
expanded = false
Toast.makeText(context, "1.1. Sub-Item", Toast.LENGTH_SHORT).show()
}
)
}
)
DropdownMenuItem(
text = { Text(text = "2. Item") },
children = {
DropdownMenuItem(
text = { Text(text = "2.1. Sub-Item") },
onClick = {
expanded = false
Toast.makeText(context, "2.1. Sub-Item", Toast.LENGTH_SHORT).show()
}
)
DropdownMenuItem(
text = { Text(text = "2.2. Sub-Item") },
children = {
DropdownMenuItem(
text = { Text(text = "2.2.1. Sub-Sub-Item") },
onClick = {
expanded = false
Toast.makeText(
context,
"2.2.1. Sub-Sub-Item",
Toast.LENGTH_SHORT
).show()
}
)
}
)
}
)
}
}
}
}
/**
* Jetpack Compose: DropDown menu.
* Example of creating a searchable ExposedDropdownMenuBox in Jetpack Compose.
*
* Read more and check samples: https://alexzh.com/jetpack-compose-dropdownmenu/#creating-a-searchable-dropdown-menu
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Demo_SearchableExposedDropdownMenuBox() {
val context = LocalContext.current
val coffeeDrinks = arrayOf("Americano", "Cappuccino", "Espresso", "Latte", "Mocha")
var expanded by remember { mutableStateOf(false) }
var selectedText by remember { mutableStateOf("") }
Box(
modifier = Modifier
.fillMaxWidth()
.height(400.dp)
.background(Color(0xFFE3E3E3))
.padding(32.dp)
) {
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
}
) {
TextField(
value = selectedText,
onValueChange = { selectedText = it },
label = { Text(text = "Start typing the name of the coffee") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
modifier = Modifier.menuAnchor()
)
val filteredOptions =
coffeeDrinks.filter { it.contains(selectedText, ignoreCase = true) }
if (filteredOptions.isNotEmpty()) {
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = {
// We shouldn't hide the menu when the user enters/removes any character
}
) {
filteredOptions.forEach { item ->
DropdownMenuItem(
text = { Text(text = item) },
onClick = {
selectedText = item
expanded = false
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
)
}
}
}
}
}
}
/**
* Jetpack Compose: DropDown menu.
* Example of creating a "Units" screen with different dropdown menu components.
*
* Note:
* - This screen is created only for demonstrating testing approaches.
* - The preview didn't work properly. Please use a device or emulator for verification.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun Demo_UnitsScreen() {
val context = LocalContext.current
var nestedMenuExpanded by remember { mutableStateOf(false) }
var moreMenuExpanded by remember { mutableStateOf(false) }
val temperatureUnits = listOf("Celsius (°C)", "Fahrenheit (°F)")
var temperatureUnitsExpanded by remember { mutableStateOf(false) }
var selectedTemperatureItem by remember { mutableStateOf(temperatureUnits.first()) }
val distanceUnits = listOf("Kilometers", "Miles")
var distanceUnitsExpanded by remember { mutableStateOf(false) }
var selectedDistanceItem by remember { mutableStateOf(distanceUnits.first()) }
val speedUnits = listOf("Kilometer/Hour", "Mile/Hour", "Meter/Second", "Kilometer/Second")
var speedUnitsExpanded by remember { mutableStateOf(false) }
var selectedSpeedItem by remember { mutableStateOf("") }
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = "Units") },
actions = {
IconButton(onClick = { nestedMenuExpanded = !nestedMenuExpanded }) {
Icon(
imageVector = Icons.Outlined.Warning,
contentDescription = "Nested menu"
)
}
IconButton(onClick = { moreMenuExpanded = !moreMenuExpanded }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "More menu"
)
}
}
)
}
) { paddingValues ->
Box(
modifier = Modifier
.fillMaxWidth()
.padding(paddingValues)
.background(Color.Red)
.wrapContentSize(Alignment.TopEnd)
) {
DropdownMenu(
expanded = moreMenuExpanded,
onDismissRequest = { moreMenuExpanded = false }
) {
DropdownMenuItem(
text = { Text("Load") },
onClick = {
moreMenuExpanded = false
Toast.makeText(context, "Load", Toast.LENGTH_SHORT).show()
},
enabled = false
)
DropdownMenuItem(
text = { Text("Save") },
onClick = {
moreMenuExpanded = false
Toast.makeText(context, "Save", Toast.LENGTH_SHORT).show()
}
)
Divider()
DropdownMenuItem(
text = { Text("Reset") },
onClick = {
moreMenuExpanded = false
Toast.makeText(context, "Reset", Toast.LENGTH_SHORT).show()
}
)
}
CascadeDropdownMenu(
expanded = nestedMenuExpanded,
onDismissRequest = { nestedMenuExpanded = false }
) {
DropdownMenuItem(
text = { Text(text = "1. Item") },
children = {
DropdownMenuItem(
text = { Text(text = "1.1. Sub-Item") },
onClick = {
nestedMenuExpanded = false
Toast.makeText(context, "1.1. Sub-Item", Toast.LENGTH_SHORT).show()
}
)
}
)
DropdownMenuItem(
text = { Text(text = "2. Item") },
children = {
DropdownMenuItem(
text = { Text(text = "2.1. Sub-Item") },
onClick = {
nestedMenuExpanded = false
Toast.makeText(context, "2.1. Sub-Item", Toast.LENGTH_SHORT).show()
}
)
DropdownMenuItem(
text = { Text(text = "2.2. Sub-Item") },
children = {
DropdownMenuItem(
text = { Text(text = "2.2.1. Sub-Sub-Item") },
onClick = {
nestedMenuExpanded = false
Toast.makeText(context, "2.2.1. Sub-Sub-Item", Toast.LENGTH_SHORT).show()
}
)
}
)
}
)
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
// Temperature
ExposedDropdownMenuBox(
expanded = temperatureUnitsExpanded,
onExpandedChange = {
temperatureUnitsExpanded = !temperatureUnitsExpanded
}
) {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.menuAnchor(),
value = selectedTemperatureItem,
label = { Text(text = "Temperature") },
onValueChange = {},
readOnly = true,
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = temperatureUnitsExpanded)
}
)
ExposedDropdownMenu(
expanded = temperatureUnitsExpanded,
onDismissRequest = { temperatureUnitsExpanded = false }
) {
temperatureUnits.forEach { item ->
DropdownMenuItem(
text = { Text(text = item) },
onClick = {
selectedTemperatureItem = item
temperatureUnitsExpanded = false
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
)
}
}
}
// Distance
ExposedDropdownMenuBox(
expanded = distanceUnitsExpanded,
onExpandedChange = {
distanceUnitsExpanded = !distanceUnitsExpanded
}
) {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.menuAnchor(),
value = selectedDistanceItem,
label = { Text(text = "Distance") },
onValueChange = {},
readOnly = true,
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = distanceUnitsExpanded)
}
)
ExposedDropdownMenu(
expanded = distanceUnitsExpanded,
onDismissRequest = { distanceUnitsExpanded = false }
) {
distanceUnits.forEach { item ->
DropdownMenuItem(
text = { Text(text = item) },
onClick = {
selectedDistanceItem = item
distanceUnitsExpanded = false
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
)
}
}
}
// Speed
ExposedDropdownMenuBox(
expanded = speedUnitsExpanded,
onExpandedChange = { speedUnitsExpanded = !speedUnitsExpanded }
) {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.menuAnchor(),
value = selectedSpeedItem,
label = { Text(text = "Speed") },
onValueChange = { selectedSpeedItem = it },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = speedUnitsExpanded)
}
)
val filteredOptions = speedUnits.filter { it.contains(selectedSpeedItem, ignoreCase = true) }
if (filteredOptions.isNotEmpty()) {
ExposedDropdownMenu(
expanded = speedUnitsExpanded,
onDismissRequest = { }
) {
filteredOptions.forEach { item ->
DropdownMenuItem(
text = { Text(text = item) },
onClick = {
selectedSpeedItem = item
speedUnitsExpanded = false
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
)
}
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 9
|
b5b2c7b4333d5c13f598f91e55cb4d7e00a869dc
| 22,920
|
ComposePlayground
|
MIT License
|
db-async-common/src/main/java/com/github/jasync/sql/db/column/InetAddressEncoderDecoder.kt
|
franklx
| 305,075,610
| true
|
{"Kotlin": 706487, "Java": 19240, "Shell": 3903}
|
package com.github.jasync.sql.db.column
import com.google.common.net.InetAddresses
import java.net.InetAddress
object InetAddressEncoderDecoder : ColumnEncoderDecoder {
override fun decode(value: String): Any = InetAddresses.forString(value)
override fun encode(value: Any): String {
return (value as InetAddress).hostAddress
}
}
| 0
|
Kotlin
|
0
| 0
|
6b03a85f76b6ddf6ed5de2f3912cb037c46f6d43
| 354
|
jasync-sql
|
Apache License 2.0
|
app/src/main/java/com/example/tonwalletapp/presentation/screen/main_wallet_screen/view/send_ton/SendTonViewController.kt
|
larkes-cyber
| 619,220,724
| false
|
{"Kotlin": 268960}
|
package com.example.tonwalletapp.presentation.screen.main_wallet_screen.view.send_ton
import android.util.Log
import androidx.lifecycle.ViewModel
import com.example.tonwalletapp.domain.model.WalletDetail
import com.example.tonwalletapp.until.Constants.CONFIRM_TRANSFER_PROGRESS
import com.example.tonwalletapp.until.Constants.ENTER_ADDRESS_TRANSFER_PROGRESS
import com.example.tonwalletapp.until.Constants.ENTER_AMOUNT_TRANSFER_PROGRESS
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.ton.block.AddrStd
import org.ton.block.MsgAddressExt
import org.ton.block.MsgAddressInt
import javax.inject.Inject
@HiltViewModel
class SendTonViewController @Inject constructor():ViewModel() {
private val _sendTonUIState = MutableStateFlow(SendTonUIState())
val sendTonUIState:StateFlow<SendTonUIState> = _sendTonUIState
fun onAddressChange(address:String){
_sendTonUIState.value = sendTonUIState.value.copy(receiverAddress = address)
}
private fun checkAddress(){
try {
AddrStd(_sendTonUIState.value.receiverAddress!!)
}catch (e:Exception){
_sendTonUIState.value = sendTonUIState.value.copy(invalidAddressException = true)
}
}
fun continueTransfer(){
when(sendTonUIState.value.transferProgress){
ENTER_ADDRESS_TRANSFER_PROGRESS -> {
checkAddress()
if(_sendTonUIState.value.invalidAddressException.not()){
_sendTonUIState.value = sendTonUIState.value.copy(transferProgress = ENTER_AMOUNT_TRANSFER_PROGRESS)
}
}
}
}
fun nextTransferStep(){
_sendTonUIState.value = sendTonUIState.value.copy(transferProgress = sendTonUIState.value.transferProgress + 1)
}
fun progressBack(){
_sendTonUIState.value = sendTonUIState.value.copy(transferProgress = sendTonUIState.value.transferProgress - 1)
}
fun backToWallet(){
_sendTonUIState.value = sendTonUIState.value.copy(transferProgress = 0)
}
fun saveMessage(msg:String){
_sendTonUIState.value = sendTonUIState.value.copy(message = msg.ifEmpty { null })
}
fun resetTonSendViewData(){
_sendTonUIState.value = SendTonUIState()
}
fun setSendAmount(amount:Float){
_sendTonUIState.value = sendTonUIState.value.copy(sendAmount = amount, transferProgress = CONFIRM_TRANSFER_PROGRESS)
}
fun initWalletInfo(walletDetail: WalletDetail){
_sendTonUIState.value = sendTonUIState.value.copy(totalTonAmount = walletDetail.balance)
}
fun resetAddressExp(){
_sendTonUIState.value = sendTonUIState.value.copy(invalidAddressException = false)
}
}
| 0
|
Kotlin
|
0
| 2
|
cc4822a1690c45f0d28b0ae3ff118de49c52855c
| 2,794
|
CryptoWalletApp
|
Apache License 2.0
|
ok-marketplace-rv-be-repository-cassandra/src/main/kotlin/ru/otus/otuskotlin/marketplace/backend/repository/cassandra/arts/ArtCassandraDao.kt
|
otuskotlin
| 327,230,292
| false
| null |
package ru.otus.otuskotlin.marketplace.backend.repository.cassandra.arts
import com.datastax.oss.driver.api.mapper.annotations.*
import com.google.common.util.concurrent.ListenableFuture
@Dao
interface ArtByIdCassandraDao {
@Insert
@StatementAttributes(consistencyLevel = "ONE")
fun createAsync(dto: ArtByIdCassandraDto): ListenableFuture<Unit>
@Select
fun readAsync(id: String): ListenableFuture<ArtByIdCassandraDto?>
/**
* В данном случае условие в Update избыточно, так как обновляется вся модель.
* Может быть нужно при обновлении отдельных полей
*/
@Update(customIfClause = "${ArtByIdCassandraDto.LOCK_VERSION} = :lock_key")
@StatementAttributes(consistencyLevel = "QUORUM")
fun updateAsync(dto: ArtByIdCassandraDto, @CqlName("lock_key") lockKey: String): ListenableFuture<Boolean>
/**
* При удалении по ключу требуется указание [entityClass], при удалении по всей модели
* класс не требуется указывать, он берется из модели
*/
@Delete(ifExists = true, entityClass = [ArtByIdCassandraDto::class])
fun deleteAsync(id: String): ListenableFuture<Boolean>
}
@Dao
interface ArtByTitleCassandraDao {
@Insert
@StatementAttributes(consistencyLevel = "ONE")
fun createAsync(dto: ArtByTitleCassandraDto): ListenableFuture<Unit>
@Select(
customWhereClause = "${ArtByTitleCassandraDto.TITLE_INDEX} LIKE :filter",
)
fun filterByTitleAsync(filter: String): ListenableFuture<Collection<ArtByTitleCassandraDto>>
@Delete
fun deleteAsync(dto: ArtByTitleCassandraDto): ListenableFuture<Unit>
}
| 0
|
Kotlin
|
0
| 0
|
9748129f56f26761f8a757a06927ca46bd3905b1
| 1,610
|
otuskotlin-202012-marketplace-rv
|
MIT License
|
app/src/main/java/com/example/weatherapplication/ui/Forecast/ForecastViewModel.kt
|
JyothiGunnam29
| 864,795,329
| false
|
{"Kotlin": 62154, "Java": 1165}
|
package com.example.weatherapplication.ui.Forecast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.weatherapplication.data.ForecastResult
class ForecastViewModel : ViewModel() {
private var forecastResult = MutableLiveData<ForecastResult?>()
var foreCastWeatherRepository: ForeCastWeatherRepository = ForeCastWeatherRepository()
init {
forecastResult = foreCastWeatherRepository.getcurrentResponseLiveData()
}
fun getforecastData(): MutableLiveData<ForecastResult?> {
return forecastResult
}
fun callApi(city: String?) {
city?.let { foreCastWeatherRepository.callforecastAPI(it) }
}
}
| 0
|
Kotlin
|
0
| 0
|
bdfacafee3e24d9de0994c2d0946c5e56e41cbc9
| 729
|
WeatherApplication
|
MIT License
|
src/main/kotlin/bsu/cc/Styles.kt
|
JordanPaoletti
| 167,065,523
| false
| null |
package bsu.cc
import javafx.geometry.Pos
import javafx.scene.paint.Color
import javafx.scene.paint.CycleMethod
import javafx.scene.paint.LinearGradient
import javafx.scene.paint.Stop
import javafx.scene.text.Font
import javafx.scene.text.FontWeight
import javafx.scene.text.TextAlignment
import tornadofx.*
import javax.swing.text.TableView
class Styles : Stylesheet() {
companion object {
val welcomeScreen by cssclass()
val content by cssclass()
val heading by cssclass()
val footer by cssclass()
val bold by cssclass()
val fileChooser by cssclass()
val font by cssclass()
val boxHeight = 40.px
}
init {
font {
fontSize = 12.pt
font = Font.font("Abel")
}
welcomeScreen {
backgroundColor += LinearGradient(0.0, 0.0, 0.0, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, c("#ddddde")), Stop(1.0, c("#eeeeee")))
minWidth = 700.px
}
heading {
padding = box(10.px)
fontSize = 3.em
textFill = Color.BLACK
fontWeight = FontWeight.BOLD
}
fileChooser {
padding = box(10.px, 0.px)
}
content {
padding = box(25.px)
button {
fontSize = 22.px
startMargin = 25.px
minHeight = boxHeight
maxHeight = boxHeight
padding = box(4.px)
}
textField {
minHeight = boxHeight
maxHeight = boxHeight
}
}
footer {
padding = box(0.px,25.px,25.px,25.px)
button {
textFill = Color.BLACK
fontSize = 22.px
}
}
bold {
fontWeight = FontWeight.EXTRA_BOLD
}
}
}
| 4
|
Kotlin
|
1
| 0
|
0b17d34f45cb162e82c76546708dca0c739880ae
| 1,876
|
Conflict_Checker
|
MIT License
|
common/common.consul/common.consul.model/src/main/kotlin/org/eclipse/slm/common/consul/model/catalog/CatalogDeregistration.kt
|
408b7f8b
| 790,281,437
| true
|
{"JSON": 26, "Maven POM": 62, "Markdown": 31, "Git Attributes": 1, "Text": 2, "Ignore List": 6, "YAML": 184, "XML": 7, "Java": 317, "Kotlin": 208, "HTTP": 11, "JavaScript": 67, "Dotenv": 7, "JSON with Comments": 2, "Dockerfile": 25, "Browserslist": 1, "HTML": 2, "Vue": 117, "SCSS": 2, "Sass": 15, "SVG": 2, "HCL": 16, "Shell": 15, "Nginx": 3, "PowerShell": 4, "SQL": 1, "Python": 1, "Java Properties": 1, "CSS": 3, "INI": 5, "Fluent": 1, "Stylus": 2, "OASv3-yaml": 1}
|
package org.eclipse.slm.common.consul.model.catalog
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
class CatalogDeregistration {
@JsonProperty("Datacenter")
var datacenter: String? = null
@JsonProperty("Node")
var node: String? = null
@JsonProperty("CheckID")
var checkId: String? = null
@JsonProperty("ServiceID")
var serviceId: String? = null
override fun toString(): String {
return "CatalogDeregistration { datacenter='${datacenter}', node='${node}, checkId='${checkId}, serviceId='${serviceId}' }";
}
}
| 0
| null |
0
| 0
|
6ccf80fb0f55f4cd65890d689193c8fd47c7db4d
| 664
|
slm
|
Apache License 2.0
|
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/impl/IrSyntheticBodyImpl.kt
|
google
| 219,902,853
| true
|
{"Markdown": 177, "Gradle": 404, "Gradle Kotlin DSL": 1123, "Java Properties": 30, "Shell": 43, "Ignore List": 21, "Batchfile": 21, "Git Attributes": 8, "JSON": 199, "XML": 803, "Kotlin": 54041, "INI": 194, "Java": 3633, "Text": 21765, "JavaScript": 315, "JAR Manifest": 2, "Roff": 256, "Roff Manpage": 52, "Protocol Buffer": 15, "Proguard": 14, "TOML": 1, "AsciiDoc": 1, "YAML": 8, "EditorConfig": 2, "OpenStep Property List": 22, "C": 210, "C++": 366, "LLVM": 1, "Pascal": 1, "Python": 3, "CMake": 2, "Objective-C++": 19, "Objective-C": 207, "Groovy": 10, "Dockerfile": 4, "Diff": 4, "EJS": 1, "CSS": 6, "HTML": 11, "Swift": 128, "JSON with Comments": 60, "TypeScript": 8, "CODEOWNERS": 1, "JFlex": 2, "Graphviz (DOT)": 98, "Ant Build System": 32, "Dotenv": 5, "Maven POM": 77, "FreeMarker": 1, "Fluent": 2, "Ruby": 19, "Scala": 1}
|
/*
* 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.ir.expressions.impl
import org.jetbrains.kotlin.ir.expressions.IrSyntheticBody
import org.jetbrains.kotlin.ir.expressions.IrSyntheticBodyKind
class IrSyntheticBodyImpl(
override val startOffset: Int,
override val endOffset: Int,
override var kind: IrSyntheticBodyKind,
) : IrSyntheticBody()
| 1
|
Kotlin
|
51
| 152
|
e302420197acfd51c6ffe53866d69fcb5b2bb5c7
| 544
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/worldcup2022/App.kt
|
noname6996-tta
| 596,634,213
| false
|
{"Gradle": 5, "JSON": 864, "Java Properties": 8, "Markdown": 5, "Shell": 2, "Text": 24, "HTML": 1, "Batchfile": 2, "INI": 8, "Proguard": 11, "XML": 556, "Kotlin": 191, "Java": 335, "SQL": 4, "Unix Assembly": 2, "Motorola 68K Assembly": 9, "Ignore List": 1}
|
package com.example.worldcup2022
import android.app.Application
import android.content.Context
import com.example.worldcup2022.ui.component.splash.SplashActivity
import com.google.firebase.FirebaseApp
import com.proxglobal.proxads.adsv2.admax.openads.AppOpenManager
import com.proxglobal.proxads.adsv2.admax.openads.MaxOpenAdsApplication
import com.proxglobal.proxads.adsv2.ads.ProxAds
import com.proxglobal.purchase.ProxPurchase
import dagger.hilt.android.HiltAndroidApp
/**
* Created by TruyenIT
*/
@HiltAndroidApp
open class App : MaxOpenAdsApplication(){
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(getApplicationContext());
ProxPurchase.getInstance().initBilling(this)
ProxAds.instance.initMax(context = this)
AppOpenManager.instance.registerDisableOpenAdsAt(SplashActivity::class.java)
}
override fun getOpenAdsId(): String = getString(R.string.id_open_ads)
}
| 0
|
Java
|
0
| 0
|
dbddd12debd5dcf85689a49f92555e5359edd130
| 949
|
WorldCupApp
|
Apache License 2.0
|
app/src/main/java/com/aykuttasil/sweetloc/ui/fragment/entry/EntryFragment.kt
|
aykuttasil
| 61,756,879
| false
|
{"Gradle Kotlin DSL": 3, "Gradle": 8, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Kotlin": 117, "Markdown": 1, "Java Properties": 2, "YAML": 2, "JSON": 2, "Proguard": 2, "Java": 10, "XML": 50, "HTML": 2, "Text": 1}
|
/* Author - <NAME>(@aykuttasil) */
package com.aykuttasil.sweetloc.ui.fragment.entry
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.aykuttasil.sweetloc.R
import com.aykuttasil.sweetloc.data.repository.UserRepository
import com.aykuttasil.sweetloc.di.Injectable
import com.aykuttasil.sweetloc.di.ViewModelFactory
import com.aykuttasil.sweetloc.helper.SweetLocHelper
import com.aykuttasil.sweetloc.ui.BaseAndroidViewModel
import com.aykuttasil.sweetloc.ui.activity.map.MapsActivity
import com.aykuttasil.sweetloc.ui.fragment.BaseFragment
import com.google.firebase.database.DatabaseReference
import com.skydoves.needs.Needs
import com.skydoves.needs.NeedsAnimation
import com.skydoves.needs.NeedsItem
import com.skydoves.needs.OnConfirmListener
import com.skydoves.needs.createNeeds
import kotlinx.android.synthetic.main.fragment_entry.*
import javax.inject.Inject
class EntryFragment : BaseFragment(), Injectable {
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var databaseReference: DatabaseReference
@Inject
lateinit var sweetLocHelper: SweetLocHelper
@Inject
lateinit var viewModelFactory: ViewModelFactory
val viewModel by viewModels<EntryViewModel>() { viewModelFactory }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_entry, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnGoUserTrackerList.setOnClickListener {
findNavController().navigate(R.id.action_mainFragment_to_roomListFragment)
}
btnCleanAllData.setOnClickListener {
showProgress()
databaseReference.removeValue().addOnCompleteListener {
dismissProgress()
}
}
btnLogout.setOnClickListener {
sweetLocHelper.resetSweetLoc(requireContext())
}
val needs = initNeeds()
btnAction.setOnClickListener {
needs.show(view)
/*
val user = userRepository.getUserEntity()
userRepository.processUserToRemote(user!!.userId) {
user.userEmail = "<EMAIL>"
it.updateChildren(mapOf("userEmail" to user.userEmail))
}.subscribe()
*/
}
btnProfile.setOnClickListener {
findNavController().navigate(R.id.action_mainFragment_to_profileFragment)
}
btnOpenMap.setOnClickListener {
startActivity(Intent(requireActivity(), MapsActivity::class.java))
}
}
private fun initNeeds(): Needs {
val needs = createNeeds(context!!) {
// titleIcon = null
title = "Permission instructions \nfor using this Android app."
// titleTextForm = null
addNeedsItem(NeedsItem(null, "SD Card", "(Required)", "Access photos, media, and files on device."))
addNeedsItem(NeedsItem(null, "Location", "(Required)", "Access this device's location."))
addNeedsItem(NeedsItem(null, "Camera", "(Optional)", "Take pictures and record video."))
addNeedsItem(NeedsItem(null, "Contact", "(Optional)", "Access this device's contacts."))
addNeedsItem(NeedsItem(null, "SMS", "(Optional)", "Send and view SMS messages."))
description = "The above accesses are used to better serve you."
confirm = "Confirm"
backgroundAlpha = 0.6f
lifecycleOwner = this@EntryFragment
// needsTheme = theme
// needsItemTheme = itemTheme
needsAnimation = NeedsAnimation.CIRCULAR
}
needs.setOnConfirmListener(object : OnConfirmListener {
override fun onConfirm() {
needs.dismiss()
viewModel.liveSnackbar.value = "Confirmed"
}
})
return needs
}
override fun initViewModel() {
// viewModel = ViewModelProviders.of(this, viewModelFactory).get(EntryViewModel::class.java)
}
override fun initUiComponents() {
}
override fun getViewModel(): BaseAndroidViewModel {
return viewModel
}
}
| 7
|
Kotlin
|
2
| 6
|
5b8e861e3feaa4ed9e90dfb9b252f1ac8d8a7ec2
| 4,495
|
sweetloc
|
Apache License 2.0
|
app/src/main/java/io/github/drumber/kitsune/data/source/network/media/model/unit/NetworkChapter.kt
|
Drumber
| 406,471,554
| false
|
{"Kotlin": 993796, "Ruby": 2109}
|
package io.github.drumber.kitsune.data.source.network.media.model.unit
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Type
import io.github.drumber.kitsune.data.common.Image
import io.github.drumber.kitsune.data.common.Titles
@Type("chapters")
data class NetworkChapter(
@Id
override val id: String?,
override val description: String?,
override val titles: Titles?,
override val canonicalTitle: String?,
override val number: Int?,
val volumeNumber: Int?,
override val length: String?,
override val thumbnail: Image?,
val published: String?
) : NetworkMediaUnit
| 6
|
Kotlin
|
4
| 92
|
ba6f2a69cb71a9fd71d4825921ff6d9b6300471e
| 654
|
Kitsune
|
Apache License 2.0
|
app/src/main/java/com/jrk/mood4food/model/api/Backend.kt
|
Honrix
| 369,880,093
| false
| null |
package com.jrk.mood4food.model.api
import android.content.Context
import android.util.Log
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import org.json.JSONException
import kotlin.reflect.KFunction1
import kotlin.reflect.KFunction2
object Backend {
val PROTOCOL = "http"
val DOMAIN = "irowall-tactical.com"
val SERVICE_PATH = "/mood4food/api"
fun getArray(context: Context, endpoints: Endpoints, params: Map<String, String>, callback: KFunction2<JsonArray, KFunction1<List<Any>, Unit>, Unit>, endpointCallback: KFunction1<List<Any>, Unit>) {
var objects = JsonArray()
val queue = Volley.newRequestQueue(context)
val url = PROTOCOL + "://" + DOMAIN + SERVICE_PATH + endpoints.path + getQuery(params)
val jsonObjectRequest = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener { response ->
try {
objects = JsonParser.parseString(response.toString()).asJsonArray
} catch (e: JSONException) {
e.printStackTrace()
} finally {
callback(objects, endpointCallback)
}
}, Response.ErrorListener {
error -> error.printStackTrace()
callback(objects, endpointCallback)
})
queue.add(jsonObjectRequest)
}
fun get(context: Context, endpoints: Endpoints, params: Map<String, String>, callback: KFunction2<JsonObject, KFunction1<Any, Unit>, Unit>, endpointCallback: KFunction1<Any, Unit>) {
var jsonObject = JsonObject()
val queue = Volley.newRequestQueue(context)
val url = PROTOCOL + "://" + DOMAIN + SERVICE_PATH + endpoints.path + getQuery(params)
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response ->
try {
jsonObject = JsonParser.parseString(response.toString()).asJsonObject
} catch (e: JSONException) {
e.printStackTrace()
} finally {
callback(jsonObject, endpointCallback)
}
}, Response.ErrorListener {
error -> error.printStackTrace()
callback(jsonObject, endpointCallback)
})
queue.add(jsonObjectRequest)
}
private fun getQuery(params: Map<String, String>): String{
var query = ""
params.entries.forEach {
if(query == ""){
query += "?";
}else{
query += "&";
}
query += it.key + "=" + it.value
}
return query
}
}
| 0
| null |
0
| 0
|
fc086543ef8993e5e43d070d8754f60c94bda003
| 2,849
|
Mood4Food
|
MIT License
|
calendarLibrary/src/main/java/com/example/calendarlibrary/utils/BaseCalendarHelper.kt
|
LeoSvjetlicic
| 830,402,028
| false
|
{"Kotlin": 79744}
|
package com.example.calendarlibrary.utils
import com.example.calendarlibrary.ui.calendar.ICalendarViewState
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.Month
import java.time.format.TextStyle
import java.time.temporal.TemporalAdjusters
import java.util.Locale
abstract class BaseCalendarHelper(
override val weekDays: List<DayOfWeek>
) : ICalendarHelper {
override fun getDaysOfWeekNames(
style: TextStyle,
locale: Locale,
): List<String> = weekDays.map { it.getDisplayName(style, locale) }
override fun generateWeeks(
year: Int,
month: Month,
): List<List<LocalDate>> {
val startOfMonth = LocalDate.of(year, month.value, 1)
val endOfMonth = startOfMonth.with(TemporalAdjusters.lastDayOfMonth())
val startOfFirstWeek = startOfMonth.with(TemporalAdjusters.previousOrSame(weekDays[0]))
val endOfLastWeek = endOfMonth.with(TemporalAdjusters.nextOrSame(weekDays.last()))
val weeks = mutableListOf<List<LocalDate>>()
var currentDate = startOfFirstWeek
while (currentDate <= endOfLastWeek) {
val datesOfWeek = mutableListOf<LocalDate>()
repeat(weekDays.size) {
datesOfWeek.add(currentDate)
currentDate = currentDate.plusDays(1)
}
currentDate = currentDate.plusDays((7 - weekDays.size).toLong())
weeks.add(datesOfWeek)
}
return weeks
}
abstract override fun generateCalendarViewState(
year: Int,
month: Month,
weekDayStyle: TextStyle,
monthStyle: TextStyle,
locale: Locale,
selectedDay: String
): ICalendarViewState
}
| 0
|
Kotlin
|
0
| 0
|
fc4aa37c7d1fa4ad577de3af3726e0bb40964c4d
| 1,723
|
CalendarLibrary
|
MIT License
|
katalog-server/src/main/kotlin/com/bol/katalog/store/BlobStoreExtensions.kt
|
csu-anzai
| 206,344,543
| true
|
{"Kotlin": 518462, "TypeScript": 149231, "HTML": 52073, "Java": 44310, "CSS": 1442, "HCL": 1015, "Dockerfile": 653, "Shell": 528}
|
package com.bol.katalog.store
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
import java.net.URI
object BlobStoreObjectMapper {
private val mapper = ObjectMapper()
init {
mapper.registerModule(KotlinModule())
mapper.registerModule(JavaTimeModule())
}
fun get() = mapper
}
suspend inline fun <reified T> BlobStore.getTyped(path: URI): T? {
val mapper = BlobStoreObjectMapper.get()
return get(path)?.let {
mapper.readValue<T>(it)
}
}
suspend inline fun <reified T> BlobStore.storeTyped(path: URI, data: T) {
val mapper = BlobStoreObjectMapper.get()
store(path, mapper.writeValueAsBytes(data))
}
| 0
| null |
0
| 0
|
e85038804bc7c146732461d3ce8decb8a5034ba6
| 832
|
katalog
|
Apache License 2.0
|
src/main/kotlin/com/manoharprabhu/pngtool/chunk/PLTEChunk.kt
|
manoharprabhu
| 380,360,424
| false
| null |
package com.manoharprabhu.pngtool.chunk
import com.manoharprabhu.pngtool.exceptions.InvalidChunkDataException
class PLTEChunk(length: Int, type: ByteArray, data: ByteArray, crc: Int) : Chunk(length, type, data, crc) {
private val paletteEntries: List<PaletteEntry>
init {
if(length % 3 != 0) {
throw InvalidChunkDataException("PLTE length is not a multiple of 3")
}
paletteEntries = parsePaletteEntries()
}
override fun toString(): String {
return "${super.toString()} | paletteEntries - ${paletteEntries.size / 3} entries"
}
private fun parsePaletteEntries(): List<PaletteEntry> {
val list = mutableListOf<PaletteEntry>()
for(i in data.indices step 3) {
list.add(PaletteEntry(data[i], data[i + 1], data[i + 2]))
}
return list
}
}
| 0
|
Kotlin
|
0
| 0
|
a2b492cc3981b798f174696617e6de5b0e67f0dd
| 850
|
PNGTool
|
MIT License
|
app/src/main/java/com/rozoomcool/archibook/ui/components/AppNavBar.kt
|
rozoomcool
| 740,731,116
| false
|
{"Kotlin": 32770}
|
package com.rozoomcool.archibook.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.compose.currentBackStackEntryAsState
import com.rozoomcool.archibook.navigation.NavigationItem
import com.rozoomcool.archibook.navigation.NavigationState
@Composable
fun AppNavBar(navigationState: NavigationState, items: List<NavigationItem>) {
val navBackStackEntry by navigationState.navHostController.currentBackStackEntryAsState()
CustomNavBar {
items.forEach { item ->
val selected: Boolean = navBackStackEntry?.destination?.hierarchy?.any {
it.route == item.screen.route
} ?: false
CustomNavBarItem(
selected = selected,
onClick = {
navigationState.navigateTo(item.screen.route)
},
icon = item.iconResId,
label = { Text(stringResource(item.titleResId), fontWeight = FontWeight.ExtraBold) },
alwaysShowLabel = false
)
}
}
}
@Composable
fun CustomNavBar(navBarItems: @Composable RowScope.() -> Unit) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.animateContentSize()
) {
Box(
modifier = Modifier
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(Color(0xFFECECEF))
// .background(MaterialTheme.colorScheme.surfaceVariant)
) {
Row(
modifier = Modifier
.padding(8.dp)
) {
navBarItems()
FilledIconButton(
shape = RoundedCornerShape(12.dp),
onClick = {}
) {
Icon(Icons.Rounded.Add, contentDescription = null)
}
}
}
}
}
@Composable
fun CustomNavBarItem(
selected: Boolean,
icon: ImageVector,
label: @Composable () -> Unit,
onClick: () -> Unit,
alwaysShowLabel: Boolean
) {
val backgroundColor = if (selected) MaterialTheme.colorScheme.background else Color.Transparent
val contentColor = if (selected) Color(0xFF1A1A1A) else Color(0xFF2A3A4A)
Box(
modifier = Modifier
.clip(CircleShape)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
) { onClick() }
) {
Row(
modifier = Modifier
.padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
) {
Icon(
modifier = Modifier
.animateContentSize()
.scale(if (selected) 1.2f else 1f),
imageVector = icon,
contentDescription = null,
tint = contentColor
)
Spacer(Modifier.width(6.dp))
AnimatedVisibility(
visible = selected
) {
label()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
33eeaf686cb6dc774b6ece5fe725161a8ae47263
| 4,841
|
taskmanager
|
MIT License
|
code/src/main/kotlin/com/expediagroup/sdk/lodgingconnectivity/configuration/ClientConfiguration.kt
|
ExpediaGroup
| 851,671,527
| false
|
{"Kotlin": 176924}
|
package com.expediagroup.sdk.lodgingconnectivity.configuration
import com.expediagroup.sdk.core.configuration.ExpediaGroupClientConfiguration
data class ClientConfiguration(
val key: String?,
val secret: String?,
val environment: ClientEnvironment?,
val requestTimeout: Long? = null,
val connectionTimeout: Long? = null,
val socketTimeout: Long? = null,
val maskedLoggingHeaders: Set<String>? = null,
val maskedLoggingBodyFields: Set<String>? = null
) {
class Builder {
private var key: String? = null
private var secret: String? = null
private var environment: ClientEnvironment? = null
private var requestTimeout: Long? = null
private var connectionTimeout: Long? = null
private var socketTimeout: Long? = null
private var maskedLoggingHeaders: Set<String>? = null
private var maskedLoggingBodyFields: Set<String>? = null
fun key(key: String) = apply {
this.key = key
}
fun secret(secret: String) = apply {
this.secret = secret
}
fun environment(environment: ClientEnvironment) = apply {
this.environment = environment
}
fun requestTimeout(requestTimeout: Long) = apply {
this.requestTimeout = requestTimeout
}
fun connectionTimeout(connectionTimeout: Long) = apply {
this.connectionTimeout = connectionTimeout
}
fun socketTimeout(socketTimeout: Long) = apply {
this.socketTimeout = socketTimeout
}
fun maskedLoggingHeaders(maskedLoggingHeaders: Set<String>) = apply {
this.maskedLoggingHeaders = maskedLoggingHeaders
}
fun maskedLoggingBodyFields(maskedLoggingBodyFields: Set<String>) = apply {
this.maskedLoggingBodyFields = maskedLoggingBodyFields
}
fun build(): ClientConfiguration {
return ClientConfiguration(
key,
secret,
environment,
requestTimeout,
connectionTimeout,
socketTimeout,
maskedLoggingHeaders,
maskedLoggingBodyFields,
)
}
}
companion object {
/** Create a new [ClientConfiguration] builder. */
@JvmStatic
fun builder(): Builder = Builder()
}
fun toExpediaGroupClientConfiguration(
endpointProvider: (ClientEnvironment) -> String,
authEndpointProvider: (ClientEnvironment) -> String
): ExpediaGroupClientConfiguration {
val environment = this.environment ?: ClientEnvironment.PROD
return ExpediaGroupClientConfiguration(
key = this.key,
secret = this.secret,
endpoint = endpointProvider(environment),
authEndpoint = authEndpointProvider(environment),
requestTimeout = this.requestTimeout,
connectionTimeout = this.connectionTimeout,
socketTimeout = this.socketTimeout,
maskedLoggingHeaders = this.maskedLoggingHeaders,
maskedLoggingBodyFields = this.maskedLoggingBodyFields
)
}
}
| 5
|
Kotlin
|
0
| 0
|
ba8232c1116444c5ae1857d71ff4e71a507dc033
| 3,204
|
lodging-connectivity-java-sdk
|
Apache License 2.0
|
app/src/main/java/com/android/goally/ui/home/adapter/CopilotListAdapter.kt
|
saifi369
| 867,819,222
| false
|
{"Kotlin": 94182}
|
package com.android.goally.ui.home.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.android.goally.R
import com.android.goally.databinding.CopilotListItemBinding
import com.android.goally.ui.home.model.CopilotListItem
import com.bumptech.glide.Glide
class CopilotListAdapter(
private val copilotList: MutableList<CopilotListItem>,
private val onCopilotClick: (CopilotListItem) -> Unit
) :
RecyclerView.Adapter<CopilotListAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding =
CopilotListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MyViewHolder(binding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val copilot = copilotList[position]
with(holder.binding) {
tvTitle.text = copilot.name
tvDays.text = copilot.displaySchedule
tvFolderName.text = copilot.folderName
Glide.with(ivTitle)
.load(copilot.imageUrl)
.placeholder(R.drawable.ic_image_placeholder)
.into(ivTitle)
root.setOnClickListener {
onCopilotClick(copilot)
}
}
}
override fun getItemCount() = copilotList.size
fun submitList(list: List<CopilotListItem>) {
copilotList.clear()
copilotList.addAll(list)
notifyDataSetChanged()
}
class MyViewHolder(val binding: CopilotListItemBinding) :
RecyclerView.ViewHolder(binding.root)
}
| 0
|
Kotlin
|
0
| 0
|
c3cc5e87f37f2840f0f25d37752a22afee096daa
| 1,670
|
GoallyAssignment
|
Apache License 2.0
|
app/src/main/java/com/android/goally/ui/home/adapter/CopilotListAdapter.kt
|
saifi369
| 867,819,222
| false
|
{"Kotlin": 94182}
|
package com.android.goally.ui.home.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.android.goally.R
import com.android.goally.databinding.CopilotListItemBinding
import com.android.goally.ui.home.model.CopilotListItem
import com.bumptech.glide.Glide
class CopilotListAdapter(
private val copilotList: MutableList<CopilotListItem>,
private val onCopilotClick: (CopilotListItem) -> Unit
) :
RecyclerView.Adapter<CopilotListAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding =
CopilotListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MyViewHolder(binding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val copilot = copilotList[position]
with(holder.binding) {
tvTitle.text = copilot.name
tvDays.text = copilot.displaySchedule
tvFolderName.text = copilot.folderName
Glide.with(ivTitle)
.load(copilot.imageUrl)
.placeholder(R.drawable.ic_image_placeholder)
.into(ivTitle)
root.setOnClickListener {
onCopilotClick(copilot)
}
}
}
override fun getItemCount() = copilotList.size
fun submitList(list: List<CopilotListItem>) {
copilotList.clear()
copilotList.addAll(list)
notifyDataSetChanged()
}
class MyViewHolder(val binding: CopilotListItemBinding) :
RecyclerView.ViewHolder(binding.root)
}
| 0
|
Kotlin
|
0
| 0
|
c3cc5e87f37f2840f0f25d37752a22afee096daa
| 1,670
|
GoallyAssignment
|
Apache License 2.0
|
feature/motion/src/main/java/com/supergene/loki/feature/motion/MotionViewModel.kt
|
victory316
| 660,866,016
| false
|
{"Kotlin": 186029, "Java": 20240}
|
package com.supergene.loki.feature.motion
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.choidev.core.actions.VibrateAction
import com.choidev.core.actions.mapToId
import com.choidev.latesteffort.core.util.motion.AccelerometerData
import com.choidev.latesteffort.core.util.motion.CachedAccelerometerData
import com.choidev.latesteffort.core.util.motion.MotionManager
import com.choidev.latesteffort.core.util.motion.SensorRate
import com.choidev.latesteffort.core.util.vibration.VibrationManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.roundToInt
private const val DEFAULT_THRESHOLD = 10f
private const val DEFAULT_DIGIT = 1
@HiltViewModel
class MotionViewModel @Inject constructor(
private val motionManager: MotionManager,
private val vibrationManager: VibrationManager
) : ViewModel() {
private val digitSet = listOf(1, 2, 3, 4, 5, 6, 7, 8)
private var fractionDigitIndex = DEFAULT_DIGIT
val currentRate = MutableStateFlow(SensorRate.NORMAL)
val shakeThreshold = MutableStateFlow(DEFAULT_THRESHOLD)
val fractionDigit = MutableStateFlow(digitSet[fractionDigitIndex])
private val _accelerometerData = MutableStateFlow(AccelerometerData())
val accelerometerData = _accelerometerData.stateIn(
scope = viewModelScope,
initialValue = AccelerometerData(),
started = SharingStarted.WhileSubscribed(5_000),
)
private val _cachedAccelerometerData = MutableStateFlow(CachedAccelerometerData())
val cachedAccelerometerData = _cachedAccelerometerData.asStateFlow()
init {
observeAccelerometer()
observeThreshold()
determineShake()
}
fun observeAccelerometer(rate: SensorRate = SensorRate.NORMAL) {
currentRate.value = rate
motionManager.observeAccelerometer(rate) { data ->
_accelerometerData.value = data.copy(
gravityX = data.gravityX.roundTo(fractionDigit.value),
gravityY = data.gravityY.roundTo(fractionDigit.value),
gravityZ = data.gravityZ.roundTo(fractionDigit.value),
accelerationX = data.accelerationX.roundTo(fractionDigit.value),
accelerationY = data.accelerationY.roundTo(fractionDigit.value),
accelerationZ = data.accelerationZ.roundTo(fractionDigit.value)
)
_cachedAccelerometerData.update {
it.copy(
accelerationX = it.accelerationX.toMutableList().apply {
add(data.accelerationX)
if (this.size > 6) removeFirst()
},
accelerationY = it.accelerationY.toMutableList().apply {
add(data.accelerationY)
if (this.size > 6) removeFirst()
},
accelerationZ = it.accelerationZ.toMutableList().apply {
add(data.accelerationZ)
if (this.size > 6) removeFirst()
}
)
}
}
}
fun incrementFractionDigit() {
if ((fractionDigitIndex + 1) <= digitSet.lastIndex) {
fractionDigitIndex++
} else {
fractionDigitIndex = 0
}
fractionDigit.value = digitSet[fractionDigitIndex]
}
private fun determineShake() = viewModelScope.launch {
var shakeFlag = false
var accSum: Float
accelerometerData.collect { data ->
accSum = data.accelerationX + data.accelerationY + data.accelerationZ
if (shakeFlag && !accSum.isNegative()) {
vibrationManager.vibrate()
shakeFlag = false
return@collect
}
if (accSum.isNegative() && accSum.absoluteValue > shakeThreshold.value) {
shakeFlag = true
}
}
}
private fun observeThreshold() = viewModelScope.launch {
shakeThreshold.collect {
vibrationManager.vibrateEffect(VibrateAction.VibrationEffect.EFFECT_TICK.mapToId())
}
}
override fun onCleared() {
super.onCleared()
motionManager.unregisterObservers()
}
private fun Float.roundTo(numFractionDigits: Int): Float {
val factor = 10.0.pow(numFractionDigits.toDouble())
return ((this * factor).roundToInt() / factor).toFloat()
}
private fun Float.isNegative(): Boolean {
return this < 0.0
}
}
| 8
|
Kotlin
|
0
| 0
|
7c233b5e26e5df8873ddb9fb5679f2a3935c854f
| 4,876
|
LatestEffort
|
Apache License 2.0
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/wafv2/CfnWebACLResponseInspectionPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.wafv2
import cloudshift.awscdk.common.CdkDslMarker
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.wafv2.CfnWebACL
/**
* The criteria for inspecting responses to login requests, used by the ATP rule group to track
* login failure rates.
*
* The ATP rule group evaluates the responses that your protected resources send back to client
* login attempts, keeping count of successful and failed attempts from each IP address and client
* session. Using this information, the rule group labels and mitigates requests from client sessions
* and IP addresses that submit too many failed login attempts in a short amount of time.
*
*
* Response inspection is available only in web ACLs that protect Amazon CloudFront distributions.
*
*
* This is part of the `AWSManagedRulesATPRuleSet` configuration in `ManagedRuleGroupConfig` .
*
* Enable login response inspection by configuring exactly one component of the response to inspect.
* You can't configure more than one. If you don't configure any of the response inspection options,
* response inspection is disabled.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.wafv2.*;
* ResponseInspectionProperty responseInspectionProperty = ResponseInspectionProperty.builder()
* .bodyContains(ResponseInspectionBodyContainsProperty.builder()
* .failureStrings(List.of("failureStrings"))
* .successStrings(List.of("successStrings"))
* .build())
* .header(ResponseInspectionHeaderProperty.builder()
* .failureValues(List.of("failureValues"))
* .name("name")
* .successValues(List.of("successValues"))
* .build())
* .json(ResponseInspectionJsonProperty.builder()
* .failureValues(List.of("failureValues"))
* .identifier("identifier")
* .successValues(List.of("successValues"))
* .build())
* .statusCode(ResponseInspectionStatusCodeProperty.builder()
* .failureCodes(List.of(123))
* .successCodes(List.of(123))
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafv2-webacl-responseinspection.html)
*/
@CdkDslMarker
public class CfnWebACLResponseInspectionPropertyDsl {
private val cdkBuilder: CfnWebACL.ResponseInspectionProperty.Builder =
CfnWebACL.ResponseInspectionProperty.builder()
/**
* @param bodyContains Configures inspection of the response body.
* AWS WAF can inspect the first 65,536 bytes (64 KB) of the response body.
*/
public fun bodyContains(bodyContains: IResolvable) {
cdkBuilder.bodyContains(bodyContains)
}
/**
* @param bodyContains Configures inspection of the response body.
* AWS WAF can inspect the first 65,536 bytes (64 KB) of the response body.
*/
public fun bodyContains(bodyContains: CfnWebACL.ResponseInspectionBodyContainsProperty) {
cdkBuilder.bodyContains(bodyContains)
}
/**
* @param header Configures inspection of the response header.
*/
public fun `header`(`header`: IResolvable) {
cdkBuilder.`header`(`header`)
}
/**
* @param header Configures inspection of the response header.
*/
public fun `header`(`header`: CfnWebACL.ResponseInspectionHeaderProperty) {
cdkBuilder.`header`(`header`)
}
/**
* @param json Configures inspection of the response JSON.
* AWS WAF can inspect the first 65,536 bytes (64 KB) of the response JSON.
*/
public fun json(json: IResolvable) {
cdkBuilder.json(json)
}
/**
* @param json Configures inspection of the response JSON.
* AWS WAF can inspect the first 65,536 bytes (64 KB) of the response JSON.
*/
public fun json(json: CfnWebACL.ResponseInspectionJsonProperty) {
cdkBuilder.json(json)
}
/**
* @param statusCode Configures inspection of the response status code.
*/
public fun statusCode(statusCode: IResolvable) {
cdkBuilder.statusCode(statusCode)
}
/**
* @param statusCode Configures inspection of the response status code.
*/
public fun statusCode(statusCode: CfnWebACL.ResponseInspectionStatusCodeProperty) {
cdkBuilder.statusCode(statusCode)
}
public fun build(): CfnWebACL.ResponseInspectionProperty = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 4,503
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
kotlin-in-action/src/main/kotlin/chapter10/Json.kt
|
highright96
| 499,829,960
| false
|
{"Kotlin": 114073, "Java": 941}
|
package chapter10
fun main() {
val person = Person("hi", 10)
//println(serialize(person))
val json = """
{
"name": "hi"
"age": 10
}
""".trimIndent()
//println(deserialize<Person>(json))
}
data class Person(
/*@JsonName("name")*/ val name: String,
/*@JsonName("age")*/ val age: Int
)
| 0
|
Kotlin
|
0
| 2
|
c3cd06deba34ac5b1e60650c638af65034d6ac42
| 354
|
kotlin-sandbox
|
MIT License
|
ws-example/src/main/kotlin/com/github/hyeyoom/springexamples/wsexample/stomp/ChatMessageController.kt
|
hyeyoom
| 234,559,842
| false
| null |
package com.github.hyeyoom.springexamples.wsexample.stomp
import com.github.hyeyoom.springexamples.wsexample.entity.ChatMessage
import org.springframework.context.annotation.Profile
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.web.bind.annotation.RestController
@Profile("stomp")
@RestController
class ChatMessageController(
val template: SimpMessagingTemplate
) {
@MessageMapping("/chat/join")
fun join(message: ChatMessage) {
message.message = "${message.writer}님이 입장하셨습니다."
template.convertAndSend("/subscribe/chat/room/${message.chatRoomId}", message)
}
@MessageMapping("/chat/message")
fun message(message: ChatMessage) {
template.convertAndSend("/subscribe/chat/room/${message.chatRoomId}", message)
}
}
| 0
|
Kotlin
|
0
| 0
|
8d7f7a11b3a05ddf727ebd3a1ee40fe951fe0a28
| 882
|
spring-examples
|
MIT License
|
app/help/src/main/kotlin/studio/lunabee/onesafe/help/main/OverrideWithBackupDialog.kt
|
LunabeeStudio
| 624,544,471
| false
|
{"Kotlin": 3214440, "Java": 11987, "Python": 3979}
|
package studio.lunabee.onesafe.help.main
import androidx.compose.runtime.Composable
import studio.lunabee.compose.core.LbcTextSpec
import studio.lunabee.onesafe.commonui.OSString
import studio.lunabee.onesafe.commonui.dialog.DialogAction
import studio.lunabee.onesafe.dialog.OSDefaultAlertDialog
@Composable
internal fun OverrideWithBackupDialog(onValid: () -> Unit, onCancel: () -> Unit) {
OSDefaultAlertDialog(
onDismissRequest = { onCancel() },
title = LbcTextSpec.StringResource(OSString.help_overrideBackupDialog_title),
message = LbcTextSpec.StringResource(OSString.help_overrideBackupDialog_message),
actionContent = {
DialogAction.commonCancel(onCancel).ActionButton()
DialogAction(
text = LbcTextSpec.StringResource(id = OSString.common_restore),
type = DialogAction.Type.Normal,
onClick = onValid,
clickLabel = LbcTextSpec.StringResource(id = OSString.common_restore),
).ActionButton()
},
)
}
| 1
|
Kotlin
|
1
| 2
|
2f1ff3aad95c748090c695743258fe3056fc6028
| 1,053
|
oneSafe6_SDK_Android
|
Apache License 2.0
|
components/home/src/commonMain/kotlin/com/nikitakrapo/monkeybusiness/home/HomeDependencies.kt
|
nikitakrapo
| 529,813,711
| false
| null |
package com.nikitakrapo.monkeybusiness.home
import com.nikitakrapo.account.AccountManager
import com.nikitakrapo.analytics.AnalyticsManager
import com.nikitakrapo.monkeybusiness.finance.account.BankAccountsRepository
import com.nikitakrapo.monkeybusiness.finances.FinancesDependencies
import com.nikitakrapo.monkeybusiness.finances.accounts.ProductOpeningLandingRouter
import com.nikitakrapo.monkeybusiness.profile.ProfileDependencies
import com.nikitakrapo.monkeybusiness.profile.edit.ProfileEditRouter
class HomeDependencies(
val analyticsManager: AnalyticsManager,
val accountManager: AccountManager,
val productOpeningLandingRouter: ProductOpeningLandingRouter,
val profileEditRouter: ProfileEditRouter,
val bankAccountsRepository: BankAccountsRepository,
) {
fun financesDependencies(): FinancesDependencies {
return FinancesDependencies(
productOpeningLandingRouter = productOpeningLandingRouter,
bankAccountsRepository = bankAccountsRepository,
)
}
fun profileDependencies() = ProfileDependencies(
profileEditRouter = profileEditRouter,
accountManager = accountManager,
)
}
| 0
|
Kotlin
|
0
| 3
|
af1dd192014c4e181cbc31be880579997bf6608b
| 1,176
|
Monkey-Business
|
Apache License 2.0
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Dna2.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
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.Dna2: ImageVector
get() {
if (_dna2 != null) {
return _dna2!!
}
_dna2 = Builder(name = "Dna2", 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(17.0f, 3.0f)
verticalLineToRelative(1.0f)
curveToRelative(-0.01f, 3.352f, -1.68f, 6.023f, -5.008f, 8.014f)
curveToRelative(-3.328f, 1.99f, 3.336f, -2.0f, 0.008f, -0.014f)
curveToRelative(-3.328f, 1.99f, -5.0f, 4.662f, -5.008f, 8.014f)
verticalLineToRelative(1.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(17.0f, 21.014f)
verticalLineToRelative(-1.0f)
curveToRelative(-0.01f, -3.352f, -1.68f, -6.023f, -5.008f, -8.014f)
curveToRelative(-3.328f, -1.99f, 3.336f, 2.0f, 0.008f, 0.014f)
curveToRelative(-3.328f, -1.991f, -5.0f, -4.662f, -5.008f, -8.014f)
verticalLineToRelative(-1.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(7.0f, 4.0f)
horizontalLineToRelative(10.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(7.0f, 20.0f)
horizontalLineToRelative(10.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(8.0f, 8.0f)
horizontalLineToRelative(8.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(8.0f, 16.0f)
horizontalLineToRelative(8.0f)
}
}
.build()
return _dna2!!
}
private var _dna2: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 3,897
|
compose-icon-collections
|
MIT License
|
features/library/src/main/java/taiwan/no/one/feat/library/domain/usecases/UpdatePlaylistOneShotCase.kt
|
pokk
| 263,073,196
| false
| null |
/*
* MIT License
*
* Copyright (c) 2021 Jieyi
*
* 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 taiwan.no.one.feat.library.domain.usecases
import taiwan.no.one.core.domain.usecase.Usecase.RequestValues
import taiwan.no.one.ext.DEFAULT_STR
import taiwan.no.one.feat.library.domain.repositories.PlaylistRepo
import taiwan.no.one.feat.library.domain.repositories.SongRepo
internal class UpdatePlaylistOneShotCase(
private val playlistRepository: PlaylistRepo,
private val songRepository: SongRepo,
) : UpdatePlaylistCase() {
override suspend fun acquireCase(parameter: Request?) = parameter.ensure {
val oldPlaylist = playlistRepository.fetchPlaylist(playlistId!!)
val newPlaylist = if (songIds == null && songsPaths == null) {
oldPlaylist.copy(name = name ?: oldPlaylist.name, refPath = refPath)
}
else {
val set = oldPlaylist.songIds.toSet()
val songIds = getSongIds(this)
val ids = when {
// Add new song ids.
isAddSongs == true && isRemoveSongs != true -> oldPlaylist.songIds.toMutableList()
.apply {
// Check the id has already been in the list.
songIds.forEach {
// If the song id is not in the list, add id into the new list.
if (!set.contains(it)) {
add(it)
}
}
}
// Remove song ids.
isAddSongs != true && isRemoveSongs == true -> oldPlaylist.songIds.toMutableList()
.apply {
// Check the id has already been in the list.
songIds.forEach {
// If the song id is in the list, remove id into the new list.
if (set.contains(it)) {
remove(it)
}
}
}
else -> oldPlaylist.songIds
}
oldPlaylist.copy(
name = name ?: oldPlaylist.name,
songIds = ids,
count = ids.size,
refPath = refPath,
)
}
playlistRepository.updatePlaylist(
if (syncStamp != null) newPlaylist.copy(syncedAt = syncStamp) else newPlaylist
)
true
}
private suspend fun getSongIds(request: UpdatePlaylistReq): List<Int> {
if (request.songIds != null) {
return request.songIds
}
return request.songsPaths?.map { songRepository.fetchMusic(null, it).id } ?: throw NullPointerException()
}
internal data class Request(
val playlistId: Int?,
val name: String? = null,
val songIds: List<Int>? = null,
val songsPaths: List<String>? = null,
val isAddSongs: Boolean? = null,
val isRemoveSongs: Boolean? = null,
val refPath: String = DEFAULT_STR,
val syncStamp: Long? = null,
) : RequestValues
}
| 2
|
Kotlin
|
3
| 16
|
6d173194dcd3c44db46dfe6b0ef691b9322da975
| 4,182
|
DropBeat
|
MIT License
|
vector/src/main/java/im/vector/riotx/features/home/room/detail/composer/ComposerEditText.kt
|
michaelwechner
| 224,202,170
| true
|
{"Kotlin": 3784708, "Java": 24146, "HTML": 22673, "Shell": 20887}
|
/*
* Copyright 2019 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.riotx.features.home.room.detail.composer
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
class ComposerEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.editTextStyle)
: AppCompatEditText(context, attrs, defStyleAttr) {
interface Callback {
fun onRichContentSelected(contentUri: Uri): Boolean
}
var callback: Callback? = null
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection {
val ic: InputConnection = super.onCreateInputConnection(editorInfo)
EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf("*/*"))
val callback =
InputConnectionCompat.OnCommitContentListener { inputContentInfo, flags, _ ->
val lacksPermission = (flags and
InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && lacksPermission) {
try {
inputContentInfo.requestPermission()
} catch (e: Exception) {
return@OnCommitContentListener false
}
}
callback?.onRichContentSelected(inputContentInfo.contentUri) ?: false
}
return InputConnectionCompat.createWrapper(ic, editorInfo, callback)
}
}
| 0
| null |
0
| 0
|
4690754f5fafda66915a1a5dd3389b0497ac1e6c
| 2,405
|
riotX-android
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.