path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
app/src/main/java/com/jx3box/ui/search/SearchViewModel.kt
JX3BOX
296,293,464
false
{"Kotlin": 416471, "Java": 413805}
/* * Copyright (C) 2020. jx3box.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jx3box.ui.search import com.jx3box.data.net.repository.RankRepository import com.jx3box.data.net.repository.SearchRepository import com.jx3box.mvvm.base.BaseViewModel /** * @author Carey * @date 2020/10/30 */ class SearchViewModel( private val repository: SearchRepository, private val rankRepository: RankRepository ) : BaseViewModel() { }
0
Kotlin
0
0
6931ec7f5edc83595f6baeec3063fd9c18759c5f
1,000
jx3box-android
Apache License 2.0
target-switch/src/main/java/com/shunan/target_switch/TargetSwitchAnimListener.kt
shubhamnandanwar
555,680,170
false
{"Kotlin": 9501}
package com.shunan.target_switch interface TargetSwitchAnimListener { fun onAnimStart() fun onAnimEnd() fun onAnimValueChanged(value: Float) }
0
Kotlin
0
0
d5a4ca0103107f81ebd81cf888965178f4ebba48
156
Target-Switch
Apache License 2.0
kgl-vulkan/src/jvmMain/kotlin/com/kgl/vulkan/enums/BufferUsage.kt
NikkyAI
168,431,916
true
{"Kotlin": 1894114, "C": 1742775}
/** * Copyright [2019] [<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.kgl.vulkan.enums import com.kgl.vulkan.utils.VkFlag import org.lwjgl.vulkan.EXTConditionalRendering import org.lwjgl.vulkan.EXTTransformFeedback import org.lwjgl.vulkan.NVRayTracing import org.lwjgl.vulkan.VK11 actual enum class BufferUsage(override val value: Int) : VkFlag<BufferUsage> { TRANSFER_SRC(VK11.VK_BUFFER_USAGE_TRANSFER_SRC_BIT), TRANSFER_DST(VK11.VK_BUFFER_USAGE_TRANSFER_DST_BIT), UNIFORM_TEXEL_BUFFER(VK11.VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT), STORAGE_TEXEL_BUFFER(VK11.VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT), UNIFORM_BUFFER(VK11.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT), STORAGE_BUFFER(VK11.VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), INDEX_BUFFER(VK11.VK_BUFFER_USAGE_INDEX_BUFFER_BIT), VERTEX_BUFFER(VK11.VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), INDIRECT_BUFFER(VK11.VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT), CONDITIONAL_RENDERING_EXT(EXTConditionalRendering.VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT), RAY_TRACING_NV(NVRayTracing.VK_BUFFER_USAGE_RAY_TRACING_BIT_NV), TRANSFORM_FEEDBACK_BUFFER_EXT(EXTTransformFeedback.VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT), TRANSFORM_FEEDBACK_COUNTER_BUFFER_EXT(EXTTransformFeedback.VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT); companion object { private val enumLookUpMap: Map<Int, BufferUsage> = enumValues<BufferUsage>().associateBy({ it.value }) fun fromMultiple(value: Int): VkFlag<BufferUsage> = VkFlag(value) fun from(value: Int): BufferUsage = enumLookUpMap[value]!! } }
0
Kotlin
0
0
51dfa8a4c655ff8bcf017d8d4a2eb660e14473ed
2,107
kgl
Apache License 2.0
libraries/text-reader/src/TextReader.kt
featurea
407,517,337
false
null
package featurea.text.reader import featurea.Bundle import featurea.System import featurea.content.Resource import featurea.content.ResourceReader import featurea.content.textExtensions import featurea.hasExtension import featurea.runtime.Container class TextReader(container: Container) : ResourceReader { private val system: System = container.import() override suspend fun readOrNull(resourcePath: String, bundle: Bundle?): Resource? { if (resourcePath.hasExtension(system.textExtensions)) { return Resource(resourcePath) } return null } }
30
Kotlin
1
6
07074dc37a838f16ece90c19a4e8d45e743013d3
596
engine
MIT License
src/main/kotlin/no/nav/sokos/pdl/proxy/config/PropertiesConfig.kt
navikt
399,444,072
false
{"Kotlin": 56280, "Shell": 568, "Dockerfile": 244}
package no.nav.sokos.pdl.proxy.config import com.natpryce.konfig.ConfigurationMap import com.natpryce.konfig.ConfigurationProperties import com.natpryce.konfig.EnvironmentVariables import com.natpryce.konfig.Key import com.natpryce.konfig.overriding import com.natpryce.konfig.stringType import java.io.File object PropertiesConfig { private val defaultProperties = ConfigurationMap( mapOf( "NAIS_APP_NAME" to "sokos-pdl-proxy", "NAIS_NAMESPACE" to "okonomi", ) ) private val localDevProperties = ConfigurationMap( "USE_AUTHENTICATION" to "true", "APPLICATION_PROFILE" to Profile.LOCAL.toString(), ) private val devProperties = ConfigurationMap(mapOf("APPLICATION_PROFILE" to Profile.DEV.toString())) private val prodProperties = ConfigurationMap(mapOf("APPLICATION_PROFILE" to Profile.PROD.toString())) private val config = when (System.getenv("NAIS_CLUSTER_NAME") ?: System.getProperty("NAIS_CLUSTER_NAME")) { "dev-gcp" -> ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding devProperties overriding defaultProperties "prod-gcp" -> ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding prodProperties overriding defaultProperties else -> ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding ConfigurationProperties.fromOptionalFile( File("defaults.properties") ) overriding localDevProperties overriding defaultProperties } private operator fun get(key: String): String = config[Key(key, stringType)] data class Configuration( val naisAppName: String = get("NAIS_APP_NAME"), val profile: Profile = Profile.valueOf(this["APPLICATION_PROFILE"]), val useAuthentication: Boolean = get("USE_AUTHENTICATION").toBoolean(), val azureAdClientConfig: AzureAdClientConfig = AzureAdClientConfig(), val azureAdServerConfig: AzureAdServerConfig = AzureAdServerConfig(), val pdlConfig: PdlConfig = PdlConfig() ) data class AzureAdClientConfig( val clientId: String = get("AZURE_APP_CLIENT_ID"), val wellKnownUrl: String = get("AZURE_APP_WELL_KNOWN_URL"), val tenantId: String = get("AZURE_APP_TENANT_ID"), val clientSecret: String = get("AZURE_APP_CLIENT_SECRET"), val pdlClientId: String = get("PDL_CLIENT_ID") ) data class AzureAdServerConfig( val clientId: String = get("AZURE_APP_CLIENT_ID"), val wellKnownUrl: String = get("AZURE_APP_WELL_KNOWN_URL"), ) data class PdlConfig( val pdlUrl: String = this["PDL_URL"] ) enum class Profile { LOCAL, DEV, PROD } }
0
Kotlin
0
0
85491008a64c21d7152d70e5511e85f0a9305262
2,780
sokos-pdl-proxy
MIT License
app/src/main/java/com/bcp/androidchallenge/data/local/ExchangeRateDao.kt
deividnew94
363,849,418
false
null
package com.bcp.androidchallenge.data.local import androidx.lifecycle.LiveData import androidx.room.* import com.bcp.androidchallenge.core.ResultType import com.bcp.androidchallenge.core.model.ExchangesRateModel import com.bcp.androidchallenge.data.model.ExchangeRateEntity /** * Created by <NAME> on 07 July 2020 */ @Dao interface ExchangeRateDao { @Query("SELECT * FROM exchangeratesTable WHERE currency LIKE '%' || :exchangeRateName || '%'") // This Like operator is needed due that the API returns blank spaces in the name suspend fun getExchangeRates(exchangeRateName: String): List<ExchangeRateEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveExchangeRate(exchangeRate: ExchangeRateEntity) @Query("SELECT * FROM exchangeratesTable") fun getAllFavoriteExchangeRateWithChanges(): LiveData<List<ExchangeRateEntity>> }
0
Kotlin
0
0
e7bf448b17bd40909180da28d2f5d6dddce51d0b
886
bcp-android-challenge
MIT License
app/src/main/java/ru/resodostudios/pokedex/presentation/pokemon/PokemonViewModel.kt
f33lnothin9
540,119,830
false
{"Kotlin": 59209}
package ru.resodostudios.pokedex.presentation.pokemon import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import ru.resodostudios.pokedex.data.remote.responses.Pokemon import ru.resodostudios.pokedex.domain.repository.PokemonRepository import ru.resodostudios.pokedex.util.Resource import javax.inject.Inject @HiltViewModel class PokemonViewModel @Inject constructor( private val repository: PokemonRepository ) : ViewModel() { suspend fun getPokemon(name: String): Resource<Pokemon> { return repository.getPokemon(name) } }
0
Kotlin
0
2
e55993f3e81c8315624ffc897156c77846b4400d
581
pokedex
Apache License 2.0
customdata-gender/src/main/java/contacts/entities/custom/gender/ContactGender.kt
vestrel00
223,332,584
false
{"Kotlin": 1616347, "Shell": 635}
package contacts.entities.custom.gender import contacts.core.Contacts import contacts.core.entities.Contact import contacts.core.entities.MutableContact import contacts.core.entities.RawContact import contacts.core.util.sortedById // Dev note: The functions that return a List instead of a Sequence are useful for Java consumers // as they will not have to convert Sequences to List. Also, all are functions instead of properties // with getters because there are some setters that have to be functions. So all are functions // to keep uniformity for OCD purposes. // region Contact /** * Returns the sequence of [Gender]s from all [Contact.rawContacts] ordered by the [Gender.id]. */ fun Contact.genders(contacts: Contacts): Sequence<Gender> = rawContacts .asSequence() .mapNotNull { it.gender(contacts) } .sortedBy { it.id } /** * Returns the list of [Gender]s from all [Contact.rawContacts] ordered by the [Gender.id]. */ fun Contact.genderList(contacts: Contacts): List<Gender> = genders(contacts).toList() // endregion // region MutableContact /** * Returns the sequence of [MutableGenderEntity]s from all [Contact.rawContacts] ordered by id. */ fun MutableContact.genders(contacts: Contacts): Sequence<MutableGenderEntity> = rawContacts .asSequence() .mapNotNull { it.gender(contacts) } .sortedById() /** * Returns the list of [MutableGender]s from all [Contact.rawContacts] ordered by id. */ fun MutableContact.genderList(contacts: Contacts): List<MutableGenderEntity> = genders(contacts).toList() /** * Sets the [RawContact.gender] of the first RawContact in [MutableContact.rawContacts] sorted by * the RawContact id. */ fun MutableContact.setGender(contacts: Contacts, gender: MutableGenderEntity?) { rawContacts.firstOrNull()?.setGender(contacts, gender) } /** * Sets the [RawContact.gender] (configured by [configureGender]) of the first RawContact in * [MutableContact.rawContacts] sorted by the RawContact id. */ fun MutableContact.setGender(contacts: Contacts, configureGender: NewGender.() -> Unit) { setGender(contacts, NewGender().apply(configureGender)) } // endregion
23
Kotlin
36
555
193014a913ad76e2de31d1da1e21f0b475887003
2,149
contacts-android
Apache License 2.0
app/src/main/java/com/zqf/kotlinwanandroid/ui/presenter/LoginPresenter.kt
zqf-dev
484,351,347
false
{"Kotlin": 130314, "Java": 98386}
package com.zqf.kotlinwanandroid.ui.presenter import android.text.TextUtils import com.hjq.toast.ToastUtils import com.zqf.kotlinwanandroid.base.BasePresenter import com.zqf.kotlinwanandroid.entity.LoginInfoEntity import com.zqf.kotlinwanandroid.http.API import com.zqf.kotlinwanandroid.interceptor.LoginInterceptChain import com.zqf.kotlinwanandroid.ui.contact.LoginContact import kotlinx.coroutines.launch import rxhttp.RxHttp import rxhttp.awaitResult import rxhttp.toResponse /** * Author: zqf * Date: 2022/09/01 */ class LoginPresenter(v: LoginContact.ILoginView) : BasePresenter<LoginContact.ILoginView>(), LoginContact.Presenter { init { attachView(v) } override fun onDestroy() { LoginInterceptChain.loginFinished() } override fun loginServer(vT: Int, ac: String, psd: String, repsd: String) { if (TextUtils.isEmpty(ac) || TextUtils.isEmpty(psd)) { ToastUtils.show("账号和密码不能为空") return } when (vT) { 0 -> { mCoroutineScope.launch { RxHttp.postForm(API.login) .add("username", ac).add("password", psd) .toResponse<LoginInfoEntity>() .awaitResult { getView()!!.loginsuc() }.onFailure { ToastUtils.show(it.message) } } } 1 -> { if (TextUtils.isEmpty(repsd) || psd != repsd) { ToastUtils.show("两次输入的密码不对") return } mCoroutineScope.launch { RxHttp.postForm(API.register) .add("username", ac) .add("password", psd) .add("repassword", repsd) .toResponse<String>() .awaitResult { getView()!!.registsuc() }.onFailure { ToastUtils.show(it.message) } } } } } }
0
Kotlin
1
6
d13eb0db92a608578943369b39221169b0098297
2,224
KotlinWanAndroid
Apache License 2.0
src/main/kotlin/tech/sprytin/starter/chatgpt/dto/ChatChoice.kt
Sprytin
608,530,834
false
null
package tech.sprytin.starter.chatgpt.dto import com.fasterxml.jackson.annotation.JsonProperty data class ChatChoice( val index: Int, val message: ChatMessage, @JsonProperty("finish_reason") val finishReason: String )
1
Kotlin
1
12
2cf682aee40db608b49faa834b9967dd11f37ea6
234
chatgpt-spring-boot-starter
MIT License
model/src/main/kotlin/org/digma/intellij/plugin/model/rest/insights/SpanQueryOptimizationInsight.kt
digma-ai
472,408,329
false
{"Kotlin": 1315823, "Java": 697153, "C#": 114216, "FreeMarker": 13319, "HTML": 13271, "Shell": 6494}
package org.digma.intellij.plugin.model.rest.insights import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import org.digma.intellij.plugin.model.InsightType import java.beans.ConstructorProperties import java.util.Date @JsonIgnoreProperties(ignoreUnknown = true) class SpanQueryOptimizationInsight @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) @ConstructorProperties( "codeObjectId", "environment", "scope", "importance", "decorators", "actualStartTime", "customStartTime", "prefixedCodeObjectId", "isRecalculateEnabled", "shortDisplayInfo", "spanInfo", "traceId", "duration", "typicalDuration", "dbStatement", "serviceName", "dbName", "endpoints", "severity", "impact", "criticality", "firstCommitId", "lastCommitId", "deactivatedCommitId", "reopenCount", "ticketLink", "firstDetected", "lastDetected" ) constructor( override val codeObjectId: String, override val environment: String, override val scope: String, override val importance: Int, override val decorators: List<CodeObjectDecorator>?, override val actualStartTime: Date?, override val customStartTime: Date?, override val prefixedCodeObjectId: String?, @get:JsonProperty("isRecalculateEnabled") @param:JsonProperty("isRecalculateEnabled") override val isRecalculateEnabled: Boolean, override val shortDisplayInfo: ShortDisplayInfo?, override val spanInfo: SpanInfo, val traceId: String?, val duration: Duration, val typicalDuration: Duration, val dbStatement: String, val serviceName: String?, val dbName: String?, val endpoints: List<QueryOptimizationEndpoints>, override val severity: Double, override val impact: Double, override val criticality: Double, override val firstCommitId: String?, override val lastCommitId: String?, override val deactivatedCommitId: String?, override val reopenCount: Int, override val ticketLink: String?, override val firstDetected: Date?, override val lastDetected: Date?, ) : SpanInsight { override val type: InsightType = InsightType.SpanQueryOptimization }
390
Kotlin
6
17
55a318082a8f8b8d3a1de7d50e83af12d1ef1657
2,544
digma-intellij-plugin
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/statistics/ui/homecards/StatisticsLayoutManager.kt
si-covid-19
286,833,811
false
null
package de.rki.coronawarnapp.statistics.ui.homecards import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView /** * A custom RecyclerView.LayoutManager implementation that extends * the height of items to match RecyclerView.  **/ class StatisticsLayoutManager : LinearLayoutManager { constructor(context: Context?) : super(context) constructor( context: Context?, @RecyclerView.Orientation orientation: Int, reverseLayout: Boolean ) : super(context, orientation, reverseLayout) constructor( context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : super(context, attrs, defStyleAttr, defStyleRes) override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams { return spanLayoutSize(super.generateDefaultLayoutParams()) } override fun generateLayoutParams(c: Context, attrs: AttributeSet): RecyclerView.LayoutParams { return spanLayoutSize(super.generateLayoutParams(c, attrs)) } override fun generateLayoutParams(lp: ViewGroup.LayoutParams): RecyclerView.LayoutParams { return spanLayoutSize(super.generateLayoutParams(lp)) } private fun spanLayoutSize(layoutParams: RecyclerView.LayoutParams): RecyclerView.LayoutParams { return RecyclerView.LayoutParams( layoutParams.width, RecyclerView.LayoutParams.MATCH_PARENT ) } }
6
Kotlin
8
15
5a3b4be63b5b030da49216a0132a3979cad89af1
1,580
ostanizdrav-android
Apache License 2.0
modules/views/src/androidMain/kotlin/splitties/views/Click.kt
LouisCAD
65,558,914
false
{"Kotlin": 682428, "Java": 1368, "Shell": 358}
/* * Copyright 2019-2020 <NAME>. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") package splitties.views import android.view.View /** * Registers the [block] lambda as [View.OnClickListener] to this View. * * If this View is not clickable, it becomes clickable. */ inline fun View.onClick(block: View.OnClickListener) = setOnClickListener(block) /** * Register the [block] lambda as [View.OnLongClickListener] to this View. * By default, [consume] is set to true because it's the most common use case, but you can set it * to false. * If you want to return a value dynamically, use [View.setOnLongClickListener] instead. * * If this view is not long clickable, it becomes long clickable. */ inline fun View.onLongClick( consume: Boolean = true, crossinline block: () -> Unit ) = setOnLongClickListener { block(); consume }
51
Kotlin
158
2,433
1ed56ba2779f31dbf909509c955fce7b9768e208
924
Splitties
Apache License 2.0
app/src/main/java/com/samiu/wangank/ui/square/WanSquareViewModel.kt
SamiuZhong
244,276,691
false
{"Kotlin": 180449}
package com.samiu.wangank.ui.square import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn /** * @author Samiu 2020/3/5 * @email <EMAIL> */ class WanSquareViewModel( wanSquareRepository: WanSquareRepository ) : ViewModel() { val articlePagingList = wanSquareRepository.getArticlePaging().cachedIn(viewModelScope) }
0
Kotlin
3
15
ec64d4f55d71140273b320e3936761dea992b5f2
397
WanAndroidGank
MIT License
routing/src/commonMain/kotlin/com/diachuk/routing/BackHandler.kt
vldi01
678,307,317
false
null
package com.diachuk.routing import androidx.compose.runtime.Composable @Composable expect fun BackHandler(enabled: Boolean, block: () -> Unit)
0
Kotlin
0
0
a4011e8d2a2ed7b33d097bd2d89c7be70c4d8431
145
BLE-LED-Hack-Multiplatform
Apache License 2.0
src/main/kotlin/org/jetbrains/plugins/lang/SimpleStructureViewFactory.kt
sabahtalateh
355,296,077
false
null
package org.jetbrains.plugins.lang import com.intellij.ide.structureView.StructureViewBuilder import com.intellij.ide.structureView.StructureViewModel import com.intellij.ide.structureView.TreeBasedStructureViewBuilder import com.intellij.lang.PsiStructureViewFactory import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile class SimpleStructureViewFactory : PsiStructureViewFactory { override fun getStructureViewBuilder(psiFile: PsiFile): StructureViewBuilder { return object : TreeBasedStructureViewBuilder() { override fun createStructureViewModel(editor: Editor?): StructureViewModel { return SimpleStructureViewModel(psiFile) } } } }
11
Kotlin
0
0
4746e0c863ac2f05796935b4de2b6cc70bc83169
724
simple-language
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/service/reports/PersonParserTest.kt
ministryofjustice
292,861,912
false
{"Kotlin": 874836, "HTML": 131707, "Shell": 20530, "CSS": 19037, "Mustache": 4593, "Dockerfile": 1110}
package uk.gov.justice.digital.hmpps.pecs.jpc.service.reports import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import uk.gov.justice.digital.hmpps.pecs.jpc.domain.personprofile.Person class PersonParserTest { @Test fun `Assert Person can be created from json`() { val personJson = """{"id":"PE1","updated_at": "2020-06-16T10:20:30+01:00","criminal_records_office":null,"nomis_prison_number":null,"police_national_computer":"83SHX5/YL","prison_number":"PRISON1","latest_nomis_booking_id":null,"gender":"male","age":100, "ethnicity" : "White American", "first_names" : "<NAME>", "last_name": "Kid", "date_of_birth" : "1980-12-25"} """.trimIndent() val parsedPerson = Person.fromJson(personJson) assertThat(reportPersonFactory()).isEqualTo(parsedPerson) } }
1
Kotlin
2
2
409dde1a40a58974f3540edf49afa18cbeb5f51d
828
calculate-journey-variable-payments
MIT License
compiler/testData/loadJava/javaAgainstKotlin/signaturePropagation/DeepSubclassingKotlinInJava/E.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
package test public open class E: D() { override fun foo(): String = "" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
79
kotlin
Apache License 2.0
app/src/main/java/com/minar/birday/activities/MainActivity.kt
zalefin
350,901,991
true
{"Kotlin": 121233}
package com.minar.birday.activities import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.content.ContentResolver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.media.AudioAttributes import android.media.AudioAttributes.Builder import android.net.Uri import android.os.* import android.text.Editable import android.text.TextWatcher import android.widget.CheckBox import android.widget.TextView import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.setupWithNavController import androidx.preference.PreferenceManager import com.afollestad.materialdialogs.LayoutMode import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.getActionButton import com.afollestad.materialdialogs.bottomsheets.BottomSheet import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.customview.getCustomView import com.afollestad.materialdialogs.datetime.datePicker import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.minar.birday.R import com.minar.birday.adapters.EventAdapter import com.minar.birday.backup.BirdayImporter import com.minar.birday.backup.ContactsImporter import com.minar.birday.model.Event import com.minar.birday.utilities.AppRater import com.minar.birday.utilities.checkString import com.minar.birday.utilities.smartCapitalize import com.minar.birday.viewmodels.HomeViewModel import kotlinx.android.synthetic.main.dialog_insert_event.view.* import java.io.IOException import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.util.* class MainActivity : AppCompatActivity() { lateinit var homeViewModel: HomeViewModel private lateinit var adapter: EventAdapter @ExperimentalStdlibApi override fun onCreate(savedInstanceState: Bundle?) { homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) adapter = EventAdapter(null) // Create the notification channel and check the permission (note: appIntro 6.0 is still buggy, better avoid to use it for asking permissions) askContactsPermission() createNotificationChannel() // Retrieve the shared preferences val sp = PreferenceManager.getDefaultSharedPreferences(this) val theme = sp.getString("theme_color", "system") val accent = sp.getString("accent_color", "brown") // Show the introduction for the first launch if (sp.getBoolean("first", true)) { val editor = sp.edit() editor.putBoolean("first", false) editor.apply() val intent = Intent(this, WelcomeActivity::class.java) startActivity(intent) finish() } // Set the base theme and the accent when (theme) { "dark" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) "light" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) "system" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) } when (accent) { "blue" -> setTheme(R.style.AppTheme_Blue) "green" -> setTheme(R.style.AppTheme_Green) "orange" -> setTheme(R.style.AppTheme_Orange) "yellow" -> setTheme(R.style.AppTheme_Yellow) "teal" -> setTheme(R.style.AppTheme_Teal) "violet" -> setTheme(R.style.AppTheme_Violet) "pink" -> setTheme(R.style.AppTheme_Pink) "lightBlue" -> setTheme(R.style.AppTheme_LightBlue) "red" -> setTheme(R.style.AppTheme_Red) "lime" -> setTheme(R.style.AppTheme_Lime) } super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Get the bottom navigation bar and configure it for the navigation plugin val navigation = findViewById<BottomNavigationView>(R.id.navigation) val navController: NavController = Navigation.findNavController(this, R.id.navHostFragment ) navigation.setupWithNavController(navController) navigation.setOnNavigationItemReselectedListener { // Just ignore the reselection of the same item } // Rating stuff AppRater.appLaunched(this) // Manage the fab val fab = findViewById<FloatingActionButton>(R.id.fab) fab.setOnClickListener { vibrate() // Show a bottom sheet containing the form to insert a new event var nameValue = "error" var surnameValue = "" var eventDateValue: LocalDate = LocalDate.of(1970,1,1) var countYearValue = true val dialog = MaterialDialog(this, BottomSheet(LayoutMode.WRAP_CONTENT)).show { cornerRadius(res = R.dimen.rounded_corners) title(R.string.new_event) icon(R.drawable.ic_party_24dp) message(R.string.new_event_description) customView(R.layout.dialog_insert_event) positiveButton(R.string.insert_event) { // Use the data to create a event object and insert it in the db val tuple = Event( id = 0, originalDate = eventDateValue, name = nameValue.smartCapitalize(), surname = surnameValue.smartCapitalize(), yearMatter = countYearValue ) // Insert using another thread val thread = Thread { homeViewModel.insert(tuple) } thread.start() dismiss() } negativeButton(R.string.cancel) { dismiss() } } // Setup listeners and checks on the fields dialog.getActionButton(WhichButton.POSITIVE).isEnabled = false val customView = dialog.getCustomView() val name = customView.findViewById<TextView>(R.id.nameEvent) val surname = customView.findViewById<TextView>(R.id.surnameEvent) val eventDate = customView.findViewById<TextView>(R.id.dateEvent) val countYear = customView.findViewById<CheckBox>(R.id.countYearCheckbox) val endDate = Calendar.getInstance() var dateDialog: MaterialDialog? = null // Update the boolean value on each click countYear.setOnCheckedChangeListener { _, isChecked -> countYearValue = isChecked } eventDate.setOnClickListener { // Prevent double dialogs on fast click if(dateDialog == null) { dateDialog = MaterialDialog(this).show { cancelable(false) cancelOnTouchOutside(false) datePicker(maxDate = endDate) { _, date -> val year = date.get(Calendar.YEAR) val month = date.get(Calendar.MONTH) + 1 val day = date.get(Calendar.DAY_OF_MONTH) eventDateValue = LocalDate.of(year, month, day) val formatter: DateTimeFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) eventDate.text = eventDateValue.format(formatter) } } Handler(Looper.getMainLooper()).postDelayed({ dateDialog = null }, 750) } } // Validate each field in the form with the same watcher var nameCorrect = false var surnameCorrect = true // Surname is not mandatory var eventDateCorrect = false val watcher = object: TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun afterTextChanged(editable: Editable) { when { editable === name.editableText -> { val nameText = name.text.toString() if (nameText.isBlank() || !checkString(nameText)) { // Setting the error on the layout is important to make the properties work. Kotlin synthetics are being used here customView.nameEventLayout.error = getString(R.string.invalid_value_name) dialog.getActionButton(WhichButton.POSITIVE).isEnabled = false nameCorrect = false } else { nameValue = nameText customView.nameEventLayout.error = null nameCorrect = true } } editable === surname.editableText -> { val surnameText = surname.text.toString() if (!checkString(surnameText)) { // Setting the error on the layout is important to make the properties work. Kotlin synthetics are being used here customView.surnameEventLayout.error = getString(R.string.invalid_value_name) dialog.getActionButton(WhichButton.POSITIVE).isEnabled = false surnameCorrect = false } else { surnameValue = surnameText customView.surnameEventLayout.error = null surnameCorrect = true } } // Once selected, the date can't be blank anymore editable === eventDate.editableText -> eventDateCorrect = true } if(eventDateCorrect && nameCorrect && surnameCorrect) dialog.getActionButton(WhichButton.POSITIVE).isEnabled = true } } name.addTextChangedListener(watcher) surname.addTextChangedListener(watcher) eventDate.addTextChangedListener(watcher) } } // Create the NotificationChannel. When created the first time, this code does nothing private fun createNotificationChannel() { val soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + applicationContext.packageName + "/" + R.raw.birday_notification) val attributes: AudioAttributes = Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build() val name = getString(R.string.events_notification_channel) val descriptionText = getString(R.string.events_channel_description) val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel("events_channel", name, importance).apply { description = descriptionText } // Additional tuning over sound, vibration and notification light channel.setSound(soundUri, attributes) channel.enableLights(true) channel.lightColor = Color.GREEN channel.enableVibration(true) // Register the channel with the system val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } // Choose a backup registering a callback and following the latest guidelines val selectBackup = registerForActivityResult(ActivityResultContracts.GetContent()) { fileUri: Uri? -> try { val birdayImporter = BirdayImporter(this, null) if (fileUri != null) birdayImporter.importBirthdays(this, fileUri) } catch (e: IOException) { e.printStackTrace() } } // Some utility functions, used from every fragment connected to this activity // Vibrate using a standard vibration pattern fun vibrate() { val sp = PreferenceManager.getDefaultSharedPreferences(this) val vib = this.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator if (sp.getBoolean("vibration", true)) // Vibrate if the vibration in options is set to on vib.vibrate(VibrationEffect.createOneShot(30, VibrationEffect.DEFAULT_AMPLITUDE)) } // Ask contacts permission fun askContactsPermission(code: Int = 101): Boolean { return if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS), code) ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED } else true } // Manage user response to permission requests override fun onRequestPermissionsResult(requestCode : Int, permissions: Array<String>, grantResults: IntArray){ super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { // Contacts at startup 101 -> { if (grantResults.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) { if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) Toast.makeText(this, getString(R.string.missing_permission_contacts), Toast.LENGTH_LONG).show() else Toast.makeText(this, getString(R.string.missing_permission_contacts_forever), Toast.LENGTH_LONG).show() } } // Contacts while trying to import Google contacts 102 -> { if (grantResults.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) { if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) Toast.makeText(this, getString(R.string.missing_permission_contacts), Toast.LENGTH_LONG).show() else Toast.makeText(this, getString(R.string.missing_permission_contacts_forever), Toast.LENGTH_LONG).show() } else { val contactImporter = ContactsImporter(this, null) contactImporter.importContacts(this) } } } } }
0
Kotlin
0
0
d6d9f77f5d8097eae94c3abdfe89bc2c4cd6d0e6
15,379
birday
MIT License
app/src/main/java/com/szymonstasik/kalkulatorsredniejwazonej/calcuatorresult/ResultViewModel.kt
DeNatur
316,006,417
false
null
package com.szymonstasik.kalkulatorsredniejwazonej.calcuatorresult import android.app.Application import android.widget.ImageView import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.szymonstasik.kalkulatorsredniejwazonej.core.BaseViewModel import com.szymonstasik.kalkulatorsredniejwazonej.database.* import com.szymonstasik.kalkulatorsredniejwazonej.utils.CalculatorState import com.szymonstasik.kalkulatorsredniejwazonej.utils.Utils import kotlinx.coroutines.* import org.koin.core.component.inject data class ChosenCircle( var circleImageView: ImageView, var colorId: Int ) class ResultViewModel(context: Application): BaseViewModel(context) { private val calculatorState: CalculatorState by inject() private val dataSource: WeightedAverageDatabase by inject() private val weightedAverageDatabase: WeightedAverageDao = dataSource.weightedAverageDao private val averageTagsDatabase: AverageTagsDao = dataSource.averageTagsDao /** * viewModelJob allows us to cancel all coroutines started by this ViewModel. */ private var viewModelJob = Job() /** * Called when the ViewModel is dismantled. * At this point, we want to cancel all coroutines; * otherwise we end up with processes that have nowhere to return to * using memory and resources. */ override fun onCleared() { super.onCleared() viewModelJob.cancel() } private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob) private val _chosenCircle = MutableLiveData<ChosenCircle>() val chosenCircle: LiveData<ChosenCircle> get() { return _chosenCircle } fun setChosenCircle(id: ImageView, colorId: Int){ val circle = ChosenCircle(circleImageView = id, colorId = colorId) _chosenCircle.value = circle } private val _chosenTags = MutableLiveData<List<AverageTag>>() val chosenTags: LiveData<List<AverageTag>> get() { return _chosenTags } private val _allAverageTags = MutableLiveData<List<TagChooser>>() val allAverageTags: LiveData<List<TagChooser>> get() { return _allAverageTags } private val _weightedAverage = MutableLiveData<WeightedAverage>() val weightedAverage: LiveData<WeightedAverage> get() { return _weightedAverage } private val _result = MutableLiveData<Float>() private val _navigateToHistory = MutableLiveData<Boolean>() val navigateToHistory: LiveData<Boolean> get() { return _navigateToHistory } private val _backPressState = MutableLiveData<Boolean>() val backPressState: LiveData<Boolean> get(){ return _backPressState } fun onPressSave(name: String){ uiScope.launch { val avgToAdd = _weightedAverage.value if (avgToAdd != null) { avgToAdd.name = name val tmpArray = ArrayList<AverageTag>() for (avg in _allAverageTags.value!!){ if(avg.chosen){ tmpArray.add(avg.averageTag) } } avgToAdd.tags = tmpArray if(avgToAdd.id != 0L){ update(avgToAdd) }else{ insert(avgToAdd) } } } _navigateToHistory.value = true } fun onPressNotSave(){ _navigateToHistory.value = true } fun donePopBack(){ _backPressState.value = false } fun onBackPressed(){ _backPressState.value = true } fun onDoneNavigatingToHistory(){ _navigateToHistory.value = false } val result: LiveData<Float> get() { return _result } init { _weightedAverage.value = calculatorState.currentWeightedAverage _chosenTags.value = ArrayList() uiScope.launch { val tags = getAllAverageTags() val tagsChooser = ArrayList<TagChooser>() for (tag in tags){ if(calculatorState.currentWeightedAverage.tags.contains(tag)) tagsChooser.add(TagChooser(tag, true)) else tagsChooser.add(TagChooser(tag, false)) } _allAverageTags.value = tagsChooser instantinateResult() } } fun addTag(name: String){ uiScope.launch { val averageTag = AverageTag(color = _chosenCircle.value!!.colorId, name = name) averageTag.id = insertAverageTag(averageTag) val tag = TagChooser(averageTag = averageTag, chosen = true) val listOfTags: ArrayList<TagChooser> = _allAverageTags.value as ArrayList<TagChooser> listOfTags.add(tag) _allAverageTags.value = listOfTags } } fun changeTagToChosen(tag:TagChooser){ val listOfTags: ArrayList<TagChooser> = _allAverageTags.value as ArrayList<TagChooser> val index = listOfTags.indexOf(tag) listOfTags.remove(tag) tag.chosen = !tag.chosen listOfTags.add(index, tag) _allAverageTags.value = listOfTags val tmpArrayList: ArrayList<AverageTag> = _chosenTags.value as ArrayList<AverageTag> if(tag.chosen){ tmpArrayList.add(tag.averageTag) }else{ tmpArrayList.remove(tag.averageTag) } _chosenTags.value = tmpArrayList } private fun instantinateResult() { val resultNoteList = _weightedAverage.value?.notes var allWeights = 0f; var allValues = 0f; if (resultNoteList != null) { for (notesNWeight in resultNoteList){ var weight: Float = notesNWeight.weight + 1f allWeights += weight var note: Float = Utils.getNoteFromId(notesNWeight.note) allValues += note * weight } _result.value = allValues / allWeights } } private suspend fun getAllAverageTags(): List<AverageTag> { return withContext(Dispatchers.IO){ averageTagsDatabase.getAllTags() } } private suspend fun getWeightedAverage(key: Long) : WeightedAverage? { return withContext(Dispatchers.IO) { weightedAverageDatabase.get(key) } } private suspend fun update(weightedAverage: WeightedAverage) { withContext(Dispatchers.IO) { weightedAverageDatabase.update(weightedAverage) } } private suspend fun insert(weightedAverage: WeightedAverage): Long { return withContext(Dispatchers.IO) { weightedAverageDatabase.insert(weightedAverage) } } private suspend fun insertAverageTag(averageTag: AverageTag): Long { return withContext(Dispatchers.IO) { averageTagsDatabase.insert(averageTag) } } }
0
Kotlin
0
0
d5989b8d8fb8fb4c24c2bc3d5828096a634375f7
7,018
Weighted-Average-Calculator
Apache License 2.0
jps/jps-plugin/testData/incremental/pureKotlin/sealedClassesAddIndirectInheritor/C.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
package test open class C : Any()
251
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
35
kotlin
Apache License 2.0
app/src/main/java/com/jintin/intention/app/MainActivity.kt
Jintin
323,768,494
false
null
package com.jintin.intention.app import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.jintin.intention.Extra import com.jintin.intention.Intention import com.jintin.intention.app.data.TestParcelable import com.jintin.intention.app.data.TestSerializable import com.jintin.intention.app.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) println("string extra = " + intent.getStringExtra(EXTRA_STRING)) println("serializable extra = " + intent.getSerializableExtra(EXTRA_SERIALIZABLE)) println("parcelable extra = " + intent.getParcelableExtra(EXTRA_PARCELABLE)) println("int extra = " + intent.getIntExtra(EXTRA_INT, 0)) binding.button.setOnClickListener { val intent = MainActivityRouterUtil.getIntent( this, TestParcelable("test1"), TestSerializable("test2"), 456 ) println(intent) startActivity(intent) MainActivityRouterUtil.getIntent(this, "value", null) } } @Intention(MainActivity::class) interface MainActivityRouter { fun getIntent( context: Context, @Extra("MyKey") value: String?, @Extra("MyKey2") value2: Int = 345 ): Intent fun getIntent( context: Context, @Extra(EXTRA_PARCELABLE) parcelable: TestParcelable, @Extra(EXTRA_SERIALIZABLE) serializable: TestSerializable, @Extra(EXTRA_INT) intValue: Int? = null, @Extra(EXTRA_STRING) stringValue: String = "default value", @Extra(EXTRA_BYTE) byteValue: Byte? = null, @Extra(EXTRA_CHAR) charValue: Char? = null, @Extra(EXTRA_SHORT) shortValue: Short? = null, @Extra(EXTRA_LONG) longValue: Long? = null, @Extra(EXTRA_DOUBLE) doubleValue: Double? = null, @Extra(EXTRA_FLOAT) floatValue: Float? = null, @Extra(EXTRA_BOOL) boolValue: Boolean? = null, ): Intent } companion object { const val EXTRA_PARCELABLE = "extra_parcelable" const val EXTRA_SERIALIZABLE = "extra_serializable" const val EXTRA_STRING = "extra_string" const val EXTRA_INT = "extra_int" const val EXTRA_BYTE = "extra_byte" const val EXTRA_CHAR = "extra_char" const val EXTRA_SHORT = "extra_short" const val EXTRA_LONG = "extra_long" const val EXTRA_DOUBLE = "extra_double" const val EXTRA_FLOAT = "extra_float" const val EXTRA_BOOL = "extra_bool" } }
0
Kotlin
0
1
a460379d55a44c773b5506072e58a49fe6d0640c
2,898
Intention
Apache License 2.0
domain/src/main/java/com/anytypeio/anytype/domain/dashboard/interactor/OpenDashboard.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.domain.dashboard.interactor import com.anytypeio.anytype.core_models.Payload import com.anytypeio.anytype.domain.auth.repo.AuthRepository import com.anytypeio.anytype.domain.base.AppCoroutineDispatchers import com.anytypeio.anytype.domain.base.ResultInteractor import com.anytypeio.anytype.domain.block.repo.BlockRepository import com.anytypeio.anytype.domain.config.ConfigStorage import kotlinx.coroutines.Dispatchers /** * Use-case for opening a dashboard by sending a special request. * * @property repo */ class OpenDashboard( private val repo: BlockRepository, private val auth: AuthRepository, private val provider: ConfigStorage, dispatchers: AppCoroutineDispatchers ) : ResultInteractor<Unit, Payload>(dispatchers.io) { override suspend fun doWork(params: Unit): Payload { val config = provider.get() val payload = repo.openDashboard( contextId = config.home, id = config.home ) return payload.also { auth.clearLastOpenedObject() } } }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
1,060
anytype-kotlin
RSA Message-Digest License
app/src/main/kotlin/id/shaderboi/cata/ui/theme/Theme.kt
andraantariksa
469,414,092
false
{"Kotlin": 153735}
package id.shaderboi.cata.ui.theme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color import id.shaderboi.cata.feature_todo.ui.common.util.LocalTheme @Composable fun CataAppTheme(theme: Theme, content: @Composable () -> Unit) { val colors = when (theme) { Theme.Dark -> darkColors( primary = Color(0xFF263238), secondary = Color.White, onPrimary = Color.White, ) Theme.Light -> lightColors( primary = Color(0xFF26A69A) ) } CompositionLocalProvider(LocalTheme provides theme) { MaterialTheme( colors = colors, content = content ) } } enum class Theme { Light, Dark; override fun toString(): String { return when (this) { Dark -> "Dark" Light -> "Light" } } }
0
Kotlin
0
0
ff0bee262ea0ce86596a73c8ccaf8b898698806f
1,081
cata
MIT License
data/repository/src/main/java/com/challenge/get/repository/di/NoteRepositoryModule.kt
merRen22
698,474,302
false
{"Kotlin": 86715}
package com.challenge.get.repository.di import com.challenge.get.database.NoteDb import com.challenge.get.repository.NoteRemoteRepository import com.challenge.get.repository.NoteRepository import com.challenge.get.repository.external.NoteRemoteDataSource import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class NoteRepositoryModule { @Singleton @Provides fun providesNoteRepository( noteDataSource: NoteRemoteDataSource, noteDb: NoteDb ): NoteRemoteRepository { return NoteRepository(noteDataSource, noteDb) } }
0
Kotlin
0
0
537dc01fb9afddff18d38d6e70506756573fead2
706
Secure-Note
MIT License
app/src/main/java/com/appbusters/robinkamboj/senseitall/ui/dashboard_activity/discover_fragment/DiscoverFragment.kt
robillo
81,729,170
false
{"Java": 721866, "Kotlin": 168268}
package com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.discover_fragment import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.view.ViewPager import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.appbusters.robinkamboj.senseitall.R import com.appbusters.robinkamboj.senseitall.utils.AppConstants import com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.discover_fragment.adapter.popular_tests.PopTestsAdapter import com.appbusters.robinkamboj.senseitall.utils.StartSnapHelper import com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.discover_fragment.temp.CardPagerAdapter import kotlinx.android.synthetic.main.fragment_discover.view.* import com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.discover_fragment.temp.CardFragmentPagerAdapter import com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.discover_fragment.temp.ShadowTransformer import android.widget.CompoundButton import com.appbusters.robinkamboj.senseitall.model.recycler.Category import com.appbusters.robinkamboj.senseitall.model.recycler.ToolsItem import com.appbusters.robinkamboj.senseitall.utils.AppConstants.* import com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.discover_fragment.temp.CustPagerTransformer import com.appbusters.robinkamboj.senseitall.ui.dashboard_activity.tools_fragment.adapter.image_tools.ImageToolsAdapter /** * A simple [Fragment] subclass. */ class DiscoverFragment : Fragment(), DiscoverInterface, CompoundButton.OnCheckedChangeListener, ViewPager.OnPageChangeListener { lateinit var mCardAdapter: CardPagerAdapter lateinit var popToolsAdapter: ImageToolsAdapter lateinit var mCardShadowTransformer: ShadowTransformer lateinit var mFragmentCardAdapter: CardFragmentPagerAdapter lateinit var mFragmentCardShadowTransformer: ShadowTransformer var categoriesList: MutableList<Category> = ArrayList() var pop_tools_list: MutableList<ToolsItem> = ArrayList() var pop_tests_list: MutableList<Category> = ArrayList() lateinit var lv: View override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the parentView for this fragment val v = inflater.inflate(R.layout.fragment_discover, container, false) setup(v) return v } override fun setup(v: View) { lv = v initialize() setToolsAdapter() setCategoriesAdapter() setViewPagerNewlyAdded() } override fun initialize() { categoriesList.add(Category( R.drawable.baseline_mobile_friendly_black_48, SENSOR, "".plus(sensorNames.size).plus(" ITEMS")) ) categoriesList.add(Category( R.drawable.baseline_battery_charging_full_black_48, FEATURE, "".plus(featureNames.size).plus(" ITEMS")) ) categoriesList.add(Category( R.drawable.baseline_system_update_black_48, SOFTWARE, "0" + trendingNames.size + " ITEMS") ) categoriesList.add(Category( R.drawable.baseline_info_black_48, INFORMATION, "0" + deviceDetailsNames.size + " ITEMS") ) categoriesList.add(Category( R.drawable.baseline_android_black_48, ANDROID, "0" + androidVersionNames.size + " ITEMS") ) } override fun setToolsAdapter() { val list : List<String> = AppConstants.popTools list.forEach { pop_tools_list.add(ToolsItem(it, AppConstants.toolImageUrlMap.get(it))) } popToolsAdapter = ImageToolsAdapter(pop_tools_list, activity, 1) lv.tools_rv.layoutManager = LinearLayoutManager( activity, LinearLayoutManager.HORIZONTAL, false ) lv.tools_rv.adapter = popToolsAdapter lv.tools_rv.onFlingListener = null StartSnapHelper().attachToRecyclerView(lv.tools_rv) } override fun setCategoriesAdapter() { val list : List<String> = AppConstants.popTests list.forEach { var type = 1 when(it) { SENSOR_PROXIMITY, SENSOR_ACCELEROMETER -> type = 1 MULTI_TOUCH, SCREEN, SOUND, FINGERPRINT, BATTERY, COMPASS -> type = 2 LABEL_GENERATOR, VIRTUAL_REALITY -> type = 4 } pop_tests_list.add(Category(AppConstants.toolImageUrlMap.get(it)!!, it, "", type)) } val adapter = PopTestsAdapter(pop_tests_list, activity) lv.categories_rv.layoutManager = LinearLayoutManager( activity, LinearLayoutManager.HORIZONTAL, false ) lv.categories_rv.adapter = adapter lv.categories_rv.onFlingListener = null StartSnapHelper().attachToRecyclerView(lv.categories_rv) } override fun setViewPagerNewlyAdded() { mCardAdapter = CardPagerAdapter() mCardAdapter.addCardItems(categoriesList) mFragmentCardAdapter = CardFragmentPagerAdapter(activity!!.supportFragmentManager, dpToPixels(2, activity!!.baseContext)) mCardShadowTransformer = ShadowTransformer(lv.viewPager, mCardAdapter) mFragmentCardShadowTransformer = ShadowTransformer(lv.viewPager, mFragmentCardAdapter) lv.viewPager.setAdapter(mCardAdapter) lv.viewPager.setPageTransformer(false, CustPagerTransformer(activity)) lv.viewPager.setOffscreenPageLimit(3) lv.page_indicator.count = lv.viewPager.childCount } override fun onCheckedChanged(compoundButton: CompoundButton, b: Boolean) { mCardShadowTransformer.enableScaling(b) mFragmentCardShadowTransformer.enableScaling(b) } fun dpToPixels(dp: Int, context: Context): Float { return dp * context.getResources().getDisplayMetrics().density } override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { lv.page_indicator.selection = position } }
0
Java
1
3
c2cdf7626b860b4b3f68927102aaa0231906d395
6,481
Sensor-Test-App
Apache License 2.0
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/variant/VariantModel.kt
jomof
374,736,765
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.variant import com.android.build.api.component.impl.TestComponentImpl import com.android.build.api.variant.impl.VariantImpl import com.android.build.gradle.internal.dsl.BuildType import com.android.build.gradle.internal.dsl.DefaultConfig import com.android.build.gradle.internal.dsl.ProductFlavor import com.android.build.gradle.internal.dsl.SigningConfig /** * Model for the variants and their inputs. * * Can also compute the default variant to be used during sync. */ interface VariantModel { val inputs: VariantInputModel<DefaultConfig, BuildType, ProductFlavor, SigningConfig> /** * the main variants. This is the output of the plugin (apk, aar, etc...) and does not * include the test components (android test, unit test) */ val variants: List<VariantImpl> /** * the test components (android test, unit test) */ val testComponents: List<TestComponentImpl> val defaultVariant: String? }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
1,614
CppBuildCacheWorkInProgress
Apache License 2.0
exposedx-dao/src/main/kotlin/io/creavity/exposedx/dao/tables/extensions.kt
creavity-io
254,755,628
false
null
package io.creavity.exposedx.dao.tables import io.creavity.exposedx.dao.entities.Entity import io.creavity.exposedx.dao.exceptions.EntityNotFoundException import io.creavity.exposedx.dao.queryset.localTransaction /** * Create a new entity with the fields that are set in the [init] block. The id will be automatically set. * * @param init The block where the entities' fields can be set. * * @return The entity that has been created. */ fun <ID : Comparable<ID>, E : Entity<ID>> EntityTable<ID, E, *>.new(init: E.() -> Unit) = localTransaction { createInstance().apply { this.init() this.save() } } /** * Reloads entity fields from database as new object. * @param flush whether pending entity changes should be flushed previously */ fun <ID : Comparable<ID>, E : Entity<ID>> EntityTable<ID, E, *>.reload(entity: E, reset: Boolean=false, flush: Boolean = false): E = entity.also { localTransaction { if (flush) { _cache.flush() } if(reset) entity.reset() _cache[this@reload].store(entity.id, entity) entity.init(this.db, entity.id, findResultRowById(entity.id) ?: throw EntityNotFoundException(entity.id, this@reload)) } }
0
Kotlin
0
0
97075942fab9719e1f8bcac450f34ce6316e77c5
1,221
exposedx
Apache License 2.0
shared/src/commonMain/kotlin/com/darrenthiores/ecoswap/domain/carbon/repository/CarbonRepository.kt
darrenthiores
688,372,873
false
{"Kotlin": 770054, "Swift": 362583}
package com.darrenthiores.ecoswap.domain.carbon.repository import com.darrenthiores.ecoswap.domain.carbon.model.Challenge import com.darrenthiores.ecoswap.domain.carbon.model.FootPrint import com.darrenthiores.ecoswap.domain.utils.Resource interface CarbonRepository { suspend fun getFootPrint( fetch: Boolean = false, viewId: String ): Resource<FootPrint> suspend fun insertCarbonReduction( categoryId: String, taskId: String, taskTitle: String, total: Double ): Resource<Unit> suspend fun getChallenges( isJoined: Boolean, page: Int ): Resource<List<Challenge>> suspend fun getChallengeById( challengeId: String ): Resource<Challenge> suspend fun joinChallenge( challengeId: String ): Resource<Unit> }
0
Kotlin
0
0
792b3293b4e378b7482f948ce4de622cb88f3cf1
829
EcoSwap
MIT License
src/jsMain/kotlin/io/dcctech/mafita/frontend/browser/components/HeaderActions.kt
timoterik
587,234,059
false
null
/* * Copyright © 2022-2023, DCCTech, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.dcctech.mafita.frontend.browser.components import io.dcctech.mafita.frontend.browser.resources.AppDarkTheme import io.dcctech.mafita.frontend.browser.resources.AppLightTheme import zakadabar.core.browser.ZkElement import zakadabar.core.browser.theme.ZkThemeRotate import zakadabar.core.resource.ZkIcons class HeaderActions : ZkElement() { override fun onCreate() { + ZkThemeRotate( ZkIcons.darkMode to AppDarkTheme(), ZkIcons.lightMode to AppLightTheme() ) } }
0
Kotlin
0
0
417bd88d2c1e7faef875df61e082f83445cab3a7
655
mafita
Apache License 2.0
shared/src/commonMain/kotlin/com/ipirangad3v/calculator/core.presentation/CalculatorViewModel.kt
ipirangad3v
679,949,004
false
{"Kotlin": 21658, "Swift": 825}
package com.ipirangad3v.calculator.core.presentation import com.ipirangad3v.calculator.util.calculate import dev.icerock.moko.mvvm.viewmodel.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class CalculatorViewModel : ViewModel() { private val _state = MutableStateFlow(CalculatorState()) val state: StateFlow<CalculatorState> = _state fun onEvent(event: CalculatorEvent) { when (event) { is CalculatorEvent.OnKeyPressed -> { when (event.key) { "+", "-", "/", "*" -> { _state.update { it.copy( previousValue = it.displayValue, operation = event.key, displayValue = "0" ) } } "AC" -> { _state.update { CalculatorState() } } "DEL" -> { _state.update { it.copy( displayValue = if (it.displayValue != "0") it.displayValue.dropLast( 1 ) else "0" ) } } "=" -> { _state.update { it.calculate() } } else -> { _state.update { it.copy(displayValue = if (it.displayValue == "0") event.key else it.displayValue + event.key) } } } } } } }
0
Kotlin
0
2
a18d27756bae61c88e0fb49f43524928257cad8d
1,877
kmp-calculator
MIT License
app/app/src/main/java/com/example/trainstationapp/data/grpc/auth/v1alpha1/AuthProtoKt.kt
Darkness4
310,007,491
false
{"Kotlin": 158741, "Java": 49450, "TypeScript": 36085, "Go": 35363, "Svelte": 8685, "Makefile": 4293, "Dockerfile": 2038, "JavaScript": 1233, "Mermaid": 981, "Shell": 831, "HTML": 329, "SCSS": 188}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: auth/v1alpha1/auth.proto // Generated files should ignore deprecation warnings @file:Suppress("DEPRECATION") package com.example.trainstationapp.data.grpc.auth.v1alpha1;
2
Kotlin
1
7
963810c02c3b81a6e5227347eae0debec26986b2
242
train-station
MIT License
ethers-abi/src/main/kotlin/io/ethers/abi/Utf8.kt
Kr1ptal
712,963,462
false
{"Kotlin": 972898, "Solidity": 28233}
/* * SOURCE: https://github.com/google/guava/blob/master/guava/src/com/google/common/base/Utf8.java * * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.ethers.abi /** * Low-level, high-performance utility methods related to the [UTF-8][Charsets.UTF_8] * character encoding. UTF-8 is defined in section D92 of [The Unicode Standard Core * Specification, Chapter 3](http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf). * * * The variant of UTF-8 implemented by this class is the restricted definition of UTF-8 * introduced in Unicode 3.1. One implication of this is that it rejects ["non-shortest form"](http://www.unicode.org/versions/corrigendum1.html) byte sequences, * even though the JDK decoder may accept them. * * @author <NAME> * @author <NAME> * @since 16.0 */ internal object Utf8 { /** * Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string, this * method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in both * time and space. * * @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired * surrogates) */ fun encodedLength(sequence: CharSequence): Int { // Warning to maintainers: this implementation is highly optimized. val utf16Length = sequence.length var utf8Length = utf16Length var i = 0 // This loop optimizes for pure ASCII. while (i < utf16Length && sequence[i].code < 0x80) { i++ } // This loop optimizes for chars less than 0x800. while (i < utf16Length) { val c = sequence[i] if (c.code < 0x800) { utf8Length += 0x7f - c.code ushr 31 // branch free! } else { utf8Length += encodedLengthGeneral(sequence, i) break } i++ } require(utf8Length >= utf16Length) { // Necessary and sufficient condition for overflow because of maximum 3x expansion "UTF-8 length does not fit in int: " + (utf8Length + (1L shl 32)) } return utf8Length } private fun encodedLengthGeneral(sequence: CharSequence, start: Int): Int { val utf16Length = sequence.length var utf8Length = 0 var i = start while (i < utf16Length) { val c = sequence[i] if (c.code < 0x800) { utf8Length += 0x7f - c.code ushr 31 // branch free! } else { utf8Length += 2 // jdk7+: if (Character.isSurrogate(c)) { if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) { // Check that we have a well-formed surrogate pair. require(Character.codePointAt(sequence, i) != c.code) { unpairedSurrogateMsg(i) } i++ } } i++ } return utf8Length } private fun unpairedSurrogateMsg(i: Int): String { return "Unpaired surrogate at index $i" } }
10
Kotlin
1
8
4a0477c9ffca05df7f812296c8cb6020bf9cb7d9
3,655
ethers-kt
Apache License 2.0
settings.gradle.kts
aliakbarmostafaei
694,889,781
false
{"Kotlin": 15970}
rootProject.name = "jetbrains-space-theme"
0
Kotlin
0
1
c0dfc8797b496c3577241711fa1ee85a9541be55
43
jetbrains-space-theme
MIT License
app/app/src/main/java/dev/mikita/bettercity/main/view/AddNewIssueLocationFragment.kt
mikicit
644,015,065
false
null
package dev.mikita.bettercity.main.view import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import dagger.hilt.android.AndroidEntryPoint import dev.mikita.bettercity.R import dev.mikita.bettercity.databinding.FragmentAddNewIssueLocationBinding import dev.mikita.bettercity.main.viewmodel.AddNewIssueViewModel @AndroidEntryPoint class AddNewIssueLocationFragment : Fragment(), OnMapReadyCallback { // View Binding private var _binding: FragmentAddNewIssueLocationBinding? = null private val binding get() = _binding!! // ViewModel private val viewModel: AddNewIssueViewModel by activityViewModels() // Utils private lateinit var mMap: GoogleMap private lateinit var requestPermissionLauncher: ActivityResultLauncher<String> // State private var markerCoordinate: LatLng? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentAddNewIssueLocationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRequestPermissionLauncher() val mapFragment = childFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment mapFragment.getMapAsync(this) viewModel.isValidScreen.value = true } override fun onDestroyView() { super.onDestroyView() _binding = null markerCoordinate?.let { coordinate -> viewModel.updateCoordinate(coordinate) } } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { setUpMap(true) } else { requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION) return } } private fun setUpMap(isGranted: Boolean) { try { // Enable MyLocation Layer of Google Map if (isGranted) { mMap.isMyLocationEnabled = true } // Get last known location if (viewModel.getCoordinates() != null) { markerCoordinate = viewModel.getCoordinates() mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerCoordinate!!, 17f)) setUpMarker() } else { if (isGranted) { val fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity()) fusedLocationClient.lastLocation .addOnCompleteListener { task -> if (task.isSuccessful) { val location = task.result if (location != null && markerCoordinate == null) { markerCoordinate = LatLng(location.latitude, location.longitude) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerCoordinate!!, 17f)) setUpMarker() } else { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(50.0755, 14.4378), 17f)) setUpMarker() } } else { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(50.0755, 14.4378), 17f)) setUpMarker() } } } else { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(50.0755, 14.4378), 17f)) setUpMarker() } } } catch (e: SecurityException) { e.printStackTrace() } } private fun setUpMarker() { if (markerCoordinate == null) { markerCoordinate = mMap.cameraPosition.target } mMap.setOnCameraMoveListener { markerCoordinate = mMap.cameraPosition.target } } private fun setupRequestPermissionLauncher() { requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> setUpMap(isGranted) } } }
0
Kotlin
0
0
5d878a12d08d72917267bfe46f3980daa3e37493
5,256
better-city-android-app
MIT License
appinfobadge/src/main/java/com/dci/dev/appinfobadge/permissions/PermissionViewHolder.kt
ditacristianionut
249,074,694
false
null
package com.dci.dev.appinfobadge.permissions import android.view.View import android.widget.ImageView import android.widget.TextView import com.afollestad.recyclical.ViewHolder import com.dci.dev.appinfobadge.R internal class PermissionViewHolder (itemView: View) : ViewHolder(itemView) { val name: TextView = itemView.findViewById(R.id.tvPermissionName) val description: TextView = itemView.findViewById(R.id.tvPermissionDetails) val settings: TextView = itemView.findViewById(R.id.tvGoToSettings) val settingsIv: ImageView = itemView.findViewById(R.id.ivGoToSettings) }
1
Kotlin
1
19
43f6c3426d51515d5b9c15734aec16eef26197a5
590
AppInfoBadge
Apache License 2.0
wasm/wasm.ir/src/org/jetbrains/kotlin/wasm/ir/source/location/Box.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.wasm.ir.source.location class Box(var value: Int)
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
289
kotlin
Apache License 2.0
domain/src/main/java/com/anytypeio/anytype/domain/config/Gateway.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.domain.config interface Gateway { fun provide(): String }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
92
anytype-kotlin
RSA Message-Digest License
app/src/main/java/com/nisaefendioglu/movieapp/api/ApiService.kt
nisaefendioglu
497,106,407
false
{"Kotlin": 8673}
package com.nisaefendioglu.movieapp.api import com.nisaefendioglu.movieapp.model.MovieResponse import com.nisaefendioglu.movieapp.helper.Constants import retrofit2.Response import retrofit2.http.GET interface ApiService { @GET(Constants.END_POINT) suspend fun getMovie(): Response<MovieResponse> }
0
Kotlin
0
2
0f58621e409641c8a32303d6746fdf0f233b55f8
309
Movie
MIT License
app/src/main/java/project/robby/assetmanagement/ui/screen/AssetManagementScreen.kt
RobbyAkbar
695,776,006
false
{"Kotlin": 48172}
package project.robby.assetmanagement.ui.screen import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.lifecycle.viewmodel.compose.viewModel import androidx.compose.ui.Modifier import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.rememberNavController import project.robby.assetmanagement.ui.screen.login.navigateToSignIn import project.robby.assetmanagement.ui.screen.login.signInScreen import project.robby.assetmanagement.navigation.popUpToInclusive import project.robby.assetmanagement.ui.screen.dashboard.DashboardDestination import project.robby.assetmanagement.ui.screen.dashboard.dashboardScreen import project.robby.assetmanagement.ui.screen.dashboard.navigateToDashboard import project.robby.assetmanagement.viewmodel.AuthViewModel @Composable fun AssetManagementScreen( modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), viewModel: AuthViewModel = viewModel() ) { val authenticationState by viewModel.isAlreadyLogged.collectAsStateWithLifecycle() LaunchedEffect(authenticationState) { authenticationState?.let { isLoggedIn -> if (isLoggedIn) { navController.navigateToDashboard { popUpToInclusive(navController.graph.id) } } else { navController.navigateToSignIn { popUpToInclusive(navController.graph.id) } } } } NavHost( modifier = modifier, navController = navController, startDestination = DashboardDestination.routeName ) { signInScreen() dashboardScreen() } }
0
Kotlin
0
0
ee5813b632ce95dddd5553d7199445afc0ac9e1c
1,876
AssetManagement
MIT License
ktor-features/ktor-locations/src/org/jetbrains/ktor/locations/Locations.kt
cy6erGn0m
40,906,748
true
{"Kotlin": 635453}
package org.jetbrains.ktor.locations import org.jetbrains.ktor.application.* import org.jetbrains.ktor.features.* import org.jetbrains.ktor.http.* import org.jetbrains.ktor.routing.* import org.jetbrains.ktor.util.* import kotlin.reflect.* import kotlin.reflect.jvm.* class InconsistentRoutingException(message: String) : Exception(message) open public class Locations(val conversionService: ConversionService) { private val rootUri = ResolvedUriInfo("", emptyList()) private val info = hashMapOf<KClass<*>, LocationInfo>() private class LocationInfoProperty(val name: String, val getter: KProperty1.Getter<*, *>, val isOptional: Boolean) private data class ResolvedUriInfo(val path: String, val query: List<Pair<String, String>>) private data class LocationInfo(val klass: KClass<*>, val parent: LocationInfo?, val parentParameter: LocationInfoProperty?, val path: String, val pathParameters: List<LocationInfoProperty>, val queryParameters: List<LocationInfoProperty>) private fun LocationInfo.create(request: RoutingApplicationCall): Any { val constructor: KFunction<Any> = klass.primaryConstructor ?: klass.constructors.single() val parameters = constructor.parameters val arguments = parameters.map { parameter -> val parameterType = parameter.type val parameterName = parameter.name ?: getParameterNameFromAnnotation(parameter) val value: Any? = if (parent != null && parameterType == parent.klass.defaultType) { parent.create(request) } else { conversionService.fromContext(request, parameterName, parameterType.javaType, parameter.isOptional) } parameter to value }.filterNot { it.first.isOptional && it.second == null }.toMap() return constructor.callBy(arguments) } @Suppress("UNUSED_PARAMETER") private fun getParameterNameFromAnnotation(parameter: KParameter): String = TODO() private fun ResolvedUriInfo.combine(relativePath: String, queryValues: List<Pair<String, String>>): ResolvedUriInfo { val pathElements = (path.split("/") + relativePath.split("/")).filterNot { it.isEmpty() } val combinedPath = pathElements.joinToString("/", "/") return ResolvedUriInfo(combinedPath, query + queryValues) } inline fun <reified T : Annotation> KAnnotatedElement.annotation(): T? { return annotations.singleOrNull { it.annotationClass == T::class } as T? } private fun getOrCreateInfo(dataClass: KClass<*>): LocationInfo { return info.getOrPut(dataClass) { val parentClass = dataClass.java.enclosingClass?.kotlin val parent = parentClass?.annotation<location>()?.let { getOrCreateInfo(parentClass) } val path = dataClass.annotation<location>()?.let { it.path } ?: "" val constructor: KFunction<Any> = dataClass.primaryConstructor ?: dataClass.constructors.single() val declaredProperties = constructor.parameters.map { parameter -> val property = dataClass.declaredMemberProperties.singleOrNull { property -> property.name == parameter.name } if (property == null) { throw InconsistentRoutingException("Parameter ${parameter.name} of constructor for class ${dataClass.qualifiedName} should have corresponding property") } LocationInfoProperty(parameter.name ?: "<unnamed>", (property as KProperty1<out Any?, *>).getter, parameter.isOptional) } val parentParameter = declaredProperties.firstOrNull { it.getter.returnType == parentClass?.defaultType } if (parent != null && parentParameter == null) { if (parent.parentParameter != null) throw InconsistentRoutingException("Nested location '$dataClass' should have parameter for parent location because it is chained to its parent") if (parent.pathParameters.any { !it.isOptional }) throw InconsistentRoutingException("Nested location '$dataClass' should have parameter for parent location because of non-optional path parameters ${parent.pathParameters.filter { !it.isOptional }}") if (parent.queryParameters.any { !it.isOptional }) throw InconsistentRoutingException("Nested location '$dataClass' should have parameter for parent location because of non-optional query parameters ${parent.queryParameters.filter { !it.isOptional }}") } val pathParameterNames = RoutingPath.parse(path).parts.filter { it.kind == RoutingPathSegmentKind.Parameter || it.kind == RoutingPathSegmentKind.TailCard }.map { it.value } val declaredParameterNames = declaredProperties.map { it.name }.toSet() val invalidParameters = pathParameterNames.filter { it !in declaredParameterNames } if (invalidParameters.any()) { throw InconsistentRoutingException("Path parameters '$invalidParameters' are not bound to '$dataClass' properties") } val pathParameters = declaredProperties.filter { it.name in pathParameterNames } val queryParameters = declaredProperties.filterNot { pathParameterNames.contains(it.name) || it == parentParameter } LocationInfo(dataClass, parent, parentParameter, path, pathParameters, queryParameters) } } @Suppress("UNCHECKED_CAST") fun <T : Any> resolve(dataClass: KClass<*>, request: RoutingApplicationCall): T { return getOrCreateInfo(dataClass).create(request) as T } // TODO: optimize allocations private fun pathAndQuery(location: Any): ResolvedUriInfo { val info = getOrCreateInfo(location.javaClass.kotlin) fun propertyValue(instance: Any, name: String): List<String> { // TODO: Cache properties by name in info val property = info.pathParameters.single { it.name == name } val value = property.getter.call(instance) return conversionService.toURI(value, name, property.getter.returnType.isMarkedNullable) } val substituteParts = RoutingPath.parse(info.path).parts.flatMap { it -> when (it.kind) { RoutingPathSegmentKind.Constant -> listOf(it.value) else -> propertyValue(location, it.value) } } val relativePath = substituteParts.filterNotNull().filterNot { it.isEmpty() }.map { encodeURLPart(it) }.joinToString("/") val parentInfo = if (info.parent == null) rootUri else if (info.parentParameter != null) { val enclosingLocation = info.parentParameter.getter.call(location)!! pathAndQuery(enclosingLocation) } else { ResolvedUriInfo(info.parent.path, emptyList()) } val queryValues = info.queryParameters .flatMap { property -> val value = property.getter.call(location) conversionService.toURI(value, property.name, property.isOptional).map { property.name to it } } return parentInfo.combine(relativePath, queryValues) } fun href(location: Any): String { val info = pathAndQuery(location) return info.path + if (info.query.any()) "?" + info.query.formUrlEncode() else "" } internal fun href(location: Any, builder: URLBuilder) { val info = pathAndQuery(location) builder.encodedPath = info.path for ((name, value) in info.query) { builder.parameters.append(name, value) } } private fun createEntry(parent: RoutingEntry, info: LocationInfo): RoutingEntry { val hierarchyEntry = info.parent?.let { createEntry(parent, it) } ?: parent val pathEntry = hierarchyEntry.createRoute(info.path) val queryEntry = info.queryParameters.fold(pathEntry) { entry, query -> val selector = if (query.isOptional) OptionalParameterRoutingSelector(query.name) else ParameterRoutingSelector(query.name) entry.select(selector) } return queryEntry } fun createEntry(parent: RoutingEntry, dataClass: KClass<*>): RoutingEntry { return createEntry(parent, getOrCreateInfo(dataClass)) } companion object LocationsFeature : ApplicationFeature<Locations> { override fun install(application: Application, configure: Locations.() -> Unit): Locations { return Locations(DefaultConversionService()).apply(configure) } override val key: AttributeKey<Locations> = AttributeKey("Locations") override val name: String = "Locations" } }
0
Kotlin
0
0
2d3b4f0b813b05370b22fae4c0d83d99122f604f
9,068
ktor
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/native-binaries/kotlin-dsl/src/commonTest/kotlin/test.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
import kotlin.test.* import com.example.exported @Test fun foo() { val exp = exported() assertTrue(exp % 7 == 0, "Not divisible by 7") println("tests.foo: exp = $exp") }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
183
kotlin
Apache License 2.0
app/src/main/java/com/wasee292/wlinker/legacy/di/AppModule.kt
wasee292
642,531,304
false
null
package com.wasee292.wlinker.legacy.di import android.content.Context import androidx.room.Room import com.wasee292.wlinker.legacy.db.AppDatabase import com.wasee292.wlinker.legacy.db.AppDatabaseConverters import com.wasee292.wlinker.legacy.db.DbConstant import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideAppDatabase( @ApplicationContext appContext: Context, appDatabaseConverters: AppDatabaseConverters, ) = Room.databaseBuilder( appContext, AppDatabase::class.java, DbConstant.dbName, ).addTypeConverter(appDatabaseConverters).build() @Singleton @Provides fun provideLinkDao(appDatabase: AppDatabase) = appDatabase.linkDao() @Singleton @Provides fun provideTagDao(appDatabase: AppDatabase) = appDatabase.tagDao() @Singleton @Provides fun provideAppDatabaseConverter(json: Json): AppDatabaseConverters = AppDatabaseConverters(json) @OptIn(ExperimentalSerializationApi::class) @Singleton @Provides fun provideJson() = Json { encodeDefaults = true; isLenient = true; ignoreUnknownKeys = true; explicitNulls = true; } }
0
Kotlin
0
0
55576f627123f52396fec866d127dc8ad769663e
1,501
wLinker-legacy
Apache License 2.0
app/src/main/java/com/oneswitch/features/login/model/productlistmodel/ProductRateListResponseModel.kt
DebashisINT
479,421,399
false
{"Kotlin": 10353900, "Java": 918198}
package com.oneswitch.features.login.model.productlistmodel import com.oneswitch.base.BaseResponse import java.io.Serializable /** * Created by Saikat on 15-01-2020. */ class ProductRateListResponseModel : BaseResponse(), Serializable { var product_rate_list: ArrayList<ProductRateDataModel>? = null }
0
Kotlin
0
0
e8a10afc0beca231a299cca19185ad2f8187c907
309
OneSwitch
Apache License 2.0
lib-widgets/src/main/java/com/ant/widgets/exercise/StarLayout.kt
Hello-Ant
227,559,703
false
{"Java": 298098, "Kotlin": 240991}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ant.widgets.exercise import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import kotlin.math.cos import kotlin.math.min import kotlin.math.sin /** * <p>------------------------------------------------------ * <p>Copyright (C) 2020 wasu company, All rights reserved. * <p>------------------------------------------------------ * <p> * <p> * * @author Ant * @date on 2020/5/20 13:53. */ class StarLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ViewGroup(context, attrs, defStyleAttr) { /** * 最小行星相对于最大行星的缩放值 */ private val maxScaleOffset = 0.3f private var maxOffsetY = 0 /** * 行星环绕恒星的半径 */ private var radius = 0; /** * 恒星的半径 */ private var fixedStarRadius = 0; /** * 行星的半径 */ private var planetsRadius = 0; /** * 相邻的星球角度偏移 */ private var angleOffset = 0f override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { setMeasuredDimension( getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec) ) val count = childCount angleOffset = 360f / count val halfSize = min( measuredWidth - paddingLeft - paddingRight, measuredHeight - paddingTop - paddingBottom ).shr(1) planetsRadius = halfSize / 9 radius = halfSize - planetsRadius maxOffsetY = sin(Math.toRadians(50.toDouble())).times(radius).toInt() val childMeasureSpec = MeasureSpec.makeMeasureSpec(planetsRadius, MeasureSpec.EXACTLY); for (index in 0 until count) { val child = getChildAt(index) child.measure(childMeasureSpec, childMeasureSpec) } } var startAngle = 0.toDouble() set(value) { field = value // ViewCompat.postInvalidateOnAnimation(this) requestLayout() } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { val count = childCount val cx = measuredWidth / 2 val cy = measuredWidth / 2 for (index in 0 until count) { val child = getChildAt(index) val radians = Math.toRadians(startAngle) val planetCx = cx + radius.times(cos(radians)).toInt() val planetCy = cy + radius.times(sin(radians)).toInt() val offsetY = sin(radians).times(maxOffsetY).toInt() child.layout( planetCx - planetsRadius, planetCy - planetsRadius - offsetY, planetCx + planetsRadius, planetCy + planetsRadius - offsetY ) val scale = 1 + maxScaleOffset.times(sin(radians)).toFloat() child.scaleX = scale child.scaleY = scale startAngle += angleOffset } } }
0
Java
0
0
3057af5717a126511affc2cf528e7c7fba3ba050
3,689
Ant
Apache License 2.0
app/src/main/java/com/flynnchow/zero/magician/search/viewmodel/SearchViewModel.kt
FlynnChow
352,288,862
false
null
package com.flynnchow.zero.magician.search.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.flynnchow.zero.common.viewmodel.BaseViewModel import com.flynnchow.zero.magician.base.provider.MediaProvider import com.flynnchow.zero.magician.search.viewdata.SearchMonthData import com.flynnchow.zero.ml_kit.MLKitHelper import com.flynnchow.zero.model.MediaModel class SearchViewModel : BaseViewModel() { var keyword = "" private val _data = MutableLiveData<List<SearchMonthData>>() val data: LiveData<List<SearchMonthData>> = _data fun onSearch(keyword: String) { this.keyword = keyword initSearchData() } private fun initSearchData() { startLaunch { val images = if (keyword.trim().isNotEmpty()) { MediaProvider.instance.getImageList().filter { MLKitHelper.isHitLabel(it, keyword) } } else { MediaProvider.instance.getImageList() } val monthList = ArrayList<SearchMonthData>() if (images.isNotEmpty()) { var monthValue = images[0].getMonth() var monthYear = images[0].getYear() var dayList = ArrayList<MediaModel>() for (image in images) { if (image.getYear() != monthYear || image.getMonth() != monthValue) { val monthBean = SearchMonthData(dayList) monthList.add(monthBean) monthValue = image.getMonth() monthYear = image.getYear() dayList = ArrayList() dayList.add(image) } dayList.add(image) } if (dayList.isNotEmpty()) { val monthBean = SearchMonthData(dayList) monthList.add(monthBean) } _data.value = monthList }else{ _data.value = ArrayList() } } } }
0
Kotlin
0
0
cde2fd65df6dd486e589cc2e7d81dedeb4a9504f
2,106
Magician
MIT License
commonadapter/src/main/java/com/mmicu/commonadapter/CommonRecyclerViewAdapterImpl.kt
topotopo
236,496,514
false
{"Kotlin": 23473}
package com.mmicu.commonadapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding class CommonRecyclerViewAdapterImpl private constructor( private val listCommonHolder: MutableList<CommonItemHolder<*>> ) { companion object { fun initialize(listCommonHolder: MutableList<CommonItemHolder<*>>): CommonRecyclerViewAdapterImpl { return CommonRecyclerViewAdapterImpl(listCommonHolder) } } private var onItemClickListener: ((pos: Int, data: Any?, view: View) -> Unit)? = null fun setItemClickListener(onItemClickListener: (pos: Int, data: Any?, view: View) -> Unit) { this.onItemClickListener = onItemClickListener } fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder { //TODO: Handle viewtype -1 val layoutInflater = LayoutInflater.from(parent.context) val binding: ViewDataBinding = DataBindingUtil.inflate( layoutInflater, viewType, parent, false ) return CommonViewHolderImpl.initialize(binding) } fun getItemCount(): Int { return listCommonHolder.size } fun onBindViewHolder(holder: CommonViewHolder, position: Int) { holder.bind(listCommonHolder[position]) listCommonHolder[position].onBindViewHolder(holder.itemView) holder.itemView.setOnClickListener { onItemClickListener?.invoke(position, listCommonHolder[position].data, holder.itemView) } } fun getItemViewType(position: Int): Int { return listCommonHolder[position].layoutId } }
0
Kotlin
1
0
4921f464329cdf63860ec86887136e6f987bdf00
1,701
android-common-recyclerview-adapter
Apache License 2.0
app/src/main/java/com/campuscoders/posterminalapp/presentation/sale/views/ProductsFragment.kt
CampusCoders
690,583,133
false
{"Kotlin": 361456, "Java": 47354}
package com.campuscoders.posterminalapp.presentation.sale.views import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.campuscoders.posterminalapp.databinding.FragmentProductsBinding import com.campuscoders.posterminalapp.presentation.SaleActivity import com.campuscoders.posterminalapp.presentation.sale.BaseViewModel import com.campuscoders.posterminalapp.utils.FilterList import com.campuscoders.posterminalapp.utils.Resource import com.campuscoders.posterminalapp.utils.hide import com.campuscoders.posterminalapp.utils.show import com.campuscoders.posterminalapp.utils.toast import kotlinx.coroutines.Job import kotlinx.coroutines.launch class ProductsFragment: Fragment() { private var _binding: FragmentProductsBinding? = null private val binding get() = _binding!! private var isFabMenuOpen: Boolean = false private lateinit var baseViewModel: BaseViewModel private var ftransaction: FragmentTransaction? = null private var saleActivity: SaleActivity? = null private val productsAdapter by lazy { ProductsAdapter() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentProductsBinding.inflate(layoutInflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var job: Job? = null binding.textInputLayoutSearch.hide() binding.textInputEditTextSearch.addTextChangedListener { job?.cancel() job = lifecycleScope.launch { it?.let { if(it.toString().isNotEmpty()) { productsAdapter.products = FilterList.bySearch(baseViewModel.statusProductsList.value?.data?: listOf(),it.toString()) } else { productsAdapter.products = baseViewModel.statusProductsList.value?.data?: listOf() } productsAdapter.notifyDataSetChanged() } } } saleActivity = activity as? SaleActivity saleActivity?.setEnabledShoppingCartIcon(true) setFabMenu() baseViewModel = ViewModelProvider(requireActivity())[BaseViewModel::class.java] ftransaction = requireActivity().supportFragmentManager.beginTransaction() val staggeredGridLayoutManager = StaggeredGridLayoutManager(3,LinearLayoutManager.VERTICAL) binding.recyclerViewProducts.adapter = productsAdapter binding.recyclerViewProducts.layoutManager = staggeredGridLayoutManager val args = arguments args?.let { val categoryId = it.getString("category_id") val topBarTitle = "Kategoriler/${changeTopBarTitle(categoryId.toString())}" saleActivity?.changeSaleActivityTopBarTitle(topBarTitle) baseViewModel.getProductsByCategoryId(categoryId!!) } productsAdapter.setOnItemClickListener { baseViewModel.addProduct(it.toString()) } observer() } private fun observer() { baseViewModel.statusProductsList.observe(viewLifecycleOwner) { when(it) { is Resource.Success -> { binding.progressBarProducts.hide() binding.linearLayoutNoProduct.hide() if (it.data!!.isNotEmpty()) { productsAdapter.products = it.data } else { toast(requireContext(),"No data",false) binding.linearLayoutNoProduct.show() } } is Resource.Loading -> { binding.progressBarProducts.show() } is Resource.Error -> { binding.progressBarProducts.hide() toast(requireContext(),it.message?:"Error Products",false) } } } } private fun changeTopBarTitle(categoryId: String): String { return when(categoryId) { "1" -> "Yiyecek" "2" -> "İçecek" "3" -> "Meyve" "4" -> "Kişisel Bakım" "5" -> "Dondurma" "6" -> "Bebek" "7" -> "Fırın" "8" -> "Sebze" "9" -> "Atıştırmalık" "10" -> "İlaç" "11" -> "Ev Eşya" else -> "null" } } private fun setFabMenu() { binding.extendedFabSettings.hide() binding.floatingActionButtonSearch.hide() binding.floatingActionButtonBarcode.hide() binding.floatingActionButtonMainAdd.setOnClickListener { toggleFabMenu() } binding.extendedFabSettings.setOnClickListener { toggleFabMenu() } binding.floatingActionButtonSearch.setOnClickListener { if (binding.textInputLayoutSearch.isVisible) { productsAdapter.products = baseViewModel.statusProductsList.value?.data?: listOf() binding.textInputLayoutSearch.hide() } else { binding.textInputLayoutSearch.show() } toggleFabMenu() } binding.floatingActionButtonBarcode.setOnClickListener { saleActivity?.goToBarcodeActivity() } } private fun toggleFabMenu() { if (isFabMenuOpen) { binding.extendedFabSettings.hide() binding.floatingActionButtonSearch.hide() binding.floatingActionButtonBarcode.hide() binding.floatingActionButtonMainAdd.show() } else { binding.floatingActionButtonMainAdd.hide() binding.extendedFabSettings.show() binding.floatingActionButtonSearch.show() binding.floatingActionButtonBarcode.show() } isFabMenuOpen = !isFabMenuOpen } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
3
0b56df5b62789e3034619d693fcd77d1ee241cf7
6,547
PosTerminalApp
MIT License
runtime/src/main/java/io/github/sgpublic/exsp/annotations/ExSharedPreference.kt
sgpublic
540,745,396
false
{"Kotlin": 36947, "Java": 988}
package io.github.sgpublic.exsp.annotations @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.CLASS) annotation class ExSharedPreference( val name: String, val mode: Int = 0x0000 )
0
Kotlin
0
0
ca52007b68e4e480cfbd9bab465b5644e7021bc2
204
XXPreference
Apache License 2.0
app/src/main/java/toan/ruler/widget/RulerView.kt
toanvc
59,611,206
false
null
package toan.ruler.widget import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.support.v4.content.ContextCompat import android.text.TextPaint import android.util.AttributeSet import android.view.MotionEvent import android.view.View import toan.ruler.R import toan.ruler.utils.RulerUtils /** * Created by <NAME> on 4/1/16. */ class RulerView(context: Context, attrs: AttributeSet) : View(context, attrs) { companion object { const val BORDER_LIMIT = 20f const val TEXT_MARGIN = 20f const val ARROW_SCALE_X = 0.3f const val ARROW_SCALE_Y = 0.5f } //2 objects private var touch1 = Coordinate() private var touch2 = Coordinate() private var rulerType = RulerType.INCH //this value controls touchable size for 2 lines private var delta = resources.getDimension(R.dimen.touch_size).toInt() private var result: Float = 0f private var pixelPerMillimeter: Float = 0f private var pixelPerInch: Float = 0f //ruler will use it for start pixel value on screen private var startPoint = 20f private val scaleLineLevel1 = resources.getDimension(R.dimen.scale_line_1) private val scaleLineLevel2 = resources.getDimension(R.dimen.scale_line_2) private val scaleLineLevel3 = resources.getDimension(R.dimen.scale_line_3) private val scaleLineLevel4 = resources.getDimension(R.dimen.scale_line_4) private val scaleLineLevel5 = resources.getDimension(R.dimen.scale_line_5) private val arrowSize = resources.getDimension(R.dimen.arrow_size) private val arrowLeftMargin = resources.getDimension(R.dimen.scale_line_5) private val minimumArrowLength = resources.getDimension(R.dimen.minimum_arrow_length) private val pathArrowUp = Path() private val pathArrowDown = Path() //paint private val linePaint = generateTouchLinePaint(R.color.yellow) private val highLinePaint = generateTouchLinePaint(R.color.cyan) private val arrowPaint = generateTouchLinePaint(R.color.white) private val rulerInchPaint = generatePaint(2f) private val textSmallPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { // typeface = Typeface.createFromAsset(context.assets, "fonts/Roboto-Regular.ttf") style = Paint.Style.STROKE textSize = resources.getDimension(R.dimen.txt_size) color = Color.WHITE } private val textBigPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE textSize = resources.getDimension(R.dimen.txt_big_size) color = Color.WHITE typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) } private val rulerPaint = generatePaint(0f) init { if (!isInEditMode) { val dm = resources.displayMetrics //divide inch by 16 because we use each unit = 1/16 inch pixelPerInch = dm.ydpi / 16 //use unit by mm pixelPerMillimeter = dm.ydpi / 25.4f } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) //initial value for 2 lines touch1.yAxis = height / 4f touch2.yAxis = height * 3f / 4 setUpPaths() calculateMeasure() } public override fun onDraw(canvas: Canvas) { if (rulerType == RulerType.INCH) { drawInch(canvas) } else { drawCm(canvas) } val textResult = RulerUtils.formatNumber(result) + getUnit(rulerType) if (checkArrowLength(minimumArrowLength)) { canvas.drawText(textResult, 30f, height - 12f, textSmallPaint) } else { drawRotateText(canvas, textResult, arrowLeftMargin - 20, (touch2.yAxis + touch1.yAxis) / 2) } canvas.drawLine(0f, touch1.yAxis, width.toFloat(), touch1.yAxis, touch1.getPaint()) canvas.drawLine(0f, touch2.yAxis, width.toFloat(), touch2.yAxis, touch2.getPaint()) canvas.drawPath(pathArrowUp, arrowPaint) canvas.drawPath(pathArrowDown, arrowPaint) canvas.drawLine(arrowLeftMargin, touch1.yAxis, arrowLeftMargin, touch2.yAxis, arrowPaint) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { // get pointer index from the event object val pointerIndex = event.actionIndex // get pointer ID val pointerId = event.getPointerId(pointerIndex) // get masked (not specific to a pointer) action val maskedAction = event.actionMasked when (maskedAction) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { // We have a new pointer val y = event.getY(pointerIndex) //check lines touch or not when { y.near(touch1.yAxis) && y.near(touch2.yAxis) -> { //prefer touch2 when 2 touches on the top half screen if (y < height / 2) { touch2.setPointer(pointerId) } else { touch1.setPointer(pointerId) } } y.near(touch1.yAxis) -> touch1.setPointer(pointerId) y.near(touch2.yAxis) -> touch2.setPointer(pointerId) } } MotionEvent.ACTION_MOVE -> { // a pointer was moved val size = event.pointerCount var i = 0 while (i < size) { val moveY = event.getY(i) //moving line if (touch1.active && event.getPointerId(i) == touch1.eventId) { touch1.yAxis = if (moveY > touch2.yAxis) touch2.yAxis else moveY } if (touch2.active && event.getPointerId(i) == touch2.eventId) { touch2.yAxis = if (moveY < touch1.yAxis) touch1.yAxis else moveY } i++ } calculateMeasure() } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> { //update touches if (touch1.active && pointerId == touch1.eventId) { touch1.release() } if (touch2.active && pointerId == touch2.eventId) { touch2.release() } } } setUpPaths() this.postInvalidate() return true } /** * toggle ruler type Inch - Cm */ fun setRulerType(type: RulerType) { this.rulerType = type //recalculate the result calculateMeasure() } /** * Set up paths for arrow */ private fun setUpPaths() { //we need to hide arrow when the space is not enough if (checkArrowLength(arrowSize * 2)) { setPathArrow(arrowLeftMargin, touch1.yAxis) setPathArrow(arrowLeftMargin, touch2.yAxis, true) } else { setPathArrow(arrowLeftMargin, touch1.yAxis, true) setPathArrow(arrowLeftMargin, touch2.yAxis) } } /** * Prepare 2 paths of arrow */ private fun setPathArrow(x: Float, y: Float, isUpPath: Boolean = false) { val (path, direction) = if (isUpPath) { Pair(pathArrowUp, 1) } else { Pair(pathArrowDown, -1) } path.reset() path.moveTo(x, y) path.lineTo(x - arrowSize * ARROW_SCALE_X, y + arrowSize * direction) path.lineTo(x, y + arrowSize * ARROW_SCALE_Y * direction) path.lineTo(x + arrowSize * ARROW_SCALE_X, y + arrowSize * direction) path.close() } /** * Draw Cm type */ private fun drawCm(canvas: Canvas) { startPoint = BORDER_LIMIT var i = 0 while (true) { if (startPoint > height - BORDER_LIMIT) { break } val size = if (i % 10 == 0) scaleLineLevel3 else if (i % 5 == 0) scaleLineLevel2 else scaleLineLevel1 canvas.drawLine(width - size, startPoint, width.toFloat(), startPoint, rulerPaint) if (i % 10 == 0) { val textX = width - scaleLineLevel3 - TEXT_MARGIN val textY = startPoint drawRotateText(canvas, (i / 10).toString(), textX, textY) } startPoint += pixelPerMillimeter i++ } } /** * Draw Inch type */ private fun drawInch(canvas: Canvas) { startPoint = BORDER_LIMIT var i = 0 while (true) { if (startPoint > height - BORDER_LIMIT) { break } val size: Float var paint: Paint = rulerPaint var textX = width - TEXT_MARGIN val textY = startPoint when { i % 16 == 0 -> { size = scaleLineLevel5 paint = rulerInchPaint textX -= size drawRotateText(canvas, (i / 16).toString(), textX, textY, textBigPaint) } i % 8 == 0 -> { size = scaleLineLevel4 textX -= size drawRotateText(canvas, "${i / 8}/2", textX, textY) } i % 4 == 0 -> size = scaleLineLevel3 else -> size = if (i % 2 == 0) scaleLineLevel2 else scaleLineLevel1 } canvas.drawLine(width - size, startPoint, width.toFloat(), startPoint, paint) startPoint += pixelPerInch i++ } } private fun drawRotateText(canvas: Canvas, text: String, x: Float, y: Float, paint: TextPaint = textSmallPaint) { //need to recalculate text size, and draw on accurate position val bounds = Rect() paint.getTextBounds(text, 0, text.length, bounds) val textHeight = bounds.height() val textWidth = bounds.left + bounds.width() //because we need to draw it in rotate 90 degree, //then textWidth and textHeight from bounds are swapped val accurateY = y - textWidth / 2 val accurateX = x - textHeight canvas.save() canvas.rotate(90f, accurateX, accurateY) canvas.drawText(text, accurateX, accurateY, paint) canvas.restore() } /** * Calculate measure * * @return result in inch or cm */ private fun calculateMeasure() { val distance = Math.abs(touch1.yAxis - touch2.yAxis) result = if (rulerType == RulerType.CM) { distance / pixelPerMillimeter / 10 } else { distance / pixelPerInch / 16 } } /** * Return cm or inch */ private fun getUnit(type: RulerType): String { return if (type == RulerType.CM) context.getString(R.string.cm) else context.getString(R.string.inch) } private fun generatePaint(stroke: Float) = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeWidth = stroke color = Color.WHITE } //initial line with normal state and touched state private fun generateTouchLinePaint(color: Int) = Paint().apply { val strokeWidth = resources.getDimension(R.dimen.line_size) style = Paint.Style.FILL setColor(ContextCompat.getColor(context, color)) this.strokeWidth = strokeWidth // pathEffect = CornerPathEffect(10f) } private fun checkArrowLength(minLength: Float): Boolean { return Math.abs(touch1.yAxis - touch2.yAxis) <= minimumArrowLength } enum class RulerType { INCH, CM } //Object contains properties of 2 lines on ruler private inner class Coordinate(var active: Boolean = false, var eventId: Int = 0) { var yAxis: Float = 0f set(value) { //limited touch area, in screen only field = when { value < BORDER_LIMIT -> BORDER_LIMIT value > height - BORDER_LIMIT -> height - BORDER_LIMIT else -> value } } fun getPaint() = if (active) highLinePaint else linePaint fun setPointer(pointerId: Int) { eventId = pointerId active = true } fun release() { eventId = 0 active = false } } private fun Float.near(point: Float): Boolean { return Math.abs(this - point) < delta } }
1
Kotlin
1
3
cd06e9e11c4a2869f713b96b9bbeeaaf2ebdfd03
13,147
PhysicRuler
Apache License 2.0
core/navigation/src/main/java/com/jeckonly/navigation/BgtTopLevelNavigationDestination.kt
JeckOnly
564,735,658
false
{"Kotlin": 493841, "Java": 69358}
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeckonly.navigation import android.util.Log import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavHostController /** * Interface for describing the Now in Android navigation destinations */ interface BgtTopLevelNavigationDestination { /** * Defines a specific route this destination belongs to. * Route is a String that defines the path to your composable. * You can think of it as an implicit deep link that leads to a specific destination. * Each destination should have a unique route. */ val route: String /** * Defines a specific destination ID. * This is needed when using nested graphs via the navigation DLS, to differentiate a specific * destination's route from the route of the entire nested graph it belongs to. */ val destination: String /** * 抽象出来的导航逻辑 */ fun navigate(navController: NavHostController, route: String = this.route) { navController.navigate(route) } /** * 抽象出来的判断逻辑 */ fun isInHierarchy(currentDestination: NavDestination?): Boolean { return topLevelDestinationIsSelected(currentDestination, route) } fun checkCurrentIsMe(currentDestination: NavDestination?): Boolean { val result = currentDestination?.let { Log.d("BgtTopLevelNavigationDestination", "currentDestinationRoute: ${it.route}, navRoute:${route}") it.route == route } ?: false return result } } fun topLevelDestinationNavigate(navController: NavHostController, route: String) { navController.navigate(route) } fun topLevelDestinationIsSelected(currentDestination: NavDestination?, route: String): Boolean { return currentDestination?.hierarchy?.any { it.route == route } == true }
0
Kotlin
0
2
21c3092c90c858023c0122682ab95bb3f4d92745
2,514
Budget
Apache License 2.0
android/src/main/kotlin/com/circuskitchens/flutter_datawedge/FlutterDatawedgePlugin.kt
circus-kitchens
572,169,824
false
null
package com.circuskitchens.flutter_datawedge import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.util.Log import androidx.annotation.NonNull import com.circuskitchens.flutter_datawedge.consts.MyChannels import com.circuskitchens.flutter_datawedge.consts.MyIntents import com.circuskitchens.flutter_datawedge.consts.MyMethods import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.EventChannel.EventSink import io.flutter.plugin.common.EventChannel.StreamHandler import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import org.json.JSONObject class FlutterDatawedgePlugin: FlutterPlugin, MethodCallHandler, StreamHandler { private val profileIntentBroadcast = "2" private lateinit var scanEventChannel: EventChannel private lateinit var commandMethodChannel: MethodChannel /** * Used to save BroadcastReceiver to be able unregister them. */ private val registeredReceivers: ArrayList<SinkBroadcastReceiver> = ArrayList() private val dwInterface = DWInterface() private lateinit var context: Context private lateinit var intentFilter: IntentFilter override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { context = flutterPluginBinding.applicationContext intentFilter = IntentFilter() intentFilter.addAction(context.packageName + MyIntents.SCAN_EVENT_INTENT_ACTION) intentFilter.addAction(DWInterface.ACTION_RESULT) intentFilter.addAction(DWInterface.ACTION_RESULT_NOTIFICATION) intentFilter.addCategory(Intent.CATEGORY_DEFAULT) scanEventChannel = EventChannel(flutterPluginBinding.binaryMessenger, MyChannels.scanChannel) scanEventChannel.setStreamHandler(this) commandMethodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, MyChannels.commandChannel) commandMethodChannel.setMethodCallHandler(this) } override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { when (call.method) { MyMethods.getPlatformVersion -> { result.success("Android ${android.os.Build.VERSION.RELEASE}") } MyMethods.sendDataWedgeCommandStringParameter -> { val arguments = JSONObject(call.arguments.toString()) val command: String = arguments.get("command") as String val parameter: String = arguments.get("parameter") as String dwInterface.sendCommandString(context, command, parameter) // result.success(0); // DataWedge does not return responses } MyMethods.createDataWedgeProfile -> { createDataWedgeProfile(call.arguments.toString()) } MyMethods.listenScannerStatus -> { listenScannerStatus() } else -> { result.notImplemented() } } } override fun onListen(arguments: Any?, events: EventSink?) { val receiver = SinkBroadcastReceiver(events) registeredReceivers.add(receiver) context.registerReceiver(receiver, intentFilter ) } override fun onCancel(arguments: Any?) { } private fun createDataWedgeProfile(profileName: String) { //https://techdocs.zebra.com/datawedge/latest/guide/api/createprofile/ dwInterface.sendCommandString(context, DWInterface.EXTRA_CREATE_PROFILE, profileName) val profileConfig = Bundle() profileConfig.putString(DWInterface.EXTRA_KEY_VALUE_NOTIFICATION_PROFILE_NAME, profileName) profileConfig.putString("PROFILE_ENABLED", "true") // These are all strings profileConfig.putString("CONFIG_MODE", "UPDATE") val barcodeConfig = Bundle() barcodeConfig.putString("PLUGIN_NAME", "BARCODE") // This is the default but never hurts to specify barcodeConfig.putString("RESET_CONFIG", "true") val barcodeProps = Bundle() barcodeConfig.putBundle("PARAM_LIST", barcodeProps) profileConfig.putBundle("PLUGIN_CONFIG", barcodeConfig) val appConfig = Bundle() // Associate the profile with this app appConfig.putString("PACKAGE_NAME", context.packageName) appConfig.putStringArray("ACTIVITY_LIST", arrayOf("*")) profileConfig.putParcelableArray("APP_LIST", arrayOf(appConfig)) dwInterface.sendCommandBundle(context, DWInterface.ACTION_SET_CONFIG, profileConfig) // You can only configure one plugin at a time in some versions of DW, now do the intent output profileConfig.remove("PLUGIN_CONFIG") val intentConfig = Bundle() intentConfig.putString("PLUGIN_NAME", "INTENT") intentConfig.putString("RESET_CONFIG", "true") val intentProps = Bundle() intentProps.putString("intent_output_enabled", "true") intentProps.putString("intent_action", context.packageName + MyIntents.SCAN_EVENT_INTENT_ACTION) intentProps.putString("intent_delivery", profileIntentBroadcast) // "2" intentConfig.putBundle("PARAM_LIST", intentProps) profileConfig.putBundle("PLUGIN_CONFIG", intentConfig) dwInterface.sendCommandBundle(context, DWInterface.ACTION_SET_CONFIG, profileConfig) } private fun listenScannerStatus(){ //https://techdocs.zebra.com/datawedge/latest/guide/api/registerfornotification val b = Bundle() b.putString(DWInterface.EXTRA_KEY_APPLICATION_NAME, context.packageName) b.putString(DWInterface.EXTRA_KEY_NOTIFICATION_TYPE, DWInterface.EXTRA_KEY_VALUE_SCANNER_STATUS) //https://techdocs.zebra.com/datawedge/latest/guide/api/setconfig/ dwInterface.sendCommandBundle(context, DWInterface.EXTRA_REGISTER_NOTIFICATION, b) } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { for (receiver in registeredReceivers) { context.unregisterReceiver(receiver) } commandMethodChannel.setMethodCallHandler(null) scanEventChannel.setStreamHandler(null) } }
3
Kotlin
3
5
9ce61a49d86368637483f44b1f8f3841440ec653
6,013
flutter_datawedge
MIT License
buildSrc/src/main/kotlin/com/masselis/tpmsadvanced/gitflow/task/AssertNewVersionTag.kt
VincentMasselis
501,773,706
false
{"Kotlin": 573141}
package com.masselis.tpmsadvanced.gitflow.task import StricSemanticVersion import com.masselis.tpmsadvanced.gitflow.valuesource.GitTagList import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.provider.Property import org.gradle.api.provider.ProviderFactory import org.gradle.api.tasks.Input import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.assign import org.gradle.kotlin.dsl.from import org.gradle.process.ExecOperations import javax.inject.Inject internal abstract class AssertNewVersionTag : DefaultTask() { @get:Inject protected abstract val execOperations: ExecOperations @get:Inject protected abstract val providerFactory: ProviderFactory @get:Input abstract val version: Property<StricSemanticVersion> private val tagList get() = providerFactory.from(GitTagList::class) { inputFilter = version.map { "$it" } } init { group = "verification" description = "Checks the current version doesn't exists on main" } @TaskAction internal fun process() { if (tagList.get().isNotEmpty()) throw GradleException("Cannot create a new version for \"${version.get()}\", a tag with the same name already exists") } }
3
Kotlin
1
2
266116e6d2b8b28a6e53dd85cad56c4b512b1fad
1,287
TPMS-advanced
Apache License 2.0
android/src/main/kotlin/com/example/foauth/FOauthPlugin.kt
kazuki229
147,997,217
false
{"Dart": 14790, "Ruby": 2792, "Kotlin": 1139, "Swift": 911, "Objective-C": 349}
package com.example.foauth import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.PluginRegistry.Registrar class FOauthPlugin(): MethodCallHandler { companion object { @JvmStatic fun registerWith(registrar: Registrar): Unit { val channel = MethodChannel(registrar.messenger(), "f_oauth") channel.setMethodCallHandler(FOauthPlugin()) } } override fun onMethodCall(call: MethodCall, result: Result): Unit { if (call.method.equals("getPlatformVersion")) { result.success("Android ${android.os.Build.VERSION.RELEASE}") } else { result.notImplemented() } } }
0
Dart
0
0
4895d45e552b1d2112c33d4baae7b82a87f5a318
796
f_oauth
Apache License 2.0
data/src/main/kotlin/io/timemates/backend/data/authorization/db/entities/DbVerification.kt
timemates
575,534,781
false
{"Kotlin": 355697, "Dockerfile": 859}
package io.timemates.backend.data.authorization.db.entities data class DbVerification( val verificationHash: String, val emailAddress: String, val code: String, val attempts: Int, val time: Long, val isConfirmed: Boolean, val metaClientName: String, val metaClientVersion: Double, val metaClientIpAddress: String, )
16
Kotlin
1
8
6c1c51f3395d8d656fabc04cd7b98a4b567c27e6
352
backend
MIT License
features/notepad/src/main/kotlin/com/dvinc/notepad/di/module/AssistedInjectModule.kt
DEcSENT
126,995,107
false
null
/* * Copyright (c) 2020 by <NAME> (<EMAIL>) * All rights reserved. */ package com.dvinc.notepad.di.module import com.squareup.inject.assisted.dagger2.AssistedModule import dagger.Module @AssistedModule @Module(includes = [AssistedInject_AssistedInjectModule::class]) interface AssistedInjectModule
11
Kotlin
3
8
1ffd25d40ba463be38d4cace16602d74d0369576
323
Notepad
MIT License
wire5/src/commonMain/kotlin/mqtt/wire5/control/packet/format/variable/property/PayloadFormatIndicator.kt
thebehera
171,056,445
false
null
@file:Suppress("EXPERIMENTAL_API_USAGE", "EXPERIMENTAL_UNSIGNED_LITERALS") package mqtt.wire5.control.packet.format.variable.property import mqtt.buffer.WriteBuffer import mqtt.wire.data.Type data class PayloadFormatIndicator(val willMessageIsUtf8: Boolean) : Property( 0x01, Type.BYTE, willProperties = true ) { override fun size() = 2u override fun write(buffer: WriteBuffer) = write(buffer, willMessageIsUtf8) }
2
Kotlin
1
32
2f2d176ca1d042f928fba3a9c49f4bc5ff39495f
434
mqtt
Apache License 2.0
analysis/low-level-api-fir/testData/lazyResolveScopes/delegateOverrideWithoutImplicitTypeInsideClassScript.kts
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
annotation class Anno(val str: String) val constant = "const" lateinit var d: IntermediateInterface class MyC<caret>lass : IntermediateInterface by d { override fun isSchemeFile(name: CharSequence): Boolean = name != "str" } interface IntermediateInterface : BaseInterface { } interface BaseInterface { fun isSchemeFile(name: CharSequence): Boolean = true fun anotherFunction(name: CharSequence): Boolean = true @Anno("property $constant") @get:Anno("property $constant") @set:Anno("property $constant") @setparam:Anno("property $constant") var propertyWithAnnotations: Int var property: Int }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
635
kotlin
Apache License 2.0
shared/feat/homeTab/api/src/commonMain/kotlin/org/mobilenativefoundation/store/news/shared/HomeTab.kt
matt-ramotar
742,173,124
false
{"Kotlin": 36554}
package org.mobilenativefoundation.store.news.shared import cafe.adriel.voyager.navigator.tab.Tab interface HomeTab : Tab
1
Kotlin
0
0
6943b9218cd1aa765dc66145b75b1e63625091af
123
news
Apache License 2.0
app/src/main/java/xyz/palaocorona/ui/features/authentication/otpverification/OtpVerificationFragment.kt
SaadAAkash
251,509,106
false
null
package xyz.palaocorona.ui.features.authentication.otpverification import android.app.Activity import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import kotlinx.android.synthetic.main.fragment_otp_verification.* import xyz.palaocorona.R import xyz.palaocorona.base.ui.BaseFragment import xyz.palaocorona.ui.dialogs.NoInternetConnectionDialog import xyz.palaocorona.ui.features.authentication.AuthenticationViewModel import xyz.palaocorona.ui.features.authentication.createprofile.CreateProfileFragment import org.jetbrains.anko.sdk27.coroutines.onClick import org.jetbrains.anko.support.v4.toast class OtpVerificationFragment: BaseFragment<AuthenticationViewModel>() { companion object { const val VERIFICATION_ID = "id" } override val layoutId: Int get() = R.layout.fragment_otp_verification override fun onCreate(savedInstanceState: Bundle?) { isActivityAsViewModelLifeCycleOwner = true super.onCreate(savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) btnVerify.onClick { viewModel.verifyOtp(arguments?.getString(VERIFICATION_ID), etOtp.text.toString()) } viewModel.noInternetConnection.observe(viewLifecycleOwner, Observer { showNoInternetConnectionDialog(object: NoInternetConnectionDialog.NoInternetDialogCallback { override fun retry() { viewModel.verifyOtp(arguments?.getString(VERIFICATION_ID), etOtp.text.toString()) } }) }) viewModel.otpInvalid.observeOn(viewLifecycleOwner, Observer { toast(R.string.invalid_otp) }) } }
0
Kotlin
8
57
80f69ecfd5941962d7e5bd5f02d5cf36064e6fc5
1,808
COVID-19-Bangladesh-Android
MIT License
src/main/java/io/sc3/plethora/gameplay/data/DamageTypeTagProvider.kt
SwitchCraftCC
491,699,521
false
{"Kotlin": 383687, "Java": 259087}
package io.sc3.plethora.gameplay.data import io.sc3.plethora.gameplay.registry.Registration import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider import net.minecraft.entity.damage.DamageType import net.minecraft.registry.RegistryKeys import net.minecraft.registry.RegistryWrapper import net.minecraft.registry.tag.DamageTypeTags import java.util.concurrent.CompletableFuture class DamageTypeTagProvider( out: FabricDataOutput, future: CompletableFuture<RegistryWrapper.WrapperLookup> ) : FabricTagProvider<DamageType>(out, RegistryKeys.DAMAGE_TYPE, future) { override fun configure(arg: RegistryWrapper.WrapperLookup) { getOrCreateTagBuilder(DamageTypeTags.IS_PROJECTILE).add(Registration.ModDamageSources.LASER) getOrCreateTagBuilder(DamageTypeTags.IS_FIRE).add(Registration.ModDamageSources.LASER) } }
26
Kotlin
8
16
1309c51911a9b146218e5dae65a16dc8f932b23e
898
Plethora-Fabric
MIT License
Submission Akhir/AplikasiGithubUser/app/src/main/java/com/yofhi/aplikasigithubuser/viewModel/SettingsViewModelFactory.kt
YofhiFauda
707,282,576
false
{"Kotlin": 81596}
package com.yofhi.aplikasigithubuser.viewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.yofhi.aplikasigithubuser.view.ui.setting.SettingsPreferences class SettingsViewModelFactory(private val pref: SettingsPreferences) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(ThemeSettingsViewModel::class.java)) { return ThemeSettingsViewModel(pref) as T } else if (modelClass.isAssignableFrom(SearchViewModel::class.java)) { return SearchViewModel(pref) as T } throw IllegalArgumentException("Uknown ViewModel class:" + modelClass.name) } }
0
Kotlin
0
0
04f8aceaf4d2b34957434c7e13249a0cae88e774
771
github-app
MIT License
app/src/main/java/ru/resodostudios/pokedex/presentation/pokemons/components/SearchBar.kt
f33lnothin9
540,119,830
false
{"Kotlin": 59209}
package ru.resodostudios.pokedex.presentation.pokemons.components /* import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField import androidx.compose.runtime.* import androidx.compose.ui.Modifier @ExperimentalMaterial3Api @Composable fun SearchBar( modifier: Modifier = Modifier, hint: String = "", onSearch: (String) -> Unit = {} ) { var text by remember { mutableStateOf("") } var isHintDisplayed by remember { mutableStateOf(hint != "") } Box(modifier = modifier) { OutlinedTextField( modifier = Modifier .fillMaxWidth(), value = text, onValueChange = { text = it onSearch(it) }, maxLines = 1, singleLine = true ) } } */
0
Kotlin
0
2
e55993f3e81c8315624ffc897156c77846b4400d
968
pokedex
Apache License 2.0
P9996.kt
daily-boj
253,815,781
false
null
fun main(args: Array<out String>) { val n = readLine()!!.toInt() val (begin, end) = readLine()!!.split("*") repeat(n) { val line = readLine()!! if (line.length >= begin.length + end.length && line.startsWith(begin) && line.endsWith(end)) { println("DA") } else { println("NE") } } }
0
Rust
0
12
74294a4628e96a64def885fdcdd9c1444224802c
355
RanolP
The Unlicense
compiler/testData/loadJava/compiledKotlin/class/SealedInterface.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
package test class Inheritor3 : SealedInterface sealed interface SealedInterface { class Inheritor1 : SealedInterface } class Inheritor2 : SealedInterface
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
162
kotlin
Apache License 2.0
js/js.translator/testData/box/polyfills/log10/log10WithoutExistedIntrinsic.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// WITH_STDLIB // TARGET_BACKEND: JS_IR // FILE: main.js Math.log10 = undefined; // FILE: main.kt import kotlin.math.log10 fun box(): String { assertEquals(log10(1.0), 0) assertEquals(log10(10.0), 1) assertEquals(log10(100.0), 2) assertEquals(js("Math.log10.called"), js("undefined")) return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
322
kotlin
Apache License 2.0
src/main/kotlin/net/danlew/predictit/analyzer/MarketAnalyzer.kt
dlew
352,497,119
false
null
package net.danlew.predictit.analyzer import net.danlew.predictit.model.Market import net.danlew.predictit.model.MarketWithPrices import net.danlew.predictit.model.Notification interface MarketAnalyzer { /** * Analyzes a [Market]'s price history then returns any [Notification]s that may result. */ fun analyze(oldMarketData: Market?, latestData: MarketWithPrices): Set<Notification> }
3
Kotlin
0
3
ff87476180bfda665021d737fd651d01025ef03b
399
predictit-bot
MIT License
app/src/main/java/mustafaozhan/github/com/androcat/main/fragment/MainFragmentViewModel.kt
MobilCat
119,292,192
false
{"Kotlin": 98626, "JavaScript": 1680}
package mustafaozhan.github.com.androcat.main.fragment import io.reactivex.subjects.PublishSubject import mustafaozhan.github.com.androcat.base.BaseViewModel import mustafaozhan.github.com.androcat.extensions.isValidUsername /** * Created by <NAME> on 2018-07-22. */ class MainFragmentViewModel : BaseViewModel() { override fun inject() { viewModelComponent.inject(this) } var loginSubject: PublishSubject<Boolean> = PublishSubject.create() fun getUserName(): String? { val username = dataManager.loadUser().username return if (username.isValidUsername()) { username } else { null } } fun isLoggedIn() = dataManager.loadUser().isLoggedIn fun updateUser(username: String? = null, isLoggedIn: Boolean? = null, token: String? = null) = dataManager.updateUser(username, isLoggedIn, token) fun authentication(isLoggedIn: Boolean) = loginSubject.onNext(isLoggedIn) }
0
Kotlin
57
84
7d0a8706a1b021ce2ef844f470f4d6f3339a15c7
982
AndroCat
Apache License 2.0
app/src/main/java/com/semisonfire/cloudgallery/core/ui/ContentActivity.kt
Semyon100116907
132,183,724
false
null
package com.semisonfire.cloudgallery.core.ui import androidx.appcompat.app.AppCompatActivity import io.reactivex.disposables.CompositeDisposable abstract class ContentActivity : AppCompatActivity() { protected val disposables: CompositeDisposable = CompositeDisposable() override fun onDestroy() { super.onDestroy() disposables.dispose() } }
0
Kotlin
0
1
59f8b94fdeaf8db0557deef84f1b25224ab768e4
373
CloudGallery
MIT License
core/system/ui/src/commonMain/kotlin/io/spherelabs/system/ui/shimmer/ShimmerWindowBounds.kt
getspherelabs
687,455,894
false
{"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048}
package io.spherelabs.system.ui.shimmer import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Rect /** * Copied from https://github.com/valentinilk/compose-shimmer/tree/master */ @Composable internal expect fun rememberWindowBounds(): Rect
18
Kotlin
24
188
902a0505c5eaf0f3848a5e06afaec98c1ed35584
269
anypass-kmp
Apache License 2.0
app/src/main/java/com/example/fitnesslog/shared/domain/use_case/SharedUseCases.kt
Mark-Vasquez
684,065,542
false
{"Kotlin": 114942}
package com.example.fitnesslog.shared.domain.use_case data class SharedUseCases( val getSelectedProgram: GetSelectedProgram, val seedInitialApplication: SeedInitialApplication, )
0
Kotlin
0
0
0ab824faa7f999ed234a9f0a3068b056e465e23f
188
Fitness-Log
Apache License 2.0
app/src/androidTest/java/com/anytypeio/anytype/features/editor/DescriptionTesting.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.features.editor import android.os.Bundle import androidx.core.os.bundleOf import androidx.fragment.app.testing.FragmentScenario import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.anytypeio.anytype.R import com.anytypeio.anytype.core_models.Block import com.anytypeio.anytype.core_models.Relations import com.anytypeio.anytype.core_models.ext.content import com.anytypeio.anytype.emojifier.data.DefaultDocumentEmojiIconProvider import com.anytypeio.anytype.features.editor.base.EditorTestSetup import com.anytypeio.anytype.features.editor.base.TestEditorFragment import com.anytypeio.anytype.presentation.MockBlockContentFactory import com.anytypeio.anytype.presentation.MockBlockFactory import com.anytypeio.anytype.test_utils.MockDataFactory import com.anytypeio.anytype.test_utils.utils.checkHasText import com.anytypeio.anytype.test_utils.utils.checkIsRecyclerSize import com.anytypeio.anytype.test_utils.utils.onItemView import com.anytypeio.anytype.test_utils.utils.rVMatcher import com.anytypeio.anytype.ui.editor.EditorFragment import com.bartoszlipinski.disableanimationsrule.DisableAnimationsRule import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class DescriptionTesting : EditorTestSetup() { @get:Rule val animationsRule = DisableAnimationsRule() private val args = bundleOf(EditorFragment.ID_KEY to root) private val title = MockBlockFactory.text( content = MockBlockContentFactory.StubTextContent( style = Block.Content.Text.Style.TITLE, text = "Description in Editor.", marks = emptyList() ) ) private val description = MockBlockFactory.text( content = MockBlockContentFactory.StubTextContent( text = "A lighthouse is a tower, building, or another type of structure designed to emit light from a system of lamps and lenses and to serve as a navigational aid for maritime pilots at sea or on inland waterways.", marks = emptyList(), style = Block.Content.Text.Style.DESCRIPTION ) ) @Before override fun setup() { super.setup() } @Test fun shouldNotRenderDescriptionAfterTitleBecauseDescriptionIsNotFeatured() { // SETUP val header = Block( id = MockDataFactory.randomUuid(), content = Block.Content.Layout( type = Block.Content.Layout.Type.HEADER ), fields = Block.Fields.empty(), children = listOf(title.id, description.id) ) val page = Block( id = root, fields = Block.Fields(emptyMap()), content = Block.Content.Smart, children = listOf(header.id) ) val document = listOf(page, header, title, description) stubInterceptEvents() stubInterceptThreadStatus() stubOpenDocument(document) stubAnalytics() launchFragment(args) // TESTING R.id.recycler.rVMatcher().apply { onItemView(0, R.id.title).checkHasText( title.content<Block.Content.Text>().text ) checkIsRecyclerSize(1) } } @Test fun shouldRenderDescriptionAfterTitleBecauseDescriptionIsFeatured() { // SETUP val header = Block( id = MockDataFactory.randomUuid(), content = Block.Content.Layout( type = Block.Content.Layout.Type.HEADER ), fields = Block.Fields.empty(), children = listOf(title.id, description.id) ) val page = Block( id = root, fields = Block.Fields(emptyMap()), content = Block.Content.Smart, children = listOf(header.id) ) val document = listOf(page, header, title, description) val details = Block.Details( mapOf( root to Block.Fields( mapOf( "iconEmoji" to DefaultDocumentEmojiIconProvider.DOCUMENT_SET.random(), "featuredRelations" to listOf(Relations.DESCRIPTION), "description" to description.content<Block.Content.Text>().text ) ) ) ) stubInterceptEvents() stubInterceptThreadStatus() stubUpdateText() stubOpenDocument( document = document, details = details ) stubAnalytics() launchFragment(args) // TESTING R.id.recycler.rVMatcher().apply { checkIsRecyclerSize(2) onItemView(0, R.id.title).checkHasText( title.content<Block.Content.Text>().text ) onItemView(1, R.id.tvBlockDescription).checkHasText( description.content<Block.Content.Text>().text ) } } private fun launchFragment(args: Bundle): FragmentScenario<TestEditorFragment> { return launchFragmentInContainer( fragmentArgs = args, themeResId = R.style.AppTheme ) } }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
5,345
anytype-kotlin
RSA Message-Digest License
src/test/kotlin/de/quantummaid/documaid/shared/filesystem/SutFileStructure.kt
quantummaid
230,588,078
false
null
/** * Copyright (c) 2020 <NAME> - https://quantummaid.de/. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 de.quantummaid.documaid.shared.filesystem import de.quantummaid.documaid.assumptions.HugoDocumentationAssumptions import de.quantummaid.documaid.config.DocuMaidConfiguration import de.quantummaid.documaid.generating.GenerationFlavorType import java.nio.file.Path class SutFileStructure internal constructor() { private val children = mutableListOf<SutFileObject>() private var basePath: Path? = null private var overriddenExpectedFileStructure: PhysicalFileSystemStructure? = null companion object { fun aFileStructureForDocuMaidToProcess(): SutFileStructure { return SutFileStructure() } } fun with(vararg children: SutFileObject): SutFileStructure { this.children.addAll(children.toList()) return this } fun inDirectory(temporaryTestDirectory: TemporaryTestDirectory): SutFileStructure { this.basePath = temporaryTestDirectory.path.toAbsolutePath() return this } fun generateFileStructureForDocuMaidToProcess(): PhysicalFileSystemStructure { return generate(basePath!!) } fun constructExpectedFileStructureForGithub(): PhysicalFileSystemStructure { return construct(basePath!!, ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_GITHUB) } fun constructExpectedFileStructureForHugo(config: DocuMaidConfiguration): PhysicalFileSystemStructure { val documentationDirectory = children.filterIsInstance(SutDirectory::class.java) .find { it.name == HugoDocumentationAssumptions.DOCUMENTATION_DIRECTORY } val generationFlavorType = config.generationFlavorType return if (generationFlavorType == GenerationFlavorType.QUANTUMMAID.name && documentationDirectory != null) { this.children.clear() this.children.addAll(documentationDirectory.children) val hugoOutputPath = basePath!!.resolve(config.hugoOutputPath) construct(hugoOutputPath, ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_HUGO) } else { val hugoOutputPath = basePath!!.resolve(config.hugoOutputPath) construct(hugoOutputPath, ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_HUGO) } } private fun generate(basePath: Path): PhysicalFileSystemStructure { val parentPath = basePath.parent createDirectoryAndParentsIfNotExisting(parentPath) val fileName = basePath.toFile().name val rootDirectory = SutDirectory.aDirectory(fileName) .with(children) .generate(parentPath) return PhysicalFileSystemStructure(rootDirectory) } private fun construct( basePath: Path, constructionForPlatformType: ConstructionForPlatformType ): PhysicalFileSystemStructure { if (overriddenExpectedFileStructure != null) { return overriddenExpectedFileStructure!! } val parentPath = basePath.parent createDirectoryAndParentsIfNotExisting(parentPath) val fileName = basePath.toFile().name val rootDirectory = SutDirectory.aDirectory(fileName) .with(children) .construct(parentPath, constructionForPlatformType) return PhysicalFileSystemStructure(rootDirectory!!) } fun cleanUp() { deleteDirectoryAndChildren(basePath!!) } fun overrideExpectedFileStructure(expectedFileStructure: PhysicalFileSystemStructure) { this.overriddenExpectedFileStructure = expectedFileStructure } } enum class ConstructionForPlatformType { EXPECTED_OUTPUT_FOR_GITHUB, EXPECTED_OUTPUT_FOR_HUGO, } interface SutFileObject { fun generate(parentPath: Path): PhysicalFileObject fun construct(parentPath: Path, constructionForPlatformType: ConstructionForPlatformType): PhysicalFileObject? } class SutDirectory private constructor(val name: String) : SutFileObject { val children = ArrayList<SutFileObject>() companion object { fun aDirectory(name: String): SutDirectory { return SutDirectory(name) } } fun with(vararg children: SutFileObject): SutDirectory { this.children.addAll(children) return this } fun with(children: List<SutFileObject>): SutDirectory { this.children.addAll(children) return this } override fun generate(parentPath: Path): PhysicalDirectory { val physicalDirectory = PhysicalDirectoryBuilder.aDirectory(name) .create(parentPath) val physicalChildren = children.map { it.generate(physicalDirectory.path) } physicalDirectory.add(physicalChildren) return physicalDirectory } override fun construct( parentPath: Path, constructionForPlatformType: ConstructionForPlatformType ): PhysicalDirectory? { val physicalDirectory = PhysicalDirectoryBuilder.aDirectory(name) .construct(parentPath) val physicalChildren = children.map { it.construct(physicalDirectory.path, constructionForPlatformType) } .filterNotNull() physicalDirectory.add(physicalChildren) return when (constructionForPlatformType) { ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_GITHUB -> { physicalDirectory } ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_HUGO -> { if (physicalChildren.isNotEmpty()) { physicalDirectory } else { null } } } } } interface ProcessedFile : SutFileObject { fun originalFile(): PhysicalFileBuilder fun unprocessedFile(): PhysicalFileBuilder fun processedFile(): PhysicalFileBuilder fun processedFileInHugoFormat(): PhysicalFileBuilder } class ProcessedFileBuilder { private var originalFile: PhysicalFileBuilder? = null private var docuMaidedFile: PhysicalFileBuilder? = null private var docuMaidedFileInHugoFormat: PhysicalFileBuilder? = null companion object { fun anExpectedFile(): ProcessedFileBuilder { return ProcessedFileBuilder() } } fun withOriginalNameAndContent(name: String, content: String): ProcessedFileBuilder { originalFile = PhysicalFileBuilder.aFile(name) .withContent(content) return this } fun withProcessedNameAndContent(name: String, content: String): ProcessedFileBuilder { docuMaidedFile = PhysicalFileBuilder.aFile(name) .withContent(content) return this } fun withProcessedNameAndContentInHugoFormat(name: String, content: String): ProcessedFileBuilder { docuMaidedFileInHugoFormat = PhysicalFileBuilder.aFile(name) .withContent(content) return this } fun build(): ProcessedFile { return SimpleProcessedFile(originalFile!!, docuMaidedFile!!, docuMaidedFileInHugoFormat!!) } } open class SimpleProcessedFile( private val originalFile: PhysicalFileBuilder, private val processedFile: PhysicalFileBuilder, private val processedFileInHugoFormat: PhysicalFileBuilder ) : ProcessedFile { override fun originalFile(): PhysicalFileBuilder { return originalFile } override fun unprocessedFile(): PhysicalFileBuilder { return originalFile } override fun processedFile(): PhysicalFileBuilder { return processedFile } override fun processedFileInHugoFormat(): PhysicalFileBuilder { return processedFileInHugoFormat } override fun generate(parentPath: Path): PhysicalFileObject { return originalFile.create(parentPath) } override fun construct( parentPath: Path, constructionForPlatformType: ConstructionForPlatformType ): PhysicalFileObject? { return when (constructionForPlatformType) { ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_GITHUB -> processedFile.construct(parentPath) ConstructionForPlatformType.EXPECTED_OUTPUT_FOR_HUGO -> { return if (originalFile.name.endsWith(".md")) { processedFileInHugoFormat.construct(parentPath) } else { null } } } } } open class NotProcessedSourceFile( notChangingFileBuilder: PhysicalFileBuilder ) : SimpleProcessedFile(notChangingFileBuilder, notChangingFileBuilder, notChangingFileBuilder) open class EmptySutFile( notChangingFileBuilder: PhysicalFileBuilder ) : SimpleProcessedFile(notChangingFileBuilder, notChangingFileBuilder, notChangingFileBuilder) { companion object { fun aFile(fileName: String): EmptySutFile { val fileBuilder = PhysicalFileBuilder.aFile(fileName) return EmptySutFile(fileBuilder) } } }
16
Kotlin
0
2
f9cf862e1ab8d539e0ef01227a555121f7354339
9,703
documaid
Apache License 2.0
compiler/psi/src/org/jetbrains/kotlin/psi/KtOperationReferenceExpression.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.psi import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.TreeElement import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.parsing.KotlinExpressionParsing import org.jetbrains.kotlin.types.expressions.OperatorConventions class KtOperationReferenceExpression(node: ASTNode) : KtSimpleNameExpressionImpl(node) { override fun getReferencedNameElement() = findChildByType<PsiElement?>(KotlinExpressionParsing.ALL_OPERATIONS) ?: this val operationSignTokenType: KtSingleValueToken? get() = (firstChild as? TreeElement)?.elementType as? KtSingleValueToken fun isConventionOperator(): Boolean { val tokenType = operationSignTokenType ?: return false return OperatorConventions.getNameForOperationSymbol(tokenType) != null } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,477
kotlin
Apache License 2.0
src/art/Dom.kt
WhiteHexagon
262,557,783
false
null
package art import de.mirkosertic.bytecoder.api.web.AnimationFrameCallback import de.mirkosertic.bytecoder.api.web.Window import ext.ExtCanvas import ext.ExtContext import ext.ExtDiv import ext.ExtWindow class Dom { data class Paper(val canvas: ExtCanvas, val ctx: ExtContext, val width: Int, val height: Int) private val window = Window.window()!! as ExtWindow private val document = window.document() private val scale = window.devicePixelRatio private val app = (document.getElementById("app") as ExtDiv) private var animationCallback: AnimationFrameCallback? = null fun createCanvasWithID(id: String): Paper { app.style("float:left; width:100%; height:100%;") val cw = app.clientWidth() val ch = app.clientHeight() val actualWidth = (cw * scale).toInt() val actualHeight = (ch * scale).toInt() val canvas = (document.createElement("canvas") as ExtCanvas).apply { id(id) width(actualWidth) height(actualHeight) style().setProperty("width", "" + cw + "px") style().setProperty("height", "" + ch + "px") style().setProperty("background-color", "#777777") } val ctx = canvas.getContext("2d") as ExtContext ctx.scale(scale, scale) app.appendChild(canvas) return Paper(canvas, ctx, cw, ch) } fun startAnimation(cb: SceneRenderer) { animationCallback = AnimationFrameCallback { aElapsedTime -> cb.draw(aElapsedTime) window.requestAnimationFrame(animationCallback) } window.requestAnimationFrame(animationCallback) } }
0
Kotlin
0
1
2056d5a313be9cd03b32b7874c917394b15da065
1,669
example-kotlin-bytecoder-wasm
The Unlicense
shakytweaks-noop/src/main/java/com/mindsea/shakytweaks/Tweak.kt
MindSea
256,023,206
false
null
/* * MIT License * * Copyright (c) 2019 MindSea * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mindsea.shakytweaks import androidx.annotation.StringRes import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty private class TweakDefaultValueDelegate<T>(private val releaseValue: T) : ReadOnlyProperty<Any?, T> { override fun getValue(thisRef: Any?, property: KProperty<*>): T = releaseValue } @Suppress("UNUSED_PARAMETER") fun booleanTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: Boolean, defaultTweakValue: Boolean? = null): ReadOnlyProperty<Any, Boolean> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun intTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: Int, minValue: Int, maxValue: Int, defaultTweakValue: Int? = null, step: Int = 0): ReadOnlyProperty<Any, Int> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun floatTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: Float, minValue: Float, maxValue: Float, defaultTweakValue: Float? = null, step: Float = 0F): ReadOnlyProperty<Any, Float> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun doubleTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: Double, minValue: Double, maxValue: Double, defaultTweakValue: Double? = null, step: Double): ReadOnlyProperty<Any, Double> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun longTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: Long, minValue: Long, maxValue: Long, defaultTweakValue: Long? = null, step: Long): ReadOnlyProperty<Any, Long> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun stringTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: String? = null, defaultTweakValue: String? = null): ReadOnlyProperty<Any, String?> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun stringOptionsTweak(tweakId: String, group: String, tweakDescription: String, releaseValue: String, defaultTweakValue: String, vararg otherOptions: String): ReadOnlyProperty<Any, String> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun stringResOptionsTweak(tweakId: String, group: String, tweakDescription: String, @StringRes releaseValue: Int, defaultTweakValue: Int, @StringRes vararg otherOptions: Int): ReadOnlyProperty<Any, Int> = TweakDefaultValueDelegate(releaseValue) @Suppress("UNUSED_PARAMETER") fun registerActionTweak(tweakId: String, group: String, tweakDescription: String, tweakAction: () -> Unit) { // Do nothing } @Suppress("UNUSED_PARAMETER") fun unregisterActionTweak(tweakId: String) { // Do nothing }
2
Kotlin
0
7
108b59f37ccdcaa96f044eca861a4f2f77d0ad43
3,880
ShakyTweaksAndroid
MIT License
app/src/main/java/com/startingground/cognebus/settings/SettingsViewModel.kt
StartingGround
434,992,176
false
{"Kotlin": 197507, "CSS": 6569}
package com.startingground.cognebus.settings import android.app.Application import android.view.View import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.preference.PreferenceManager import com.google.android.material.switchmaterial.SwitchMaterial import com.startingground.cognebus.R import com.startingground.cognebus.utilities.MINIMAL_CYCLE_INCREMENT import com.startingground.cognebus.utilities.MINIMAL_MAX_DAYS_PER_CYCLE import com.startingground.cognebus.utilities.StringUtils import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor(private val applicationContext: Application) : ViewModel() { companion object{ //File Default Options const val ENABLE_HTML_KEY = "enable_html" const val ONLY_PRACTICE_ENABLED_KEY = "only_practice_enabled" const val REPETITION_ENABLED_KEY = "repetition_enabled" const val CONTINUE_REPETITION_KEY = "continue_repetition" const val CYCLE_INCREMENT_KEY = "cycle_increment" const val MAX_DAYS_PER_CYCLE_KEY = "max_days_per_cycle" const val ENABLE_HTML_DEFAULT_VALUE = false const val ONLY_PRACTICE_ENABLED_DEFAULT_VALUE = false const val REPETITION_ENABLED_DEFAULT_VALUE = true const val CONTINUE_REPETITION_DEFAULT_VALUE = false const val CYCLE_INCREMENT_DEFAULT_VALUE: Int = 15 const val MAX_DAYS_PER_CYCLE_DEFAULT_VALUE: Int = 60 //Flashcard Options const val CONSECUTIVE_FLASHCARD_CREATION_KEY = "consecutive_flashcard_creation" const val CROP_IMAGE_WHEN_ADDED_KEY = "crop_image_when_added" const val CONSECUTIVE_FLASHCARD_CREATION_DEFAULT_VALUE = false const val CROP_IMAGE_WHEN_ADDED_DEFAULT_VALUE = false } private fun switchValueChangedHandler(view: View, key: String, mutableLiveDataOfSwitch: MutableLiveData<Boolean>){ if(view !is SwitchMaterial) return with(preferences.edit()){ putBoolean(key, view.isChecked) apply() } mutableLiveDataOfSwitch.value = view.isChecked } private val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) //File Default Options private val _enableHTML: MutableLiveData<Boolean> = MutableLiveData( preferences.getBoolean(ENABLE_HTML_KEY, ENABLE_HTML_DEFAULT_VALUE) ) val enableHTML: LiveData<Boolean> get() = _enableHTML fun onEnableHtmlChanged(view: View){ switchValueChangedHandler(view, ENABLE_HTML_KEY, _enableHTML) } private val _onlyPracticeEnabled: MutableLiveData<Boolean> = MutableLiveData( preferences.getBoolean(ONLY_PRACTICE_ENABLED_KEY, ONLY_PRACTICE_ENABLED_DEFAULT_VALUE) ) val onlyPracticeEnabled: LiveData<Boolean> get() = _onlyPracticeEnabled fun onOnlyPracticeEnabledChanged(view: View){ switchValueChangedHandler(view, ONLY_PRACTICE_ENABLED_KEY, _onlyPracticeEnabled) } private val _repetitionEnabled: MutableLiveData<Boolean> = MutableLiveData( preferences.getBoolean(REPETITION_ENABLED_KEY, REPETITION_ENABLED_DEFAULT_VALUE) ) val repetitionEnabled: LiveData<Boolean> get() = _repetitionEnabled fun onRepetitionEnabledChanged(view: View){ switchValueChangedHandler(view, REPETITION_ENABLED_KEY, _repetitionEnabled) } private val _continueRepetition: MutableLiveData<Boolean> = MutableLiveData( preferences.getBoolean(CONTINUE_REPETITION_KEY, CONTINUE_REPETITION_DEFAULT_VALUE) ) val continueRepetition: LiveData<Boolean> get() = _continueRepetition fun onContinueRepetitionChanged(view: View){ switchValueChangedHandler(view, CONTINUE_REPETITION_KEY, _continueRepetition) } private val _cycleIncrement: MutableLiveData<Int> = MutableLiveData( preferences.getInt(CYCLE_INCREMENT_KEY, CYCLE_INCREMENT_DEFAULT_VALUE) ) val cycleIncrement: LiveData<Int> get() = _cycleIncrement private val _cycleIncrementError: MutableLiveData<String?> = MutableLiveData(null) val cycleIncrementError: LiveData<String?> get() = _cycleIncrementError fun onCycleIncrementChanged(text: String){ val errorText = StringUtils.getErrorForInvalidIntegerValueInString( text, applicationContext.getString(R.string.file_fragment_cycle_increment_edit_text_invalid_input_error), MINIMAL_CYCLE_INCREMENT, applicationContext.getString(R.string.file_fragment_cycle_increment_edit_text_value_under_error, MINIMAL_CYCLE_INCREMENT) ) _cycleIncrementError.value = errorText if(errorText != null) return val value = text.toInt() with(preferences.edit()){ putInt(CYCLE_INCREMENT_KEY, value) apply() } _cycleIncrement.value = value } private val _maxDaysPerCycle: MutableLiveData<Int> = MutableLiveData( preferences.getInt(MAX_DAYS_PER_CYCLE_KEY, MAX_DAYS_PER_CYCLE_DEFAULT_VALUE) ) val maxDaysPerCycle: LiveData<Int> get() = _maxDaysPerCycle private val _maxDaysPerCycleError: MutableLiveData<String?> = MutableLiveData(null) val maxDaysPerCycleError: LiveData<String?> get() = _maxDaysPerCycleError fun onMaxDaysPerCycleChanged(text: String){ val errorText = StringUtils.getErrorForInvalidIntegerValueInString( text, applicationContext.getString(R.string.file_fragment_max_days_per_cycle_edit_text_invalid_input_error), MINIMAL_MAX_DAYS_PER_CYCLE, applicationContext.getString(R.string.file_fragment_max_days_per_cycle_edit_text_value_under_error, MINIMAL_MAX_DAYS_PER_CYCLE) ) _maxDaysPerCycleError.value = errorText if(errorText != null) return val value = text.toInt() with(preferences.edit()){ putInt(MAX_DAYS_PER_CYCLE_KEY, value) apply() } _maxDaysPerCycle.value = value } //Flashcard Options private val _consecutiveFlashcardCreation: MutableLiveData<Boolean> = MutableLiveData( preferences.getBoolean(CONSECUTIVE_FLASHCARD_CREATION_KEY, CONSECUTIVE_FLASHCARD_CREATION_DEFAULT_VALUE) ) val consecutiveFlashcardCreation: LiveData<Boolean> get() = _consecutiveFlashcardCreation fun onConsecutiveFlashcardCreationChanged(view: View){ switchValueChangedHandler(view, CONSECUTIVE_FLASHCARD_CREATION_KEY, _consecutiveFlashcardCreation) } private val _cropImageWhenAdded: MutableLiveData<Boolean> = MutableLiveData( preferences.getBoolean(CROP_IMAGE_WHEN_ADDED_KEY, CROP_IMAGE_WHEN_ADDED_DEFAULT_VALUE) ) val cropImageWhenAdded: LiveData<Boolean> get() = _cropImageWhenAdded fun onCropImageWhenAddedChanged(view: View){ switchValueChangedHandler(view, CROP_IMAGE_WHEN_ADDED_KEY, _cropImageWhenAdded) } }
0
Kotlin
0
0
ca4a7ec801bccf08b34bec55eb6ffad6a43f72f3
6,971
Cognebus
MIT License
app/src/main/java/com/ajcm/chessapp/ui/adapters/BoardAdapter.kt
jassielcastro
364,715,505
false
null
package com.ajcm.chessapp.ui.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.ajcm.chess.board.Board import com.ajcm.chess.board.Position import com.ajcm.chess.piece.Piece import com.ajcm.chessapp.R import com.ajcm.chessapp.extensions.getImage import com.ajcm.design.ViewHolder @SuppressLint("NotifyDataSetChanged") class BoardAdapter( private val board: Board, private val onClickListener: (Piece) -> Unit, private val onMoveClickListener: (Position) -> Unit, ) : RecyclerView.Adapter<ViewHolder>() { var whiteAvailablePieces: List<Piece> = emptyList() set(value) { field = value notifyDataSetChanged() } var blackAvailablePieces: List<Piece> = emptyList() set(value) { field = value notifyDataSetChanged() } private var possiblesMoves: List<Position> = emptyList() set(value) { field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_board, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentPosition = board.positions[holder.bindingAdapterPosition] with(holder.itemView) { val bg = findViewById<View>(R.id.bgItem) val imgPiece = findViewById<ImageView>(R.id.imgPiece) val possibleView = findViewById<View>(R.id.bgPossibleMove) val pieceOnBoard = getPossiblePieceFrom(currentPosition) pieceOnBoard?.let { imgPiece.setImageResource(it.getImage()) } ?: imgPiece.setImageResource(0) checkPossibleMoves(currentPosition, possibleView, pieceOnBoard) addClickListener(imgPiece, currentPosition) if ((currentPosition.x + currentPosition.y) % 2 == 0) { bg.setBackgroundResource(R.drawable.white_board_piece) } else { bg.setBackgroundResource(R.drawable.black_board_piece) } } } private fun checkPossibleMoves( currentPosition: Position, possibleView: View, pieceOnBoard: Piece? ) { if (possiblesMoves.contains(currentPosition)) { possibleView.visibility = View.VISIBLE possibleView.background = pieceOnBoard?.let { ContextCompat.getDrawable(possibleView.context, R.drawable.possible_move_checked) .also { possibleView.alpha = 0.6f } } ?: ContextCompat.getDrawable(possibleView.context, R.drawable.possible_move_selector) .also { possibleView.alpha = 1f } } else { possibleView.visibility = View.GONE } } private fun addClickListener(imgPiece: ImageView, currentPosition: Position) { imgPiece.setOnClickListener { val pieceOnBoard = getPossiblePieceFrom(currentPosition) if (pieceOnBoard != null && pieceOnBoard.playerIsMoving()) { possiblesMoves = if (possiblesMoves.isEmpty()) { pieceOnBoard.getAllPossibleMoves() } else { emptyList() } onClickListener(pieceOnBoard) } else if (possiblesMoves.isNotEmpty() && possiblesMoves.contains(currentPosition)) { onMoveClickListener(currentPosition) possiblesMoves = emptyList() } } } private fun getPossiblePieceFrom(currentPosition: Position): Piece? { return whiteAvailablePieces .firstOrNull { it.position.value == currentPosition } ?: blackAvailablePieces.firstOrNull { it.position.value == currentPosition } } override fun getItemCount(): Int = board.positions.size }
0
Kotlin
0
9
621e9f7f77fac0f82a067f0843a2196e21e22226
4,234
ChessApp
MIT License
app/src/main/java/id/yanuar/weather/util/RecyclerViewExt.kt
januaripin
146,331,939
false
null
package id.yanuar.weather.util import android.support.annotation.LayoutRes import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * Created by <NAME> * <EMAIL> */ fun ViewGroup.inflate(@LayoutRes layoutRes: Int): View { return LayoutInflater.from(context).inflate(layoutRes, this, false) } fun <T> RecyclerView.Adapter<*>.autoNotify(old: List<T>, new: List<T>, compare: (T, T) -> Boolean) { val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return compare(old[oldItemPosition], new[newItemPosition]) } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return old[oldItemPosition] == new[newItemPosition] } override fun getOldListSize() = old.size override fun getNewListSize() = new.size }) diff.dispatchUpdatesTo(this) }
0
Kotlin
0
0
bebf7539c84a5ce9c063d7a4faa5a78e8f9c8c73
1,096
weather
MIT License
app/src/main/java/app/dphone/Compress.kt
arinyguedes
199,085,881
false
null
package app.dphone import java.io.ByteArrayOutputStream import java.nio.charset.StandardCharsets.UTF_8 import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream class Compress { fun gzip(content: String): ByteArray { val bos = ByteArrayOutputStream() GZIPOutputStream(bos).bufferedWriter(UTF_8).use { it.write(content) } return bos.toByteArray() } fun ungzip(content: ByteArray): String = GZIPInputStream(content.inputStream()).bufferedReader(UTF_8).use { it.readText() } }
1
Kotlin
5
26
ffc9c331bcf63ed08b255680c3ee9d35b1baebbb
537
dphone
MIT License
spring-boot/src/test/kotlin/dev/dcas/util/spring/responses/ResponsesTest.kt
djcass44
220,928,039
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package dev.dcas.util.spring.responses import dev.dcas.util.spring.test.BaseSpringBootTest import io.restassured.module.kotlin.extensions.Then import io.restassured.module.kotlin.extensions.When import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource class ResponsesTest: BaseSpringBootTest() { @ParameterizedTest @ValueSource(ints = [400, 401, 403, 404, 409, 429, 500]) fun `when error is thrown, correct status code is returned`(code: Int) { When { get("/$code") } Then { statusCode(code) } } }
0
Kotlin
0
0
30f06edb1a98dfb7bd740f85b211400726cd5395
1,191
castive-utilities
Apache License 2.0
bot/engine/src/main/kotlin/admin/story/StoryDefinitionConfiguration.kt
YazidDjaoudi
314,241,412
true
{"Kotlin": 4678640, "TypeScript": 786341, "HTML": 307983, "CSS": 166236, "SCSS": 26072, "JavaScript": 4807, "Shell": 4071}
/* * Copyright (C) 2017/2020 e-voyageurs technologies * * 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 ai.tock.bot.admin.story import ai.tock.bot.admin.answer.AnswerConfiguration import ai.tock.bot.admin.answer.AnswerConfigurationType import ai.tock.bot.admin.answer.AnswerConfigurationType.builtin import ai.tock.bot.admin.answer.BuiltInAnswerConfiguration import ai.tock.bot.admin.answer.DedicatedAnswerConfiguration import ai.tock.bot.admin.bot.BotApplicationConfigurationKey import ai.tock.bot.definition.BotDefinition import ai.tock.bot.definition.Intent import ai.tock.bot.definition.IntentWithoutNamespace import ai.tock.bot.definition.StoryDefinition import ai.tock.bot.definition.StoryTag import ai.tock.bot.engine.BotBus import ai.tock.bot.engine.BotRepository import ai.tock.shared.defaultNamespace import org.litote.kmongo.Id import org.litote.kmongo.newId import java.util.Locale /** * A [StoryDefinition] defined at runtime. */ data class StoryDefinitionConfiguration( /** * The story definition identifier. */ val storyId: String, /** * The bot identifier. */ val botId: String, /** * The target main intent. */ val intent: IntentWithoutNamespace, /** * The type of answer configuration. */ override val currentType: AnswerConfigurationType, /** * The answers available. */ override val answers: List<AnswerConfiguration>, /** * The version of the story. */ val version: Int = 0, /** * The namespace of the story. */ val namespace: String = defaultNamespace, /** * The mandatory entities. */ val mandatoryEntities: List<StoryDefinitionConfigurationMandatoryEntity> = emptyList(), /** * The optional steps. */ val steps: List<StoryDefinitionConfigurationStep> = emptyList(), /** * The name of the story. */ val name: String = storyId, /** * The category of the story. */ val category: String = "default", /** * The description of the story. */ val description: String = "", /** * The user sentence sample. */ val userSentence: String = "", /** * The user sentence sample locale. */ val userSentenceLocale: Locale? = null, /** * The configuration name if any. */ val configurationName: String? = null, /** * Current features. */ val features: List<StoryDefinitionConfigurationFeature> = emptyList(), /** * The configuration identifier. */ val _id: Id<StoryDefinitionConfiguration> = newId(), /** * The story definition tags that specify different story types or roles. */ val tags: List<StoryTag> = emptyList(), /** * Answers by bot application configuration */ val configuredAnswers: List<DedicatedAnswerConfiguration> = emptyList(), /** * Steps by bot application configuration */ val configuredSteps: List<StoryDefinitionConfigurationByBotStep> = emptyList() ) : StoryDefinitionAnswersContainer { constructor(botDefinition: BotDefinition, storyDefinition: StoryDefinition, configurationName: String?) : this( storyId = storyDefinition.id, tags = storyDefinition.tags, botId = botDefinition.botId, intent = storyDefinition.mainIntent().intentWithoutNamespace(), currentType = builtin, answers = listOf(BuiltInAnswerConfiguration(storyDefinition.javaClass.kotlin.qualifiedName)), namespace = botDefinition.namespace, configurationName = configurationName, steps = storyDefinition.steps.map { StoryDefinitionConfigurationStep(it) } ) override fun findNextSteps(bus: BotBus, story: StoryDefinitionConfiguration): List<CharSequence> = findSteps(BotApplicationConfigurationKey(bus)).map { it.userSentenceLabel ?: it.userSentence } internal fun findSteps(key: BotApplicationConfigurationKey?): List<StoryDefinitionConfigurationStep> = (key?.let { val configurationName = BotRepository.getConfigurationByApplicationId(key)?.name configuredSteps.firstOrNull { it.botConfiguration == configurationName }?.steps } ?: steps) private fun findFeatures(applicationId: String?): List<StoryDefinitionConfigurationFeature> = when { features.isEmpty() -> emptyList() applicationId == null -> features.filter { it.botApplicationConfigurationId == null } else -> { val app = BotRepository.getConfigurationByApplicationId( BotApplicationConfigurationKey( applicationId = applicationId, namespace = namespace, botId = botId ) ) features.filter { it.supportConfiguration(app) } } } internal fun isDisabled(applicationId: String?): Boolean = findFeatures(applicationId).let { when { it.isEmpty() -> false else -> it.any { f -> f.switchToStoryId == null && !f.enabled } } } internal fun findEnabledStorySwitchId(applicationId: String?): String? { val features = findEnabledFeatures(applicationId) val app = applicationId?.let { BotRepository.getConfigurationByApplicationId( BotApplicationConfigurationKey( applicationId = applicationId, namespace = namespace, botId = botId ) ) } //search first for dedicated features if (app != null) { val conf = features.find { it.switchToStoryId != null && it.supportDedicatedConfiguration(app) } if (conf != null) { return conf.switchToStoryId } } return features.find { it.switchToStoryId != null }?.switchToStoryId } private fun findEnabledFeatures(applicationId: String?): List<StoryDefinitionConfigurationFeature> = findFeatures(applicationId).filter { it.enabled } @Transient internal val mainIntent: Intent = intent.intent(namespace) }
0
null
0
1
ac3dd89bb072c8046f921a9319dabc72f7227a77
6,868
tock
Apache License 2.0
api/library/kotlin-simple-api-annotation/src/commonMain/kotlin/kim/jeonghyeon/annotation/ApiParameterType.kt
dss99911
138,060,985
false
{"Kotlin": 356216, "Swift": 24520, "Ruby": 6567, "Shell": 4020}
package kim.jeonghyeon.annotation public enum class ApiParameterType { HEADER, QUERY, PATH, BODY, NONE }
0
Kotlin
2
38
e9da57fdab9c9c1169fab422fac7432143e2c02c
109
kotlin-simple-architecture
Apache License 2.0
src/main/kotlin/com/cpsc471/tms/data/repository/users/User.kt
Sonicskater
227,043,523
false
null
package com.cpsc471.tms.data.repository.users import com.cpsc471.tms.RepoHelper import com.cpsc471.tms.data.annotations.Display import com.cpsc471.tms.data.annotations.DisplayCategory import com.cpsc471.tms.data.annotations.DisplayTypeClasif import com.cpsc471.tms.data.repository.DBAbstract import com.cpsc471.tms.data.repository.DBKey import com.cpsc471.tms.data.repository.userContactInfos.UserContactInfo import com.vaadin.flow.component.UI import com.vaadin.flow.data.binder.ValidationResult import com.vaadin.flow.data.binder.Validator import org.springframework.data.repository.CrudRepository import java.io.Serializable import javax.persistence.* @Entity @Table(name = "user") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="type", discriminatorType = DiscriminatorType.INTEGER) @DiscriminatorValue("0") open class User: DBAbstract(), Serializable { override fun view(ui: UI) { ui.navigate("/users") } @Display open var firstName: String? =null @Display open var lastName: String? =null @Display(DisplayTypeClasif.COMPOSITE) @EmbeddedId var userKey: UserKey = UserKey() @Display(category = DisplayCategory.VERBOSE) open var country: String? = null @Display(category = DisplayCategory.VERBOSE) open var province: String? = null @Display open var city: String? = null @Display(category = DisplayCategory.VERBOSE) open var streetAddress: String? = null @Display(category = DisplayCategory.VERBOSE) open var postalCode: String? = null /** @ManyToMany(targetEntity = DateRecord::class) @JoinTable(name = "is_available", joinColumns = [JoinColumn(name = "Email")], inverseJoinColumns = [ JoinColumn(name = "Month"), JoinColumn(name = "Year"), JoinColumn(name = "Number") ]) var available_days: List<DateRecord>, */ open var password: String? = null @Display(DisplayTypeClasif.LIST, type = UserContactInfo::class) @OneToMany(targetEntity = UserContactInfo::class, mappedBy = "userContactInfoKey.user") open var contactInfo: MutableList<UserContactInfo> = mutableListOf() override fun delete() { RepoHelper.userRepository.deleteById(this.userKey) } override fun <T> validator(clazz: Class<T>, creation: Boolean): Validator<in T>? { return Validator { user, _ -> val user1 = user as User when{ RepoHelper.userRepository.existsById(user1.userKey) -> ValidationResult.error("Exists as unassigned") RepoHelper.artistRepository.existsById(user1.userKey) -> ValidationResult.error("Exists as artist") RepoHelper.managerRepository.existsById(user1.userKey) -> ValidationResult.error("Exists as manager") else -> ValidationResult.ok() } } } override fun <T, ID> repo(classT: Class<T>, classID: Class<ID>): CrudRepository<T, ID> { return RepoHelper.userRepository as CrudRepository<T, ID> } override fun keyType(): Class<out DBKey> { return userKey::class.java } override fun iDforDb(): List<Any> { return(listOf(userKey)) } }
3
Kotlin
0
1
c9926be8054eb597178d62ab4a2442baca1a33fd
3,202
vaadin-kotlin-CRUD
The Unlicense
app/src/main/java/com/zonkey/simplemealplanner/di/FirebaseBindingDaggerModule.kt
NickalasB
166,567,754
false
null
package com.zonkey.simplemealplanner.di import com.firebase.ui.auth.AuthUI import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.zonkey.simplemealplanner.firebase.DefaultFirebaseAuthRepository import com.zonkey.simplemealplanner.firebase.DefaultFirebaseInstanceIdRepository import com.zonkey.simplemealplanner.firebase.DefaultFirebaseRecipeRepository import com.zonkey.simplemealplanner.firebase.FirebaseAuthRepository import com.zonkey.simplemealplanner.firebase.FirebaseInstanceIdRepository import com.zonkey.simplemealplanner.firebase.FirebaseRecipeRepository import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class FirebaseBindingDaggerModule { @Provides @Singleton fun providesFirebaseDatabase(): FirebaseDatabase = FirebaseDatabase.getInstance() @Provides @Singleton fun providesFirebaseInstanceRepository() : FirebaseInstanceIdRepository = DefaultFirebaseInstanceIdRepository() @Provides @Singleton fun provideFirebaseRecipeRepository( firebaseInstance: FirebaseDatabase, firebaseAuthRepo: FirebaseAuthRepository, firebaseInstanceIdRepository: FirebaseInstanceIdRepository): FirebaseRecipeRepository = DefaultFirebaseRecipeRepository(firebaseInstance, firebaseAuthRepo, firebaseInstanceIdRepository) @Provides @Singleton fun providesFirebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance() @Provides @Singleton fun providesFirebaseAuthUi() = AuthUI.getInstance() @Provides @Singleton fun provideFirebaseAuthRepository(authUi: AuthUI, firebaseAuth: FirebaseAuth) : FirebaseAuthRepository = DefaultFirebaseAuthRepository(authUi, firebaseAuth) }
11
Kotlin
0
0
43a059e07b0f5170f59a8223a85d62b2fdd53d06
1,713
SimpleMealPlanner
MIT License
app/src/main/java/com/yuriisurzhykov/pointdetector/presentation/points/create/PointCreationResultFragment.kt
yuriisurzhykov
524,002,724
false
{"Kotlin": 270404, "Java": 1165}
package com.yuriisurzhykov.pointdetector.presentation.points.create import com.yuriisurzhykov.pointdetector.R import com.yuriisurzhykov.pointdetector.presentation.core.AbstractStyleFragment import java.util.* import kotlin.concurrent.timerTask class PointCreationResultFragment : AbstractStyleFragment(R.layout.fragment_point_creation_result) { override fun onStart() { super.onStart() scheduleClosing(2000) } private fun scheduleClosing(scheduleTime: Long) { Timer().schedule(timerTask { openMainFragment() }, scheduleTime) } }
1
Kotlin
0
2
b0882a4a7f80705cff8432b3c0a2155c4650fe67
572
PointDetector
MIT License
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/filled/AspectRatio.kt
wiryadev
380,639,096
false
{"Kotlin": 4825599}
package com.wiryadev.bootstrapiconscompose.bootstrapicons.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.wiryadev.bootstrapiconscompose.bootstrapicons.FilledGroup public val FilledGroup.AspectRatio: ImageVector get() { if (_aspectRatio != null) { return _aspectRatio!! } _aspectRatio = Builder(name = "AspectRatio", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(0.0f, 12.5f) verticalLineToRelative(-9.0f) arcTo(1.5f, 1.5f, 0.0f, false, true, 1.5f, 2.0f) horizontalLineToRelative(13.0f) arcTo(1.5f, 1.5f, 0.0f, false, true, 16.0f, 3.5f) verticalLineToRelative(9.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, -1.5f, 1.5f) horizontalLineToRelative(-13.0f) arcTo(1.5f, 1.5f, 0.0f, false, true, 0.0f, 12.5f) close() moveTo(2.5f, 4.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.5f, 0.5f) verticalLineToRelative(3.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 1.0f, 0.0f) lineTo(3.0f, 5.0f) horizontalLineToRelative(2.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f) horizontalLineToRelative(-3.0f) close() moveTo(13.5f, 12.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.5f, -0.5f) verticalLineToRelative(-3.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -1.0f, 0.0f) lineTo(13.0f, 11.0f) horizontalLineToRelative(-2.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 1.0f) horizontalLineToRelative(3.0f) close() } } .build() return _aspectRatio!! } private var _aspectRatio: ImageVector? = null
0
Kotlin
0
2
1c199d953dc96b261aab16ac230dc7f01fb14a53
2,724
bootstrap-icons-compose
MIT License
app/src/main/kotlin/jp/co/yumemi/android/codeCheck/data/repository/GitHubApiStargazersRepositoryImpl.kt
hirotask
614,928,997
false
null
package jp.co.yumemi.android.codeCheck.data.repository import jp.co.yumemi.android.codeCheck.domain.Stargazer import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject class GitHubApiStargazersRepositoryImpl @Inject constructor() : GitHubApiStargazersRepository { private val mutableItemState = MutableStateFlow<List<Stargazer>>(emptyList()) override fun observe(): StateFlow<List<Stargazer>> { return mutableItemState.asStateFlow() } override suspend fun update(list: List<Stargazer>) { mutableItemState.emit(list) } }
0
Kotlin
0
0
de4b427c84b650492eb903714a2fb4d582eaadb7
662
android-engineer-codecheck
Apache License 2.0
src/commonMain/kotlin/app/thelema/phys/IBodyContact.kt
zeganstyl
275,550,896
false
null
/* * Copyright 2020-2021 <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 app.thelema.phys import app.thelema.math.IVec3 /** @author zeganstyl */ interface IBodyContact { val body1: IRigidBody val body2: IRigidBody val position: IVec3 val normal: IVec3 val depth: Float }
3
Kotlin
5
61
8e2943b6d2de3376ce338025b58ff31c14097caf
831
thelema-engine
Apache License 2.0
app/src/main/kotlin/me/sweetll/tucao/model/raw/Bangumi.kt
blackbbc
78,953,199
false
null
package me.sweetll.tucao.model.raw import me.sweetll.tucao.model.json.Video import me.sweetll.tucao.model.json.Channel data class Bangumi(val banners: List<Banner>, val recommends: List<Pair<Channel,List<Video>>>)
13
Java
209
1,014
cdae0b953c3fe61c463783de6339e1bea2298fe7
235
Tucao
MIT License
app/src/main/java/com/sinthoras/randograf/cardviews/CardCoverView.kt
SinTh0r4s
444,149,281
false
{"Java": 18033, "Kotlin": 17451}
package com.sinthoras.randograf.cardviews import android.view.View import android.widget.ImageView import android.widget.TextView import com.sinthoras.randograf.R import com.sinthoras.randograf.cards.covers.CardCover class CardCoverView : CardView(R.layout.fragment_card_cover) { override fun onResume() { super.onResume() view?.findViewById<ImageView>(R.id.ruinIcon)?.visibility = if(getCard<CardCover>().getDrawWithRuin()) View.VISIBLE else View.GONE view?.findViewById<TextView>(R.id.textNewSeason)?.setText(getCard<CardCover>().getTitle()) } }
1
Java
0
0
5319ccb2ebbb9e90f957a065794ad5aebff20459
583
Randograf
MIT License
src/main/java/com/anyascii/build/gen/Php.kt
nghiepdev
401,247,056
true
{"Kotlin": 50573, "Java": 10682, "Rust": 6817, "C": 4877, "C#": 4505, "Python": 4145, "Shell": 3859, "Ruby": 3511, "PHP": 3401, "Julia": 3385, "Go": 3254, "JavaScript": 3173, "Perl": 378}
package com.anyascii.build.gen import java.nio.file.Files import java.nio.file.Path fun php(g: Generator) { val dirPath = Path.of("impl/php/_data") dirPath.toFile().deleteRecursively() Files.createDirectories(dirPath) for ((blockNum, block) in g.blocks) { Files.newBufferedWriter(dirPath.resolve("_%03x.php".format(blockNum))).use { w -> val s = block.noAscii().joinToString("\t").replace("\\", "\\\\").replace("'", "\\'") w.write("<?php return explode('\t','$s');") } } }
0
Kotlin
0
1
7b579df65aa5e81227df0410183c5408962a9b7c
535
anyascii
ISC License
ide-common/src/main/kotlin/org/digma/intellij/plugin/notifications/NoInsightsYetNotification.kt
digma-ai
472,408,329
false
{"Kotlin": 1315823, "Java": 697153, "C#": 114216, "FreeMarker": 13319, "HTML": 13271, "Shell": 6494}
package org.digma.intellij.plugin.notifications import com.intellij.collaboration.async.disposingScope import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.digma.intellij.plugin.PluginId import org.digma.intellij.plugin.common.findActiveProject import org.digma.intellij.plugin.log.Log import org.digma.intellij.plugin.persistence.PersistenceService import org.digma.intellij.plugin.posthog.ActivityMonitor import java.time.Instant import java.time.temporal.ChronoUnit const val STICKY_REMINDERS_NOTIFICATION_GROUP = "Digma sticky Reminders Group" const val FADING_REMINDERS_NOTIFICATION_GROUP = "Digma fading Reminders Group" fun startNoInsightsYetNotificationTimer(parentDisposable: Disposable) { if (service<PersistenceService>().isFirstTimeInsightReceived()) { return } @Suppress("UnstableApiUsage") parentDisposable.disposingScope().launch { Log.log(AppNotificationCenter.logger::info, "Starting tNoInsightsYetNotificationTimer") var firstConnectionTime = service<PersistenceService>().getFirstTimeConnectionEstablishedTimestamp() while (firstConnectionTime == null) { delay(60000) firstConnectionTime = service<PersistenceService>().getFirstTimeConnectionEstablishedTimestamp() } Log.log(AppNotificationCenter.logger::info, "in NoInsightsYetNotificationTimer, got firstConnectionTime {}", firstConnectionTime) val after30Minutes = firstConnectionTime.plus(30, ChronoUnit.MINUTES) Log.log( AppNotificationCenter.logger::info, "in NoInsightsYetNotificationTimer, waiting 30 minutes after firstConnectionTime {}", firstConnectionTime ) while (Instant.now().isBefore(after30Minutes)) { delay(60000) } if (!service<PersistenceService>().isFirstTimeInsightReceived()) { Log.log(AppNotificationCenter.logger::info, "in NoInsightsYetNotificationTimer, showing notification") showNoInsightsYetNotification() } else { Log.log( AppNotificationCenter.logger::info, "in NoInsightsYetNotificationTimer, not showing notification because firstTimeInsightReceived is true" ) } } } private fun showNoInsightsYetNotification() { //if a project was not found there is no notification findActiveProject()?.let { project -> ActivityMonitor.getInstance(project).registerNotificationCenterEvent("Show.NoInsightsYetNotification", mapOf()) val notification = NotificationGroupManager.getInstance().getNotificationGroup(STICKY_REMINDERS_NOTIFICATION_GROUP) .createNotification("We noticed Digma hasn't received any data yet, do you need help with setup?", NotificationType.INFORMATION) notification.addAction(ShowTroubleshootingAction(project, notification, "NoInsightsYetNotification")) notification.whenExpired { Log.log(AppNotificationCenter.logger::info, "in NoInsightsYetNotification, notification expired") service<PersistenceService>().setNoInsightsYetNotificationPassed() } notification.setImportant(true) notification.setToolWindowId(PluginId.TOOL_WINDOW_ID) notification.notify(project) } }
390
Kotlin
6
17
55a318082a8f8b8d3a1de7d50e83af12d1ef1657
3,519
digma-intellij-plugin
MIT License
app/src/main/java/com/luksiv/entdiffy/MainActivity.kt
luksiv
313,904,223
false
null
package com.luksiv.entdiffy import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.luksiv.entdiffy.entities.Person import com.luksiv.entdiffy.entities.PersonDiffUtil import com.luksiv.entdiffy.entities.PersonDiffUtilExtensions.calculateDiff class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val person_1 = Person("Lukas", "Sivickas", "Vilnius", "Lithuania", "22") val person_2 = Person("Edgar", "Zigis", "Kaunas", "Poland", "30") val result = PersonDiffUtil.calculateDiff(person_1, person_2) println(result) } } fun main() { val person_1 = Person("Lukas", "Sivickas", "Vilnius", "Lithuania", "22") val person_2 = Person("Edgar", "Zigis", "Vilnius", "Lithuania", "30") val cachedPerson = null val result = PersonDiffUtil.calculateDiff(person_1, person_2) println(result) val result_b = PersonDiffUtil.calculateDiff(person_1, cachedPerson) println(result_b) println(person_1.calculateDiff(cachedPerson)) }
0
Kotlin
0
1
bd12c9d6a5f3318887b946a93e58baa844d8c7fd
1,149
entdiffy
MIT License
compiler/testData/codegen/bytecodeListing/annotations/literals.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
@Target(AnnotationTarget.CLASS) annotation class ClsAnn @Target(AnnotationTarget.FUNCTION) annotation class FunAnn @Target(AnnotationTarget.EXPRESSION) @Retention(AnnotationRetention.SOURCE) annotation class ExprAnn fun bar(arg: () -> Int) = arg() open class My fun foo(arg: Int): My { bar @FunAnn { arg } bar @ExprAnn { arg } val x = @FunAnn fun() = arg return (@ClsAnn object: My() {}) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
410
kotlin
Apache License 2.0
src/main/kotlin/com/kneelawk/packvulcan/ui/theme/PackVulcanIcons.kt
Kneelawk
464,289,102
false
{"Kotlin": 540809}
package com.kneelawk.packvulcan.ui.theme import androidx.compose.ui.res.loadSvgPainter import androidx.compose.ui.unit.Density import java.io.InputStream object PackVulcanIcons { private val loader = PackVulcanIcons.javaClass.classLoader private fun InputStream?.orError(resourceName: String): InputStream { if (this == null) { throw IllegalStateException("Unable to load $resourceName icon") } else { return this } } val bolt = loader.getResourceAsStream("bolt_black_24dp.svg").orError("bolt") .use { loadSvgPainter(it, Density(1f)) } val bug = loader.getResourceAsStream("bug_report_black_24dp.svg").orError("bug") .use { loadSvgPainter(it, Density(1f)) } val codeBox = loader.getResourceAsStream("integration_instructions_black_24dp.svg").orError("codeBox") .use { loadSvgPainter(it, Density(1f)) } val construction = loader.getResourceAsStream("construction_black_24dp.svg").orError("construction") .use { loadSvgPainter(it, Density(1f)) } val createNewFolder = loader.getResourceAsStream("create_new_folder_black_24dp.svg").orError("createNewFolder") .use { loadSvgPainter(it, Density(1f)) } val desktop = loader.getResourceAsStream("desktop_mac_black_24dp.svg").orError("desktop") .use { loadSvgPainter(it, Density(1f)) } val download = loader.getResourceAsStream("download_black_24dp.svg").orError("download") .use { loadSvgPainter(it, Density(1f)) } val compass = loader.getResourceAsStream("explore_black_24dp.svg").orError("compass") .use { loadSvgPainter(it, Density(1f)) } val error = loader.getResourceAsStream("error_black_24dp.svg").orError("error") .use { loadSvgPainter(it, Density(1f)) } val fancySuitcase = loader.getResourceAsStream("business_center_black_24dp.svg").orError("fancySuitcase") .use { loadSvgPainter(it, Density(1f)) } val file = loader.getResourceAsStream("description_black_24dp.svg").orError("file") .use { loadSvgPainter(it, Density(1f)) } val flame = loader.getResourceAsStream("local_fire_department_black_24dp.svg").orError("flame") .use { loadSvgPainter(it, Density(1f)) } val folder = loader.getResourceAsStream("folder_black_24dp.svg").orError("folder") .use { loadSvgPainter(it, Density(1f)) } val forum = loader.getResourceAsStream("forum_black_24dp.svg").orError("forum") .use { loadSvgPainter(it, Density(1f)) } val house = loader.getResourceAsStream("house_black_24dp.svg").orError("house") .use { loadSvgPainter(it, Density(1f)) } val image = loader.getResourceAsStream("image_black_24dp.svg").orError("image") .use { loadSvgPainter(it, Density(1f)) } val inventory = loader.getResourceAsStream("inventory_black_24dp.svg").orError("inventory") .use { loadSvgPainter(it, Density(1f)) } val laptop = loader.getResourceAsStream("laptop_black_24dp.svg").orError("laptop") .use { loadSvgPainter(it, Density(1f)) } val microscope = loader.getResourceAsStream("biotech_black_24dp.svg").orError("microscope") .use { loadSvgPainter(it, Density(1f)) } val modrinth = loader.getResourceAsStream("modrinth_icon_24dp.svg").orError("modrinth") .use { loadSvgPainter(it, Density(1f)) } val movie = loader.getResourceAsStream("movie_black_24dp.svg").orError("movie") .use { loadSvgPainter(it, Density(1f)) } val music = loader.getResourceAsStream("music_note_black_24dp.svg").orError("music") .use { loadSvgPainter(it, Density(1f)) } val noImage = loader.getResourceAsStream("no_photography_black_24dp.svg").orError("noImage") .use { loadSvgPainter(it, Density(1f)) } val public = loader.getResourceAsStream("public_black_24dp.svg").orError("public") .use { loadSvgPainter(it, Density(1f)) } val restaurant = loader.getResourceAsStream("restaurant_black_24dp.svg").orError("restaurant") .use { loadSvgPainter(it, Density(1f)) } val save = loader.getResourceAsStream("save_black_24dp.svg").orError("save") .use { loadSvgPainter(it, Density(1f)) } val shield = loader.getResourceAsStream("shield_black_24dp.svg").orError("shield") .use { loadSvgPainter(it, Density(1f)) } val shipping = loader.getResourceAsStream("local_shipping_black_24dp.svg").orError("shipping") .use { loadSvgPainter(it, Density(1f)) } val storage = loader.getResourceAsStream("storage_black_24dp.svg").orError("storage") .use { loadSvgPainter(it, Density(1f)) } val trophy = loader.getResourceAsStream("emoji_events_black_24dp.svg").orError("trophy") .use { loadSvgPainter(it, Density(1f)) } val fabric = loader.getResourceAsStream("fabric_smooth_filled_24dp.svg").orError("fabric") .use { loadSvgPainter(it, Density(1f)) } val forge = loader.getResourceAsStream("conda_forge_filled_24dp.svg").orError("forge") .use { loadSvgPainter(it, Density(1f)) } val quilt = loader.getResourceAsStream("quilt_logo_mono_black_transparent_24dp.svg").orError("quilt") .use { loadSvgPainter(it, Density(1f)) } }
0
Kotlin
0
4
7e296751d8bb2a939b4d2aa51a44884b4a62233d
5,162
PackVulcan
MIT License
agp-7.1.0-alpha01/tools/base/wizard/template-impl/src/com/android/tools/idea/wizard/template/impl/fragments/settingsFragment/settingsFragmentRecipe.kt
jomof
374,736,765
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.wizard.template.impl.fragments.settingsFragment import com.android.tools.idea.wizard.template.Language import com.android.tools.idea.wizard.template.ModuleTemplateData import com.android.tools.idea.wizard.template.RecipeExecutor import com.android.tools.idea.wizard.template.impl.activities.common.addAllKotlinDependencies import com.android.tools.idea.wizard.template.impl.fragments.settingsFragment.res.values.arraysXml import com.android.tools.idea.wizard.template.impl.fragments.settingsFragment.res.values.stringsXml import com.android.tools.idea.wizard.template.impl.fragments.settingsFragment.res.xml.rootPreferencesXml import com.android.tools.idea.wizard.template.impl.fragments.settingsFragment.src.app_package.singleScreenSettingsFragmentJava import com.android.tools.idea.wizard.template.impl.fragments.settingsFragment.src.app_package.singleScreenSettingsFragmentKt fun RecipeExecutor.settingsFragmentRecipe( moduleData: ModuleTemplateData, fragmentClass: String, packageName: String ) { val (projectData, srcOut, resOut, _) = moduleData val ktOrJavaExt = projectData.language.extension addAllKotlinDependencies(moduleData) addDependency(mavenCoordinate = "androidx.preference:preference:+", minRev = "1.1+") mergeXml(stringsXml(), resOut.resolve("values/strings.xml")) mergeXml(arraysXml(), resOut.resolve("values/arrays.xml")) mergeXml(rootPreferencesXml(), resOut.resolve("xml/root_preferences.xml")) val singleScreenSettingsFragment = when (projectData.language) { Language.Java -> singleScreenSettingsFragmentJava(fragmentClass, packageName) Language.Kotlin -> singleScreenSettingsFragmentKt(fragmentClass, packageName) } save(singleScreenSettingsFragment, srcOut.resolve("${fragmentClass}.${ktOrJavaExt}")) open(srcOut.resolve("${fragmentClass}.${ktOrJavaExt}")) }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
2,478
CppBuildCacheWorkInProgress
Apache License 2.0
app/src/main/java/ir/beigirad/zeroapplication/bases/BaseFragment.kt
beigirad
172,877,353
false
null
package ir.beigirad.zeroapplication.bases import android.app.ProgressDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import ir.beigirad.nearly.R /** * Created by farhad-mbp on 9/12/17. */ abstract class BaseFragment : Fragment(),HasToolbar { override val toolbar: Toolbar? get() = null override val toolbarTitle: Int? get() = null override val toolbarTitleS: String? get() = null override val toolbarLogo: Int? get() = null protected abstract val childView: Int private lateinit var progressDialog: ProgressDialog override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(childView, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initToolbar() initUI() } protected open fun initUI() {} override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initVariables() } protected open fun initVariables() { progressDialog = ProgressDialog(context) } override fun onDetach() { progressDialog.dismiss() super.onDetach() } protected open fun showProgress(message: String = getString(R.string.please_wait)) { progressDialog.setMessage(message) progressDialog.show() } protected open fun hideProgress() { progressDialog.hide() } }
0
Kotlin
0
1
1d090452cbe6b45cc66f200d6bd386e3dc9b693a
1,719
Nearly
MIT License
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/targets/js/KotlinJsTargets.kt
android
263,405,600
true
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.targets.js import org.jetbrains.kotlin.gradle.plugin.KotlinJsCompilerType import org.jetbrains.kotlin.gradle.targets.js.dsl.KotlinJsTargetDsl import org.jetbrains.kotlin.gradle.targets.js.ir.KotlinJsIrTarget fun KotlinJsTargetDsl.calculateJsCompilerType(): KotlinJsCompilerType { return when { this is KotlinJsTarget && this.irTarget == null -> KotlinJsCompilerType.LEGACY this is KotlinJsIrTarget && !this.mixedMode -> KotlinJsCompilerType.IR this is KotlinJsTarget && this.irTarget != null -> KotlinJsCompilerType.BOTH else -> throw IllegalStateException("Unable to find previous Kotlin/JS compiler type for $this") } }
34
Kotlin
49
316
74126637a097f5e6b099a7b7a4263468ecfda144
909
kotlin
Apache License 2.0
src/main/kotlin/io/github/markgregg/common/protocol/EndTestResponse.kt
markgregg
565,567,948
false
{"Kotlin": 35072}
package io.github.markgregg.common.protocol class EndTestResponse( success: Boolean, message: String? ) : Response(success, message)
0
Kotlin
0
0
66fc5d6c7e659e696674727bac87bfb2ac9029e6
141
adaptable-common
Apache License 2.0