path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/ru/mobileup/integrationhms/MainActivity.kt | MobileUpLLC | 495,305,519 | false | {"Kotlin": 82696} | package ru.mobileup.integrationhms
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.arkivanov.decompose.defaultComponentContext
import ru.mobileup.core.ComponentFactory
import ru.mobileup.core.koin
import ru.mobileup.features.root.ui.RootUi
import ru.mobileup.core.theme.AppTheme
import ru.mobileup.features.notification.data.DeeplinkParser
import ru.mobileup.features.root.createRootComponent
import ru.mobileup.features.root.ui.RootComponent
class MainActivity : ComponentActivity() {
private lateinit var rootComponent: RootComponent
private lateinit var deeplinkParser: DeeplinkParser
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val deeplink = deeplinkParser.getDeeplink(intent)
deeplink?.let { rootComponent.onDeepLink(it) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val componentFactory = application.koin.get<ComponentFactory>()
rootComponent = componentFactory.createRootComponent(defaultComponentContext())
deeplinkParser = application.koin.get()
val deeplink = deeplinkParser.getDeeplink(intent)
deeplink?.let { rootComponent.onDeepLink(it) }
setContent {
AppTheme {
RootUi(rootComponent)
}
}
}
} | 0 | Kotlin | 1 | 3 | 4f486b7a96775d262e8cd179ef70d7f0e2531f0b | 1,444 | Push-Notifications-Android | MIT License |
app/src/main/java/com/example/bankuish_technical_challenge/core/application/BankuishTechnicalChallengeApp.kt | MJackson22-bit | 842,190,889 | false | {"Kotlin": 68012} | package com.example.bankuish_technical_challenge.core.application
import android.app.Application
import com.example.bankuish_technical_challenge.core.koinModules
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.core.logger.Level
class BankuishTechnicalChallengeApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger(Level.DEBUG)
androidContext(this@BankuishTechnicalChallengeApp)
modules(koinModules)
}
}
override fun onTerminate() {
super.onTerminate()
stopKoin()
}
} | 0 | Kotlin | 0 | 0 | faf1fbd0483ade4fa9bddbd1de7e7e5e20231c44 | 738 | bankuish-technical-challenge | MIT License |
app/src/main/java/com/matiasmandelbaum/alejandriaapp/common/auth/AuthManager.kt | mandelbaummatias | 696,924,886 | false | {"Kotlin": 218948} | package com.matiasmandelbaum.alejandriaapp.common.auth
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
object AuthManager {
private val auth = FirebaseAuth.getInstance()
private val _authStateLiveData = MutableLiveData<FirebaseUser?>()
val authStateLiveData: LiveData<FirebaseUser?> = _authStateLiveData
init {
auth.addAuthStateListener { firebaseAuth ->
_authStateLiveData.value = firebaseAuth.currentUser
}
}
fun signOut() {
auth.signOut()
_authStateLiveData.postValue(null)
}
fun getCurrentUser(): FirebaseUser? {
return auth.currentUser
}
}
| 0 | Kotlin | 0 | 0 | 82f90a11529a20489e8beb1dfa7a0d958874c6e8 | 765 | AlejandriaApp | Apache License 2.0 |
buildSrc/src/main/kotlin/korlibs/korge/gradle/targets/jvm/KorgeJavaExec.kt | korlibs | 80,095,683 | false | {"Kotlin": 3929805, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "Batchfile": 41, "CSS": 33} | package korlibs.korge.gradle.targets.jvm
import korlibs.korge.gradle.*
import korlibs.korge.gradle.targets.*
import org.gradle.api.*
import org.gradle.api.artifacts.*
import org.gradle.api.file.*
import org.gradle.api.tasks.*
import org.gradle.jvm.tasks.*
import java.io.*
fun Project.findAllProjectDependencies(visited: MutableSet<Project> = mutableSetOf()): Set<Project> {
if (this in visited) return visited
visited.add(this)
val dependencies = project.configurations.flatMap { it.dependencies.withType(ProjectDependency::class.java) }.filterIsInstance<ProjectDependency>()
return (dependencies.flatMap { it.dependencyProject.findAllProjectDependencies(visited) } + this).toSet()
}
open class KorgeJavaExecWithAutoreload : KorgeJavaExec() {
@get:Input
var enableRedefinition: Boolean = false
@get:Input
var doConfigurationCache: Boolean = true
companion object {
const val ARGS_SEPARATOR = "<:/:>"
const val CMD_SEPARATOR = "<@/@>"
}
private lateinit var projectPaths: List<String>
private var rootDir: File = project.rootProject.rootDir
@get:InputFiles
lateinit var rootJars: List<File>
//@get:InputFile
//private var reloadAgentConfiguration: Configuration = project.configurations.getByName(KORGE_RELOAD_AGENT_CONFIGURATION_NAME)//.resolve().first()
//lateinit var reloadAgentJar: File
init {
//val reloadAgent = project.findProject(":korge-reload-agent")
//if (reloadAgent != null)
//project.dependencies.add()
/*
project.afterEvaluate {
project.afterEvaluate {
project.afterEvaluate {
//project.configurations.getByName("compile")
//println("*****" + project.findAllProjectDependencies())
val allProjects = project.findAllProjectDependencies()
val allProjectsWithCompileKotinJvm = allProjects.filter { it.tasks.findByName("compileKotlinJvm") != null }
projectPaths = allProjectsWithCompileKotinJvm.map { it.path }
rootJars = allProjectsWithCompileKotinJvm
.mapNotNull { (it.tasks.findByName("compileKotlinJvm") as? org.jetbrains.kotlin.gradle.tasks.KotlinCompile?)?.outputs?.files }
.reduce { a, b -> a + b }
println("allProjects=${allProjects.map { it.name }}")
println("allProjectsWithCompileKotinJvm=${allProjectsWithCompileKotinJvm.map { it.name }}")
println("rootJars=\n${rootJars.toList().joinToString("\n")}")
//println("::::" + project.configurations.toList())
}
}
}
*/
val reloadAgent = project.findProject(":korge-reload-agent")
val reloadAgentJar = when {
reloadAgent != null -> (project.rootProject.tasks.getByPath(":korge-reload-agent:jar") as Jar).outputs.files.files.first()
else -> project.configurations.getByName(KORGE_RELOAD_AGENT_CONFIGURATION_NAME).resolve().first()
}
project.afterEvaluate {
val allProjects = project.findAllProjectDependencies()
//projectPaths = allProjects.map { it.path }
projectPaths = listOf(project.path)
rootJars = allProjects.map { File(it.buildDir, "classes/kotlin/jvm/main") }
//println("allProjects=${allProjects.map { it.name }}")
//println("projectPaths=$projectPaths")
//println("rootJars=\n${rootJars.toList().joinToString("\n")}")
//println("runJvmAutoreload:reloadAgentJar=$reloadAgentJar")
//val outputJar = JvmTools.findPathJar(Class.forName("korlibs.korge.reloadagent.KorgeReloadAgent"))
//val agentJarTask: org.gradle.api.tasks.bundling.Jar = project(":korge-reload-agent").tasks.findByName("jar") as org.gradle.api.tasks.bundling.Jar
//val outputJar = agentJarTask.outputs.files.files.first()
//println("agentJarTask=$outputJar")
jvmArgs(
"-javaagent:$reloadAgentJar=${listOf(
"$httpPort",
ArrayList<String>().apply {
add("-classpath")
add("${rootDir}/gradle/wrapper/gradle-wrapper.jar")
add("org.gradle.wrapper.GradleWrapperMain")
//add("--no-daemon") // This causes: Continuous build does not work when file system watching is disabled
add("--watch-fs")
add("--warn")
add("--project-dir=${rootDir}")
if (doConfigurationCache) {
add("--configuration-cache")
add("--configuration-cache-problems=warn")
}
add("-t")
add("compileKotlinJvm")
//add("compileKotlinJvmAndNotify")
for (projectPath in projectPaths) {
add("${projectPath.trimEnd(':')}:compileKotlinJvmAndNotify")
}
}.joinToString(CMD_SEPARATOR),
"$enableRedefinition",
rootJars.joinToString(CMD_SEPARATOR) { it.absolutePath }
).joinToString(ARGS_SEPARATOR)}"
)
environment("KORGE_AUTORELOAD", "true")
}
}
}
fun Project.getKorgeClassPath(): FileCollection {
return ArrayList<FileCollection>().apply {
val mainJvmCompilation = project.mainJvmCompilation
add(mainJvmCompilation.runtimeDependencyFiles)
add(mainJvmCompilation.compileDependencyFiles)
//if (project.korge.searchResourceProcessorsInMainSourceSet) {
add(mainJvmCompilation.output.allOutputs)
add(mainJvmCompilation.output.classesDirs)
//}
//project.kotlin.jvm()
add(project.files().from(project.getCompilationKorgeProcessedResourcesFolder(mainJvmCompilation)))
//add(project.files().from((project.tasks.findByName(jvmProcessedResourcesTaskName) as KorgeProcessedResourcesTask).processedResourcesFolder))
}
.reduceRight { l, r -> l + r }
}
open class KorgeJavaExec : JavaExec() {
//dependsOn(getKorgeProcessResourcesTaskName("jvm", "main"))
@get:Input
var logLevel = "info"
@get:InputFiles
val korgeClassPath: FileCollection = project.getKorgeClassPath()
override fun exec() {
classpath = korgeClassPath
for (classPath in classpath.toList()) {
logger.info("- $classPath")
}
environment("LOG_LEVEL", logLevel)
super.exec()
}
@get:Input
@Optional
var firstThread: Boolean? = null
init {
systemProperties = (System.getProperties().toMutableMap() as MutableMap<String, Any>) - "java.awt.headless"
defaultCharacterEncoding = Charsets.UTF_8.toString()
// https://github.com/korlibs/korge-plugins/issues/25
val firstThread = firstThread
?: (
System.getenv("KORGE_START_ON_FIRST_THREAD") == "true"
|| System.getenv("KORGW_JVM_ENGINE") == "sdl"
//|| project.findProperty("korgw.jvm.engine") == "sdl"
)
if (javaVersion.isCompatibleWith(JavaVersion.VERSION_17)) {
jvmArgs("-XX:+UnlockExperimentalVMOptions", "-XX:+IgnoreUnrecognizedVMOptions", "-XX:+UseZGC", "-XX:+ZGenerational")
}
//jvmArgs("-XX:+UseZGC")
if (firstThread && isMacos) {
jvmArgs("-XstartOnFirstThread")
}
//jvmArgumentProviders.add(provider)
}
}
/*
open class KorgeJavaExec : JavaExec() {
private val jvmCompilation get() = project.kotlin.targets.getByName("jvm").compilations as NamedDomainObjectSet<*>
private val mainJvmCompilation get() = jvmCompilation.getByName("main") as org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmCompilation
@get:InputFiles
val korgeClassPath: FileCollection = mainJvmCompilation.runtimeDependencyFiles + mainJvmCompilation.compileDependencyFiles + mainJvmCompilation.output.allOutputs + mainJvmCompilation.output.classesDirs
override fun exec() {
systemProperties = (System.getProperties().toMutableMap() as MutableMap<String, Any>) - "java.awt.headless"
if (!JvmAddOpens.beforeJava9) jvmArgs(*JvmAddOpens.createAddOpensTypedArray())
classpath = korgeClassPath
super.exec()
//project.afterEvaluate {
//if (firstThread == true && OS.isMac) task.jvmArgs("-XstartOnFirstThread")
//}
}
}
*/
/*
open class KorgeJavaExec : JavaExec() {
private val jvmCompilation get() = project.kotlin.targets.getByName("jvm").compilations as NamedDomainObjectSet<*>
private val mainJvmCompilation get() = jvmCompilation.getByName("main") as org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmCompilation
@get:InputFiles
val korgeClassPath: FileCollection = mainJvmCompilation.runtimeDependencyFiles + mainJvmCompilation.compileDependencyFiles + mainJvmCompilation.output.allOutputs + mainJvmCompilation.output.classesDirs
override fun exec() {
systemProperties = (System.getProperties().toMutableMap() as MutableMap<String, Any>) - "java.awt.headless"
if (!JvmAddOpens.beforeJava9) jvmArgs(*JvmAddOpens.createAddOpensTypedArray())
classpath = korgeClassPath
super.exec()
//project.afterEvaluate {
//if (firstThread == true && OS.isMac) task.jvmArgs("-XstartOnFirstThread")
//}
}
}
*/
| 461 | Kotlin | 120 | 2,394 | 0ca8644eb43c2ea8148dcd94d5c2a063466b0079 | 9,649 | korge | Apache License 2.0 |
app/src/main/java/com/alpriest/energystats/ui/summary/SolarForecastViewModel.kt | alpriest | 606,081,400 | false | {"Kotlin": 595301} | package com.alpriest.energystats.ui.summary
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.alpriest.energystats.models.RawVariable
import com.alpriest.energystats.models.ReportVariable
import com.alpriest.energystats.models.SolcastForecastResponse
import com.alpriest.energystats.models.toHalfHourOfDay
import com.alpriest.energystats.services.FoxESSNetworking
import com.alpriest.energystats.stores.ConfigManaging
import com.alpriest.energystats.ui.paramsgraph.DateTimeFloatEntry
import com.alpriest.energystats.ui.settings.solcast.SolarForecasting
import com.alpriest.energystats.ui.theme.AppTheme
import com.patrykandpatrick.vico.core.entry.ChartEntry
import com.patrykandpatrick.vico.core.entry.ChartEntryModelProducer
import com.patrykandpatrick.vico.core.entry.ChartModelProducer
import com.patrykandpatrick.vico.core.entry.FloatEntry
import kotlinx.coroutines.flow.MutableStateFlow
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.Date
import kotlin.time.Duration.Companion.hours
data class SolarForecastViewData(
val error: String?,
val today: ChartEntryModelProducer,
val todayTotal: Double,
val tomorrow: ChartEntryModelProducer,
val tomorrowTotal: Double,
val name: String?,
val resourceId: String
)
class SolarForecastViewModelFactory(
private val solarForecastProvider: SolarForecasting,
private val themeStream: MutableStateFlow<AppTheme>
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return SolarForecastViewModel(solarForecastProvider, themeStream) as T
}
}
class SolarForecastViewModel(
private val solarForecastProvider: SolarForecasting,
private val themeStream: MutableStateFlow<AppTheme>
) : ViewModel() {
val hasSitesStream = MutableStateFlow<Boolean>(false)
val dataStream = MutableStateFlow<List<SolarForecastViewData>>(listOf())
suspend fun load() {
val settings = themeStream.value.solcastSettings
if (settings.sites.isEmpty() || settings.apiKey == null) {
return
}
dataStream.value = settings.sites.map {
val forecasts = solarForecastProvider.fetchForecast(it, settings.apiKey).forecasts
val today = getToday()
val tomorrow = getTomorrow()
val todayData = forecasts.filter { response ->
isSameDay(response.periodEnd, today)
}
val tomorrowData = forecasts.filter { response ->
isSameDay(response.periodEnd, tomorrow)
}
SolarForecastViewData(
error = null,
today = ChartEntryModelProducer(todayData.map { response ->
DateFloatEntry(
date = response.periodEnd,
x = response.periodEnd.toHalfHourOfDay().toFloat(),
y = response.pvEstimate.toFloat(),
)
}),
todayTotal = total(todayData),
tomorrow = ChartEntryModelProducer(tomorrowData.map { response ->
DateFloatEntry(
date = response.periodEnd,
x = response.periodEnd.toHalfHourOfDay().toFloat(),
y = response.pvEstimate.toFloat(),
)
}),
tomorrowTotal = total(tomorrowData),
name = it.name,
resourceId = it.resourceId
)
}
}
fun total(forecasts: List<SolcastForecastResponse>): Double {
return forecasts.fold(0.0) { total, forecast ->
val periodHours = convertPeriodToHours(period = forecast.period)
total + (forecast.pvEstimate * periodHours)
}
}
private fun convertPeriodToHours(period: String): Double {
// Regular expression to extract the numeric value from the period string (assuming format "PT30M")
val regex = """(\d+)""".toRegex()
val matchResult = regex.find(period)
return matchResult?.let {
val periodMinutes = it.groupValues[1].toDoubleOrNull()
periodMinutes?.div(60.0) ?: 0.0 // Convert minutes to hours, defaulting to 0.0 if null
} ?: 0.0
}
fun isSameDay(date1: Date, date2: Date): Boolean {
val localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
val localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
return localDate1 == localDate2
}
private fun getTomorrow(): Date {
val date = LocalDate.now().plusDays(1)
return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant())
}
private fun getToday(): Date {
val date = LocalDate.now()
return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant())
}
}
class DateFloatEntry(
val date: Date,
override val x: Float,
override val y: Float
) : ChartEntry {
override fun withY(y: Float): ChartEntry = DateFloatEntry(
date = date,
x = x,
y = y
)
}
| 8 | Kotlin | 3 | 3 | 4fcac98b325ecb5ce45c287d8bdc220947735b8f | 5,242 | EnergyStats-Android | MIT License |
Backend/domain/src/test/kotlin/dev/honegger/jasstracker/domain/services/ContractServiceImplTest.kt | PascalHonegger | 503,086,739 | false | {"Kotlin": 227825, "Vue": 82519, "TypeScript": 33748, "CSS": 2019, "HTML": 665, "JavaScript": 638, "Dockerfile": 601} | package dev.honegger.jasstracker.domain.services
import dev.honegger.jasstracker.domain.Contract
import dev.honegger.jasstracker.domain.ContractType
import dev.honegger.jasstracker.domain.PlayerSession
import dev.honegger.jasstracker.domain.repositories.ContractRepository
import io.mockk.*
import java.util.*
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class ContractServiceImplTest {
private val repository = mockk<ContractRepository>()
private val dummySession = PlayerSession(UUID.randomUUID(), false, "dummy", "Dummy")
private val service = ContractServiceImpl(repository)
@BeforeTest
fun setup() {
clearMocks(repository)
}
@AfterTest
fun teardown() {
confirmVerified(repository)
}
@Test
fun `getContracts returns all contracts in repository`() {
val dummyAcorns = Contract(
id = UUID.randomUUID(),
name = "Eichle",
multiplier = 1,
type = ContractType.Acorns,
)
val dummyShields = Contract(
id = UUID.randomUUID(),
name = "Schilte",
multiplier = 3,
type = ContractType.Shields,
)
every { repository.getContracts() } returns listOf(
dummyAcorns,
dummyShields,
)
val loadedContracts = service.getContracts(dummySession)
assertEquals(listOf(dummyAcorns, dummyShields), loadedContracts)
verify(exactly = 1) { repository.getContracts() }
}
}
| 0 | Kotlin | 0 | 6 | 8c6ea53e4fb25e6d2cff8421e7f5f7efe51c8a17 | 1,576 | JassTracker | MIT License |
app/src/main/java/com/example/wordapp/WordsActivity.kt | KrishnaTech6 | 855,242,495 | false | {"Kotlin": 8191} | package com.example.wordapp
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.input
import com.example.wordapp.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class WordsActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel by viewModels<WordsViewModel>()
private lateinit var wordsAdapter: WordsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
setUpRecyclerView()
binding.fabWords.setOnClickListener{
showInputDialog()
}
viewModel.getAllWords().observe(this){
wordsAdapter.submitList(it)
wordsAdapter.notifyDataSetChanged() // Force the adapter to refresh
}
}
private fun setUpRecyclerView() {
binding.wordsRv.apply {
wordsAdapter = WordsAdapter(viewModel)
layoutManager = LinearLayoutManager(this@WordsActivity)
adapter = wordsAdapter
}
}
@SuppressLint("CheckResult")
private fun showInputDialog(){
MaterialDialog(this).show {
input { dialog, text ->
viewModel.saveWord(text.toString()).observe(this@WordsActivity){
if (it)
Snackbar.make(binding.root, "Saved Successfully", Snackbar.LENGTH_SHORT).show()
else
Snackbar.make(binding.root, "Error Saving", Snackbar.LENGTH_SHORT).show()
}
}
positiveButton(text = "Submit")
}
}
}
| 0 | Kotlin | 0 | 0 | 56f097cd2f12984d55c6c8b6328271071a1ad5af | 2,497 | WordApp | MIT License |
libaray/src/test/java/wang/isam/libaray/Kotlin.kt | samwangds | 140,137,056 | false | {"Java": 20973, "Kotlin": 10964} | package wang.isam.libaray
import org.junit.Test
class Kotlin {
@Test
fun testSamName() {
hello(1)
}
fun hello(num: Int) {
println(num)
val num = 3
print(num)
}
} | 1 | null | 1 | 1 | e6806ecdb6b124f94341b66425378a7aea5605af | 217 | SamAndroidLibrary-kotlin | Apache License 2.0 |
ktor-sample/src/main/kotlin/com/example/Application.kt | omarmiatello | 260,911,759 | false | null | package com.example
import com.github.omarmiatello.telegram.*
import io.ktor.http.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
// Starting point for a Ktor app:
routing {
post("/") {
// Endpoint for Telegram webhook. Parse the Telegram request
val request: Update = call.receiveText().parseTelegramRequest()
val inputText = request.message?.text
if (inputText != null) {
call.respondText(
// Send a message back to the user
TelegramRequest.SendMessageRequest(
chat_id = request.message!!.chat.id.toString(),
text = "Message: ${request.message}",
parse_mode = ParseMode.HTML,
).toJsonForResponse(),
ContentType.Application.Json
)
}
if (call.response.status() == null) call.respond(HttpStatusCode.NoContent)
}
}
}.start(wait = true)
}
| 0 | Kotlin | 1 | 8 | 37ebbc8db223bf568e55aa953d8100364e8dd68b | 1,329 | telegram | MIT License |
sample-kotlin/src/main/java/com/rudderstack/android/sample/kotlin/MainApplication.kt | thuannv | 429,683,529 | false | {"Java Properties": 4, "Markdown": 2, "Gradle": 12, "Shell": 3, "Batchfile": 2, "Text": 1, "Ignore List": 9, "Proguard": 7, "XML": 60, "Kotlin": 13, "Java": 87, "HTML": 1} | package com.rudderstack.android.sample.kotlin
import android.app.Application
import android.os.Handler
import com.rudderstack.android.sdk.core.RudderClient
import com.rudderstack.android.sdk.core.RudderConfig
import com.rudderstack.android.sdk.core.RudderLogger
class MainApplication : Application() {
companion object {
var rudderClient: RudderClient? = null
const val TAG = "MainApplication"
const val DATA_PLANE_URL = "https://e5757ebd4d1a.ngrok.io"
const val CONTROL_PLANE_URL = "https://0e741f50e567.ngrok.io"
const val WRITE_KEY = "<KEY>"
}
override fun onCreate() {
super.onCreate()
// rudderClient = RudderClient.getInstance(
// this,
// WRITE_KEY,
// RudderConfig.Builder()
// .withDataPlaneUrl(DATA_PLANE_URL)
// .withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
// .withTrackLifecycleEvents(false)
// .withRecordScreenViews(false)
// .build(), RudderOption()
// .putIntegration("MIXPANEL",true)
// )
rudderClient = RudderClient.getInstance(
this,
WRITE_KEY,
RudderConfig.Builder()
.withDataPlaneUrl(DATA_PLANE_URL)
.withLogLevel(RudderLogger.RudderLogLevel.DEBUG)
.withTrackLifecycleEvents(false)
.withRecordScreenViews(false)
.withCustomFactory(CustomFactory.FACTORY)
.build()
)
rudderClient!!.putDeviceToken("some_device_token")
rudderClient!!.track("first_event")
Handler().postDelayed({
RudderClient.updateWithAdvertisingId("some_idfa_changed")
rudderClient!!.track("second_event")
}, 3000)
}
}
| 1 | null | 1 | 1 | acffb52122ce85eac6bb60c95bbb9c2a3b6495fc | 1,811 | rudder-sdk-android | MIT License |
src/main/kotlin/io/framed/framework/pictogram/ConnectionEnd.kt | Eden-06 | 138,000,306 | false | {"Kotlin": 675525, "SCSS": 21894, "HTML": 768} | package io.framed.framework.pictogram
/**
* ViewModel class representing a endpoint of a connection.
*
* @author Lars Westermann, David Oberacker
*/
class ConnectionEnd {
/**
* Defines the foldback of the arrow on the connection end.
*
* @see <a href="https://docs.jsplumbtoolkit.com/community/current/articles/overlays.html">JsPlumb Endpoints</a>
*/
var foldback: Double = 1.0
/**
* Direction of the endpoint arrow on the connection.
* 0 points towards the source, 1 towards the target.
*
* TODO: Rethink the attributes for source and target connection ends.
*
* @see <a href="https://docs.jsplumbtoolkit.com/community/current/articles/overlays.html">JsPlumb Endpoints</a>
*/
var direction: Int = 1
/**
* Location of the endpoint arrow on the connection.
* 0 represents the beginning, 1 the end.
*
* TODO: Rethink the attributes for source and target connection ends.
*
* @see <a href="https://docs.jsplumbtoolkit.com/community/current/articles/overlays.html">JsPlumb Endpoints</a>
*/
var location: Double = 1.0
/**
* Width of the endpoint arrow.
*/
var width: Int = 20
/**
* Length of the endpoint arrow.
*/
var length: Int = 20
var paintStyle: PaintStyle = PaintStyle()
}
fun connectionEnd(init: ConnectionEnd.() -> Unit) = ConnectionEnd().also(init)
| 5 | Kotlin | 1 | 2 | 27f4a4c44d90f20f748ab779c3c184cb012a59fe | 1,420 | FRaMED-io | MIT License |
app/src/main/java/com/example/android/weather/data/remote/WeatherDto.kt | ezzahmed77 | 596,073,211 | false | null | package com.example.android.weather.data.remote
import com.squareup.moshi.Json
data class WeatherDto(
@field:Json(name = "hourly")
val weatherHourlyDataDto: WeatherHourlyDataDto,
@field:Json(name = "daily")
val weatherDailyDataDto: WeatherDailyDataDto
)
| 5 | Kotlin | 0 | 2 | ac216ed459a6d8d4fbdc32cc54b4fe4d467badc4 | 273 | weather | MIT License |
src/test/kotlin/no/nav/helse/flex/KluentExt.kt | navikt | 451,810,928 | false | null | package no.nav.helse.flex
import org.amshove.kluent.`should be equal to`
import java.time.Instant
import java.time.OffsetDateTime
import java.time.temporal.ChronoUnit
fun Instant.trunacteNanoUTC(): Instant = this.truncatedTo(ChronoUnit.MILLIS)
@Suppress("ktlint:standard:function-naming")
infix fun Instant.`should be equal to ignoring nano and zone`(expected: Instant) =
this.trunacteNanoUTC() `should be equal to` expected.trunacteNanoUTC()
@Suppress("ktlint:standard:function-naming")
infix fun OffsetDateTime.`should be equal to ignoring nano and zone`(expected: Instant?) =
this.toInstant() `should be equal to ignoring nano and zone` expected!!
| 6 | Kotlin | 0 | 0 | ad8285fcf8ce5232e604415c0e0372a997cec8c9 | 663 | sykepengesoknad-arkivering-oppgave | MIT License |
src/test/kotlin/io/vexel/kobold/test/parser/dsl/support/Label.kt | RowDaBoat | 758,112,583 | false | {"Kotlin": 89642} | package io.vexel.kobold.test.parser.dsl.support
import io.vexel.kobold.Symbol
import io.vexel.kobold.Token
data class Label(override val children: List<Symbol>): Symbol {
constructor(text: String) : this(text.map { Token(it.toString()) })
val text = children.map { it as Token }.joinToString("") { it.text }
override fun equals(other: Any?) = other is Label && text == other.text
override fun toString() = text
} | 0 | Kotlin | 0 | 5 | c5b70d1eaa787210ed65b2240af0bb70d9b0617a | 433 | kobold-parsing-kit | ISC License |
app/src/test/java/com/example/gumtree/GumtreeUnitTest.kt | rezakhmf | 243,719,655 | false | null | package com.example.gumtree
import com.example.gumtree.model.weather.WeatherModel
import com.example.gumtree.model.weather.repository.WeatherRepository
import com.google.gson.Gson
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.MockitoAnnotations
import org.mockito.junit.MockitoJUnit
import javax.inject.Inject
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
private const val MOCK_WEATHER = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":300,\"main\":\"Drizzle\",\"description\":\"light intensity drizzle\",\"icon\":\"09d\"}],\"base\":\"stations\",\"main\":{\"temp\":280.32,\"pressure\":1012,\"humidity\":81,\"temp_min\":279.15,\"temp_max\":281.15},\"visibility\":10000,\"wind\":{\"speed\":4.1,\"deg\":80},\"clouds\":{\"all\":90},\"dt\":1485789600,\"sys\":{\"type\":1,\"id\":5091,\"message\":0.0103,\"country\":\"GB\",\"sunrise\":1485762037,\"sunset\":1485794875},\"id\":2643743,\"name\":\"London\",\"cod\":200}"
@RunWith(JUnit4::class)
class GumtreeUnitTest {
@Rule
@JvmField
var mockitoRule = MockitoJUnit.rule()
@Inject
lateinit var weatherInfoRepositoryMock: WeatherRepository
lateinit var gson: Gson
lateinit var weatherModel: WeatherModel
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
gson = Gson()
weatherModel = gson.fromJson(MOCK_WEATHER, WeatherModel::class.java)
}
@Test
fun testWeatherInfoForLondon() = runBlocking {
/* Given */
whenever(weatherInfoRepositoryMock.getWeatherByCity("sydney")).thenReturn(weatherModel)
/* When */
/* Then */
Assert.assertEquals(weatherModel.name, "London")
Assert.assertEquals(weatherModel.id, 300)
Assert.assertEquals(weatherModel.sys?.country, "GB")
}
@Test
fun testWeatherInfoForFalseLondon() = runBlocking {
/* Given */
whenever(weatherInfoRepositoryMock.getWeatherByCity("sydney")).thenReturn(weatherModel)
/* When */
/* Then */
Assert.assertNotEquals(weatherModel.name, "Sydney")
Assert.assertNotEquals(weatherModel.id, 100)
Assert.assertEquals(weatherModel.sys?.country, "AU")
}
}
| 0 | Kotlin | 0 | 0 | fbc2852004c7b6a1f4d43d19c57bcca20559988e | 2,498 | weatherInfo | MIT License |
app-common/src/main/java/ru/shafran/common/customers/details/search/CustomerSearchByName.kt | SuLG-ik | 384,238,863 | false | null | package ru.shafran.common.customers.details.search
import com.arkivanov.decompose.router.RouterState
import com.arkivanov.decompose.value.Value
import ru.shafran.network.customers.data.Customer
interface CustomerSearchByName {
val router: Value<RouterState<FoundCustomerConfiguration, FoundCustomerChild>>
fun onFind(customer: Customer.ActivatedCustomer)
fun onSearch(name: String)
} | 0 | Kotlin | 0 | 1 | aef4a3083c87e2bd2de1eaff2b9925a5dc226fe2 | 401 | ShafranCards | Apache License 2.0 |
sample/src/main/java/com/sunzn/pay/sample/MainActivity.kt | uncn | 219,644,621 | false | null | package com.sunzn.pay.sample
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.sunzn.pay.alipay.AliPay
import com.sunzn.pay.alipay.AliPayParams
import com.sunzn.pay.master.Consumer
import com.sunzn.pay.master.PayListener
import com.sunzn.pay.sample.alipay.OrderProxy
import com.sunzn.pay.sample.wechat.ParamProxy
import com.sunzn.pay.wechat.WXPay
import com.sunzn.pay.wechat.WXPayParams
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.btn_alipay).setOnClickListener { alipay() }
findViewById<View>(R.id.btn_wechat).setOnClickListener { wechat() }
}
private fun alipay() {
val aliPay = AliPay()
val params = AliPayParams(OrderProxy.buildOrder())
Consumer.pay(aliPay, this, params, object : PayListener {
override fun onSuccess() {
Toast.makeText(this@MainActivity, "成功", Toast.LENGTH_SHORT).show()
}
override fun onFailure(errCode: String?, errText: String?) {
Toast.makeText(this@MainActivity, errText, Toast.LENGTH_SHORT).show()
}
override fun onCancel() {
Toast.makeText(this@MainActivity, "取消", Toast.LENGTH_SHORT).show()
}
})
}
private fun wechat() {
val wxPay: WXPay = WXPay.instance
val params: WXPayParams = ParamProxy.buildParam()
Consumer.pay(wxPay, this, params, object : PayListener {
override fun onSuccess() {
Toast.makeText(this@MainActivity, "成功", Toast.LENGTH_SHORT).show()
}
override fun onFailure(errCode: String?, errText: String?) {
Toast.makeText(this@MainActivity, errText, Toast.LENGTH_SHORT).show()
}
override fun onCancel() {
Toast.makeText(this@MainActivity, "取消", Toast.LENGTH_SHORT).show()
}
})
}
}
| 0 | Kotlin | 0 | 0 | 9b18b951c15bfdf86e6f7600478f4a3562c7d6e0 | 2,130 | pay | Apache License 2.0 |
app/src/main/java/kek/enxy/plantwriter/presentation/main/details/view/DetailView.kt | enxy0 | 276,753,408 | false | null | package kek.enxy.plantwriter.presentation.main.details.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.content.withStyledAttributes
import androidx.core.view.setPadding
import kek.enxy.plantwriter.R
import kek.enxy.plantwriter.databinding.ViewDetailBinding
class DetailView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val binding = ViewDetailBinding.inflate(LayoutInflater.from(context), this)
var type = DetailType.MONEY
set(value) {
field = value
binding.textTitle.text = getTitleByType(value)
binding.image.setImageDrawable(getIconByType(value))
}
init {
orientation = VERTICAL
background = ContextCompat.getDrawable(context, R.drawable.bg_detail)
setPadding(resources.getDimensionPixelSize(R.dimen.margin_normal))
initAttrs(context, attrs)
}
private fun initAttrs(context: Context, attrs: AttributeSet?) = with(binding) {
context.withStyledAttributes(attrs, R.styleable.DetailView) {
type = DetailType.values()[getInt(R.styleable.DetailView_dv_type, DetailType.MONEY.ordinal)]
getString(R.styleable.DetailView_dv_title)?.let { title ->
textTitle.text = title
}
getString(R.styleable.DetailView_dv_value)?.let { value ->
textValue.text = value
}
getDrawable(R.styleable.DetailView_dv_icon)?.let { drawable ->
image.setImageDrawable(drawable)
}
}
}
fun setDetails(value: String? = null, title: String? = null) = with(binding) {
title?.let { textTitle.text = it }
value?.let { textValue.text = it }
}
private fun getTitleByType(type: DetailType) = when (type) {
DetailType.MONEY -> resources.getString(R.string.detail_balance)
DetailType.DATE -> resources.getString(R.string.detail_date)
DetailType.GROUND_TOTAL,
DetailType.UNDERGROUND_TOTAL -> resources.getString(R.string.detail_count)
}
private fun getIconByType(type: DetailType) = when (type) {
DetailType.MONEY -> ContextCompat.getDrawable(context, R.drawable.ic_outline_info_24)
DetailType.DATE -> ContextCompat.getDrawable(context, R.drawable.ic_outline_date_range_24)
DetailType.GROUND_TOTAL -> ContextCompat.getDrawable(context, R.drawable.ic_bus_24)
DetailType.UNDERGROUND_TOTAL -> ContextCompat.getDrawable(context, R.drawable.ic_metro_24)
}
enum class DetailType {
MONEY, DATE, GROUND_TOTAL, UNDERGROUND_TOTAL
}
}
| 0 | Kotlin | 5 | 35 | fa17dd7457be5d6d949e5419dc936fdade2ef60e | 2,840 | Plantain | MIT License |
moove/metrics/src/main/kotlin/io/charlescd/moove/metrics/interactor/impl/RetrieveCirclesMetricsInteractorImpl.kt | ZupIT | 249,519,503 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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.charlescd.moove.metrics.interactor.impl
import io.charlescd.moove.domain.repository.CircleRepository
import io.charlescd.moove.metrics.api.response.CirclesMetricsRepresentation
import io.charlescd.moove.metrics.interactor.RetrieveCirclesMetricsInteractor
import org.springframework.stereotype.Component
@Component
class RetrieveCirclesMetricsInteractorImpl(val circleRepository: CircleRepository) : RetrieveCirclesMetricsInteractor {
override fun execute(workspaceId: String): CirclesMetricsRepresentation {
return CirclesMetricsRepresentation.from(
this.circleRepository.countGroupedByStatus(workspaceId),
this.circleRepository.getNotDefaultCirclesAverageLifeTime(workspaceId)
)
}
}
| 93 | null | 76 | 343 | a65319e3712dba1612731b44346100e89cd26a60 | 1,374 | charlescd | Apache License 2.0 |
data/RF01177/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01177"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
1 to 132
}
value = "#46ffa8"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 399 | Rfam-for-RNArtist | MIT License |
api/src/main/java/com/getcode/network/service/ChatServiceV2.kt | code-payments | 723,049,264 | false | {"Kotlin": 2101954, "C": 198685, "C++": 83029, "Java": 52287, "Ruby": 4594, "Shell": 4515, "CMake": 2594} | package com.getcode.network.service
import com.codeinc.gen.chat.v2.ChatService
import com.codeinc.gen.chat.v2.ChatService.ChatMemberId
import com.codeinc.gen.chat.v2.ChatService.NotifyIsTypingResponse
import com.codeinc.gen.chat.v2.ChatService.OpenChatEventStream
import com.codeinc.gen.chat.v2.ChatService.PointerType
import com.codeinc.gen.chat.v2.ChatService.RevealIdentityResponse
import com.codeinc.gen.chat.v2.ChatService.SendMessageResponse
import com.codeinc.gen.chat.v2.ChatService.StreamChatEventsRequest
import com.codeinc.gen.chat.v2.ChatService.StreamChatEventsResponse
import com.codeinc.gen.common.v1.Model.ClientPong
import com.getcode.ed25519.Ed25519.KeyPair
import com.getcode.mapper.ChatMessageV2Mapper
import com.getcode.mapper.ChatMetadataV2Mapper
import com.getcode.mapper.PointerMapper
import com.getcode.model.Conversation
import com.getcode.model.Cursor
import com.getcode.model.chat.ChatMessage
import com.getcode.model.ID
import com.getcode.model.MessageStatus
import com.getcode.model.SocialUser
import com.getcode.model.chat.Chat
import com.getcode.model.chat.ChatIdV2
import com.getcode.model.chat.ChatStreamEventUpdate
import com.getcode.model.chat.ChatType
import com.getcode.model.chat.OutgoingMessageContent
import com.getcode.model.chat.Platform
import com.getcode.model.description
import com.getcode.model.uuid
import com.getcode.network.api.ChatApiV2
import com.getcode.network.client.ChatMessageStreamReference
import com.getcode.network.core.NetworkOracle
import com.getcode.network.repository.sign
import com.getcode.network.repository.toByteString
import com.getcode.network.repository.toSolanaAccount
import com.getcode.utils.ErrorUtils
import com.getcode.utils.TraceType
import com.getcode.utils.bytes
import com.getcode.utils.trace
import com.google.protobuf.Timestamp
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.grpc.stub.StreamObserver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.suspendCancellableCoroutine
import timber.log.Timber
import java.util.UUID
import javax.inject.Inject
import kotlin.coroutines.resume
/**
* Abstraction layer to handle [ChatApiV2] request results and map to domain models
*/
class ChatServiceV2 @Inject constructor(
private val api: ChatApiV2,
private val chatMapper: ChatMetadataV2Mapper,
private val messageMapper: ChatMessageV2Mapper,
private val pointerMapper: PointerMapper,
private val networkOracle: NetworkOracle,
) {
private fun observeChats(owner: KeyPair): Flow<Result<List<Chat>>> {
return networkOracle.managedRequest(api.fetchChats(owner))
.map { response ->
when (response.result) {
ChatService.GetChatsResponse.Result.OK -> {
Result.success(response.chatsList.map(chatMapper::map))
}
ChatService.GetChatsResponse.Result.NOT_FOUND -> {
val error = Throwable("Error: chats not found for owner")
Timber.e(t = error)
Result.failure(error)
}
ChatService.GetChatsResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
}
}
@Throws(NoSuchElementException::class)
suspend fun fetchChats(owner: KeyPair): Result<List<Chat>> {
return runCatching { observeChats(owner).first() }.getOrDefault(Result.success(emptyList()))
}
suspend fun setMuteState(owner: KeyPair, chatId: ID, muted: Boolean): Result<Boolean> {
return try {
networkOracle.managedRequest(api.setMuteState(owner, chatId, muted))
.map { response ->
when (response.result) {
ChatService.SetMuteStateResponse.Result.OK -> {
Result.success(muted)
}
ChatService.SetMuteStateResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: chat not found for $chatId")
Timber.e(t = error)
Result.failure(error)
}
ChatService.SetMuteStateResponse.Result.CANT_MUTE -> {
val error = Throwable("Error: Unable to change mute state for $chatId.")
Timber.e(t = error)
Result.failure(error)
}
ChatService.SetMuteStateResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
}.first()
} catch (e: Exception) {
ErrorUtils.handleError(e)
Result.failure(e)
}
}
suspend fun setSubscriptionState(
owner: KeyPair,
chatId: ID,
subscribed: Boolean,
): Result<Boolean> {
return try {
networkOracle.managedRequest(api.setSubscriptionState(owner, chatId, subscribed))
.map { response ->
when (response.result) {
ChatService.SetSubscriptionStateResponse.Result.OK -> {
Result.success(subscribed)
}
ChatService.SetSubscriptionStateResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: chat not found for $chatId")
Timber.e(t = error)
Result.failure(error)
}
ChatService.SetSubscriptionStateResponse.Result.CANT_UNSUBSCRIBE -> {
val error = Throwable("Error: Unable to change mute state for $chatId.")
Timber.e(t = error)
Result.failure(error)
}
ChatService.SetSubscriptionStateResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
}.first()
} catch (e: Exception) {
ErrorUtils.handleError(e)
Result.failure(e)
}
}
suspend fun fetchMessagesFor(
owner: KeyPair,
chat: Chat,
cursor: Cursor? = null,
limit: Int? = null
): Result<List<ChatMessage>> {
return try {
val memberId = chat.members
.filter { it.isSelf }
.map { it.id }
.firstOrNull()
?: throw IllegalStateException("Fetching messages for a chat you are not a member in")
networkOracle.managedRequest(
api.fetchChatMessages(
owner,
chat.id,
memberId,
cursor,
limit
)
)
.map { response ->
when (response.result) {
ChatService.GetMessagesResponse.Result.OK -> {
Result.success(response.messagesList.map {
messageMapper.map(chat to it)
})
}
ChatService.GetMessagesResponse.Result.MESSAGE_NOT_FOUND -> {
val error =
Throwable("Error: messages not found for chat ${chat.id.description}")
Result.failure(error)
}
ChatService.GetMessagesResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Unrecognized request.")
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Result.failure(error)
}
}
}.first()
} catch (e: Exception) {
ErrorUtils.handleError(e)
Result.failure(e)
}
}
suspend fun advancePointer(
owner: KeyPair,
chatId: ID,
memberId: UUID,
to: ID,
status: MessageStatus,
): Result<Unit> {
val type = when (status) {
MessageStatus.Sent -> PointerType.SENT
MessageStatus.Delivered -> PointerType.DELIVERED
MessageStatus.Read -> PointerType.READ
MessageStatus.Unknown -> return Result.failure(Throwable("Can't update a pointer to Unknown"))
}
return try {
networkOracle.managedRequest(api.advancePointer(owner, chatId, memberId, to, type))
.map { response ->
when (response.result) {
ChatService.AdvancePointerResponse.Result.OK -> {
Result.success(Unit)
}
ChatService.AdvancePointerResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: chat not found $chatId")
Timber.e(t = error)
Result.failure(error)
}
ChatService.AdvancePointerResponse.Result.MESSAGE_NOT_FOUND -> {
val error = Throwable("Error: message not found $to")
Timber.e(t = error)
Result.failure(error)
}
ChatService.AdvancePointerResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
}.first()
} catch (e: Exception) {
ErrorUtils.handleError(e)
Result.failure(e)
}
}
suspend fun startChat(
owner: KeyPair,
self: SocialUser,
with: SocialUser,
intentId: ID,
type: ChatType
): Result<Chat> {
trace("Creating $type chat for ${intentId.description}")
return when (type) {
ChatType.Unknown -> throw IllegalArgumentException("Unknown chat type provided")
ChatType.Notification -> throw IllegalArgumentException("Unable to create notification chats from client")
ChatType.TwoWay -> {
try {
networkOracle.managedRequest(api.startChat(owner, self, with, intentId))
.map { response ->
when (response.result) {
ChatService.StartChatResponse.Result.OK -> {
trace("Chat created for ${intentId.description}")
Result.success(chatMapper.map(response.chat))
}
ChatService.StartChatResponse.Result.DENIED -> {
val error = Throwable("Error: Denied")
Timber.e(t = error)
Result.failure(error)
}
ChatService.StartChatResponse.Result.INVALID_PARAMETER -> {
val error = Throwable("Error: Invalid parameter")
Timber.e(t = error)
Result.failure(error)
}
ChatService.StartChatResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
}.first()
} catch (e: Exception) {
ErrorUtils.handleError(e)
Result.failure(e)
}
}
}
}
fun openChatStream(
scope: CoroutineScope,
conversation: Conversation,
memberId: UUID,
owner: KeyPair,
chatLookup: (Conversation) -> Chat,
onEvent: (Result<ChatStreamEventUpdate>) -> Unit
): ChatMessageStreamReference {
trace("Chat ${conversation.id.description} Opening stream.")
val streamReference = ChatMessageStreamReference(scope)
streamReference.retain()
streamReference.timeoutHandler = {
trace("Chat ${conversation.id.description} Stream timed out")
openChatStream(
conversation = conversation,
memberId = memberId,
owner = owner,
reference = streamReference,
chatLookup = chatLookup,
onEvent = onEvent
)
}
openChatStream(conversation, memberId, owner, streamReference, chatLookup, onEvent)
return streamReference
}
private fun openChatStream(
conversation: Conversation,
memberId: UUID,
owner: KeyPair,
reference: ChatMessageStreamReference,
chatLookup: (Conversation) -> Chat,
onEvent: (Result<ChatStreamEventUpdate>) -> Unit
) {
try {
reference.cancel()
reference.stream =
api.streamChatEvents(object : StreamObserver<StreamChatEventsResponse> {
override fun onNext(value: StreamChatEventsResponse?) {
val result = value?.typeCase
if (result == null) {
trace(
message = "Chat ${conversation.id.description} Server sent empty message. This is unexpected.",
type = TraceType.Error
)
return
}
when (result) {
StreamChatEventsResponse.TypeCase.EVENTS -> {
val pointerStatuses = value.events.eventsList
.map { it.pointer }
.mapNotNull { pointerMapper.map(it) }
val messages = value.events.eventsList
.map { it.message }
.map { messageMapper.map(chatLookup(conversation) to it) }
val isTyping = value.events.eventsList
.map { it.isTyping }
.find { it.isTyping && it.memberId.value.toList().uuid != memberId } != null
trace("Chat ${conversation.id.description} received ${messages.count()} messages and ${pointerStatuses.count()} status updates.")
val update = ChatStreamEventUpdate(messages, pointerStatuses, isTyping)
onEvent(Result.success(update))
}
StreamChatEventsResponse.TypeCase.PING -> {
val stream = reference.stream ?: return
val request = StreamChatEventsRequest.newBuilder()
.setPong(
ClientPong.newBuilder()
.setTimestamp(
Timestamp.newBuilder()
.setSeconds(System.currentTimeMillis() / 1_000)
)
).build()
reference.receivedPing(updatedTimeout = value.ping.pingDelay.seconds * 1_000L)
stream.onNext(request)
trace("Pong Chat ${conversation.id.description} Server timestamp: ${value.ping.timestamp}")
}
StreamChatEventsResponse.TypeCase.TYPE_NOT_SET -> Unit
StreamChatEventsResponse.TypeCase.ERROR -> {
trace(
type = TraceType.Error,
message = "Chat ${conversation.id.description} hit a snag. ${value.error.code}"
)
}
}
}
override fun onError(t: Throwable?) {
val statusException = t as? StatusRuntimeException
if (statusException?.status?.code == Status.Code.UNAVAILABLE) {
trace("Chat ${conversation.id.description} Reconnecting keepalive stream...")
openChatStream(
conversation,
memberId,
owner,
reference,
chatLookup,
onEvent
)
} else {
t?.printStackTrace()
}
}
override fun onCompleted() {
}
})
val request = StreamChatEventsRequest.newBuilder()
.setOpenStream(OpenChatEventStream.newBuilder()
.setChatId(
ChatIdV2.newBuilder()
.setValue(conversation.id.toByteString())
.build()
)
.setMemberId(
ChatMemberId.newBuilder()
.setValue(memberId.bytes.toByteString())
)
.setOwner(owner.publicKeyBytes.toSolanaAccount())
.apply { setSignature(sign(owner)) }
).build()
reference.stream?.onNext(request)
trace("Chat ${conversation.id.description} Initiating a connection...")
} catch (e: Exception) {
if (e is IllegalStateException && e.message == "call already half-closed") {
// ignore
} else {
ErrorUtils.handleError(e)
}
}
}
suspend fun sendMessage(
owner: KeyPair,
chat: Chat,
memberId: UUID,
content: OutgoingMessageContent,
): Result<ChatMessage> = suspendCancellableCoroutine { cont ->
val chatId = chat.id
try {
api.sendMessage(
owner = owner,
chatId = chatId,
memberId = memberId,
content = content,
observer = object : StreamObserver<SendMessageResponse> {
override fun onNext(value: SendMessageResponse?) {
val requestResult = value?.result
if (requestResult == null) {
trace(
message = "Chat SendMessage Server returned empty message. This is unexpected.",
type = TraceType.Error
)
return
}
val result = when (requestResult) {
SendMessageResponse.Result.OK -> {
trace("Chat message sent =: ${value.message.messageId.value.toList().description}")
val message = messageMapper.map(chat to value.message)
Result.success(message)
}
SendMessageResponse.Result.DENIED -> {
val error = Throwable("Error: Send Message: Denied")
Timber.e(t = error)
Result.failure(error)
}
SendMessageResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: Send Message: chat not found $chatId")
Timber.e(t = error)
Result.failure(error)
}
SendMessageResponse.Result.INVALID_CHAT_TYPE -> {
val error = Throwable("Error: Send Message: invalid chat type")
Timber.e(t = error)
Result.failure(error)
}
SendMessageResponse.Result.INVALID_CONTENT_TYPE -> {
val error = Throwable("Error: Send Message: invalid content type")
Timber.e(t = error)
Result.failure(error)
}
SendMessageResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Send Message: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
cont.resume(result)
}
override fun onError(t: Throwable?) {
val error = t ?: Throwable("Error: Hit a snag")
ErrorUtils.handleError(error)
cont.resume(Result.failure(error))
}
override fun onCompleted() {
}
}
)
} catch (e: Exception) {
ErrorUtils.handleError(e)
cont.resume(Result.failure(e))
}
}
suspend fun revealIdentity(
owner: KeyPair,
chat: Chat,
memberId: UUID,
platform: Platform,
username: String,
): Result<ChatMessage> = suspendCancellableCoroutine { cont ->
val chatId = chat.id
try {
api.revealIdentity(
owner,
chatId,
memberId,
platform,
username,
observer = object : StreamObserver<RevealIdentityResponse> {
override fun onNext(value: RevealIdentityResponse?) {
val requestResult = value?.result
if (requestResult == null) {
trace(
message = "Chat SendMessage Server returned empty message. This is unexpected.",
type = TraceType.Error
)
return
}
val result = when (requestResult) {
RevealIdentityResponse.Result.OK -> {
trace("Chat message sent =: ${value.message.messageId.value.toList().description}")
val message = messageMapper.map(chat to value.message)
Result.success(message)
}
RevealIdentityResponse.Result.DENIED -> {
val error = Throwable("Error: Send Message: Denied")
Timber.e(t = error)
Result.failure(error)
}
RevealIdentityResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: Send Message: chat not found $chatId")
Timber.e(t = error)
Result.failure(error)
}
RevealIdentityResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Send Message: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
cont.resume(result)
}
override fun onError(t: Throwable?) {
val error = t ?: Throwable("Error: Hit a snag")
ErrorUtils.handleError(error)
cont.resume(Result.failure(error))
}
override fun onCompleted() {
}
}
)
} catch (e: Exception) {
ErrorUtils.handleError(e)
cont.resume(Result.failure(e))
}
}
suspend fun onStartedTyping(
owner: KeyPair,
chat: Chat,
memberId: UUID,
): Result<Unit> = suspendCancellableCoroutine { cont ->
val chatId = chat.id
try {
api.onStartedTyping(
owner,
chatId,
memberId,
observer = object : StreamObserver<NotifyIsTypingResponse> {
override fun onNext(value: NotifyIsTypingResponse?) {
val requestResult = value?.result
if (requestResult == null) {
trace(
message = "Chat NotifyIsTyping Server returned empty message. This is unexpected.",
type = TraceType.Error
)
return
}
val result = when (requestResult) {
NotifyIsTypingResponse.Result.OK -> {
Result.success(Unit)
}
NotifyIsTypingResponse.Result.DENIED -> {
val error = Throwable("Error: Send Message: Denied")
Timber.e(t = error)
Result.failure(error)
}
NotifyIsTypingResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: Send Message: chat not found $chatId")
Timber.e(t = error)
Result.failure(error)
}
NotifyIsTypingResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: Send Message: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
cont.resume(result)
}
override fun onError(t: Throwable?) {
val error = t ?: Throwable("Error: Hit a snag")
ErrorUtils.handleError(error)
cont.resume(Result.failure(error))
}
override fun onCompleted() {
}
}
)
} catch (e: Exception) {
ErrorUtils.handleError(e)
cont.resume(Result.failure(e))
}
}
suspend fun onStoppedTyping(
owner: KeyPair,
chat: Chat,
memberId: UUID,
): Result<Unit> = suspendCancellableCoroutine { cont ->
val chatId = chat.id
try {
api.onStoppedTyping(
owner,
chatId,
memberId,
observer = object : StreamObserver<NotifyIsTypingResponse> {
override fun onNext(value: NotifyIsTypingResponse?) {
val requestResult = value?.result
if (requestResult == null) {
trace(
message = "Chat NotifyIsTyping Server returned empty message. This is unexpected.",
type = TraceType.Error
)
return
}
val result = when (requestResult) {
NotifyIsTypingResponse.Result.OK -> {
Result.success(Unit)
}
NotifyIsTypingResponse.Result.DENIED -> {
val error = Throwable("Error: NotifyIsTyping: Denied")
Timber.e(t = error)
Result.failure(error)
}
NotifyIsTypingResponse.Result.CHAT_NOT_FOUND -> {
val error = Throwable("Error: NotifyIsTyping: chat not found $chatId")
Timber.e(t = error)
Result.failure(error)
}
NotifyIsTypingResponse.Result.UNRECOGNIZED -> {
val error = Throwable("Error: NotifyIsTyping: Unrecognized request.")
Timber.e(t = error)
Result.failure(error)
}
else -> {
val error = Throwable("Error: Unknown")
Timber.e(t = error)
Result.failure(error)
}
}
cont.resume(result)
}
override fun onError(t: Throwable?) {
val error = t ?: Throwable("Error: Hit a snag")
ErrorUtils.handleError(error)
cont.resume(Result.failure(error))
}
override fun onCompleted() {
}
}
)
} catch (e: Exception) {
ErrorUtils.handleError(e)
cont.resume(Result.failure(e))
}
}
} | 4 | Kotlin | 13 | 14 | f7078b30d225ca32796fda8792b8a99646967183 | 32,987 | code-android-app | MIT License |
entities/src/main/java/org/odk/collect/entities/javarosa/filter/LocalEntitiesFilterStrategy.kt | getodk | 40,213,809 | false | {"Java": 3391347, "Kotlin": 2711239, "JavaScript": 2830, "Shell": 2689} | package org.odk.collect.entities.javarosa.filter
import org.javarosa.core.model.CompareToNodeExpression
import org.javarosa.core.model.condition.EvaluationContext
import org.javarosa.core.model.condition.FilterStrategy
import org.javarosa.core.model.instance.DataInstance
import org.javarosa.core.model.instance.TreeReference
import org.javarosa.xpath.expr.XPathEqExpr
import org.javarosa.xpath.expr.XPathExpression
import org.odk.collect.entities.javarosa.intance.LocalEntitiesInstanceAdapter
import org.odk.collect.entities.javarosa.intance.LocalEntitiesInstanceProvider
import org.odk.collect.entities.storage.EntitiesRepository
import java.util.function.Supplier
/**
* A JavaRosa [FilterStrategy] that will use an [EntitiesRepository] to perform filters. For
* supported expressions, this prevents JavaRosa from using it's standard [FilterStrategy] chain
* which requires loading the whole secondary instance into memory (assuming that
* [LocalEntitiesInstanceProvider] or similar is used to take advantage of JavaRosa's partial
* parsing).
*/
class LocalEntitiesFilterStrategy(entitiesRepository: EntitiesRepository) :
FilterStrategy {
private val dataAdapter = LocalEntitiesInstanceAdapter(entitiesRepository)
override fun filter(
sourceInstance: DataInstance<*>,
nodeSet: TreeReference,
predicate: XPathExpression,
children: MutableList<TreeReference>,
evaluationContext: EvaluationContext,
next: Supplier<MutableList<TreeReference>>
): List<TreeReference> {
if (!dataAdapter.supportsInstance(sourceInstance.instanceId)) {
return next.get()
}
val candidate = CompareToNodeExpression.parse(predicate)
return when (val original = candidate?.original) {
is XPathEqExpr -> {
if (original.isEqual) {
val child = candidate.nodeSide.steps[0].name.name
val value = candidate.evalContextSide(sourceInstance, evaluationContext)
val results = dataAdapter.queryEq(
sourceInstance.instanceId,
child,
value as String
)
return if (results != null) {
sourceInstance.replacePartialElements(results)
results.map {
it.parent = sourceInstance.root
it.ref
}
} else {
next.get()
}
} else {
next.get()
}
}
else -> {
next.get()
}
}
}
}
| 285 | Java | 1368 | 712 | a153d02bcb3d991a477261ec30f7b757f612c016 | 2,748 | collect | Apache License 2.0 |
src/main/kotlin/xyz/xasmc/hashbook/listener/OpenBookListener.kt | XAS-Dev | 811,903,369 | false | {"Kotlin": 42558} | package xyz.xasmc.hashbook.listener
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.Action
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.inventory.meta.BookMeta
import xyz.xasmc.hashbook.HashBook
import xyz.xasmc.hashbook.service.ItemDataServices
import xyz.xasmc.hashbook.service.StorageServices
import xyz.xasmc.hashbook.util.BlockUtil
import xyz.xasmc.hashbook.util.BookUtil
import xyz.xasmc.hashbook.util.MessageUtil.debugMiniMessage
import xyz.xasmc.hashbook.util.MessageUtil.sendMiniMessage
import xyz.xasmc.hashbook.util.MessageUtil.shortHashMessage
class OpenBookListener : Listener {
@EventHandler
fun onPlayerInteract(event: PlayerInteractEvent) {
if (event.action == Action.RIGHT_CLICK_BLOCK && !BlockUtil.checkInteractiveBlock(event.clickedBlock ?: return))
else if (event.action == Action.RIGHT_CLICK_AIR)
else return
val msgTitle = "<dark_aqua>[HashBook]</dark_aqua>"
val player = event.player
val hand = event.hand ?: run {
player.debugMiniMessage("$msgTitle <aqua>[debug] 无法获取装备槽")
return@onPlayerInteract
}
val item = event.item ?: return
if (item.type != Material.WRITTEN_BOOK) return
if (HashBook.config.setHashWhenOpenBook) BookUtil.storeBook(item, player, hand)
if (!ItemDataServices.hasItemData(item, "HashBook.Hash")) return
val hash = ItemDataServices.getItemData(item, "HashBook.Hash", ItemDataServices.DataType.String) ?: run {
player.sendMiniMessage("$msgTitle <yellow>[warn] 无法读取成书哈希值")
event.isCancelled = true
return@onPlayerInteract
}
val bookMeta = item.itemMeta as BookMeta
bookMeta.pages(BookUtil.deserializePages(StorageServices.read(hash) ?: run {
val shortHashMsg = shortHashMessage(hash)
player.sendMiniMessage("$msgTitle <yellow>[warn] 无法读取成书书页")
player.sendMiniMessage("$msgTitle <yellow>[warn] <aqua>hash</aqua>: <green>$shortHashMsg")
event.isCancelled = true
return@onPlayerInteract
}))
val shortHashMsg = shortHashMessage(hash)
player.openBook(bookMeta)
player.debugMiniMessage("$msgTitle <aqua>[debug] <dark_green>成功替换数据")
player.debugMiniMessage("$msgTitle <aqua>[debug] <aqua>hash</aqua>: <green>$shortHashMsg")
event.isCancelled = true
}
}
| 0 | Kotlin | 0 | 3 | 847c46517bcc404c29d7de8d98178a87c4b01e40 | 2,498 | HashBook | MIT License |
src/main/kotlin/me/rerere/virtualtag/tag/VirtualTagManager.kt | jiangdashao | 389,961,986 | false | null | package me.rerere.virtualtag.tag
import me.rerere.virtualtag.api.Tag
import me.rerere.virtualtag.api.colorful
import me.rerere.virtualtag.hook.applyPlaceholderAPI
import me.rerere.virtualtag.util.allPlayers
import me.rerere.virtualtag.util.timerTask
import me.rerere.virtualtag.virtualTag
import org.bukkit.entity.Player
import java.util.*
class VirtualTagManager {
// Cache the tag when the player uploads the update to prevent frequent tag updates
private val previousTagCache = hashMapOf<UUID, Tag>()
// Ensure that the tag can be updated every certain time even though it has not changed
private val noUpdateTicks = hashMapOf<UUID, Int>()
val task = timerTask(
interval = virtualTag().configModule.mainConfig.updateInterval.toLong()
) {
updateAll()
}
private fun updateAll() {
allPlayers {
updatePlayerTag(it)
}
}
fun updatePlayerTag(player: Player) {
val mainConfig = virtualTag().configModule.mainConfig
val matchedTags = mainConfig.groups
.filter {
it.permission.isBlank() || player.isOp || player.hasPermission(it.permission)
}
.sortedByDescending { it.priority }
.let {
if (mainConfig.multipleNameTags) {
it
} else {
listOf(it.firstOrNull())
}
}
val targetTag = Tag(
prefix = matchedTags.joinToString(separator = "") { it?.prefix ?: "" },
suffix = matchedTags.joinToString(separator = "") { it?.suffix ?: "" }
).apply {
applyPlaceholderAPI(player)
colorful()
}
val previousTag = previousTagCache[player.uniqueId]
// Name tag changed, require update
if (targetTag != previousTag || (noUpdateTicks[player.uniqueId] ?: 0) > 100) {
previousTagCache[player.uniqueId] = targetTag
noUpdateTicks[player.uniqueId] = 0
virtualTag().tagHandler.setPlayerTag(player, targetTag)
} else {
noUpdateTicks[player.uniqueId] = noUpdateTicks[player.uniqueId]?.plus(1) ?: 1
}
}
fun playerQuit(player: Player) {
previousTagCache -= player.uniqueId
noUpdateTicks -= player.uniqueId
}
} | 1 | null | 3 | 8 | d4481846e199e3f39a98067f77c6f7f5ec68ac00 | 2,332 | VirtualTag | Apache License 2.0 |
src/me/anno/ecs/prefab/Prefab.kt | AntonioNoack | 266,471,164 | false | null | package me.anno.ecs.prefab
import me.anno.ecs.prefab.PrefabCache.loadPrefab
import me.anno.ecs.prefab.change.CAdd
import me.anno.ecs.prefab.change.CSet
import me.anno.ecs.prefab.change.Change
import me.anno.ecs.prefab.change.Path
import me.anno.ecs.prefab.change.Path.Companion.ROOT_PATH
import me.anno.io.ISaveable
import me.anno.io.Saveable
import me.anno.io.base.BaseWriter
import me.anno.io.files.FileReference
import me.anno.io.files.InvalidRef
import me.anno.io.serialization.NotSerializedProperty
import me.anno.utils.files.LocalFile.toGlobalFile
import me.anno.utils.structures.maps.CountMap
import me.anno.utils.structures.maps.KeyPairMap
import org.apache.logging.log4j.LogManager
class Prefab : Saveable {
constructor() : super()
constructor(clazzName: String) : this() {
this.clazzName = clazzName
}
constructor(clazzName: String, prefab: FileReference) : this(clazzName) {
this.prefab = prefab
}
constructor(prefab: Prefab) {
this.clazzName = prefab.clazzName
this.prefab = prefab.source
}
var clazzName: String = ""
val addCounts = CountMap<Pair<Char, Path>>()
var adds: List<CAdd> = emptyList()
val sets = KeyPairMap<Path, String, Any?>(256)
var prefab: FileReference = InvalidRef
var wasCreatedFromJson = false
var source: FileReference = InvalidRef
fun invalidateInstance() {
synchronized(this) {
sampleInstance?.destroy()
sampleInstance = null
isValid = false
}
// todo all child prefab instances would need to be invalidated as well
}
val instanceName get() = sets[ROOT_PATH, "name"]?.toString()
@NotSerializedProperty
var isWritable = true
private set
fun sealFromModifications() {
isWritable = false
// make adds and sets immutable?
}
fun ensureMutableLists() {
if (adds !is MutableList) adds = ArrayList(adds)
// if (sets !is MutableList) sets = ArrayList(sets)
}
fun addAll(changes: Collection<Change>) {
if (!isWritable) throw ImmutablePrefabException(source)
for (change in changes) {
add(change)
}
}
fun getPrefabOrSource() = prefab.nullIfUndefined() ?: source
fun countTotalChanges(async: Boolean): Int {
var sum = adds.size + sets.size
if (prefab != InvalidRef) {
val prefab = loadPrefab(prefab, HashSet(), async)
if (prefab != null) sum += prefab.countTotalChanges(async)
}
for (change in adds) {
val childPrefab = change.prefab
if (childPrefab != InvalidRef) {
val prefab = loadPrefab(childPrefab, HashSet(), async)
if (prefab != null) sum += prefab.countTotalChanges(async)
}
}
return sum
}
// for the game runtime, we could save the prefab instance here
// or maybe even just add the changes, and merge them
// (we don't need to override twice or more times)
var history: ChangeHistory? = null
var isValid = false
fun add(change: CAdd, index: Int): Path {
return add(change).getChildPath(index)
}
fun set(path: Path, name: String, value: Any?) {
// add(CSet(path, name, value))
if (!isWritable) throw ImmutablePrefabException(source)
sets[path, name] = value
// apply to sample instance to keep it valid
updateSample(path, name, value)
// todo all child prefab instances would need to be updated as well
// todo same for add...
}
fun setIfNotExisting(path: Path, name: String, value: Any?) {
if (!sets.contains(path, name)) {// could be optimized to use no instantiations
set(path, name, value)
}
}
/**
* does not check, whether the change already exists;
* it assumes, that it does not yet exist
* */
fun setUnsafe(path: Path, name: String, value: Any?) {
/*ensureMutableLists()
(sets as MutableList).add(CSet(path, name, value))*/
sets[path, name] = value
}
fun add(parentPath: Path, typeChar: Char, type: String, name: String, index: Int): Path {
return add(CAdd(parentPath, typeChar, type, name, InvalidRef)).getChildPath(index)
}
fun add(parentPath: Path, typeChar: Char, type: String, name: String, ref: FileReference): Path {
val index = addCounts.getAndInc(typeChar to parentPath)
return add(CAdd(parentPath, typeChar, type, name, ref)).getChildPath(index)
}
fun add(parentPath: Path, typeChar: Char, clazzName: String): Path {
val index = addCounts.getAndInc(typeChar to parentPath)
return add(CAdd(parentPath, typeChar, clazzName, clazzName, InvalidRef)).getChildPath(index)
}
fun add(parentPath: Path, typeChar: Char, clazzName: String, index: Int): Path {
return add(CAdd(parentPath, typeChar, clazzName, clazzName, InvalidRef)).getChildPath(index)
}
fun add(parentPath: Path, typeChar: Char, clazzName: String, name: String): Path {
val index = addCounts.getAndInc(typeChar to parentPath)
return add(CAdd(parentPath, typeChar, clazzName, name, InvalidRef)).getChildPath(index)
}
fun <V : Change> add(change: V): V {
if (!isWritable) throw ImmutablePrefabException(source)
when (change) {
is CAdd -> {
ensureMutableLists()
(adds as MutableList).add(change)
isValid = false
}
is CSet -> {
/*ensureMutableLists()
if (sets.none {
if (it.path == change.path && it.name == change.name) {
it.value = change.value
true
} else false
}) {
(sets as MutableList).add(change)
}*/
sets[change.path, change.name!!] = change.value
// apply to sample instance to keep it valid
updateSample(change)
}
else -> LOGGER.warn("Unknown change type")
}
return change
}
private fun updateSample(change: CSet) {
val sampleInstance = sampleInstance
if (sampleInstance != null && isValid) {
change.apply(sampleInstance, null)
}
}
private fun updateSample(path: Path, name: String, value: Any?) {
val sampleInstance = sampleInstance
if (sampleInstance != null && isValid) {
CSet.apply(sampleInstance, path, name, value)
}
}
fun setProperty(name: String, value: Any?) {
set(ROOT_PATH, name, value)
}
fun setProperty(path: Path, name: String, value: Any?) {
set(path, name, value)
}
fun getProperty(name: String): Any? {
return sets[ROOT_PATH, name]
}
private var sampleInstance: PrefabSaveable? = null
override fun save(writer: BaseWriter) {
super.save(writer)
writer.writeFile("prefab", prefab)
writer.writeString("className", clazzName)
writer.writeObjectList(null, "adds", adds)
writer.writeObjectList(null, "sets", sets.map { k1, k2, v -> CSet(k1, k2, v) })
writer.writeObject(null, "history", history)
}
override fun readString(name: String, value: String?) {
if (!isWritable) throw ImmutablePrefabException(source)
when (name) {
"prefab" -> prefab = value?.toGlobalFile() ?: InvalidRef
"className" -> clazzName = value ?: ""
else -> super.readString(name, value)
}
}
override fun readFile(name: String, value: FileReference) {
if (!isWritable) throw ImmutablePrefabException(source)
when (name) {
"prefab" -> prefab = value
else -> super.readFile(name, value)
}
}
override fun readObjectArray(name: String, values: Array<ISaveable?>) {
if (!isWritable) throw ImmutablePrefabException(source)
when (name) {
"changes" -> {
adds = values.filterIsInstance<CAdd>()
for (v in values) {
if (v is CSet) {
val vName = v.name
if (vName != null) {
sets[v.path, vName] = v.value
}
}
}
}
"adds" -> adds = values.filterIsInstance<CAdd>()
"sets" -> {
for (v in values) {
if (v is CSet) {
val vName = v.name
if (vName != null) {
sets[v.path, vName] = v.value
}
}
}
}
else -> super.readObjectArray(name, values)
}
}
override fun readObject(name: String, value: ISaveable?) {
if (!isWritable) throw ImmutablePrefabException(source)
when (name) {
"history" -> history = value as? ChangeHistory ?: return
else -> super.readObject(name, value)
}
}
fun getSampleInstance(chain: MutableSet<FileReference>? = HashSet()): PrefabSaveable {
if (!isValid) synchronized(this) {
if (!isValid) {
val instance = PrefabCache.createInstance(this, prefab, adds, sets, chain, clazzName)
instance.forAll {
if (it.prefab !== this) {
throw IllegalStateException("Incorrectly created prefab!")
}
}
// assign super instance? we should really cache that...
sampleInstance = instance
isValid = true
}
}
return sampleInstance!!
}
fun createInstance(chain: MutableSet<FileReference>? = HashSet()): PrefabSaveable {
val clone = getSampleInstance(chain).clone()
clone.forAll {
if (it.prefab !== this)
throw IllegalStateException("Incorrectly created prefab!")
}
return clone
}
override val className: String = "Prefab"
override val approxSize: Int = 1_000_000_000
override fun isDefaultValue(): Boolean =
adds.isEmpty() && sets.isEmpty() && prefab == InvalidRef && history == null
companion object {
private val LOGGER = LogManager.getLogger(Prefab::class)
}
} | 0 | Kotlin | 1 | 8 | e5f0bb17202552fa26c87c230e31fa44cd3dd5c6 | 10,539 | RemsStudio | Apache License 2.0 |
xml/src/commonMain/kotlin/pw/binom/xml/XmlException.kt | caffeine-mgn | 182,165,415 | false | {"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88} | package pw.binom.xml
import pw.binom.io.IOException
open class XmlException : IOException {
constructor(message: String) : super(message)
constructor() : super()
} | 7 | C | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 173 | pw.binom.io | Apache License 2.0 |
src/main/kotlin/jp/live/ugai/d2j/AttentionCues.kt | takanori-ugai | 531,855,045 | false | {"Kotlin": 292175, "Java": 3032} | package jp.live.ugai.d2j
import ai.djl.ndarray.NDManager
fun main() {
val manager = NDManager.newBaseManager()
}
class AttentionCues
| 0 | Kotlin | 0 | 0 | ed1956795468b0475f1edffa683aa61d55eb227f | 140 | D2J | Apache License 2.0 |
modules/aql/arrow-query-language/src/main/kotlin/arrow/aql/Sum.kt | Krishan14sharma | 183,217,828 | true | {"Kotlin": 2391225, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Java": 4465, "Shell": 3043, "Ruby": 1598} | package arrow.aql
import arrow.core.ForId
import arrow.core.Id
import arrow.core.identity
import arrow.core.value
import arrow.typeclasses.Foldable
interface Sum<F> {
fun foldable(): Foldable<F>
infix fun <A, Z> Query<F, A, Z>.sum(f: A.() -> Long): Query<ForId, Long, Long> =
foldable().run {
Query(
select = ::identity,
from = Id(from.foldLeft(0L) { acc, a ->
acc + f(a)
})
)
}
fun Query<ForId, Long, Long>.value(): Long =
foldable().run {
[email protected]()
}
}
| 1 | Kotlin | 0 | 1 | 2b26976e1a8fbf29b7a3786074d56612440692a8 | 548 | arrow | Apache License 2.0 |
TheDailyNewscast/app/src/main/java/com/thenewsapp/activities/fragments/ReadMoreFragment.kt | ArbeenaKhanum | 326,688,659 | false | null | package com.thenewsapp.thedailynewscast.activities.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.thenewsapp.thedailynewscast.activities.R
import kotlinx.android.synthetic.main.fragment_read_more.*
class ReadMoreFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_read_more, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
searchListBackBtn.setOnClickListener {
openSearchListFragment()
}
getReadMoreBundle()
}
private fun openSearchListFragment() {
}
private fun getReadMoreBundle() {
val rmImg = arguments!!.getString("readMoreImg")
Glide.with(ivReadMoreNewsImg).load(rmImg).into(ivReadMoreNewsImg)
val rmHeadline = arguments!!.getString("readMoreHeadline")
tvNewsReadMoreHeadlines.text = rmHeadline
val rmNewsDesc = arguments!!.getString("readMoreDesc")
tvReadMoreNewsDesc.text = rmNewsDesc
val rmNewsTime = arguments!!.getString("readMoreTime")
tvReadMoreTime.text = rmNewsTime
val rmNewsDate = arguments!!.getString("readMoreDate")
tvReadMoreDate.text = rmNewsDate
val rmNewsAuthor = arguments!!.getString("readMoreAuthor")
tvReadMoreAuthor.text = rmNewsAuthor
}
} | 0 | Kotlin | 0 | 1 | 4e570cf694f3e7a88f0c9551ce39d7615f6ceeed | 1,808 | TheNewsApp | Apache License 2.0 |
compiler/testData/diagnostics/tests/platformTypes/nullableTypeArgument.fir.kt | JetBrains | 3,432,266 | false | null | import java.util.ArrayList
fun foo() {
val list = ArrayList<String?>()
for (s in list) {
s.length
}
} | 132 | null | 5074 | 40,992 | 57fe6721e3afb154571eb36812fd8ef7ec9d2026 | 123 | kotlin | Apache License 2.0 |
flick_player/src/main/java/com/flipkart/flick/ui/listeners/OnContentChangeListener.kt | flipkart-incubator | 354,808,240 | false | null | /*
* Copyright (C) 2021 Flipkart Internet Pvt Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flipkart.flick.ui.listeners
import com.flipkart.flick.core.model.ContentData
/**
* Called when content is changed
*/
interface OnContentChangeListener {
fun onContentChange(content: ContentData)
} | 1 | Kotlin | 7 | 23 | 9007af5431245c69ba8e85e5a382c247e57f9664 | 830 | android-video-player | Apache License 2.0 |
shared/src/androidMain/kotlin/com/habileducation/themovie/util/FileReader.kt | annasta13 | 434,181,410 | false | {"Kotlin": 146355, "Swift": 34780, "HTML": 9438, "JavaScript": 5252, "CSS": 3780, "Ruby": 1780} | package com.habileducation.themovie.util
/**
* Created by <NAME> on 15/08/22.
*
*/
actual class FileReader actual constructor(){
actual fun readFile(fileName: String): String {
return this::class.java.classLoader!!.getResourceAsStream(fileName).bufferedReader()
.use { it.readText() }
}
} | 0 | Kotlin | 4 | 23 | 8b00376470d25dc243dca4ef85b18f8883308b17 | 320 | The-Movies | Apache License 2.0 |
jps/jps-plugin/testData/incremental/lookupTracker/jvm/conventions/other.K1.kt | JetBrains | 3,432,266 | false | null | package foo.bar
/*p:foo.bar*/fun testOther(a: /*p:foo.bar*/A, b: /*p:foo.bar*/Int, c: /*p:foo.bar*/Any, na: /*p:foo.bar*/A?) {
/*p:foo.bar(A) p:foo.bar(set) p:foo.bar.A(getSET) p:foo.bar.A(getSet) p:foo.bar.A(set)*/a[1] = /*p:foo.bar(A) p:foo.bar.A(get)*/a[2]
b /*p:foo.bar.A(contains)*/in /*p:foo.bar(A)*/a
"s" /*p:foo.bar(contains) p:foo.bar.A(contains) p:foo.bar.A(getCONTAINS) p:foo.bar.A(getContains)*/!in /*p:foo.bar(A)*/a
/*p:foo.bar.A(invoke)*/a()
/*p:foo.bar p:foo.bar(invoke) p:foo.bar.A(invoke)*/a(1)
val (/*p:foo.bar.A(component1)*/h, /*p:foo.bar(component2) p:foo.bar.A(component2) p:foo.bar.A(getComponent2)*/t) = /*p:foo.bar(A)*/a;
for ((/*p:foo.bar.A(component1)*/f, /*p:foo.bar(component2) p:foo.bar.A(component2) p:foo.bar.A(getComponent2)*/s) in /*p:foo.bar(A) p:foo.bar(hasNext) p:foo.bar.A(getHASNext) p:foo.bar.A(getHasNext) p:foo.bar.A(hasNext) p:foo.bar.A(iterator) p:foo.bar.A(next)*/a);
for ((/*p:foo.bar.A(component1)*/f, /*p:foo.bar(component2) p:foo.bar.A(component2) p:foo.bar.A(getComponent2)*/s) in /*p:foo.bar(A) p:foo.bar(hasNext) p:foo.bar(iterator) p:foo.bar.A(getHASNext) p:foo.bar.A(getHasNext) p:foo.bar.A(getITERATOR) p:foo.bar.A(getIterator) p:foo.bar.A(hasNext) p:foo.bar.A(iterator) p:foo.bar.A(next)*/na);
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,289 | kotlin | Apache License 2.0 |
core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/sync/impl/SynchronizedSemaphore.kt | ndkoval | 124,298,574 | true | {"Kotlin": 1846254, "CSS": 8706, "Python": 7129, "JavaScript": 3487, "Ruby": 1927, "HTML": 1675, "Shell": 1308} | package kotlinx.coroutines.experimental.sync.impl
import kotlinx.coroutines.experimental.sync.AbstractSemaphore
import kotlinx.coroutines.experimental.sync.SuspendStrategy
import java.util.*
class SynchronizedSemaphore(maxPermits: Int) : AbstractSemaphore(maxPermits) {
private var _availablePermits = maxPermits
private var _queue = ArrayDeque<Any>()
override val availablePermits: Int get() = _availablePermits
@Synchronized
override fun tryAcquire(): Boolean {
if (_availablePermits > 0) {
_availablePermits--
return true
}
return false
}
@Synchronized
override fun acquireSuspend(item: Any, suspendStrategy: SuspendStrategy) {
if (_availablePermits > 0) {
_availablePermits--
suspendStrategy.resume(item)
return
}
suspendStrategy.suspendPrepare(item, {})
_queue.offer(item)
}
@Synchronized
override fun releaseImpl(suspendStrategy: SuspendStrategy) {
while (true) {
if (_availablePermits > 0 || _queue.isEmpty()) {
check(availablePermits < maxPermits)
_availablePermits++
return
} else {
if (suspendStrategy.resumeIfNotCancelled(_queue.poll()))
return
}
}
}
} | 0 | Kotlin | 0 | 0 | 225e777ca8b6920eb4e68632ce7080c601e5470b | 1,369 | kotlinx.coroutines | Apache License 2.0 |
kotlinq/src/main/kotlin/org/gradle/kotlin/dsl/KotlinqExt.kt | kotlinqs | 490,325,539 | false | {"Kotlin": 65504} | package org.gradle.kotlin.dsl
import io.github.kotlinq.plugin.KotlinqExtension
import org.gradle.api.Project
fun Project.kotlinq(init: (KotlinqExtension).() -> Unit) {
extensions.configure(KotlinqExtension::class.java) {
init(it)
}
}
| 0 | Kotlin | 0 | 1 | 21b213de61cc0506464e6baf5a6f51aeb811ec0b | 252 | kotlinq | Do What The F*ck You Want To Public License |
app/src/main/java/com/aditya/googledeveloperscommunityvisualisationtool/fragments/Notification/Notification.kt | soCallmeAdityaKumar | 647,671,779 | false | {"Kotlin": 441339} | package com.aditya.googledeveloperscommunityvisualisationtool.fragments.Notification
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView.RecyclerListener
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aditya.googledeveloperscommunityvisualisationtool.MainActivity
import com.aditya.googledeveloperscommunityvisualisationtool.fragments.home.GdgChaptersAdapter
import com.aditya.googledeveloperscommunityvisualisationtool.roomdatabase.notificationRoom.NotifyEntity
import com.aditya.googledeveloperscommunityvisualisationtool.roomdatabase.notificationRoom.NotifyViewModel
import com.aditya.googledeveloperscommunityvisualisationtool.roomdatabase.notificationRoom.NotifyViewModelFactory
import com.aditya.googledeveloperscommunityvisualisationtool.utility.ConstantPrefs
import com.aditya.googledeveloperscommunityvisualisationtool.R
import com.aditya.googledeveloperscommunityvisualisationtool.databinding.FragmentNotificationBinding
class Notification : Fragment() {
lateinit var binding: FragmentNotificationBinding
lateinit var notificationViewmodel:NotifyViewModel
lateinit var recyclerView:RecyclerView
lateinit var notificationAdapter: NotifyAdapter
lateinit var notificationList:ArrayList<notificationData>
lateinit var noItemText:TextView
lateinit var clearAll:Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding= FragmentNotificationBinding.inflate(inflater,container,false)
val view=binding.root
clearAll=binding.ClearButtton
noItemText=binding.NoItemText
notificationList= arrayListOf()
recyclerView=binding.NotificationrecyclerView
notificationAdapter = NotifyAdapter(notificationList)
recyclerView.layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = notificationAdapter
noItemText.visibility=View.VISIBLE
recyclerView.visibility=View.GONE
clearAll.visibility=View.GONE
return view
}
override fun onResume() {
super.onResume()
loadConnectionStatus()
val customAppBar = (activity as MainActivity).binding.appBarMain
val menuButton = customAppBar.menuButton
val navController = findNavController()
val isRootFragment = navController.graph.startDestinationId == navController.currentDestination?.id
if (isRootFragment) {
menuButton.setBackgroundResource(R.drawable.baseline_menu_24)
// menuButton?.visibility = View.VISIBLE
// backButton?.visibility = View.GONE
} else {
menuButton.setBackgroundResource(R.drawable.backarrow)
// menuButton?.visibility = View.GONE
// backButton?.visibility = View.VISIBLE
menuButton?.setOnClickListener {
(activity as MainActivity).onBackPressed()
}
}
}
private fun loadConnectionStatus() {
val sharedPreferences = activity?.getSharedPreferences(
ConstantPrefs.SHARED_PREFS.name,
Context.MODE_PRIVATE
)
val isConnected = sharedPreferences?.getBoolean(ConstantPrefs.IS_CONNECTED.name, false)
val act=activity as MainActivity
if (isConnected!!) {
act.binding.appBarMain.LGConnected.visibility=View.VISIBLE
act.binding.appBarMain.LGNotConnected.visibility=View.INVISIBLE
} else {
act.binding.appBarMain.LGConnected.visibility=View.INVISIBLE
act.binding.appBarMain.LGNotConnected.visibility=View.VISIBLE
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
notificationViewmodel=ViewModelProvider(requireActivity(),NotifyViewModelFactory(requireContext())).get(NotifyViewModel::class.java)
notificationViewmodel.readAllNotification.observe(requireActivity(), Observer{
notificationList=convertListType(it)
if(notificationList.isNotEmpty()){
noItemText.visibility=View.GONE
recyclerView.visibility=View.VISIBLE
clearAll.visibility=View.VISIBLE
}
notificationAdapter.refreshData(notificationList)
})
clearAll.setOnClickListener {
notificationViewmodel.deleteAllNotification()
noItemText.visibility=View.VISIBLE
recyclerView.visibility=View.GONE
clearAll.visibility=View.GONE
}
}
private fun convertListType(it: List<NotifyEntity>?): ArrayList<notificationData> {
val ls=ArrayList<notificationData>()
for(i in 0 until it!!.size){
ls.add(notificationData(it[i].image,it[i].desc,it[i].title,it[i].timeinMiliSec,it[i].time))
}
return ls
}
} | 0 | Kotlin | 1 | 6 | 21eabc0cd5a5041f79cfb78bfe4c20d6ffeaaf80 | 5,397 | Google-Developers-Community-Visualization-Tool | MIT License |
client/src/androidMain/kotlin/com/github/mustafaozhan/ccc/client/di/KoinAndroid.kt | shoanchikato | 389,199,653 | true | {"Kotlin": 263455, "Swift": 50806, "HTML": 797} | /*
* Copyright (c) 2021 <NAME>. All rights reserved.
*/
package com.github.mustafaozhan.ccc.client.di
import android.content.Context
import com.github.mustafaozhan.ccc.client.base.BaseViewModel
import com.github.mustafaozhan.ccc.client.di.module.clientModule
import com.github.mustafaozhan.ccc.client.di.module.getAndroidModule
import com.github.mustafaozhan.ccc.common.di.modules.apiModule
import com.github.mustafaozhan.ccc.common.di.modules.getDatabaseModule
import com.github.mustafaozhan.ccc.common.di.modules.getSettingsModule
import com.github.mustafaozhan.logmob.kermit
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.KoinApplication
import org.koin.core.context.startKoin
import org.koin.core.definition.Definition
import org.koin.core.instance.InstanceFactory
import org.koin.core.module.Module
import org.koin.core.qualifier.Qualifier
fun initAndroid(context: Context): KoinApplication = startKoin {
modules(
getAndroidModule(context),
clientModule,
apiModule,
getDatabaseModule(),
getSettingsModule()
)
}.also {
kermit.d { "KoinAndroid initAndroid" }
}
actual inline fun <reified T : BaseViewModel> Module.viewModelDefinition(
qualifier: Qualifier?,
createdAtStart: Boolean,
noinline definition: Definition<T>
): Pair<Module, InstanceFactory<T>> = viewModel(
qualifier = qualifier,
definition = definition
)
| 0 | null | 0 | 0 | a07fa9d230f86201b9ad348c98a23859fc01b082 | 1,420 | CCC | Apache License 2.0 |
app/src/main/java/com/amachikhin/testapplication/storage/dao/CurrentWeatherDao.kt | shustreek | 259,710,149 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 54, "XML": 26, "Java": 1} | package com.amachikhin.testapplication.storage.dao
import androidx.room.Dao
import androidx.room.Query
import com.amachikhin.testapplication.storage.entity.CurrentWeatherEntity
@Dao
interface CurrentWeatherDao : BaseDao<CurrentWeatherEntity> {
@Query("SELECT * FROM current_weather WHERE id =:id")
fun getWeather(id: Long): CurrentWeatherEntity?
} | 1 | null | 1 | 1 | cd17c880561a88d0c77dd625ad699560a2e140ce | 358 | progress | Apache License 2.0 |
src/main/kotlin/com/github/kerubistan/kerub/data/EventDao.kt | kerubistan | 19,528,622 | false | null | package com.github.kerubistan.kerub.data
import com.github.kerubistan.kerub.model.Event
import java.util.UUID
interface EventDao
: DaoOperations.Read<Event, UUID>, DaoOperations.Add<Event, UUID>, DaoOperations.PagedList<Event, UUID> | 109 | Kotlin | 4 | 14 | 99cb43c962da46df7a0beb75f2e0c839c6c50bda | 235 | kerub | Apache License 2.0 |
src/main/kotlin/ru/quipy/common/security/JwtAuthenticationFilter.kt | sad-bkt | 622,333,499 | false | null | package ru.quipy.common.security
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import ru.quipy.service.JwtTokenManager
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Component
class JwtAuthenticationFilter(private val tokenManager: JwtTokenManager) : OncePerRequestFilter() {
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
val token = retrieveToken(request)
if (token == null) {
filterChain.doFilter(request, response)
return
}
kotlin.runCatching { tokenManager.readAccessToken(token) }
.onSuccess { user ->
SecurityContextHolder.getContext().authentication =
UsernamePasswordAuthenticationToken(user, token, user.authorities)
}.onFailure { exc ->
logger.info(exc.message)
}
filterChain.doFilter(request, response)
}
} | 0 | Kotlin | 1 | 0 | ee51280a483cb804483ec1a747865ca3324aa49a | 1,279 | tiny-event-sourcing-demo | Apache License 2.0 |
uisdk/src/test/java/tech/dojo/pay/uisdk/domain/MakeCardPaymentUseCaseTest.kt | dojo-engineering | 478,120,913 | false | {"Kotlin": 1010135} | package tech.dojo.pay.uisdk.domain
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.given
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import tech.dojo.pay.uisdk.domain.entities.MakeCardPaymentParams
import tech.dojo.pay.uisdk.domain.entities.RefreshPaymentIntentResult
class MakeCardPaymentUseCaseTest {
private val updatePaymentStateUseCase: UpdatePaymentStateUseCase = mock()
private val getRefreshedPaymentTokenFlow: GetRefreshedPaymentTokenFlow = mock()
private val refreshPaymentIntentUseCase: RefreshPaymentIntentUseCase = mock()
private lateinit var makeCardPaymentUseCase: MakeCardPaymentUseCase
@Before
fun setup() {
makeCardPaymentUseCase = MakeCardPaymentUseCase(
updatePaymentStateUseCase,
getRefreshedPaymentTokenFlow,
refreshPaymentIntentUseCase,
)
}
@Test
fun `when calling makeCardPayment with successful refresh token should start payment process and updatePaymentSate`() =
runTest {
// arrange
val params = MakeCardPaymentParams(
paymentId = "123",
fullCardPaymentPayload = mock(),
dojoCardPaymentHandler = mock(),
)
given(getRefreshedPaymentTokenFlow.getUpdatedPaymentTokenFlow()).willReturn(
MutableStateFlow(
RefreshPaymentIntentResult.Success(token = "token"),
),
)
// act
makeCardPaymentUseCase.makeCardPayment(params, {})
// assert
verify(getRefreshedPaymentTokenFlow).getUpdatedPaymentTokenFlow()
verify(updatePaymentStateUseCase).updatePaymentSate(true)
verify(params.dojoCardPaymentHandler).executeCardPayment(any(), any())
verifyNoMoreInteractions(updatePaymentStateUseCase)
verifyNoMoreInteractions(getRefreshedPaymentTokenFlow)
}
@Test
fun `when calling makeCardPayment with RefreshFailure for token should not start payment and run onUpdateTokenError`() =
runTest {
// arrange
val params = MakeCardPaymentParams(
paymentId = "123",
fullCardPaymentPayload = mock(),
dojoCardPaymentHandler = mock(),
)
given(getRefreshedPaymentTokenFlow.getUpdatedPaymentTokenFlow()).willReturn(
MutableStateFlow(
RefreshPaymentIntentResult.RefreshFailure,
),
)
val onUpdateTokenError = mock<() -> Unit>()
// act
makeCardPaymentUseCase.makeCardPayment(params, onUpdateTokenError)
// assert
verify(updatePaymentStateUseCase).updatePaymentSate(false)
verify(onUpdateTokenError).invoke()
}
}
| 1 | Kotlin | 2 | 3 | 4f9e9be58189d22f5269a53bcc1a2b2028a777df | 3,036 | android-dojo-pay-sdk | MIT License |
plugins/terminal/completion/testSrc/com/intellij/terminal/completion/ShellCommandTreeAssertionsImpl.kt | JetBrains | 2,489,216 | false | null | package com.intellij.terminal.completion
import com.intellij.terminal.completion.engine.*
import com.intellij.util.containers.JBIterable
import com.intellij.util.containers.TreeTraversal
import junit.framework.TestCase.assertTrue
internal class ShellCommandTreeAssertionsImpl(root: ShellCommandTreeNode<*>) : ShellCommandTreeAssertions {
private val allChildren: JBIterable<ShellCommandTreeNode<*>> = TreeTraversal.PRE_ORDER_DFS.traversal(root) { node -> node.children }
override fun assertSubcommandOf(cmd: String, parentCmd: String) {
val childNode = allChildren.find { it.text == cmd } ?: error("Not found node with name: $cmd")
assertTrue("Expected that child is subcommand", childNode is ShellCommandNode)
assertTrue("Expected that parent of '$cmd' is a subcommand '$parentCmd', but was: ${childNode.parent}",
(childNode.parent as? ShellCommandNode)?.text == parentCmd)
}
override fun assertOptionOf(option: String, subcommand: String) {
val childNode = allChildren.find { it.text == option } ?: error("Not found node with name: $option")
assertTrue("Expected that child is option", childNode is ShellOptionNode)
assertTrue("Expected that parent of '$option' is a subcommand '$subcommand', but was: ${childNode.parent}",
(childNode.parent as? ShellCommandNode)?.text == subcommand)
}
override fun assertArgumentOfOption(arg: String, option: String) {
val childNode = allChildren.find { it.text == arg } ?: error("Not found node with name: $arg")
assertTrue("Expected that child is argument", childNode is ShellArgumentNode)
assertTrue("Expected that parent of '$arg' is an option '$option', but was: ${childNode.parent}",
(childNode.parent as? ShellOptionNode)?.text == option)
}
override fun assertArgumentOfSubcommand(arg: String, subcommand: String) {
val childNode = allChildren.find { it.text == arg } ?: error("Not found node with name: $arg")
assertTrue("Expected that child is argument", childNode is ShellArgumentNode)
assertTrue("Expected that parent of '$arg' is an option '$subcommand', but was: ${childNode.parent}",
(childNode.parent as? ShellCommandNode)?.text == subcommand)
}
override fun assertUnknown(child: String, parent: String) {
val childNode = allChildren.find { it.text == child } ?: error("Not found node with name: $child")
assertTrue("Expected that child is unknown", childNode is ShellUnknownNode)
assertTrue("Expected that parent of '$child' is '$parent', but was: ${childNode.parent}",
childNode.parent?.text == parent)
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 2,624 | intellij-community | Apache License 2.0 |
KotlinMultiplatform/XFullStack/shared/src/commonMain/kotlin/core/models/response/SendMessageResponse.kt | pradyotprksh | 385,586,594 | false | {"Kotlin": 2946772, "Dart": 1066884, "Python": 321205, "Rust": 180589, "Swift": 149624, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354} | package core.models.response
import kotlinx.serialization.Serializable
@Serializable
data class SendMessageResponse(
val chatId: String,
)
| 0 | Kotlin | 11 | 24 | da2054de505260bdfa5ffa6d67674f0fa5ba8d3c | 145 | development_learning | MIT License |
simplecloud-launcher/src/main/kotlin/eu/thesimplecloud/launcher/exception/module/ModuleLoadException.kt | theSimpleCloud | 270,085,977 | false | null | /*
* MIT License
*
* Copyright (C) 2020-2022 The SimpleCloud authors
*
* 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 eu.thesimplecloud.launcher.exception.module
class ModuleLoadException(moduleName: String, ex: Exception?) :
Exception("An error occurred while loading module: $moduleName", ex) {
constructor(moduleName: String) : this(moduleName, null)
} | 8 | null | 43 | 98 | 8f10768e2be523e9b2e7c170965ca4f52a99bf09 | 1,402 | SimpleCloud | MIT License |
app/src/main/java/com/gan/breakingbad/characters/domain/BreakingBadResultsActionHandler.kt | Raghuramchowdary-tech | 313,477,929 | false | null | package com.gan.breakingbad.characters.domain
import com.gan.breakingbad.characters.presentation.BreakingBadCharactersListPresenter
internal interface BreakingBadResultsActionHandler {
fun onErrorButtonClicked(errorState: BreakingBadCharactersListPresenter.ErrorState)
} | 0 | Kotlin | 0 | 0 | 16b2cdb270dda49f057f058f1e93e51261ed73fb | 276 | BreakingBadTask | Apache License 2.0 |
client/app/src/main/java/com/microsoft/research/karya/fetchData/FirstLoadFetchData.kt | sorskog | 367,672,600 | true | {"TypeScript": 729546, "Kotlin": 312743, "Java": 32041, "JavaScript": 6753, "CSS": 1987, "HTML": 1428} | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* This activity fetches all core data from the server. Core data includes all records from the
* language table, scenario table, language resource table, and the language resource value table.
* As the activity is executed before the user chooses any language, it cannot display any text
* messages. We can perhaps look into having images that can mark absence of network connection.
*/
package com.microsoft.research.karya.fetchData
import android.content.Intent
import com.microsoft.research.karya.common.NetworkActivity
import com.microsoft.research.karya.database.models.LanguageResourceType
import com.microsoft.research.karya.selectAppLanguage.SelectAppLanguage
import com.microsoft.research.karya.utils.AppConstants
import com.microsoft.research.karya.utils.FileUtils
import kotlinx.android.synthetic.main.activity_network_activity.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Response
import java.io.File
class FirstLoadFetchData : NetworkActivity(
indeterminateProgress = false,
noMessage = true,
allowRetry = false
) {
enum class FetchDataState {
FETCH_START,
SENT_LANGUAGE_REQUEST,
SENT_SCENARIO_REQUEST,
SENT_LANGUAGE_RESOURCE_REQUEST,
SENT_LANGUAGE_RESOURCE_VALUE_REQUEST,
RECEIVED_LANGUAGES,
RECEIVED_SCENARIOS,
RECEIVED_LANGUAGE_RESOURCES,
RECEIVED_LANGUAGE_RESOURCE_VALUES,
SENT_FILE_LANGUAGE_RESOURCE_REQUEST,
RECEIVED_FILE_LANGUAGE_RESOURCES,
FETCH_END
}
/**
* This activity is run before the user has fetched any language. Therefore, it is not possible
* to display any message or error.
*/
override suspend fun getStringsForActivity() = Unit
/**
* Set the initial UI strings
*/
override suspend fun setInitialUIStrings() = Unit
/**
* Execute the network requests to fetch the data. Update the UI on successful requests.
*/
override suspend fun executeRequest() {
/** Set initial state for the progress bar */
uiScope.launch {
networkRequestPb.max = FetchDataState.FETCH_END.ordinal
updateActivityProgress(FetchDataState.FETCH_START)
}
/** Get all the languages */
val languagesResponseDeferred = ioScope.async { karyaAPI.getLanguages() }
updateActivityProgress(FetchDataState.SENT_LANGUAGE_REQUEST)
/** Get all the scenarios */
val scenariosResponseDeferred = ioScope.async { karyaAPI.getScenarios() }
updateActivityProgress(FetchDataState.SENT_SCENARIO_REQUEST)
/** Get all the language resources */
val lrResponseDeferred = ioScope.async { karyaAPI.getLanguageResources() }
updateActivityProgress(FetchDataState.SENT_LANGUAGE_RESOURCE_REQUEST)
/** Get all the language resource values */
val lrvResponseDeferred = ioScope.async { karyaAPI.getLanguageResourceValues() }
updateActivityProgress(FetchDataState.SENT_LANGUAGE_RESOURCE_VALUE_REQUEST)
val languagesResponse = languagesResponseDeferred.await()
updateActivityProgress(FetchDataState.RECEIVED_LANGUAGES)
val scenariosResponse = scenariosResponseDeferred.await()
updateActivityProgress(FetchDataState.RECEIVED_SCENARIOS)
val lrResponse = lrResponseDeferred.await()
updateActivityProgress(FetchDataState.RECEIVED_LANGUAGE_RESOURCES)
val lrvResponse = lrvResponseDeferred.await()
updateActivityProgress(FetchDataState.RECEIVED_LANGUAGE_RESOURCE_VALUES)
/** If any of the calls have failed, then call error */
if (!languagesResponse.isSuccessful ||
!scenariosResponse.isSuccessful ||
!lrResponse.isSuccessful ||
!lrvResponse.isSuccessful) {
networkErrorMessage = ""
networkRetryMessage = ""
throw Exception("no_internet")
}
/** Gather all the data */
val languages = languagesResponse.body()!!
val scenarios = scenariosResponse.body()!!
val languageResourceValues = lrvResponse.body()!!
/** Gather and sort language resources */
val languageResources = lrResponse.body()!!.sortedWith(Comparator { r1, r2 ->
when {
r1.type == LanguageResourceType.string_resource -> -1
r2.type == LanguageResourceType.file_resource -> -1
else -> 1
}
})
/** Upsert all of them into the local db */
karyaDb.languageDao().upsert(languages)
karyaDb.scenarioDao().upsert(scenarios)
karyaDb.languageResourceDao().upsert(languageResources)
karyaDb.languageResourceValueDao().upsert(languageResourceValues)
/** Get all list file resources */
val listResources = karyaDb.languageResourceDaoExtra().getListFileResources()
val listFileRequests: MutableList<Deferred<Response<ResponseBody>>?> = mutableListOf()
for (resId in listResources) {
val filePath = getBlobPath(KaryaFileContainer.LR_LRVS, resId.toString())
if (!File(filePath).exists()) {
val requestDeferred = ioScope.async {
karyaAPI.getFileLanguageResourceValuesByLanguageResourceId(resId)
}
listFileRequests.add(requestDeferred)
} else {
listFileRequests.add(null)
}
}
updateActivityProgress(FetchDataState.SENT_FILE_LANGUAGE_RESOURCE_REQUEST)
val langResDir = getContainerDirectory(KaryaFileContainer.LANG_RES)
for ((resId, deferredRequest) in listResources zip listFileRequests) {
val filePath = getBlobPath(KaryaFileContainer.LR_LRVS, resId.toString())
// Download file if request was sent
if (deferredRequest != null) {
val response = deferredRequest.await()
if (response.isSuccessful) {
FileUtils.downloadFileToLocalPath(response, filePath)
}
}
if (File(filePath).exists()) {
FileUtils.extractTarBallIntoDirectory(filePath, langResDir)
}
}
updateActivityProgress(FetchDataState.RECEIVED_FILE_LANGUAGE_RESOURCES)
updateActivityProgress(FetchDataState.FETCH_END)
}
/**
* Start the select app language activity
*/
override fun startNextActivity() {
val nextIntent = Intent(applicationContext, SelectAppLanguage::class.java)
nextIntent.putExtra(
AppConstants.SELECT_APP_LANGUAGE_CALLER,
AppConstants.FETCH_DATA_ON_INIT
)
startActivity(nextIntent)
}
/**
* Override the function to set error message. This activity cannot display any message as it is
* run before the user selects a language.
*/
override fun setErrorMessage() {
finish()
}
/**
* Update the progress of the activity
*/
private fun updateActivityProgress(state: FetchDataState) = uiScope.launch {
networkRequestPb.progress = state.ordinal
}
}
| 0 | null | 0 | 0 | 66d97154bc39d3107a0cd0f0694a68a81bd7b251 | 7,298 | rural-crowdsourcing-toolkit | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/subjectaccessrequestworker/gateways/ProbationApiGatewayTest.kt | ministryofjustice | 748,250,175 | false | {"Kotlin": 264949, "Mustache": 105858, "Shell": 7048, "Dockerfile": 1161} | package uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.gateways
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import org.mockito.Mockito
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Import
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.config.ApplicationInsightsConfiguration
import uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.mockservers.ProbationApiMockServer
@ActiveProfiles("test")
@Import(ApplicationInsightsConfiguration::class)
@ContextConfiguration(
initializers = [ConfigDataApplicationContextInitializer::class],
classes = [(ProbationApiGateway::class)],
)
class ProbationApiGatewayTest(
@Autowired val probationApiGateway: ProbationApiGateway,
@MockBean val mockHmppsAuthGateway: HmppsAuthGateway,
) : DescribeSpec(
{
val probationApiMockServer = ProbationApiMockServer()
Mockito.`when`(mockHmppsAuthGateway.getClientToken()).thenReturn("mock-bearer-token")
beforeEach {
probationApiMockServer.start()
probationApiMockServer.stubGetOffenderDetails()
}
afterTest {
probationApiMockServer.stop()
}
describe("getOffenderName") {
it("returns the offender name") {
val offenderName = probationApiGateway.getOffenderName("A999999")
offenderName.shouldBe("LASTNAME, Firstname")
}
}
},
)
| 3 | Kotlin | 0 | 1 | 82d22434568c80edb191920f67aa4e1cf583657a | 1,697 | hmpps-subject-access-request-worker | MIT License |
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/VpnFeaturesRegistryImpl.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2022 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.mobile.android.vpn
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.data.store.api.SharedPreferencesProvider
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.mobile.android.vpn.service.TrackerBlockingVpnService
import com.squareup.anvil.annotations.ContributesBinding
import dagger.SingleInstanceIn
import java.util.UUID
import javax.inject.Inject
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import logcat.logcat
private const val PREFS_FILENAME = "com.duckduckgo.mobile.android.vpn.feature.registry.v1"
private const val IS_INITIALIZED = "IS_INITIALIZED"
@ContributesBinding(
scope = AppScope::class,
boundType = VpnFeaturesRegistry::class,
)
@ContributesBinding(
scope = AppScope::class,
boundType = Vpn::class,
)
@SingleInstanceIn(AppScope::class)
class VpnFeaturesRegistryImpl @Inject constructor(
private val vpnServiceWrapper: VpnServiceWrapper,
private val sharedPreferencesProvider: SharedPreferencesProvider,
private val dispatcherProvider: DispatcherProvider,
) : VpnFeaturesRegistry, Vpn {
private val mutex = Mutex()
private val preferences: SharedPreferences by lazy {
sharedPreferencesProvider.getSharedPreferences(PREFS_FILENAME, multiprocess = true, migrate = false)
}
override suspend fun registerFeature(feature: VpnFeature) = withContext(dispatcherProvider.io()) {
mutex.lock()
try {
logcat { "registerFeature: $feature" }
preferences.edit(commit = true) {
// we use random UUID to force change listener to be called
putString(feature.featureName, UUID.randomUUID().toString())
}
vpnServiceWrapper.restartVpnService(forceRestart = true)
} finally {
mutex.unlock()
}
}
override suspend fun unregisterFeature(feature: VpnFeature) = withContext(dispatcherProvider.io()) {
mutex.lock()
try {
if (preferences.contains(feature.featureName)) {
preferences.edit(commit = true) {
remove(feature.featureName)
}
logcat { "unregisterFeature: $feature" }
if (registeredFeatures().isNotEmpty()) {
vpnServiceWrapper.restartVpnService(forceRestart = true)
} else {
vpnServiceWrapper.stopService()
}
}
} finally {
mutex.unlock()
}
}
override suspend fun isFeatureRunning(feature: VpnFeature): Boolean = withContext(dispatcherProvider.io()) {
return@withContext isFeatureRegistered(feature) && vpnServiceWrapper.isServiceRunning()
}
override suspend fun isFeatureRegistered(feature: VpnFeature): Boolean = withContext(dispatcherProvider.io()) {
return@withContext registeredFeatures().contains(feature.featureName)
}
override suspend fun isAnyFeatureRunning(): Boolean = withContext(dispatcherProvider.io()) {
return@withContext isAnyFeatureRegistered() && vpnServiceWrapper.isServiceRunning()
}
override suspend fun isAnyFeatureRegistered(): Boolean = withContext(dispatcherProvider.io()) {
return@withContext registeredFeatures().isNotEmpty()
}
override suspend fun refreshFeature(feature: VpnFeature) = withContext(dispatcherProvider.io()) {
vpnServiceWrapper.restartVpnService(forceRestart = false)
}
override suspend fun getRegisteredFeatures(): List<VpnFeature> = withContext(dispatcherProvider.io()) {
return@withContext registeredFeatures().keys.map { VpnFeature { it } }
}
private fun registeredFeatures(): Map<String, Any?> {
return preferences.all.filter { it.key != IS_INITIALIZED }
}
override suspend fun start() = withContext(dispatcherProvider.io()) {
vpnServiceWrapper.startService()
}
override suspend fun pause() {
vpnServiceWrapper.stopService()
}
override suspend fun stop() {
try {
mutex.lock()
// unregister all features
getRegisteredFeatures().onEach {
preferences.edit(commit = true) {
remove(it.featureName)
}
}
// stop VPN
vpnServiceWrapper.stopService()
} finally {
mutex.unlock()
}
}
override suspend fun snooze(triggerAtMillis: Long) {
vpnServiceWrapper.snoozeService(triggerAtMillis)
}
}
/**
* This class is here purely to wrap TrackerBlockingVpnService static calls that deal with enable/disable VPN, so that we can
* unit test the [VpnFeaturesRegistryImpl] class.
*
* The class is marked as open to be able to mock it in tests.
*/
open class VpnServiceWrapper @Inject constructor(
private val context: Context,
) {
open fun restartVpnService(forceRestart: Boolean) {
TrackerBlockingVpnService.restartVpnService(context, forceRestart = forceRestart)
}
open fun stopService() {
TrackerBlockingVpnService.stopService(context)
}
open fun startService() {
TrackerBlockingVpnService.startService(context)
}
open fun snoozeService(triggerAtMillis: Long) {
TrackerBlockingVpnService.snoozeService(context, triggerAtMillis)
}
open fun isServiceRunning(): Boolean {
return TrackerBlockingVpnService.isServiceRunning(context)
}
}
| 67 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 6,205 | Android | Apache License 2.0 |
data/RF02921/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF02921"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
3 to 5
68 to 70
}
value = "#db8f2c"
}
color {
location {
6 to 9
63 to 66
}
value = "#95dfc0"
}
color {
location {
14 to 15
59 to 60
}
value = "#f710d2"
}
color {
location {
25 to 27
49 to 51
}
value = "#414e93"
}
color {
location {
31 to 35
44 to 48
}
value = "#3d0041"
}
color {
location {
97 to 100
121 to 124
}
value = "#6905ec"
}
color {
location {
141 to 142
199 to 200
}
value = "#8df823"
}
color {
location {
143 to 146
194 to 197
}
value = "#b42abd"
}
color {
location {
148 to 150
188 to 190
}
value = "#2ae212"
}
color {
location {
154 to 156
184 to 186
}
value = "#4fb9f1"
}
color {
location {
163 to 164
177 to 178
}
value = "#af323e"
}
color {
location {
6 to 5
67 to 67
}
value = "#4983d8"
}
color {
location {
10 to 13
61 to 62
}
value = "#6b2ac5"
}
color {
location {
16 to 24
52 to 58
}
value = "#853c68"
}
color {
location {
28 to 30
49 to 48
}
value = "#b502f9"
}
color {
location {
36 to 43
}
value = "#25029b"
}
color {
location {
101 to 120
}
value = "#d7a49f"
}
color {
location {
143 to 142
198 to 198
}
value = "#480f7f"
}
color {
location {
147 to 147
191 to 193
}
value = "#a4aea0"
}
color {
location {
151 to 153
187 to 187
}
value = "#9de407"
}
color {
location {
157 to 162
179 to 183
}
value = "#8865e7"
}
color {
location {
165 to 176
}
value = "#a30e3e"
}
color {
location {
1 to 2
}
value = "#9cb557"
}
color {
location {
71 to 96
}
value = "#a6f00b"
}
color {
location {
125 to 140
}
value = "#5953c6"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 3,791 | Rfam-for-RNArtist | MIT License |
combined/src/main/kotlin/com/github/jan222ik/ui/feature/SharedCommands.kt | jan222ik | 462,289,211 | false | {"Kotlin": 852617, "Java": 17948} | package com.github.jan222ik.ui.feature
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.ui.geometry.Offset
import com.github.jan222ik.model.TMM
import com.github.jan222ik.model.command.CommandStackHandler
import com.github.jan222ik.model.command.ICommand
import com.github.jan222ik.ui.components.menu.DrawableIcon
import com.github.jan222ik.ui.components.menu.MenuContribution
import com.github.jan222ik.ui.feature.main.diagram.EditorManager
import com.github.jan222ik.ui.feature.main.diagram.canvas.DNDCreation
import com.github.jan222ik.ui.feature.main.diagram.canvas.EditorTabViewModel
import com.github.jan222ik.ui.feature.main.footer.progress.JobHandler
import com.github.jan222ik.ui.feature.main.keyevent.ShortcutAction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
object SharedCommands {
var forceOpenProperties: (() -> Unit)? = null
var showHideExplorer: ShortcutAction? = null
var showHidePalette: ShortcutAction? = null
var showHidePropertiesView: ShortcutAction? = null
} | 0 | Kotlin | 0 | 0 | e67597e41b47ec7676aa0e879062d8356f1b4672 | 1,102 | MSc-Master-Composite | Apache License 2.0 |
src/main/kotlin/org/t246osslab/easybuggy4kt/troubles/DeadlockController2.kt | k-tamura | 107,135,934 | false | null | package org.t246osslab.easybuggy4kt.troubles
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.DataAccessException
import org.springframework.dao.DeadlockLoserDataAccessException
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Controller
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.support.DefaultTransactionDefinition
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.servlet.ModelAndView
import org.t246osslab.easybuggy4kt.controller.AbstractController
import org.t246osslab.easybuggy4kt.core.model.User
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession
@Controller
class DeadlockController2 : AbstractController() {
@Autowired
internal var jdbcTemplate: JdbcTemplate? = null
@Autowired
private val txMgr: PlatformTransactionManager? = null
@RequestMapping(value = "/deadlock2")
fun process(req: HttpServletRequest, ses: HttpSession, mav: ModelAndView, locale: Locale): ModelAndView {
setViewAndCommonObjects(mav, locale, "deadlock2")
// Overwrite title (because title is the same as xee page)
mav.addObject("title", msg?.getMessage("title.xee.page", null, locale))
val users: MutableList<User>?
val order = getOrder(req)
if ("POST" == req.method) {
users = ArrayList()
var j = 0
while (true) {
val uid = req.getParameter("uid_" + (j + 1)) ?: break
val user = User()
user.userId = uid
user.name = req.getParameter(uid + "_name")
user.phone = req.getParameter(uid + "_phone")
user.mail = req.getParameter(uid + "_mail")
users.add(user)
j++
}
updateUsers(users, locale, mav)
} else {
users = selectUsers(order, locale, mav)
}
mav.addObject("userList", users)
mav.addObject("order", order)
return mav
}
private fun getOrder(req: HttpServletRequest): String {
var order = req.getParameter("order")
order = if ("asc" == order) {
"desc"
} else {
"asc"
}
return order
}
private fun selectUsers(order: String, locale: Locale, mav: ModelAndView): MutableList<User>? {
var users: MutableList<User>? = null
try {
users = jdbcTemplate!!.query("select * from users where ispublic = 'true' order by id " + if ("desc" == order) "desc" else "asc", { rs, _ ->
val user = User()
user.userId = rs.getString("id")
user.name = rs.getString("name")
user.phone = rs.getString("phone")
user.mail = rs.getString("mail")
user
})
} catch (e: DataAccessException) {
mav.addObject("errmsg",
msg?.getMessage("msg.db.access.error.occur", arrayOf(e.message), null, locale))
log.error("DataAccessException occurs: ", e)
} catch (e: Exception) {
mav.addObject("errmsg",
msg?.getMessage("msg.unknown.exception.occur", arrayOf(e.message), null, locale))
log.error("Exception occurs: ", e)
}
return users
}
private fun updateUsers(users: List<User>, locale: Locale, mav: ModelAndView) {
val dtDef = DefaultTransactionDefinition()
val trnStatus = txMgr!!.getTransaction(dtDef)
var executeUpdate = 0
try {
for (user in users) {
executeUpdate += jdbcTemplate!!.update("Update users set name = ?, phone = ?, mail = ? where id = ?",
user.name, user.phone, user.mail, user.userId)
log.info(user.userId + " is updated.")
Thread.sleep(500)
}
txMgr!!.commit(trnStatus)
mav.addObject("msg", msg?.getMessage("msg.update.records", arrayOf<Any>(executeUpdate), null, locale))
} catch (e: DeadlockLoserDataAccessException) {
txMgr!!.rollback(trnStatus)
mav.addObject("errmsg", msg?.getMessage("msg.deadlock.occurs", null, locale))
log.error("DeadlockLoserDataAccessException occurs: ", e)
} catch (e: DataAccessException) {
txMgr!!.rollback(trnStatus)
mav.addObject("errmsg",
msg?.getMessage("msg.db.access.error.occur", arrayOf(e.message), null, locale))
log.error("DataAccessException occurs: ", e)
} catch (e: Exception) {
txMgr!!.rollback(trnStatus)
mav.addObject("errmsg",
msg?.getMessage("msg.unknown.exception.occur", arrayOf(e.message), null, locale))
log.error("Exception occurs: ", e)
}
}
}
| 0 | Kotlin | 4 | 3 | 837775d00038e482647a6fcbe1c8ddfed0ef906f | 4,994 | easybuggy4kt | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day13Test.kt | dirkgroot | 317,968,017 | false | null | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
private fun solution1(input: String) = parse(input)
.mapIndexed { index, packets -> index to packets }
.filter { (_, packets) -> packets.first < packets.second }
.sumOf { (index, _) -> index + 1 }
private val div1 = parseEntry("[[2]]")
private val div2 = parseEntry("[[6]]")
private fun solution2(input: String) = parse(input).flatMap { it.toList() }
.plus(listOf(div1, div2))
.sorted().let { (it.indexOf(div1) + 1) * (it.indexOf(div2) + 1) }
private fun parse(input: String) = input.split("\n\n")
.map { it.split("\n") }
.map { (l, r) -> parseEntry(l) to parseEntry(r) }
private fun parseEntry(input: String) = "\\[|]|\\d+".toRegex().findAll(input)
.map { match -> match.value }
.let { tokens -> parse(tokens.iterator()) ?: throw IllegalStateException() }
private fun parse(tokens: Iterator<String>): Entry? =
when (val token = tokens.next()) {
"]" -> null
"[" -> ListEntry(generateSequence { parse(tokens) }.toList())
else -> IntEntry(token.toInt())
}
private sealed interface Entry : Comparable<Entry>
private data class ListEntry(val values: List<Entry>) : Entry {
override fun compareTo(other: Entry): Int = when (other) {
is IntEntry -> compareTo(ListEntry(listOf(other)))
is ListEntry -> values.zip(other.values)
.map { (a, b) -> a.compareTo(b) }
.firstOrNull { it != 0 } ?: values.size.compareTo(other.values.size)
}
}
private data class IntEntry(val value: Int) : Entry {
override fun compareTo(other: Entry) = when (other) {
is IntEntry -> value.compareTo(other.value)
is ListEntry -> ListEntry(listOf(this)).compareTo(other)
}
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 13
class Day13Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 13 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 6369 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 140 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 25800 }
})
private val exampleInput =
"""
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
""".trimIndent()
| 0 | Kotlin | 1 | 1 | 15fc4f7ce13082159ecb3912cca95ab067901403 | 2,782 | adventofcode-kotlin | MIT License |
compiler/tests-spec/testData/psi/linked/when-expression/p-3/neg/1.1.kt | tnorbye | 162,147,688 | true | {"Kotlin": 32763299, "Java": 7651072, "JavaScript": 152998, "HTML": 71905, "Lex": 18278, "IDL": 10641, "ANTLR": 9803, "Shell": 7727, "Groovy": 6091, "Batchfile": 5362, "CSS": 4679, "Scala": 80} | /*
* KOTLIN PSI SPEC TEST (NEGATIVE)
*
* SECTIONS: when-expression
* PARAGRAPH: 3
* SENTENCE: [1] When expression without bound value (the form where the expression enclosed in parantheses is absent) evaluates one of the many different expressions based on corresponding conditions present in the same when entry.
* NUMBER: 1
* DESCRIPTION: 'When' without bound value and missed control structure body.
*/
fun case_1() {
when {
value == 1 ->
}
} | 0 | Kotlin | 2 | 2 | b6be6a4919cd7f37426d1e8780509a22fa49e1b1 | 470 | kotlin | Apache License 2.0 |
src/test/kotlin/dev/shtanko/algorithms/leetcode/NumRookCapturesTest.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5994492, "Shell": 1168, "Makefile": 961} | /*
* Copyright 2021 Oleksii Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.stream.Stream
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class NumRookCapturesTest<out T : NumRookCaptures>(private val strategy: T) {
private class InputArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
arrayOf(
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'p', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'R', '.', '.', '.', 'p'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'p', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
),
3,
),
Arguments.of(
arrayOf(
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', 'p', 'p', 'p', 'p', 'p', '.', '.'),
charArrayOf('.', 'p', 'p', 'B', 'p', 'p', '.', '.'),
charArrayOf('.', 'p', 'B', 'R', 'B', 'p', '.', '.'),
charArrayOf('.', 'p', 'p', 'B', 'p', 'p', '.', '.'),
charArrayOf('.', 'p', 'p', 'p', 'p', 'p', '.', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
),
0,
),
Arguments.of(
arrayOf(
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'p', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'p', '.', '.', '.', '.'),
charArrayOf('p', 'p', '.', 'R', '.', 'p', 'B', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'B', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', 'p', '.', '.', '.', '.'),
charArrayOf('.', '.', '.', '.', '.', '.', '.', '.'),
),
3,
),
)
}
@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `num Rook captures test`(board: Array<CharArray>, expected: Int) {
val actual = strategy.perform(board)
assertThat(actual).isEqualTo(expected)
}
}
class NumRookCapturesSFTest : NumRookCapturesTest<NumRookCapturesSF>(NumRookCapturesSF())
class NumRookCapturesSearchTest : NumRookCapturesTest<NumRookCapturesSearch>(NumRookCapturesSearch())
| 4 | Kotlin | 0 | 19 | aacc85a5d7a83b8a0294ee7311eb97990d53366b | 3,772 | kotlab | Apache License 2.0 |
profile/src/test/java/rdx/works/profile/accountextensions/TransferBetweenOwnedAccountsTest.kt | radixdlt | 513,047,280 | false | null | package rdx.works.profile.accountextensions
import com.radixdlt.sargon.Account
import com.radixdlt.sargon.AssetException
import com.radixdlt.sargon.Cap26KeyKind
import com.radixdlt.sargon.DepositAddressExceptionRule
import com.radixdlt.sargon.DepositRule
import com.radixdlt.sargon.DerivationPath
import com.radixdlt.sargon.DeviceInfo
import com.radixdlt.sargon.DisplayName
import com.radixdlt.sargon.FactorSource
import com.radixdlt.sargon.FactorSourceId
import com.radixdlt.sargon.HostId
import com.radixdlt.sargon.HostInfo
import com.radixdlt.sargon.MnemonicWithPassphrase
import com.radixdlt.sargon.NetworkId
import com.radixdlt.sargon.Profile
import com.radixdlt.sargon.ResourceAddress
import com.radixdlt.sargon.ThirdPartyDeposits
import com.radixdlt.sargon.extensions.AssetsExceptionList
import com.radixdlt.sargon.extensions.DepositorsAllowList
import com.radixdlt.sargon.extensions.account
import com.radixdlt.sargon.extensions.derivePublicKey
import com.radixdlt.sargon.extensions.id
import com.radixdlt.sargon.extensions.init
import com.radixdlt.sargon.samples.sample
import com.radixdlt.sargon.samples.sampleMainnet
import io.mockk.coEvery
import io.mockk.mockk
import org.junit.Assert.assertFalse
import org.junit.Before
import org.junit.Test
import rdx.works.core.sargon.addAccounts
import rdx.works.core.sargon.babylon
import rdx.works.core.sargon.initBabylon
import rdx.works.core.sargon.isSignatureRequiredBasedOnDepositRules
import rdx.works.core.sargon.updateThirdPartyDepositSettings
import rdx.works.profile.data.repository.MnemonicRepository
import kotlin.test.assertTrue
class TransferBetweenOwnedAccountsTest {
private val mnemonicWithPassphrase = MnemonicWithPassphrase.init(
phrase = "bright club bacon dinner achieve pull grid save ramp cereal blush woman " +
"humble limb repeat video sudden possible story mask neutral prize goose mandate"
)
private val hostId = HostId.sample()
private val hostInfo = HostInfo.sample.other()
private val babylonFactorSource = FactorSource.Device.babylon(
mnemonicWithPassphrase = mnemonicWithPassphrase,
hostInfo = hostInfo,
isMain = true
)
var profile = Profile.init(
deviceFactorSource = babylonFactorSource,
hostId = hostId,
hostInfo = hostInfo
)
private val defaultNetwork = NetworkId.MAINNET
private lateinit var targetAccount: Account
private val asset1address = ResourceAddress.sampleMainnet.random()
private val asset2address = ResourceAddress.sampleMainnet.random()
private val targetAccountWithAsset1 = listOf(asset1address)
private val acceptAll = ThirdPartyDeposits(
depositRule = DepositRule.ACCEPT_ALL,
assetsExceptionList = AssetsExceptionList().asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val acceptAllAndDenyAsset1 = ThirdPartyDeposits(
depositRule = DepositRule.ACCEPT_ALL,
assetsExceptionList = AssetsExceptionList(
AssetException(
address = asset1address,
exceptionRule = DepositAddressExceptionRule.DENY
)
).asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val denyAll = ThirdPartyDeposits(
depositRule = DepositRule.DENY_ALL,
assetsExceptionList = AssetsExceptionList().asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val denyAllAndAllowAsset1 = ThirdPartyDeposits(
depositRule = DepositRule.DENY_ALL,
assetsExceptionList = AssetsExceptionList(
AssetException(
address = asset1address,
exceptionRule = DepositAddressExceptionRule.ALLOW
)
).asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val denyAllAndDenyAsset1 = ThirdPartyDeposits(
depositRule = DepositRule.DENY_ALL,
assetsExceptionList = AssetsExceptionList(
AssetException(
address = asset1address,
exceptionRule = DepositAddressExceptionRule.DENY
)
).asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val acceptKnown = ThirdPartyDeposits(
depositRule = DepositRule.ACCEPT_KNOWN,
assetsExceptionList = AssetsExceptionList().asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val acceptKnownAndAllowAsset1 = ThirdPartyDeposits(
depositRule = DepositRule.ACCEPT_KNOWN,
assetsExceptionList = AssetsExceptionList(
AssetException(
address = asset1address,
exceptionRule = DepositAddressExceptionRule.ALLOW
)
).asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
private val acceptKnownAndDenyAsset1 = ThirdPartyDeposits(
depositRule = DepositRule.ACCEPT_KNOWN,
assetsExceptionList = AssetsExceptionList(
AssetException(
address = asset1address,
exceptionRule = DepositAddressExceptionRule.DENY
)
).asList(),
depositorsAllowList = DepositorsAllowList().asList()
)
@Before
fun setUp() {
val mnemonicRepository = mockk<MnemonicRepository>()
coEvery { mnemonicRepository.createNew() } returns Result.success(mnemonicWithPassphrase)
val derivationPath = DerivationPath.Cap26.account(
networkId = defaultNetwork,
keyKind = Cap26KeyKind.TRANSACTION_SIGNING,
index = 0u
)
targetAccount = Account.initBabylon(
networkId = defaultNetwork,
displayName = DisplayName("target account"),
hdPublicKey = mnemonicWithPassphrase.derivePublicKey(path = derivationPath),
factorSourceId = profile.factorSources.first().id as FactorSourceId.Hash
)
profile = profile.addAccounts(
accounts = listOf(targetAccount),
onNetwork = defaultNetwork
)
}
@Test
fun `given accept all, when transfer between user's own accounts, then signature is not required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptAll
)
assertFalse(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given deny all, when transfer between user's own accounts, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = denyAll
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept all and deny Asset1 rule, when transfer Asset2 between user's own accounts, then signature is not required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptAllAndDenyAsset1
)
assertFalse(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset2address))
}
@Test
fun `given accept all and deny Asset1 rule, when transfer Asset1 between user's own accounts, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptAllAndDenyAsset1
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given deny all and allow Asset1 rule, when transfer Asset2 between user's own accounts, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = denyAllAndAllowAsset1
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset2address))
}
@Test
fun `given deny all and allow Asset1 rule, when transfer Asset1 between user's own accounts, then signature is not required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = denyAllAndAllowAsset1
)
assertFalse(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given deny all and deny Asset1 rule, when transfer Asset1 between user's own accounts, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = denyAllAndDenyAsset1
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept known and target account has not Asset1, when transfer Asset1 from user's own account to user's target account, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnown
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept known and allow Asset1 rule and target account has not Asset1, when transfer Asset1 from user's own account to user's target account, then signature is not required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnownAndAllowAsset1
)
assertFalse(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept known and deny Asset1 rule and target account has not Asset1, when transfer Asset1 from user's own account to user's target account, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnownAndDenyAsset1
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept known and target account has Asset1, when transfer Asset1 from user's own account to user's target account, then signature is not required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnown
)
assertFalse(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address, targetAccountWithAsset1))
}
@Test
fun `given accept known and allow Asset1 rule and target account has Asset1, when transfer Asset1 from user's own account to user's target account, then signature is not required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnownAndAllowAsset1
)
assertFalse(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept known and deny Asset1 rule and target account has Asset1, when transfer Asset1 from user's own account to user's target account, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnownAndDenyAsset1
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset1address))
}
@Test
fun `given accept known and allow Asset1 rule and target account has Asset1 but not Asset2, when transfer Asset2 from user's own account to user's target account, then signature is required`() {
profile = profile.updateThirdPartyDepositSettings(
account = targetAccount,
thirdPartyDeposits = acceptKnownAndAllowAsset1
)
assertTrue(profile.networks[0].accounts[0].isSignatureRequiredBasedOnDepositRules(asset2address))
}
} | 6 | null | 6 | 9 | a973af97556c2c3c5c800dac937d0007a13a3a1c | 12,245 | babylon-wallet-android | Apache License 2.0 |
app/TaskManagerPlus/app/src/main/java/maif/taskmanagerplus/data/model/Task.kt | maiconfang | 867,286,298 | false | {"Kotlin": 40210} | package maif.taskmanagerplus.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "tasks")
data class Task(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val title: String,
val description: String?,
val status: String // Could be "Pending" or "Completed"
)
| 0 | Kotlin | 0 | 0 | 09826d038529e49c76c153b13ccf96dbb263cc11 | 317 | taskmanagerplus-android-app | MIT License |
modules/education/src/main/java/edu/stanford/spezi/modules/education/videos/component/ExpandableVideoSection.kt | StanfordSpezi | 787,513,636 | false | {"Kotlin": 865422, "Ruby": 1755, "Shell": 212} | package edu.stanford.spezi.modules.education.videos.component
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import edu.stanford.spezi.core.design.theme.Colors
import edu.stanford.spezi.core.design.theme.Sizes
import edu.stanford.spezi.core.design.theme.Spacings
import edu.stanford.spezi.core.design.theme.SpeziTheme
import edu.stanford.spezi.core.design.theme.TextStyles
import edu.stanford.spezi.core.design.theme.TextStyles.titleLarge
import edu.stanford.spezi.core.design.theme.ThemePreviews
import edu.stanford.spezi.core.design.theme.lighten
import edu.stanford.spezi.modules.education.videos.Video
import edu.stanford.spezi.modules.education.videos.VideoItem
@Composable
internal fun SectionHeader(
text: String?,
isExpanded: Boolean,
onHeaderClicked: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { onHeaderClicked() }
.padding(Spacings.medium),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
text?.let {
Text(
text = it,
style = titleLarge
)
}
ExpandIcon(isExpanded)
}
}
@Composable
internal fun ExpandableVideoSection(
modifier: Modifier = Modifier,
title: String?,
description: String?,
videos: List<Video> = emptyList(),
expandedStartValue: Boolean = false,
onExpand: () -> Unit = {},
onActionClick: (Video) -> Unit = { _ -> },
) {
var expanded by remember { mutableStateOf(expandedStartValue) }
ElevatedCard(
elevation = CardDefaults.cardElevation(defaultElevation = Sizes.Elevation.medium),
shape = RoundedCornerShape(Sizes.RoundedCorner.large),
colors = CardDefaults.cardColors(
containerColor = Colors.surface.lighten(),
),
modifier = modifier
.fillMaxWidth()
.padding(Spacings.small)
.clickable { expanded = !expanded }
) {
Column(
modifier = Modifier.background(Colors.surface.lighten())
) {
SectionHeader(
text = title,
isExpanded = expanded,
onHeaderClicked = {
expanded = !expanded
onExpand()
}
)
description?.let {
Text(
style = TextStyles.bodyMedium,
text = it,
modifier = Modifier
.fillMaxWidth()
.padding(Spacings.medium),
color = MaterialTheme.colorScheme.onBackground,
)
}
AnimatedVisibility(
visible = expanded,
enter = expandVertically(),
exit = shrinkVertically()
) {
Column {
videos.forEach { video ->
VideoItem(video,
onVideoClick = {
onActionClick(
video
)
})
}
}
}
}
}
}
@Composable
internal fun ExpandIcon(expanded: Boolean) {
val vector = if (expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown
Icon(
imageVector = vector,
contentDescription = null,
)
}
private class ExpandableSectionPreviewProvider :
PreviewParameterProvider<ExpandableVideoSectionParams> {
val factory = ExpandableVideoSectionParamsFactory()
override val values: Sequence<ExpandableVideoSectionParams> = sequenceOf(
factory.createParams(),
factory.createParams().copy(expandedStartValue = true),
)
override val count: Int = values.count()
}
@ThemePreviews
@Composable
private fun ExpandableVideoSectionPreview(
@PreviewParameter(ExpandableSectionPreviewProvider::class) params: ExpandableVideoSectionParams,
) {
SpeziTheme {
Column {
ExpandableVideoSection(
title = params.title,
description = params.description,
expandedStartValue = params.expandedStartValue
)
}
}
}
private data class ExpandableVideoSectionParams(
val title: String?,
val description: String?,
val content: @Composable () -> Unit,
val expandedStartValue: Boolean = false,
)
private class ExpandableVideoSectionParamsFactory {
fun createParams(
title: String? = "Title",
description: String? = "Description",
content: @Composable () -> Unit = { Text(text = "Content") },
expandedStartValue: Boolean = false,
): ExpandableVideoSectionParams {
return ExpandableVideoSectionParams(
title = title,
description = description,
content = content,
expandedStartValue = expandedStartValue
)
}
}
| 24 | Kotlin | 1 | 8 | ac28a4eab4e6d6b300202260ed8269f3b512fb40 | 6,358 | SpeziKt | MIT License |
src/main/kotlin/com/neva/gradle/fork/config/AbstractRule.kt | neva-dev | 108,767,312 | false | null | package com.neva.gradle.fork.config
import com.neva.gradle.fork.file.FileOperations
import com.neva.gradle.fork.file.visitAll
import org.gradle.api.file.FileTree
import org.gradle.api.file.FileVisitDetails
import java.io.File
abstract class AbstractRule(val config: Config) : Rule {
protected val project = config.project
protected val logger = project.logger
override fun validate() {
// nothing to do
}
fun visitTree(
tree: FileTree,
condition: (FileVisitDetails) -> Boolean,
callback: (FileHandler, FileVisitDetails) -> Unit
) {
val actions = mutableListOf<() -> Unit>()
tree.visitAll { fileDetail ->
if (condition(fileDetail)) {
val fileHandler = FileHandler(config, fileDetail.file)
callback(fileHandler, fileDetail)
actions += fileHandler.actions
}
}
actions.forEach { it.invoke() }
}
fun visitAll(tree: FileTree, callback: (FileHandler, FileVisitDetails) -> Unit) {
visitTree(tree, { true }, callback)
}
fun visitDirs(tree: FileTree, callback: (FileHandler, FileVisitDetails) -> Unit) {
visitTree(tree, { it.isDirectory }, callback)
}
fun visitFiles(tree: FileTree, callback: (FileHandler, FileVisitDetails) -> Unit) {
visitTree(tree, { !it.isDirectory }, callback)
}
fun removeEmptyDirs() {
val emptyDirs = mutableListOf<File>()
visitDirs(config.targetTree) { handler, _ ->
val dir = handler.file
if (FileOperations.isDirEmpty(dir)) {
emptyDirs += dir
}
}
emptyDirs.forEach { dir ->
var current = dir
while (current != config.targetDir && FileOperations.isDirEmpty(current)) {
logger.debug("Cleaning empty directory: $current")
if (current.delete()) {
current.delete()
current = current.parentFile
} else {
logger.debug("Cannot delete empty directory: $current")
break
}
}
}
}
}
| 12 | Kotlin | 1 | 9 | b50f475bf9628d9d405fb608bf1ef7483e84def5 | 1,952 | gradle-fork-plugin | Apache License 2.0 |
src/main/kotlin/com/dc2f/util/Strings.kt | dc2f | 169,700,633 | false | {"Kotlin": 154139, "Shell": 419, "Sass": 44} | package com.dc2f.util
/**
* Returns a substring before the first occurrence of [delimiter].
* If the string does not contain the delimiter, returns [missingDelimiterValue] which defaults to the original string.
*/
public fun String.substringBefore(delimiter: String, missingDelimiterValueProducer: () -> String): String {
val index = indexOf(delimiter)
return if (index == -1) missingDelimiterValueProducer() else substring(0, index)
}
| 0 | Kotlin | 0 | 1 | 3eebc777ef432c5c1e16245cf8a66b5e4b80685d | 448 | dc2f.kt | Apache License 2.0 |
core/src/commonMain/kotlin/misskey4j/api/response/i/IGalleryPostsResponse.kt | uakihir0 | 756,689,268 | false | {"Kotlin": 138345, "Java": 71374, "Ruby": 2188, "Shell": 1485, "Makefile": 315} | package misskey4j.api.response.i
import kotlinx.serialization.Serializable
import misskey4j.entity.GalleryPost
@Serializable
class IGalleryPostsResponse : GalleryPost()
| 0 | Kotlin | 0 | 0 | 9cddb8fcbab49f3c61f2e7e5e7a2380939a3f1c1 | 171 | kmisskey | MIT License |
app/src/main/java/com/sec/fizz/start/ARouterInitializer.kt | liuhuiAndroid | 311,604,995 | false | null | package com.sec.fizz.start
import android.app.Application
import android.content.Context
import androidx.startup.Initializer
import com.alibaba.android.arouter.launcher.ARouter
import com.sec.fizz.BuildConfig
import timber.log.Timber
class ARouterInitializer : Initializer<Unit> {
override fun create(context: Context) {
if (BuildConfig.DEBUG) {
// 打印日志
ARouter.openLog()
// 开启调试模式
ARouter.openDebug()
}
// 尽可能早,推荐在Application中初始化
ARouter.init(context.applicationContext as Application?)
}
override fun dependencies(): MutableList<Class<out Initializer<*>>> {
return mutableListOf()
}
} | 0 | Kotlin | 0 | 1 | 2ccbf66a540cc4db738f9d3e0fdcc6f5db014526 | 695 | fizz | MIT License |
gaia/src/main/kotlin/fyi/pauli/ichor/gaia/models/Identifier.kt | ichor-dev | 676,285,724 | false | {"Kotlin": 95608} | package fyi.pauli.ichor.gaia.models
data class Identifier(val namespace: String, val value: String) {
override fun toString(): String {
return "$namespace:$value"
}
} | 4 | Kotlin | 0 | 0 | 466f531b1a45887f71188453d8fbf7c11008f7cb | 171 | ichor | Apache License 2.0 |
src/main/kotlin/de/gmuth/ipp/client/IppExchangeException.kt | gmuth | 247,626,449 | false | {"Kotlin": 291690} | package de.gmuth.ipp.client
/**
* Copyright (c) 2020-2024 <NAME>
*/
import de.gmuth.ipp.core.IppException
import de.gmuth.ipp.core.IppRequest
import java.io.File
import java.util.logging.Level
import java.util.logging.Level.INFO
import java.util.logging.Logger
import kotlin.io.path.createTempDirectory
import kotlin.io.path.pathString
open class IppExchangeException(
val request: IppRequest,
message: String = "Exchanging request '${request.operation}' failed",
cause: Throwable? = null
) : IppException(message, cause) {
open fun log(logger: Logger, level: Level = INFO): Unit = with(logger) {
log(level) { message }
request.log(this, level, prefix = "REQUEST: ")
}
open fun saveMessages(
fileNameWithoutSuffix: String = "ipp_exchange_exception",
directory: String = createTempDirectory("ipp-client-").pathString
) {
request.saveBytes(File(directory, "$fileNameWithoutSuffix.request"))
}
} | 0 | Kotlin | 11 | 76 | 1501c3ae4aeefd4ce536cd7496abfd03b36e58ec | 972 | ipp-client-kotlin | MIT License |
ktgram/src/main/kotlin/ru/lavafrai/ktgram/types/media/Dice.kt | lavaFrai | 812,095,309 | false | null | package ru.lavafrai.ktgram.types.media
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import ru.lavafrai.ktgram.types.TelegramObject
/**
* This object represents an animated emoji that displays a random value.
*
* @param emoji Emoji on which the dice throw animation is based
* @param value Value of the dice, 1-6 for “🎲”, “🎯” and “🎳” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji
*/
@Serializable
class Dice(
@SerialName("emoji") val emoji: String,
@SerialName("value") val value: Int,
) : TelegramObject()
enum class DiceEmoji(val emoji: String) {
DICE("🎲"),
DART("🎯"),
BOWLING("🎳"),
BASKETBALL("🏀"),
FOOTBALL("⚽"),
SLOT_MACHINE("🎰"),
} | 0 | null | 0 | 3 | 3b8e3d8aeb8a60445a84a57aaf91fda7baf038ea | 735 | ktgram | Apache License 2.0 |
app/src/main/java/de/kauker/glyphtorch/views/routes/main/pages/MainRouteFinalPage.kt | aimok04 | 673,954,193 | false | null | package de.kauker.glyphtorch.views.routes.main.pages
import android.os.Build
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Done
import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.kauker.glyphtorch.R
import de.kauker.glyphtorch.models.AppViewModel
import de.kauker.glyphtorch.service.AccessibilityService
import de.kauker.glyphtorch.service.QuickSettingsTileService
import de.kauker.glyphtorch.views.routes.main.MainRouteBasePage
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun MainRouteFinalPage(vm: AppViewModel) {
val context = LocalContext.current
MainRouteBasePage(
title = stringResource(id = R.string.route_main_page_final_title),
icon = Icons.Rounded.Done,
buttons = {
FlowRow(
horizontalArrangement = Arrangement.Center
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) FilledTonalButton(onClick = {
QuickSettingsTileService.addQuickTileDialog(context)
}) {
Text(stringResource(id = R.string.route_main_page_final_button_add_to_quick_settings))
}
Spacer(Modifier.width(16.dp))
Button(onClick = {
AccessibilityService.openTorch(context)
}) {
Text(stringResource(id = R.string.route_main_page_final_button_use_torch))
}
}
}
) {
Text(
modifier = Modifier.fillMaxWidth(0.8f),
text = stringResource(id = R.string.route_main_page_final_body),
textAlign = TextAlign.Center
)
}
} | 0 | Kotlin | 0 | 0 | 0052aad13d5f282d793b425fc0c2e460d424db34 | 2,084 | glyphtorch-non-root | Apache License 2.0 |
server/lib/base/src/main/kotlin/dev/reprator/base/usecase/AppResult.kt | TheReprator | 781,077,991 | false | {"Kotlin": 399028, "Swift": 5325, "HTML": 357, "JavaScript": 92} | package dev.reprator.base.usecase
sealed class AppResult<out T> {
/**
* Represents successful network responses (2xx).
*/
data class Success<T>(val body: T) : AppResult<T>()
sealed class Error<E> : AppResult<E>() {
/**
* Represents server errors.
* @param code HTTP Status code
* @param errorBody Response body
* @param errorMessage Custom error message
*/
data class HttpError<E>(
val code: Int,
val errorBody: String?,
val errorMessage: String?,
) : Error<E>()
/**
* Represent other exceptions.
* @param message Detail exception message
* @param errorMessage Formatted error message
*/
data class GenericError(
val message: String?,
val errorMessage: String?,
) : Error<Nothing>()
}
} | 1 | Kotlin | 0 | 0 | 1468ecc36c791f643973d0fadae9f6154d726b84 | 904 | ExpenseManagment | Apache License 2.0 |
app/src/main/java/com/azhar/tambalban/data/model/details/ModelOpening.kt | AzharRivaldi | 392,888,909 | false | null | package com.azhar.tambalban.data.model.details
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME> on 24-07-2021
* Youtube Channel : https://bit.ly/2PJMowZ
* Github : https://github.com/AzharRivaldi
* Twitter : https://twitter.com/azharrvldi_
* Instagram : https://www.instagram.com/azhardvls_
* LinkedIn : https://www.linkedin.com/in/azhar-rivaldi
*/
class ModelOpening {
@SerializedName("open_now")
var openNow: Boolean? = null
@SerializedName("weekday_text")
lateinit var weekdayText: List<String>
} | 0 | Kotlin | 2 | 9 | c86d49290f44ab1b08f660f175819836362d4a0f | 551 | Tambal-Ban | Apache License 2.0 |
api/src/main/java/com/nspu/riotapi/models/LanguageStrings.kt | nspu | 127,918,560 | false | null | package fr.nspu.riot_api.models
import android.os.Parcel
import android.os.Parcelable
data class LanguageStrings(var data: Map<String, String>? = null,
var version: String? = null,
var type: String? = null) : Parcelable {
constructor(source: Parcel) : this(
emptyMap<String, String>().apply { source.readMap(this, Map::class.java.classLoader) },
source.readString(),
source.readString()
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeMap(data)
writeString(version)
writeString(type)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<LanguageStrings> = object : Parcelable.Creator<LanguageStrings> {
override fun createFromParcel(source: Parcel): LanguageStrings = LanguageStrings(source)
override fun newArray(size: Int): Array<LanguageStrings?> = arrayOfNulls(size)
}
}
} | 0 | null | 0 | 1 | 75fa318a2a936438edc9eb45056cd1b27bcc0f3d | 1,045 | riot-api-android | MIT License |
data/src/test/kotlin/org/a_cyb/sayitalarm/data/model/AlarmSpec.kt | a-cyborg | 751,578,623 | false | {"Kotlin": 713068} | /*
* Copyright (c) 2024 <NAME> / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package org.a_cyb.sayitalarm.data.model
import org.a_cyb.sayitalarm.entity.Alarm
import org.a_cyb.sayitalarm.entity.AlarmType
import org.a_cyb.sayitalarm.entity.AlertType
import org.a_cyb.sayitalarm.entity.Hour
import org.a_cyb.sayitalarm.entity.Label
import org.a_cyb.sayitalarm.entity.Minute
import org.a_cyb.sayitalarm.entity.Ringtone
import org.a_cyb.sayitalarm.entity.SayItScripts
import org.a_cyb.sayitalarm.entity.WeeklyRepeat
import org.a_cyb.sayitalarm.util.mustBe
import java.util.Calendar
import kotlin.test.Test
import org.acyb.sayitalarm.database.Alarm as AlarmDTO
class AlarmSpec {
@Test
fun `When toAlarm is called it maps DTO to Alarm`() {
// Given
val hour = 3
val minute = 33
val weeklyRepeat = 85 // 0b1010101 : [Sun, Tue, Tur, Sat].
val label = "Label"
val enabled = true
val alertType: Long = AlertType.SOUND_ONLY.ordinal.toLong()
val ringtone = "content://media/internal/audio/media/190?title=Drip&canonical=1"
val alarmType: Long = AlarmType.SAY_IT.ordinal.toLong()
val sayItScripts = "script A,script B,script C"
val dto =
AlarmDTO(
id = 0L,
hour.toLong(),
minute.toLong(),
weeklyRepeat.toLong(),
label,
enabled,
alertType,
ringtone,
alarmType,
sayItScripts,
)
// When
val actual = dto.toAlarm()
// Then
actual mustBe
Alarm(
id = 0L,
hour = Hour(hour),
minute = Minute(minute),
weeklyRepeat = WeeklyRepeat(
setOf(
Calendar.SUNDAY,
Calendar.TUESDAY,
Calendar.THURSDAY,
Calendar.SATURDAY,
),
),
label = Label(label),
enabled = enabled,
alertType = AlertType.SOUND_ONLY,
ringtone = Ringtone(ringtone),
alarmType = AlarmType.SAY_IT,
sayItScripts = SayItScripts(listOf("script A", "script B", "script C")),
)
}
@Test
fun `When toAlarmEntity is called it maps Alarm to AlarmEntity`() {
// Given
val alarm =
Alarm(
id = 0L,
hour = Hour(3),
minute = Minute(3),
weeklyRepeat = WeeklyRepeat(
setOf(
Calendar.SUNDAY,
Calendar.TUESDAY,
Calendar.THURSDAY,
Calendar.SATURDAY,
),
),
label = Label("Label"),
enabled = true,
alertType = AlertType.SOUND_AND_VIBRATE,
ringtone = Ringtone("content://media/internal/audio/media/190?title=Drip&canonical=1"),
alarmType = AlarmType.SAY_IT,
sayItScripts = SayItScripts(listOf("script A", "script B", "script C")),
)
// When
val actual = alarm.toDTO()
// Then
actual mustBe
AlarmDTO(
id = 0L,
hour = 3,
minute = 3,
weeklyRepeat = 85,
label = "Label",
enabled = true,
alertType = 2,
ringtone = "content://media/internal/audio/media/190?title=Drip&canonical=1",
alarmType = 0,
sayItScripts = "script A,script B,script C",
)
}
}
| 0 | Kotlin | 0 | 0 | f20079c06adf86e8297ab8322887c875715e6cd1 | 3,833 | SayItAlarm | Apache License 2.0 |
ProjetoCapacitacao/app/src/main/java/com/example/pokedex/data/modeldados/remoto/Responses/Pokemon.kt | CarolShiny | 853,970,575 | false | {"Kotlin": 31109} | package com.example.pokedex.data.modeldados.remoto.Responses
data class Pokemon(
val abilities: List<com.example.pokedex.data.modeldados.remoto.Responses.Ability>,
val base_experience: Int,
val cries: com.example.pokedex.data.modeldados.remoto.Responses.Cries,
val forms: List<com.example.pokedex.data.modeldados.remoto.Responses.Form>,
val game_indices: List<com.example.pokedex.data.modeldados.remoto.Responses.GameIndice>,
val height: Int,
val held_items: List<com.example.pokedex.data.modeldados.remoto.Responses.HeldItem>,
val id: Int,
val is_default: Boolean,
val location_area_encounters: String,
val moves: List<com.example.pokedex.data.modeldados.remoto.Responses.Move>,
val name: String,
val order: Int,
val past_abilities: List<Any?>,
val past_types: List<Any?>,
val species: com.example.pokedex.data.modeldados.remoto.Responses.Species,
val sprites: com.example.pokedex.data.modeldados.remoto.Responses.Sprites,
val stats: List<com.example.pokedex.data.modeldados.remoto.Responses.Stat>,
val types: List<com.example.pokedex.data.modeldados.remoto.Responses.Type>,
val weight: Int
) | 0 | Kotlin | 0 | 0 | 7ce18ec55c2de7a57c1b5ffefb330e46b5783006 | 1,174 | Pokedex | MIT License |
core/src/main/java/com/tink/core/provider/ProviderRepository.kt | jangillich | 248,710,545 | true | {"Kotlin": 307756, "Shell": 3385} | package com.tink.core.provider
import com.tink.core.TinkScope
import com.tink.core.coroutines.launchForResult
import com.tink.model.provider.Provider
import com.tink.service.handler.ResultHandler
import com.tink.service.provider.ProviderService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import javax.inject.Inject
/**
* Repository for retrieving [Provider]s
*
* @constructor Create a new repository instance from a [ProviderService].
* This is usually done inside the TinkLink framework and it should normally not be necessary to create your own instance.
*/
@TinkScope
class ProviderRepository @Inject constructor(private val service: ProviderService) {
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
/**
* List all providers on the current market. The result will already be filtered to only contain
* providers that are [enabled][Provider.Status.ENABLED]
* @param handler the [ResultHandler] for processing error and success callbacks
* @param includeDemoProviders Set this to true if the response should contain demo providers.
* This is very useful for test and demonstration purposes, but should be set to `false`
* in the release version of the application.
*/
@JvmOverloads
fun listProviders(
handler: ResultHandler<List<Provider>>,
includeDemoProviders: Boolean = false
) {
scope.launchForResult(handler) {
service.listProviders(includeDemoProviders)
}
}
} | 0 | Kotlin | 0 | 0 | 2119f5e3b825906262d07e8bdce1cd7eeb646740 | 1,576 | tink-core-android | MIT License |
app/src/main/java/com/example/mediaplayer/model/folder.kt | AbdelrhmanSror | 205,750,290 | false | null | /*
package com.example.mediaplayer.model
data class Folder(
val title: String,
val path: String,
val size: Int
)*/
| 0 | Kotlin | 0 | 0 | 0485e592998b4a2818f69a86294dad113faf7354 | 141 | MediaPlayer | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindMedianSortedArrays.kt | ashtanko | 203,993,092 | false | {"Kotlin": 6042782, "Shell": 1168, "Makefile": 961} | /*
* 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.shtanko.algorithms.leetcode
/**
* 4. Median of Two Sorted Arrays
* @see <a href="https://leetcode.com/problems/median-of-two-sorted-arrays">Source</a>
*/
fun interface FindMedianSortedArrays {
operator fun invoke(nums1: IntArray, nums2: IntArray): Double
}
class FindMedianSortedArraysBS : FindMedianSortedArrays {
override fun invoke(nums1: IntArray, nums2: IntArray) = (nums1 to nums2).findMedianSortedArrays()
private fun Pair<IntArray, IntArray>.findMedianSortedArrays(): Double {
val m = first.size
val n = second.size
val l = m.plus(n).plus(1).div(2)
val r = m.plus(n).plus(2).div(2)
val local = findKth(first, 0, second, 0, l) + findKth(first, 0, second, 0, r)
return local.div(2.0)
}
private fun findKth(nums1: IntArray, aStart: Int, nums2: IntArray, bStart: Int, k: Int): Double {
if (aStart >= nums1.size) {
return nums2[bStart + k - 1].toDouble()
}
if (bStart >= nums2.size) {
return nums1[aStart + k - 1].toDouble()
}
if (k == 1) {
return nums1[aStart].coerceAtMost(nums2[bStart]).toDouble()
}
val aMid = aStart + k / 2 - 1
val bMid = bStart + k / 2 - 1
val aVal = if (aMid >= nums1.size) Int.MAX_VALUE else nums1[aMid]
val bVal = if (bMid >= nums2.size) Int.MAX_VALUE else nums2[bMid]
return if (aVal <= bVal) {
findKth(nums1, aMid + 1, nums2, bStart, k - k / 2)
} else {
findKth(nums1, aStart, nums2, bMid + 1, k - k / 2)
}
}
}
| 5 | Kotlin | 0 | 19 | e7063905fd9b543055a7d8c2826db73cc65715db | 2,193 | kotlab | Apache License 2.0 |
app/src/main/java/com/ihegyi/alexiguitartuner/commons/presentation/ui/CreateTuningDialog.kt | ihegyi500 | 582,416,278 | false | {"Kotlin": 185211} | package com.ihegyi.alexiguitartuner.commons.presentation.ui
import android.R
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.ihegyi.alexiguitartuner.commons.presentation.adapter.PitchListAdapter
import com.ihegyi.alexiguitartuner.commons.presentation.viewmodel.CreateTuningViewModel
import com.ihegyi.alexiguitartuner.databinding.DialogCreateTuningBinding
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
class CreateTuningDialog : DialogFragment() {
private val viewModel: CreateTuningViewModel by viewModels(
ownerProducer = { requireParentFragment() }
)
private var _binding: DialogCreateTuningBinding? = null
private val binding get() = _binding!!
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
_binding = DialogCreateTuningBinding.inflate(layoutInflater)
return AlertDialog.Builder(requireContext())
.setView(binding.root)
.create()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
lateinit var adapterOfInstruments: ArrayAdapter<String>
binding.actInstrument.setOnItemClickListener { _, _, pos, _ ->
viewModel.changeSelectedInstrument(pos)
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
adapterOfInstruments = ArrayAdapter(
[email protected](),
R.layout.simple_spinner_item,
ArrayList<String>()
)
binding.actInstrument.setAdapter(adapterOfInstruments)
viewModel.uiState.collectLatest { uiState ->
adapterOfInstruments.clear()
adapterOfInstruments.addAll(uiState.instrumentList.map { it.name })
adapterOfInstruments.notifyDataSetChanged()
if (uiState.instrumentList.isNotEmpty()) {
binding.actInstrument.setText(uiState.selectedInstrument?.name, false)
}
}
}
launch {
val pitchListAdapter = PitchListAdapter(viewModel,lifecycleScope)
binding.pitchListRecyclerView.adapter = pitchListAdapter
viewModel.uiState.collectLatest {
pitchListAdapter.submitList(it.pitchesOfTuning)
}
}
}
}
binding.btnOk.setOnClickListener {
viewModel.insertTuning(binding.mtwTuningName.text.toString())
dismiss()
}
binding.btnCancel.setOnClickListener {
dismiss()
}
viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
_binding = null
}
})
super.onViewCreated(view, savedInstanceState)
}
}
| 0 | Kotlin | 0 | 0 | ad624d69abeffa9f979b94febd50ea3afe11487e | 3,756 | AlexiGuitarTuner | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumGeneticMutation.kt | ashtanko | 203,993,092 | false | null | /*
* Copyright 2022 Oleksii Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 433. Minimum Genetic Mutation
* @see <a href="https://leetcode.com/problems/minimum-genetic-mutation/">leetcode page</a>
*/
fun interface MinimumGeneticMutation {
fun minMutation(start: String, end: String, bank: Array<String>): Int
}
/**
* Approach: BFS (Breadth-First Search)
*/
class MinimumGeneticMutationBFS : MinimumGeneticMutation {
override fun minMutation(start: String, end: String, bank: Array<String>): Int {
val queue: Queue<String> = LinkedList()
val seen: MutableSet<String> = HashSet()
queue.add(start)
seen.add(start)
var steps = 0
while (!queue.isEmpty()) {
val nodesInQueue: Int = queue.size
for (j in 0 until nodesInQueue) {
val node: String = queue.remove()
if (node == end) {
return steps
}
for (c in charArrayOf('A', 'C', 'G', 'T')) {
for (i in node.indices) {
val neighbor = node.substring(0, i) + c + node.substring(i + 1)
if (!seen.contains(neighbor) && bank.contains(neighbor)) {
queue.add(neighbor)
seen.add(neighbor)
}
}
}
}
steps++
}
return -1
}
}
| 6 | null | 0 | 19 | 20af84428e9e55ea4b3f3794f1e7659734a8631e | 2,078 | kotlab | Apache License 2.0 |
app/src/main/java/com/alvaromart/weatherapp/ui/activities/MainActivity.kt | alvaromart | 167,804,891 | false | null | package com.alvaromart.weatherapp.ui.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import com.alvaromart.weatherapp.R
import com.alvaromart.weatherapp.domain.commands.RequestForecastCommand
import com.alvaromart.weatherapp.domain.model.ForecastList
import com.alvaromart.weatherapp.extensions.DelegatesExtensions
import com.alvaromart.weatherapp.ui.adapters.ForecastListAdapter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import org.jetbrains.anko.coroutines.experimental.bg
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
class MainActivity() : AppCompatActivity(), ToolbarManager {
private val zipCode: Long by DelegatesExtensions.preference(this,
SettingsActivity.ZIP_CODE, SettingsActivity.DEFAULT_ZIP)
override val toolbar by lazy { find<Toolbar>(R.id.toolbar) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initToolbar()
forecastList.layoutManager = LinearLayoutManager(this)
attachToScroll(forecastList)
loadForecast()
}
private fun loadForecast() = async(UI) {
val result = bg { RequestForecastCommand(zipCode).execute() }
updateUI(result.await())
}
private fun updateUI(weekForecast: ForecastList) {
val adapter = ForecastListAdapter(weekForecast) {
startActivity<DetailActivity>(DetailActivity.ID to it.id,
DetailActivity.CITY_NAME to weekForecast.city)
}
forecastList.adapter = adapter
toolbarTitle = "${weekForecast.city} (${weekForecast.country})"
}
override fun onResume() {
super.onResume()
loadForecast()
}
}
| 0 | Kotlin | 0 | 0 | 3871fead0fb2a1b421e2d140205e01d156226537 | 1,973 | WeatherAppKotlin | Apache License 2.0 |
app/src/main/java/com/illu/demo/ui/home/hot/HotViewModel.kt | mosquitoxiang | 624,018,018 | false | null | package com.illu.demo.ui.home.hot
import androidx.lifecycle.MutableLiveData
import com.illu.demo.base.BaseViewModel
import com.illu.demo.bean.ArticleBean
import com.illu.demo.common.UserManager
import com.illu.demo.common.bus.Bus
import com.illu.demo.common.bus.USER_COLLECT_UPDATE
import com.illu.demo.common.isLogin
import com.illu.demo.common.loadmore.LoadMoreStatus | 0 | Kotlin | 0 | 0 | f426367fb3d129889ebd323bf9b0339605b8caf5 | 370 | wanandroid-compose | Apache License 2.0 |
gsonpath-compiler/src/main/java/gsonpath/generator/HandleResult.kt | morristech | 99,539,630 | true | {"YAML": 2, "Java Properties": 2, "Markdown": 4, "Text": 1, "Gradle": 6, "Shell": 1, "Ignore List": 1, "Java": 179, "Kotlin": 44, "JSON": 5} | package gsonpath.generator
import com.squareup.javapoet.ClassName
class HandleResult(val originalClassName: ClassName, val generatedClassName: ClassName)
| 0 | Java | 0 | 0 | b441ae79beffddf14af1f0cf7b070079138bef5d | 156 | gsonpath | MIT License |
app/src/main/java/com/maijia/QR/activity/TopSlidingChangeBigActivity.kt | Hunter2916 | 188,981,047 | false | null | package com.maijia.QR.activity
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import com.maijia.QR.R
import com.maijia.QR.ScaleTransitionPagerTitleView
import com.maijia.QR.adapter.ExamplePagerAdapter
import kotlinx.android.synthetic.main.activity_top_sliding_change_big.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import java.util.*
class TopSlidingChangeBigActivity : AppCompatActivity() {
private val CHANNELS = arrayOf("CUPCAKE", "DONUT", "ECLAIR", "GINGERBREAD", "HONEYCOMB", "ICE_CREAM_SANDWICH", "JELLY_BEAN", "KITKAT", "LOLLIPOP", "M", "NOUGAT")
private val mDataList = Arrays.asList(*CHANNELS)
val fragments = ArrayList<Fragment>()
// private val mExamplePagerAdapter = ExamplePagerAdapter(mDataList)
private val mExamplePagerAdapter = ExamplePagerAdapter(Arrays.asList(*arrayOf("大头", "二花")))
// private val pagerAdapter=MainPagerAdapter(supportFragmentManager,fragments)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_top_sliding_change_big)
initView()
}
private fun initView() {
view_pager!!.setAdapter(mExamplePagerAdapter)
initMagicIndicator5()
}
private fun initMagicIndicator5() {
magic_indicator5.setBackgroundColor(Color.WHITE)
val commonNavigator = CommonNavigator(this)
commonNavigator.scrollPivotX = 0.8f
commonNavigator.adapter = object : CommonNavigatorAdapter() {
override fun getCount(): Int {
return mDataList?.size ?: 0
}
override fun getTitleView(context: Context, index: Int): IPagerTitleView {
val simplePagerTitleView = ScaleTransitionPagerTitleView(context)
simplePagerTitleView.setText(mDataList[index])
simplePagerTitleView.setTextSize(18f)
simplePagerTitleView.setNormalColor(Color.parseColor("#616161"))
simplePagerTitleView.setSelectedColor(Color.parseColor("#f57c00"))
simplePagerTitleView.setOnClickListener(View.OnClickListener { view_pager.setCurrentItem(index) })
return simplePagerTitleView
}
override fun getIndicator(context: Context): IPagerIndicator {
val indicator = LinePagerIndicator(context)
indicator.startInterpolator = AccelerateInterpolator()
indicator.endInterpolator = DecelerateInterpolator(1.6f)
indicator.yOffset = UIUtil.dip2px(context, 39.0).toFloat()
indicator.lineHeight = UIUtil.dip2px(context, 1.0).toFloat()
indicator.setColors(Color.parseColor("#f57c00"))
return indicator
}
}
magic_indicator5.navigator = commonNavigator
ViewPagerHelper.bind(magic_indicator5, view_pager)
}
}
| 1 | null | 1 | 1 | 24138f8baad96dd83c62df13d859f34894796769 | 3,664 | QRCodeDemo | MIT License |
src/main/java/top/zbeboy/isy/config/LoggingAspectConfiguration.kt | zbeboy | 71,459,176 | false | {"JavaScript": 423, "JSON": 1, "Markdown": 5, "Maven POM": 1, "Text": 3, "Ignore List": 1, "XML": 8, "YAML": 2, "CSS": 59, "Kotlin": 380, "Java": 277, "Java Properties": 3, "HTML": 189, "SQL": 2} | package top.zbeboy.isy.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.EnableAspectJAutoProxy
import org.springframework.context.annotation.Profile
import top.zbeboy.isy.aop.logging.LoggingAspect
import top.zbeboy.isy.aop.logging.LoggingRecordAspect
import top.zbeboy.isy.config.Workbook
/**
* 日志切面环境配置.
*
* @author zbeboy
* @version 1.0
* @since 1.0
*/
@Configuration
@EnableAspectJAutoProxy
open class LoggingAspectConfiguration {
/**
* 仅在开发环境打印所有日志
*
* @return
*/
@Bean
@Profile(Workbook.SPRING_PROFILE_DEVELOPMENT)
open fun loggingAspect(): LoggingAspect {
return LoggingAspect()
}
/**
* 保存日志
*
* @return
*/
@Bean
@Profile(Workbook.SPRING_PROFILE_DEVELOPMENT, Workbook.SPRING_PROFILE_PRODUCTION, Workbook.SPRING_PROFILE_TEST)
open fun loggingRecordAspect(): LoggingRecordAspect {
return LoggingRecordAspect()
}
} | 7 | JavaScript | 2 | 7 | 9634602adba558dbdb945c114692019accdb50a9 | 1,038 | ISY | MIT License |
grpc-multiplatform-lib/src/commonMain/kotlin/io/github/timortel/kotlin_multiplatform_grpc_lib/io/message_reader.kt | TimOrtel | 503,391,702 | false | {"Kotlin": 330017, "ANTLR": 2178, "Dockerfile": 193, "HTML": 191} | package io.github.timortel.kotlin_multiplatform_grpc_lib.io
import io.github.timortel.kotlin_multiplatform_grpc_lib.message.DataType
import io.github.timortel.kotlin_multiplatform_grpc_lib.message.KMMessage
fun <M : KMMessage> readKMMessage(
wrapper: CodedInputStream,
messageFactory: (CodedInputStream) -> M
): M = recursiveRead(wrapper) { messageFactory(wrapper) }
/*
Adapted version of https://github.com/protocolbuffers/protobuf/blob/520c601c99012101c816b6ccc89e8d6fc28fdbb8/objectivec/GPBDictionary.m#L455
*/
fun <K, V> readMapEntry(
inputStream: CodedInputStream,
map: MutableMap<K, V>,
keyDataType: DataType,
valueDataType: DataType,
defaultKey: K?,
defaultValue: V?,
readKey: CodedInputStream.() -> K,
readValue: CodedInputStream.() -> V
) {
recursiveRead(inputStream) {
val keyTag = wireFormatMakeTag(kMapKeyFieldNumber, wireFormatForType(keyDataType, false))
val valueTag =
wireFormatMakeTag(kMapValueFieldNumber, wireFormatForType(valueDataType, false))
var key: K? = defaultKey
var value: V? = defaultValue
var hitError = false
while (true) {
when (val tag = inputStream.readTag()) {
0 -> break
keyTag -> key = inputStream.readKey()
valueTag -> value = inputStream.readValue()
else -> {
//Unknown
if (!inputStream.skipField(tag)) {
hitError = true
break
}
}
}
}
if (!hitError && key != null && value != null) {
map[key] = value
}
}
}
private fun <T> recursiveRead(stream: CodedInputStream, block: () -> T): T {
checkRecursionLimit(stream)
val length: Int = stream.readInt32()
val oldLimit = stream.pushLimit(length)
stream.recursionDepth++
val r = block()
stream.checkLastTagWas(0)
stream.recursionDepth--
stream.popLimit(oldLimit)
return r
//checkRecursionLimit(wrapper)
//val length: int32_t = wrapper.stream.readInt32()
//val oldLimit = wrapper.stream.pushLimit(length.toULong())
//wrapper.recursionDepth++
//val r = block()
//wrapper.stream.checkLastTagWas(0)
//wrapper.recursionDepth--
//wrapper.stream.popLimit(oldLimit)
//return r
}
private fun checkRecursionLimit(wrapper: CodedInputStream) {
if (wrapper.recursionDepth >= 100) {
throw RuntimeException("Recursion depth exceeded.")
}
} | 6 | Kotlin | 14 | 62 | c2ab8b52c36cade78ba8cc5be1123ff006f715a2 | 2,562 | GRPC-Kotlin-Multiplatform | Apache License 2.0 |
app/src/main/kotlin/com/zj/weather/widget/glance/TodayGlanceReceiver.kt | zhujiang521 | 422,904,634 | false | {"Kotlin": 288676} | package com.zj.weather.widget.glance
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
class TodayGlanceReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = TodayGlanceWidget()
} | 5 | Kotlin | 78 | 479 | a731e0b502fc22baf832307bb60b263c16376dab | 276 | PlayWeather | MIT License |
plugins/kotlin/idea/tests/testData/intentions/usePropertyAccessSyntax/propertyTypeIsMoreSpecific1.kt | ingokegel | 72,937,917 | false | null | // IS_APPLICABLE: false
// WITH_STDLIB
abstract class KotlinClass : JavaInterface {
override fun getSomething(): String = ""
}
fun foo(k: KotlinClass) {
k.<caret>setSomething(1)
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 191 | intellij-community | Apache License 2.0 |
modules/clients/telegram/src/gen/kotlin/dev/mbo/telegrambot/client/telegram/model/UserDto.kt | mbogner | 469,946,409 | false | {"Kotlin": 58137, "Mustache": 7257} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package dev.mbo.telegrambot.client.telegram.model
import com.fasterxml.jackson.annotation.JsonProperty
/**
*
*
* @param id
* @param isBot
* @param firstName
* @param lastName
* @param username
* @param languageCode
* @param canJoinGroups
* @param canReadAllGroupMessages
* @param supportsInlineQueries
*/
data class UserDto (
@field:JsonProperty("id")
val id: kotlin.Long? = null,
@field:JsonProperty("is_bot")
val isBot: kotlin.Boolean? = null,
@field:JsonProperty("first_name")
val firstName: kotlin.String? = null,
@field:JsonProperty("last_name")
val lastName: kotlin.String? = null,
@field:JsonProperty("username")
val username: kotlin.String? = null,
@field:JsonProperty("language_code")
val languageCode: kotlin.String? = null,
@field:JsonProperty("can_join_groups")
val canJoinGroups: kotlin.Boolean? = null,
@field:JsonProperty("can_read_all_group_messages")
val canReadAllGroupMessages: kotlin.Boolean? = null,
@field:JsonProperty("supports_inline_queries")
val supportsInlineQueries: kotlin.Boolean? = null
)
| 1 | Kotlin | 0 | 0 | dd54818834ce313562326181854f192724529044 | 1,402 | telegram-bot | Apache License 2.0 |
ui/src/commonMain/kotlin/com/popalay/barnee/ui/common/Dialog.kt | Popalay | 349,051,151 | false | null | /*
* Copyright (c) 2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.popalay.barnee.ui.common
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
@Composable
expect fun Dialog(
onDismissRequest: () -> Unit,
properties: DialogProperties = DialogProperties(),
content: @Composable () -> Unit,
)
@Immutable
data class DialogProperties(
val dismissOnBackPress: Boolean = true,
val dismissOnClickOutside: Boolean = true,
val usePlatformDefaultWidth: Boolean = false,
val decorFitsSystemWindows: Boolean = true,
val size: DpSize = DpSize(400.dp, 300.dp),
val title: String = "Untitled",
val icon: Painter? = null,
val resizable: Boolean = true,
)
| 21 | Kotlin | 3 | 15 | 0d25ca9033065ff4c9b6f044550f7c02f96f97bd | 1,902 | Barnee | MIT License |
modules/presentation/src/main/java/kr/co/knowledgerally/ui/component/AddScheduleButton.kt | YAPP-Github | 475,728,173 | false | {"Kotlin": 454888} | package kr.co.knowledgerally.ui.component
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import kr.co.knowledgerally.ui.R
import kr.co.knowledgerally.ui.theme.KnowllyTheme
@Composable
fun AddScheduleButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Surface(
shape = RoundedCornerShape(10.dp),
onClick = onClick,
modifier = modifier
.fillMaxWidth()
.height(52.dp),
color = KnowllyTheme.colors.primaryLight,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
Icon(
painter = painterResource(id = R.drawable.ic_add),
contentDescription = null,
tint = KnowllyTheme.colors.primaryDark
)
Text(
text = stringResource(id = R.string.register_schedule_add_schedule),
modifier = Modifier.padding(start = 2.dp),
style = KnowllyTheme.typography.button1,
color = KnowllyTheme.colors.primaryDark,
)
}
}
}
| 2 | Kotlin | 1 | 4 | 01db68b42594360a9285af458eb812ad83acef70 | 1,823 | 20th-ALL-Rounder-Team-2-Android | Apache License 2.0 |
antlr-kotlin-examples-jvm/src/main/kotlin/com/strumenta/antlrkotlin/examples/UsingParser.kt | Strumenta | 145,450,730 | false | null | /*
* Copyright (C) 2021 Strumenta
*
* 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.strumenta.antlrkotlin.examples
import org.antlr.v4.kotlinruntime.CharStreams
import org.antlr.v4.kotlinruntime.CommonTokenStream
fun main(args: Array<String>) {
// if (MiniCalcLexer.serializedATN.length != MiniCalcLexer.serializedIntegersATN.size) {
// throw RuntimeException("DIFFERENT LENGTHS")
// }
// for (i in 0..MiniCalcLexer.serializedATN.length) {
// if (MiniCalcLexer.serializedATN[i].toInt() != MiniCalcLexer.serializedIntegersATN[i]) {
// throw RuntimeException("DIFFERENT AT $i ${MiniCalcLexer.serializedATN[i].toInt()} ${MiniCalcLexer.serializedIntegersATN[i]}")
// }
// }
val input = CharStreams.fromString("input Int width\n")
val lexer = MiniCalcLexer(input)
val parser = MiniCalcParser(CommonTokenStream(lexer))
try {
val root = parser.miniCalcFile()
println("Parsed: ${root.javaClass}")
println("Parsed: ${root.childCount}")
println("Parsed: ${root.children!![0].javaClass}")
} catch (e: Throwable) {
println("Error: $e")
}
}
| 41 | Kotlin | 43 | 171 | 70d79b7eb111c495c6f1e6299457682dd4270ef0 | 1,662 | antlr-kotlin | Apache License 2.0 |
conversation-core/src/main/java/com/safechat/conversation/ConversationService.kt | asymmetric-team | 58,806,571 | false | {"Gradle": 23, "Shell": 2, "INI": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Java Properties": 1, "JSON": 3, "XML": 30, "Kotlin": 105, "Java": 1} | package com.safechat.conversation
import rx.Observable
interface ConversationService {
fun listenForMessages(myPublicKey: String, otherPublicKey: String): Observable<com.safechat.message.Message>
fun postMessage(myPublicKey: String, otherPublicKey: String, message: com.safechat.message.Message): Observable<Unit>
} | 6 | null | 2 | 1 | 34274e068eef9e297c6ad9e7f3d896d37fd0d125 | 326 | secure-messenger-android | Apache License 2.0 |
core/src/main/java/io/timeandspace/jpsg/Generator.kt | TimeAndSpaceIO | 156,392,429 | false | null | /*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.timeandspace.jpsg
import io.timeandspace.jpsg.CheckingPattern.compile
import io.timeandspace.jpsg.Dimensions.Parser.Companion.parseOptions
import io.timeandspace.jpsg.GeneratorConstants.*
import io.timeandspace.jpsg.MalformedTemplateException.Companion.near
import io.timeandspace.jpsg.RegexpUtils.removeSubGroupNames
import io.timeandspace.jpsg.concurrent.ForkJoinTaskShim
import io.timeandspace.jpsg.concurrent.ForkJoinTasks
import io.timeandspace.jpsg.function.Predicate
import io.timeandspace.jpsg.function.UnaryOperator
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.lang.String.format
import java.util.*
import java.util.concurrent.Callable
import java.util.regex.Pattern
class Generator {
private var isInit = false
private var source: File? = null
internal var target: File? = null
private var defaultTypes: MutableList<Option> =
ArrayList(PrimitiveType.NUMERIC_TYPES_WITH_SHORT_IDS)
private var dimensionsParser: Dimensions.Parser? = null
private val processors = mutableListOf(
// in chronological order
OptionProcessor(),
ConstProcessor(),
BlocksProcessor(),
GenericsProcessor(),
DefinitionProcessor(),
FloatingWrappingProcessor(),
RawModifierProcessor(),
BitsModifierPreProcessor(),
BitsModifierPostProcessor(),
AAnProcessor(),
OverviewProcessor(),
PrintProcessor()
)
private class UnparsedDimensions(
val dimensions: String,
val parse: (Dimensions.Parser, String) -> Dimensions)
private fun Dimensions.Parser.parse(unparsedDimensions: UnparsedDimensions): Dimensions {
return unparsedDimensions.parse(this, unparsedDimensions.dimensions)
}
private val with = ArrayList<UnparsedDimensions>()
private var defaultContext: Context? = null
private val never = ArrayList<String>()
private var excludedTypes: List<Option>? = null
private val included = ArrayList<UnparsedDimensions>()
private var permissiveConditions: List<Dimensions>? = null
private val excluded = ArrayList<UnparsedDimensions>()
private var prohibitingConditions: List<Dimensions>? = null
private var firstProcessor: TemplateProcessor? = null
fun setDefaultTypes(defaultTypes: String): Generator {
val defaultTypes = ArrayList(parseOptions(defaultTypes))
for (option in defaultTypes) {
if (option is SimpleOption) {
throw IllegalArgumentException(
"Simple options like $option are not allowed in defaultTypes configuration")
}
}
this.defaultTypes = defaultTypes
return this
}
fun withCLI(defaultContext: Iterable<String>) : Generator {
for (cxt in defaultContext) {
with.add(UnparsedDimensions(cxt, Dimensions.Parser::parseCLI))
}
return this
}
fun with(defaultContext: Iterable<String>): Generator {
for (cxt in defaultContext) {
val withDimensions: Dimensions = checkingDimensionsParser.parseForContext(cxt)
for ((dim, options) in withDimensions.dimensions) {
if (options.size > 1) {
throw IllegalArgumentException(
"with() accepts only dimensions with a single option, $dim has $options"
)
}
}
with.add(UnparsedDimensions(cxt, Dimensions.Parser::parseForContext))
}
return this
}
fun with(vararg defaultContext: String): Generator {
return with(Arrays.asList(*defaultContext))
}
fun addProcessor(processor: TemplateProcessor): Generator {
processors.add(processor)
return this
}
fun addPrimitiveTypeModifierProcessors(
keyword: String, typeMapper: UnaryOperator<PrimitiveType>,
dimFilter: Predicate<String>): Generator {
addProcessor(PrimitiveTypeModifierPreProcessor(keyword, typeMapper, dimFilter))
addProcessor(PrimitiveTypeModifierPostProcessor(keyword, typeMapper, dimFilter))
return this
}
fun addProcessor(processorClass: Class<out TemplateProcessor>): Generator {
try {
return addProcessor(processorClass.newInstance())
} catch (e: InstantiationException) {
throw IllegalArgumentException("$processorClass template processor class should have public no-arg constructor")
} catch (e: IllegalAccessException) {
throw IllegalArgumentException("$processorClass template processor class should have public no-arg constructor")
}
}
fun addProcessor(processorClassName: String): Generator {
try {
// noinspection unchecked
return addProcessor(
Class.forName(processorClassName) as Class<out TemplateProcessor>)
} catch (e: ClassNotFoundException) {
throw IllegalArgumentException("Template processor class with $processorClassName name is not found")
}
}
fun never(options: Iterable<String>): Generator {
for (opts in options) {
never.add(opts)
}
return this
}
fun never(vararg options: String): Generator {
return never(Arrays.asList(*options))
}
fun includeCLI(conditions: Iterable<String>): Generator {
for (condition in conditions) {
included.add(UnparsedDimensions(condition, Dimensions.Parser::parseCLI))
}
return this
}
fun include(conditions: Iterable<String>): Generator {
for (condition in conditions) {
included.add(UnparsedDimensions(condition, Dimensions.Parser::parseForContext))
}
return this
}
fun include(vararg conditions: String): Generator {
return include(Arrays.asList(*conditions))
}
fun excludeCLI(conditions: Iterable<String>): Generator {
for (condition in conditions) {
excluded.add(UnparsedDimensions(condition, Dimensions.Parser::parseCLI))
}
return this
}
fun exclude(conditions: Iterable<String>): Generator {
for (condition in conditions) {
excluded.add(UnparsedDimensions(condition, Dimensions.Parser::parseForContext))
}
return this
}
fun exclude(vararg conditions: String): Generator {
return exclude(Arrays.asList(*conditions))
}
fun setSource(source: File): Generator {
this.source = source
return this
}
fun setSource(source: String): Generator {
this.source = File(source)
return this
}
fun getSource(): File {
return source!!
}
fun setTarget(target: File): Generator {
this.target = target
return this
}
fun setTarget(target: String): Generator {
this.target = File(target)
return this
}
fun getTarget(): File {
return target!!
}
@Throws(IOException::class)
fun generate() {
log.debug("Generator source: {}", source)
log.debug("Generator target: {}", target)
if (!source!!.exists()) {
return
}
if (!target!!.exists()) {
target!!.mkdirs()
} else if (!target!!.isDirectory) {
log.error("Target {} should be a dir", target)
throw IllegalArgumentException("$target generation destination should be a dir")
}
init()
if (source!!.isDirectory) {
class DirGeneration(val dir: File) : Callable<Unit> {
override fun call() {
try {
val subTasks = ArrayList<ForkJoinTaskShim<Unit>>()
val targetDir = target!!.resolve(dir.relativeTo([email protected]!!))
try {
dir.copyTo(targetDir)
} catch (e: IOException) {
if (!targetDir.isDirectory)
throw e
}
dir.walkTopDown().onEnter { d ->
if (dir != d) {
subTasks.add(ForkJoinTasks.adapt(DirGeneration(d)))
false
} else {
true
}
}.filter { it.isFile }.forEach { f ->
val targetFile = target!!.resolve(f.relativeTo(source!!))
if (f.lastModified() < targetFile.lastModified()) {
log.info("File {} is up to date, not processing source",
targetFile)
}
subTasks.add(ForkJoinTasks.adapt(Callable<Unit> {
doGenerate(f, File(targetFile.parent))
}))
}
ForkJoinTasks.invokeAll(subTasks)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
ForkJoinTasks.adapt(DirGeneration(source!!)).forkAndGet()
} else {
ForkJoinTasks.adapt(Callable<Unit> { doGenerate(source!!, target!!) }).forkAndGet()
}
}
@Synchronized fun init() {
if (isInit)
return
isInit = true
dimensionsParser = Dimensions.Parser(defaultTypes)
defaultContext = Context.Builder().makeContext()
for (context in with) {
val contexts = dimensionsParser!!.parse(context).generateContexts()
if (contexts.size > 1) {
throw IllegalArgumentException(
"Default context should have only trivial dimensions")
}
defaultContext = defaultContext!!.join(contexts[0])
}
excludedTypes = never.flatMap { options -> parseOptions(options) }.toList()
permissiveConditions = included.map { dimensionsParser!!.parse(it) }.toList()
prohibitingConditions = excluded.map { dimensionsParser!!.parse(it) }.toList()
initProcessors()
}
private fun initProcessors() {
processors.sortWith(compareBy(TemplateProcessor::priority))
var prev: TemplateProcessor? = null
for (processor in processors) {
processor.dimensionsParser = dimensionsParser
processor.setNext(prev)
prev = processor
}
firstProcessor = processors[processors.size - 1]
}
@Throws(IOException::class)
private fun doGenerate(sourceFile: File, targetDir: File) {
setCurrentGenerator(this)
setCurrentSourceFile(sourceFile)
log.info("Processing file: {}", sourceFile)
val sourceFileName = sourceFile.name
var targetDims: Dimensions = dimensionsParser!!.parseClassName(sourceFileName)
var rawContent = sourceFile.readText()
val fileDimsM = CONTEXT_START_P.matcher(rawContent)
if (fileDimsM.find() && fileDimsM.start() == 0) {
val explicitContext = fileDimsM.group()
targetDims = parseAndCheckExplicitContext(explicitContext, sourceFile)
rawContent = rawContent.substring(fileDimsM.end()).trim { it <= ' ' } + "\n"
}
log.info("Target dimensions: {}", targetDims)
val targetContexts: List<Context> = targetDims.generateContexts()
val mainContext = defaultContext!!.join(targetContexts[0])
val fileCondM = COND_START_P.matcher(rawContent)
var fileCond: Condition? = null
if (fileCondM.find() && fileCondM.start() == 0) {
fileCond = Condition.parseCheckedCondition(
getBlockGroup(fileCondM.group(), COND_START_BLOCK_P, "condition"),
dimensionsParser!!, mainContext,
rawContent, fileCondM.start())
rawContent = rawContent.substring(fileCondM.end()).trim { it <= ' ' } + "\n"
}
val content = rawContent
val contextGenerationTasks = ArrayList<ForkJoinTaskShim<Unit>>()
for (tc in targetContexts) {
if (!checkContext(tc)) {
log.debug("Context filtered by generator: {}", tc)
continue
}
val target = defaultContext!!.join(tc)
if (fileCond != null && !fileCond.check(target)) {
log.debug("Context filtered by file condition: {}", target)
continue
}
var generatedFileName = generate(mainContext, target, sourceFileName)
var generatedFile = targetDir.resolve(generatedFileName)
contextGenerationTasks.add(ForkJoinTasks.adapt(Callable<Unit> {
setCurrentGenerator(this@Generator)
setCurrentSourceFile(sourceFile)
setRedefinedClassName(null)
val generatedContent = generate(mainContext, target, content)
val redefinedClassName: String? = getRedefinedClassName()
// `substringAfterLast('.')` in order to support service file names in resources:
// META-INF/services/com.mypackage.ByteShortType
val generatedClassName =
generatedFileName.removeSuffix(".java").substringAfterLast('.')
if (redefinedClassName != null && generatedClassName != redefinedClassName) {
log.info("Class name redefined: {} -> {}",
generatedClassName, redefinedClassName)
generatedFileName =
generatedFileName.replace(generatedClassName, redefinedClassName)
generatedFile = targetDir.resolve(generatedFileName)
}
if (generatedFile.exists()) {
if (generatedFile.isDirectory) {
throw IllegalStateException(
"$generatedFileName in $targetDir is a directory, " +
"$mainContext, $target, $sourceFileName")
}
val targetContent = generatedFile.readText()
if (generatedContent == targetContent) {
log.warn("Already generated: {}", generatedFileName)
return@Callable
}
}
writeFile(generatedFile, generatedContent)
log.info("Wrote: {}", generatedFileName)
}))
}
ForkJoinTasks.invokeAll(contextGenerationTasks)
}
private fun parseAndCheckExplicitContext(explicitContext: String, sourceFile: File):
Dimensions {
val targetDims: Dimensions = dimensionsParser!!.parseForContext(
getBlockGroup(explicitContext, CONTEXT_START_BLOCK_P, "dimensions"))
val mainExplicitContext: Context = targetDims.generateContexts()[0]
for ((dim, option) in mainExplicitContext) {
if (!Context.stringIncludesOption(sourceFile.name, option)) {
throw RuntimeException(
"Dimension $dim with options ${targetDims.dimensions[dim]} specified " +
"explicitly in $sourceFile is not found in the file name")
}
}
return targetDims
}
@Throws(IOException::class)
internal fun writeFile(file: File, content: String) {
file.writeText(content)
}
fun generate(source: Context, target: Context, template: String): String {
return firstProcessor!!.generate(source, target, template)
}
private fun checkContext(target: Context): Boolean {
for ((_, option) in target) {
if (excludedTypes!!.contains(option))
return false
}
if (!checkPermissive(target))
return false
if (prohibitingConditions!!.isNotEmpty()) {
for (prohibitingCondition in prohibitingConditions!!) {
if (prohibitingCondition.checkAsCondition(target))
return false
}
}
return true
}
private fun checkPermissive(target: Context): Boolean {
if (permissiveConditions!!.isNotEmpty()) {
for (permissiveCondition in permissiveConditions!!) {
if (permissiveCondition.checkAsCondition(target))
return true
}
// context isn't permitted by any condition
return false
}
return true
}
inner class BlocksProcessor : TemplateProcessor() {
override fun priority(): Int {
return BLOCKS_PROCESSOR_PRIORITY
}
override fun process(sb: StringBuilder, source: Context, target: Context, template: String) {
val blockStartMatcher = ANY_BLOCK_PART_P.matcher(template)
var prevBlockEndPos = 0
blockSearch@ while (blockStartMatcher.find()) {
val blockDefPos = blockStartMatcher.start()
val linearBlock = template.substring(prevBlockEndPos, blockDefPos)
postProcess(sb, source, target, linearBlock)
val blockStart = blockStartMatcher.group()
var condM = COND_START_P.matcher(blockStart)
if (condM.matches()) {
var prevBranchCond = Condition.parseCheckedCondition(
getBlockGroup(condM.group(), COND_PART_BLOCK_P, "condition"),
dimensionsParser!!, source,
template, blockStartMatcher.start())
var branchStartPos = blockStartMatcher.end()
var nest = 0
condM = COND_PART_P.matcher(template)
condM.region(branchStartPos, template.length)
while (condM.find()) {
var condPart = condM.group()
if (COND_START_P.matcher(condPart).matches()) {
nest++
} else if (nest != 0) {
if (COND_END_P.matcher(condPart).matches()) {
nest--
}
// no special processing of nested `elif` branches
} else {
if (prevBranchCond.check(target)) {
// condition of the previous `if` or `elif` branch
// triggers on the context
val branchEndPos = condM.start()
val block = template.substring(branchStartPos, branchEndPos)
process(sb, source, target, block)
if (COND_END_P.matcher(condPart).matches()) {
prevBlockEndPos = condM.end()
blockStartMatcher.region(prevBlockEndPos, template.length)
continue@blockSearch
} else {
// skip the rest `elif` branches
while (condM.find()) {
condPart = condM.group()
if (COND_END_P.matcher(condPart).matches()) {
if (nest == 0) {
prevBlockEndPos = condM.end()
blockStartMatcher.region(
prevBlockEndPos, template.length)
continue@blockSearch
} else {
nest--
}
} else if (COND_START_P.matcher(condPart).matches()) {
nest++
}
}
throw near(template, blockDefPos, "`if` block is not closed")
}
} else {
if (COND_END_P.matcher(condPart).matches()) {
prevBlockEndPos = condM.end()
blockStartMatcher.region(prevBlockEndPos, template.length)
continue@blockSearch
} else {
// `elif` branch
prevBranchCond = Condition.parseCheckedCondition(
getBlockGroup(condM.group(), COND_PART_BLOCK_P,
"condition"),
dimensionsParser!!, source,
template, condM.start())
branchStartPos = condM.end()
}
}
}
}
throw near(template, blockDefPos, "`if` block is not closed")
} else {
// `with` block
var contextM = CONTEXT_START_P.matcher(blockStart)
if (contextM.matches()) {
val additionalDims = dimensionsParser!!.parseForContext(
getBlockGroup(contextM.group(), CONTEXT_START_BLOCK_P,
"dimensions"))
val blockStartPos = blockStartMatcher.end()
var nest = 0
contextM = CONTEXT_PART_P.matcher(template)
contextM.region(blockStartPos, template.length)
while (contextM.find()) {
val contextPart = contextM.group()
if (CONTEXT_END_P.matcher(contextPart).matches()) {
if (nest == 0) {
val blockEndPos = contextM.start()
val block = template.substring(blockStartPos, blockEndPos)
val addContexts = additionalDims.generateContexts()
val newSource = source.join(addContexts[0])
for (addCxt in addContexts) {
val newTarget = target.join(addCxt)
// if addContext size is 1, this context is not
// for generation. For example to prevent
// unwanted generation:
// /*with int|long dim*/ generated int 1 /*with int elem*/
// always int /*endwith*/ generated int 2 /*endwith*/
// -- for example. We don't filter such contexts.
if (addContexts.size == 1 || checkContext(newTarget)) {
process(sb, newSource, newTarget, block)
}
}
prevBlockEndPos = contextM.end()
blockStartMatcher.region(prevBlockEndPos, template.length)
continue@blockSearch
} else {
// nesting `with` end
nest--
}
} else {
// nesting `with` start
nest++
}
}
} else {
throw near(template, blockDefPos,
"Block end or `elif` branch without start")
}
}
}
val tail = template.substring(prevBlockEndPos)
postProcess(sb, source, target, tail)
}
}
companion object {
private val log = LoggerFactory.getLogger(Generator::class.java)
@JvmStatic
private val checkingDimensionsParser: Dimensions.Parser = Dimensions.Parser(emptyList())
private val currentSource = ThreadLocal<File>()
fun setCurrentSourceFile(source: File) {
currentSource.set(source)
}
@JvmStatic
fun currentSourceFile(): File? {
return currentSource.get()
}
private val currentGenerator = ThreadLocal<Generator>()
private fun setCurrentGenerator(generator: Generator) {
currentGenerator.set(generator)
}
@JvmStatic
fun currentGenerator(): Generator {
return currentGenerator.get()
}
private val redefinedClassName = ThreadLocal<String?>()
@JvmStatic
fun setRedefinedClassName(className: String?) {
redefinedClassName.set(className)
}
private fun getRedefinedClassName(): String? {
return redefinedClassName.get()
}
@JvmStatic
fun compileBlock(insideBlockRegex: String, keyword: String): CheckingPattern {
val checkingBlockBlockCommentOpening = "/\\*\\s*$keyword[^/*]*+[*/]/"
// Don't allow blocks starting with `//` to be multiline (the only difference of the
// checkingBlockDoubleSlash regex from checkingBlockBlockCommentOpening is exclusion of
// '\n'). This is to reduce false-positive "Malformed template near" errors by JPSG on
// normal // comments that happen to start with "if" or "with".
val checkingBlockDoubleSlash = "//\\s*$keyword[^/*\\n]*+[*/]/"
val checkingBlock = "($checkingBlockBlockCommentOpening|$checkingBlockDoubleSlash)"
val block = "/[*/]\\s*" + removeSubGroupNames(insideBlockRegex) + "\\s*[*/]/"
return compile(justBlockOrWholeLine(checkingBlock), justBlockOrWholeLine(block))
}
private fun justBlockOrWholeLine(block: String): String {
return format("^[^\\S\\r\\n]*%s[^\\S\\n]*?\\n|%s", block, block)
}
@JvmStatic
fun wrapBlock(insideBlockRegex: String): Pattern {
return RegexpUtils.compile("\\s*/[*/]\\s*$insideBlockRegex\\s*[*/]/\\s*")
}
private fun getBlockGroup(block: String, pattern: Pattern, group: String): String {
val m = pattern.matcher(block)
if (m.matches()) {
return m.group(group)
} else {
throw AssertionError()
}
}
const val BLOCKS_PROCESSOR_PRIORITY: Int = TemplateProcessor.DEFAULT_PRIORITY + 100
}
}
| 3 | Java | 1 | 29 | b88de9f19058520e04eb204e46024b978b22f8d1 | 28,047 | java-primitive-specializations-generator | Apache License 2.0 |
compiler/testData/diagnostics/tests/secondaryConstructors/headerCallChecker/memberFunAccess.fir.kt | prasenjitghose36 | 258,198,392 | false | null | // !DIAGNOSTICS: -UNUSED_PARAMETER
class A {
fun foo() = 1
constructor(x: Int)
constructor(x: Int, y: Int, z: Int = x + foo() + this.foo()) :
<!INAPPLICABLE_CANDIDATE!>this<!>(x <!AMBIGUITY!>+<!> <!UNRESOLVED_REFERENCE!>foo<!>() + this.<!UNRESOLVED_REFERENCE!>foo<!>())
}
| 0 | null | 0 | 2 | acced52384c00df5616231fa5ff7e78834871e64 | 292 | kotlin | Apache License 2.0 |
form/src/main/java/com/thejuki/kformmaster/model/FormButtonElement.kt | area55git | 134,616,709 | false | null | package com.thejuki.kformmaster.model
import android.os.Parcel
import android.os.Parcelable
/**
* Form Button Element
*
* Form element for Button
*
* @author **TheJuki** ([GitHub](https://github.com/TheJuki))
* @version 1.0
*/
class FormButtonElement : BaseFormElement<String> {
/**
* No validation needed
*/
override val isValid: Boolean
get() = true
/**
* Nothing to clear
*/
override fun clear() {}
/**
* Parcelable boilerplate
*/
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
}
constructor() : super()
constructor(tag: Int) : super(tag)
constructor(`in`: Parcel) : super(`in`) {}
companion object {
/**
* Creates an instance
*/
fun createInstance(): FormButtonElement {
return FormButtonElement()
}
val CREATOR: Parcelable.Creator<FormButtonElement> = object : Parcelable.Creator<FormButtonElement> {
override fun createFromParcel(source: Parcel): FormButtonElement {
return FormButtonElement(source)
}
override fun newArray(size: Int): Array<FormButtonElement?> {
return arrayOfNulls(size)
}
}
}
}
| 1 | null | 1 | 1 | f2a736d94a917ab215794687665eeafdf3c9816c | 1,374 | KFormMaster | Apache License 2.0 |
app/src/main/java/org/stepic/droid/features/deadlines/storage/dao/DeadlinesBannerDaoImpl.kt | Ujjawal-Anand | 142,415,269 | false | null | package org.stepic.droid.features.deadlines.storage.dao
import android.content.ContentValues
import android.database.Cursor
import org.stepic.droid.features.deadlines.storage.structure.DbStructureDeadlinesBanner
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import javax.inject.Inject
class DeadlinesBannerDaoImpl
@Inject
constructor(databaseOperations: DatabaseOperations): DaoBase<Long>(databaseOperations), DeadlinesBannerDao {
override fun getDbName() =
DbStructureDeadlinesBanner.DEADLINES_BANNER
override fun getDefaultPrimaryColumn() =
DbStructureDeadlinesBanner.Columns.COURSE_ID
override fun getDefaultPrimaryValue(persistentObject: Long) =
persistentObject.toString()
override fun getContentValues(persistentObject: Long): ContentValues = ContentValues().apply {
put(DbStructureDeadlinesBanner.Columns.COURSE_ID, persistentObject)
}
override fun parsePersistentObject(cursor: Cursor) =
cursor.getLong(cursor.getColumnIndex(DbStructureDeadlinesBanner.Columns.COURSE_ID))
} | 0 | null | 0 | 1 | 256a90051eefe8db83f7053914004905bbb1f8d0 | 1,127 | stepik-android | Apache License 2.0 |
app/src/main/java/com/frankenstein/screenx/capture/RequestCaptureActivity.kt | pavan142 | 346,975,893 | false | null | package com.frankenstein.screenx.capture
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class RequestCaptureActivity : AppCompatActivity() {
private var requestStartTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Draw transparent status and navigation bar
val window = this.window
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = ContextCompat.getColor(this, android.R.color.transparent)
window.navigationBarColor = ContextCompat.getColor(this, android.R.color.transparent)
requestScreenCapturePermission()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_SCREEN_CAPTURE_PERMISSION) {
val intent = Intent(getResultBroadcastAction(this))
intent.putExtra(RESULT_EXTRA_CODE, resultCode)
intent.putExtra(RESULT_EXTRA_DATA, data)
intent.putExtra(RESULT_EXTRA_PROMPT_SHOWN, promptShown())
androidx.localbroadcastmanager.content.LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
finish()
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun requestScreenCapturePermission() {
val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val intent = mediaProjectionManager.createScreenCaptureIntent()
requestStartTime = System.currentTimeMillis()
startActivityForResult(intent, REQUEST_CODE_SCREEN_CAPTURE_PERMISSION)
}
private fun promptShown(): Boolean {
// Assume that the prompt was shown if the response took 200ms or more to return.
return System.currentTimeMillis() - requestStartTime > 200
}
companion object {
const val RESULT_EXTRA_CODE = "code"
const val RESULT_EXTRA_DATA = "data"
const val RESULT_EXTRA_PROMPT_SHOWN = "prompt-shown"
private const val REQUEST_CODE_SCREEN_CAPTURE_PERMISSION = 1
fun getResultBroadcastAction(context: Context): String {
return context.packageName + ".CAPTURE"
}
}
}
| 22 | null | 2 | 2 | 6a5ef3260e82d9ee80689f2eb68918d3b716d37f | 2,672 | ScreenX | MIT License |
idea/tests/testData/codeInsight/overrideImplement/enumClass2.kt | JetBrains | 278,369,660 | false | null | // FIR_IDENTICAL
enum <caret>class Foo {
} | 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 42 | intellij-kotlin | Apache License 2.0 |
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileCommand.kt | Nyrheim | 269,929,653 | true | {"Gradle": 71, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "YAML": 103, "Kotlin": 1043, "Java": 291, "HTML": 23, "CSS": 2, "JavaScript": 1} | package com.rpkit.players.bukkit.command.profile
import com.rpkit.players.bukkit.RPKPlayersBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class ProfileCommand(private val plugin: RPKPlayersBukkit): CommandExecutor {
val profileNameCommand = ProfileNameCommand(plugin)
val profilePasswordCommand = ProfilePasswordCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["profile-usage"])
return true
}
val newArgs = args.drop(1).toTypedArray()
return when (args[0].toLowerCase()) {
"name" -> profileNameCommand.onCommand(sender, command, label, newArgs)
"password" -> profilePasswordCommand.onCommand(sender, command, label, newArgs)
else -> {
sender.sendMessage(plugin.messages["profile-usage"])
true
}
}
}
} | 0 | null | 0 | 0 | f2196a76e0822b2c60e4a551de317ed717bbdc7e | 1,080 | RPKit | Apache License 2.0 |
analysis/analysis-api/testData/components/compilerFacility/compilation/codeFragments/annotationUsage.fragment.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} | foo() + bar() | 166 | Kotlin | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 13 | kotlin | Apache License 2.0 |
feature/input/src/main/java/com/freshdigitable/udonroad2/input/TweetInputEvents.kt | akihito104 | 149,869,805 | false | null | /*
* Copyright (c) 2020. Matsuda, Akihit (akihito104)
*
* 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.freshdigitable.udonroad2.input
import com.freshdigitable.udonroad2.model.app.AppFilePath
import com.freshdigitable.udonroad2.model.app.StateGraph
import com.freshdigitable.udonroad2.model.app.navigation.AppEvent
sealed class TweetInputEvent : AppEvent {
object Open : TweetInputEvent()
object Opened : TweetInputEvent()
data class Send(val tweet: InputTweet) : TweetInputEvent()
object Cancel : TweetInputEvent()
data class TextUpdated(val text: String) : TweetInputEvent()
}
internal sealed class CameraApp : TweetInputEvent() {
sealed class Event : CameraApp() {
data class CandidateQueried(val apps: List<Components>, val path: AppFilePath) : Event()
data class Chosen(val app: Components) : Event()
data class OnFinish(val result: MediaChooserResultContract.MediaChooserResult) : Event()
}
sealed class State : CameraApp() {
object Idling : State()
data class WaitingForChosen(val apps: List<Components>, val path: AppFilePath) : State()
data class Selected(
/**
* component information that selected camera app in intent chooser.
* on Android 10+, intent chooser does not pass the information.
* so, all components that known at WaitingForChosen are passed for grant uri permission.
*/
val app: List<Components>,
val path: AppFilePath,
) : State()
data class Finished(
/**
* component information that selected camera app in intent chooser.
* on Android 10+, intent chooser does not pass the information.
* so, all components that known at WaitingForChosen are passed for revoke uri permission.
*/
val app: List<Components>,
val path: AppFilePath,
) : State()
}
companion object {
fun State.transition(event: Event): State = stateGraph.transition(this, event)
private val stateGraph = StateGraph.create<State, Event> {
state<State.Idling> {
accept<Event.CandidateQueried> { State.WaitingForChosen(it.apps, it.path) }
doNotCare<Event.OnFinish>()
}
state<State.WaitingForChosen> {
accept<Event.Chosen> {
when {
it.app == Components.UNKNOWN -> return@accept State.Selected(apps, path)
apps.contains(it.app) -> State.Selected(listOf(it.app), path)
else -> State.Idling
}
}
accept<Event.CandidateQueried> { State.WaitingForChosen(it.apps, it.path) }
accept<Event.OnFinish> { State.Idling }
}
state<State.Selected> {
accept<Event.OnFinish> { State.Finished(app, path) }
}
state<State.Finished> {
accept<Event.CandidateQueried> { State.WaitingForChosen(it.apps, it.path) }
}
}
}
}
data class Components(
val packageName: String,
val className: String,
) {
companion object {
val UNKNOWN: Components = Components("", "")
}
}
| 21 | null | 1 | 1 | 7ec50f204fda79cf222b24623f22e80d05301555 | 3,836 | UdonRoad2 | Apache License 2.0 |
src/scanner/kotlin/org/platestack/bukkit/scanner/structure/changes.kt | PlateStack | 91,766,425 | false | {"Git Config": 1, "Gradle": 2, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "YAML": 2, "Java": 11, "Kotlin": 23} | /*
* Copyright (C) 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.platestack.bukkit.scanner.structure
interface Change {
val from: Any
val to: Any
}
/**
* A field name
*/
data class FieldChange(val name: Name): Change {
override val from = FieldIdentifier(name.from)
override val to get() = FieldIdentifier(name.to)
override fun toString() = "$from -> $to"
}
/**
* A method name and its descriptor
*/
data class MethodChange(val name: Name, val descriptorType: MethodDescriptor) : Change {
override val from = MethodIdentifier(name.from, descriptorType.from)
override val to get() = MethodIdentifier(name.to, descriptorType.to)
override fun toString() = "$from -> $to"
}
/**
* A package name
* @property parent The parent where this class resides
* @property name The actual name of this package. Must contains not contains any separation character!
*/
data class PackageChange(val parent: PackageChange?, var moveTo: PackageChange?, val name: PackageName) : Change {
override val from: PackageIdentifier = PackageIdentifier(parent?.from, name.from)
@Suppress("RecursivePropertyAccessor")
override val to: PackageIdentifier get() = PackageIdentifier(moveTo?.to, name.to)
override fun toString() = "$from -> $to"
}
/**
* A migration from a location to an other
*/
interface Move {
/**
* The old location
*/
val old: Change?
/**
* The new location
*/
val new: Change?
val from: Identifier?
val to: Identifier?
}
/**
* A migration from one package to another
*/
data class PackageMove(override val old: PackageChange, override var new: PackageChange = old) : Move {
override val from get() = old.from
override val to get() = new.to
override fun toString() = "$from -> $to"
}
/**
* A full class name
* @property package The package where this class resides
* @property parent The class which nests this class or is referred by this class name before the actual name
* @property name The actual name of this class. Must contains the separation character.
*/
data class ClassChange(val `package`: PackageMove, var parent: ClassChange?, val name: ClassName) : Change {
override val from: ClassIdentifier = ClassIdentifier(parent?.from?.`package` ?: `package`.from, parent?.from, name.from)
@Suppress("RecursivePropertyAccessor")
override val to: ClassIdentifier get() = ClassIdentifier(parent?.to?.`package` ?: `package`.to, parent?.to, name.to)
override fun toString() = "$from -> $to"
}
| 1 | null | 1 | 1 | 7616eb3b281ab8b8f3d3c14d2b6a03374fd2202d | 3,080 | PlateBukkit | Apache License 2.0 |
modules/presentation/src/main/java/kr/co/knowledgerally/ui/register/lounge/RegisterLoungeItem.kt | YAPP-Github | 475,728,173 | false | {"Kotlin": 454888} | package kr.co.knowledgerally.ui.register.lounge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import kr.co.knowledgerally.domain.model.LectureInfo
import kr.co.knowledgerally.model.toPresentation
import kr.co.knowledgerally.ui.R
import kr.co.knowledgerally.ui.component.ContainedBadge
import kr.co.knowledgerally.ui.component.LectureImage
import kr.co.knowledgerally.ui.theme.KnowllyTheme
@Composable
fun RegisterLoungeItemHeader() {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 28.dp)
) {
Text(
text = stringResource(id = R.string.register_lounge_register_time),
style = KnowllyTheme.typography.headline4
)
Text(
text = stringResource(id = R.string.register_lounge_register_time_description),
modifier = Modifier.padding(top = 4.dp),
style = KnowllyTheme.typography.body1,
color = KnowllyTheme.colors.gray8F,
)
}
}
@Composable
fun RegisterLoungeItem(
lectureInfo: LectureInfo,
navigateToSchedule: (Long) -> Unit,
) {
Column(modifier = Modifier.fillMaxWidth()) {
Row {
LectureImage(
imageUrl = lectureInfo.thumbnailImageUrl,
modifier = Modifier.size(88.dp),
)
Column(
modifier = Modifier
.padding(start = 18.dp)
.weight(1f)
) {
Text(
text = lectureInfo.topic,
style = KnowllyTheme.typography.subtitle2,
)
ContainedBadge(
text = stringResource(lectureInfo.category.toPresentation().text),
contentColor = KnowllyTheme.colors.secondaryIndigo,
backgroundColor = KnowllyTheme.colors.secondaryIndigoLight,
modifier = Modifier.padding(top = 10.dp),
)
}
}
Surface(
modifier = Modifier
.padding(top = 20.dp)
.fillMaxWidth()
.height(40.dp),
color = KnowllyTheme.colors.primaryLight,
shape = RoundedCornerShape(18.dp),
onClick = { navigateToSchedule(lectureInfo.id) }
) {
Row(
modifier = Modifier
.fillMaxSize()
.height(40.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_add),
modifier = Modifier.size(16.dp),
tint = KnowllyTheme.colors.primaryDark,
contentDescription = null,
)
Text(
text = stringResource(id = R.string.register_lounge_register_time_button),
modifier = Modifier.padding(start = 2.dp),
style = KnowllyTheme.typography.button1,
color = KnowllyTheme.colors.primaryDark
)
}
}
}
}
@Composable
fun RegisterLoungeItemDivider() {
Divider(
modifier = Modifier
.padding(top = 24.dp, bottom = 16.dp)
.height(1.dp),
color = KnowllyTheme.colors.grayEF
)
}
| 2 | Kotlin | 1 | 4 | 01db68b42594360a9285af458eb812ad83acef70 | 4,228 | 20th-ALL-Rounder-Team-2-Android | Apache License 2.0 |
solar/src/main/java/com/chiksmedina/solar/lineduotone/__Weather.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.lineduotone
import androidx.compose.ui.graphics.vector.ImageVector
import com.chiksmedina.solar.LineDuotoneSolar
import com.chiksmedina.solar.lineduotone.weather.Cloud
import com.chiksmedina.solar.lineduotone.weather.CloudBolt
import com.chiksmedina.solar.lineduotone.weather.CloudBoltMinimalistic
import com.chiksmedina.solar.lineduotone.weather.CloudCheck
import com.chiksmedina.solar.lineduotone.weather.CloudDownload
import com.chiksmedina.solar.lineduotone.weather.CloudMinus
import com.chiksmedina.solar.lineduotone.weather.CloudPlus
import com.chiksmedina.solar.lineduotone.weather.CloudRain
import com.chiksmedina.solar.lineduotone.weather.CloudSnowfall
import com.chiksmedina.solar.lineduotone.weather.CloudSnowfallMinimalistic
import com.chiksmedina.solar.lineduotone.weather.CloudStorm
import com.chiksmedina.solar.lineduotone.weather.CloudSun
import com.chiksmedina.solar.lineduotone.weather.CloudSun2
import com.chiksmedina.solar.lineduotone.weather.CloudUpload
import com.chiksmedina.solar.lineduotone.weather.CloudWaterdrop
import com.chiksmedina.solar.lineduotone.weather.CloudWaterdrops
import com.chiksmedina.solar.lineduotone.weather.Clouds
import com.chiksmedina.solar.lineduotone.weather.CloudyMoon
import com.chiksmedina.solar.lineduotone.weather.CloundCross
import com.chiksmedina.solar.lineduotone.weather.Fog
import com.chiksmedina.solar.lineduotone.weather.Moon
import com.chiksmedina.solar.lineduotone.weather.MoonFog
import com.chiksmedina.solar.lineduotone.weather.MoonSleep
import com.chiksmedina.solar.lineduotone.weather.MoonStars
import com.chiksmedina.solar.lineduotone.weather.Snowflake
import com.chiksmedina.solar.lineduotone.weather.Stars
import com.chiksmedina.solar.lineduotone.weather.Sun
import com.chiksmedina.solar.lineduotone.weather.Sun2
import com.chiksmedina.solar.lineduotone.weather.SunFog
import com.chiksmedina.solar.lineduotone.weather.Sunrise
import com.chiksmedina.solar.lineduotone.weather.Sunset
import com.chiksmedina.solar.lineduotone.weather.Temperature
import com.chiksmedina.solar.lineduotone.weather.Tornado
import com.chiksmedina.solar.lineduotone.weather.TornadoSmall
import com.chiksmedina.solar.lineduotone.weather.Waterdrops
import com.chiksmedina.solar.lineduotone.weather.Wind
import kotlin.collections.List as KtList
object WeatherGroup
val LineDuotoneSolar.Weather: WeatherGroup
get() = WeatherGroup
private var _AllIcons: KtList<ImageVector>? = null
val WeatherGroup.AllIcons: KtList<ImageVector>
get() {
if (_AllIcons != null) {
return _AllIcons!!
}
_AllIcons = listOf(
Cloud,
Clouds,
CloudyMoon,
CloudBolt,
CloudBoltMinimalistic,
CloudCheck,
CloudDownload,
CloudMinus,
CloudPlus,
CloudRain,
CloudSnowfall,
CloudSnowfallMinimalistic,
CloudStorm,
CloudSun,
CloudSun2,
CloudUpload,
CloudWaterdrop,
CloudWaterdrops,
CloundCross,
Fog,
Moon,
MoonFog,
MoonSleep,
MoonStars,
Snowflake,
Stars,
Sun,
Sunrise,
Sunset,
Sun2,
SunFog,
Temperature,
Tornado,
TornadoSmall,
Waterdrops,
Wind
)
return _AllIcons!!
}
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 3,503 | SolarIconSetAndroid | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.