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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bucketsdk/src/main/java/bucket/sdk/extensions/Any.kt
|
buckettech
| 128,779,649
| false
| null |
package bucket.sdk.extensions
var Any?.isNil : Boolean
get() { return this == null }
private set(value) {}
| 0
|
Kotlin
|
2
| 0
|
4123e9373f080af4e6b9702a98321cd4cbc5322e
| 115
|
BucketSDK-Android
|
MIT License
|
app/src/main/kotlin/org/jdc/template/ui/compose/form/TextWithTitle.kt
|
jeffdcamp
| 12,853,600
| false
|
{"Kotlin": 391385, "HTML": 58007}
|
package org.jdc.template.ui.compose.form
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import org.jdc.template.ui.compose.PreviewDefault
@Composable
fun TextWithTitle(
text: String?,
label: String? = null,
textStyle: TextStyle = MaterialTheme.typography.bodyMedium
) {
if (text.isNullOrBlank()) {
return
}
Column {
if (label != null) {
Text(
text = label,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.padding(top = 8.dp)
)
}
Text(
text = text,
style = textStyle,
modifier = Modifier
.padding(top = if (label != null) 4.dp else 8.dp, bottom = 8.dp)
)
}
}
@PreviewDefault
@Composable
private fun Preview() {
MaterialTheme {
Column(
modifier = Modifier.fillMaxWidth()
) {
TextWithTitle(text = "John", label = "First Name")
TextWithTitle(text = "Adams", label = "Last Name")
TextWithTitle(text = "123 Main Street")
}
}
}
| 0
|
Kotlin
|
40
| 99
|
21136fcddd0632b5d48892583acf84fa34bca285
| 1,483
|
android-template
|
Apache License 2.0
|
src/test/java/com/filestack/internal/UploadServiceTest.kt
|
filestack
| 93,534,425
| false
|
{"SVG": 1, "Markdown": 5, "Gradle": 1, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "XML": 3, "Java Properties": 1, "Kotlin": 12, "Java": 150, "Proguard": 1, "INI": 1, "HTML": 176, "CSS": 1, "JavaScript": 1}
|
package com.filestack.internal
import com.filestack.bodyParams
import com.filestack.internal.responses.CompleteResponse
import com.filestack.internal.responses.StartResponse
import com.filestack.internal.responses.UploadResponse
import com.filestack.tempFile
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.RequestBody
import okio.Buffer
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.ArgumentCaptor
import java.net.URLConnection
class UploadServiceTest {
val networkClient: NetworkClient = mock()
val uploadService = UploadService(networkClient)
@Test
fun start() {
val file = tempFile(sizeInBytes = 1024)
val baseParams = mutableMapOf<String, RequestBody>()
baseParams["apikey"] = Util.createStringPart("api_key")
baseParams["size"] = Util.createStringPart(file.length().toString())
baseParams["policy"] = Util.createStringPart("my_policy")
baseParams["signature"] = Util.createStringPart("my_signature")
uploadService.start(baseParams)
val argumentCaptor = ArgumentCaptor.forClass(okhttp3.Request::class.java)
verify(networkClient).call(argumentCaptor.capture(), eq(StartResponse::class.java))
val request = argumentCaptor.value
assertEquals(
HttpUrl.get("https://upload.filestackapi.com/multipart/start"),
request.url()
)
assertEquals("POST", request.method())
val bodyParams = request.bodyParams()
assertEquals("api_key", bodyParams["apikey"])
assertEquals(file.length().toString(), bodyParams["size"])
assertEquals("my_policy", bodyParams["policy"])
assertEquals("my_signature", bodyParams["signature"])
}
@Test
fun upload() {
val fileToUpload = tempFile(postfix = ".jpg", sizeInBytes = 1024)
val type = URLConnection.guessContentTypeFromName(fileToUpload.name)
val requestBody = RequestBody.create(MediaType.get(type), fileToUpload)
val params = mutableMapOf<String, RequestBody>()
params["apikey"] = Util.createStringPart("api_key")
params["size"] = Util.createStringPart(fileToUpload.length().toString())
params["policy"] = Util.createStringPart("my_policy")
params["signature"] = Util.createStringPart("my_signature")
params["content"] = requestBody
uploadService.upload(params)
val argumentCaptor = ArgumentCaptor.forClass(okhttp3.Request::class.java)
verify(networkClient).call(argumentCaptor.capture(), eq(UploadResponse::class.java))
val request = argumentCaptor.value
assertEquals(
HttpUrl.get("https://upload.filestackapi.com/multipart/upload"),
request.url()
)
assertEquals("POST", request.method())
val bodyParams = request.bodyParams()
assertEquals("api_key", bodyParams["apikey"])
assertEquals(fileToUpload.length().toString(), bodyParams["size"])
assertEquals("my_policy", bodyParams["policy"])
assertEquals("my_signature", bodyParams["signature"])
}
@Test
fun uploadS3() {
val headers = mapOf(
"Header1" to "HeaderValue1",
"Header2" to "HeaderValue2"
)
val url = "https://s3.url.test.com"
val fileToUpload = tempFile(postfix = ".jpg", sizeInBytes = 1024)
val type = URLConnection.guessContentTypeFromName(fileToUpload.name)
val requestBody = RequestBody.create(MediaType.get(type), fileToUpload)
uploadService.uploadS3(headers, url, requestBody)
val argumentCaptor = ArgumentCaptor.forClass(okhttp3.Request::class.java)
verify(networkClient).call(argumentCaptor.capture())
val request = argumentCaptor.value
assertEquals(
HttpUrl.get(url),
request.url()
)
assertEquals("PUT", request.method())
val requestHeaders = request.headers()
assertEquals("HeaderValue1", requestHeaders.get("Header1"))
assertEquals("HeaderValue2", requestHeaders.get("Header2"))
val body = request.body()!!
assertEquals(MediaType.get("image/jpeg"), body.contentType())
assertEquals(fileToUpload.length(), body.contentLength())
}
@Test
fun commit() {
val file = tempFile(sizeInBytes = 1024)
val baseParams = mutableMapOf<String, RequestBody>()
baseParams["apikey"] = Util.createStringPart("api_key")
baseParams["size"] = Util.createStringPart(file.length().toString())
baseParams["policy"] = Util.createStringPart("my_policy")
baseParams["signature"] = Util.createStringPart("my_signature")
uploadService.commit(baseParams)
val argumentCaptor = ArgumentCaptor.forClass(okhttp3.Request::class.java)
verify(networkClient).call(argumentCaptor.capture())
val request = argumentCaptor.value
assertEquals(
HttpUrl.get("https://upload.filestackapi.com/multipart/commit"),
request.url()
)
assertEquals("POST", request.method())
val bodyParams = request.bodyParams()
assertEquals("api_key", bodyParams["apikey"])
assertEquals(file.length().toString(), bodyParams["size"])
assertEquals("my_policy", bodyParams["policy"])
assertEquals("my_signature", bodyParams["signature"])
}
@Test
fun complete() {
val file = tempFile(sizeInBytes = 1024)
val baseParams = mutableMapOf<String, RequestBody>()
baseParams["apikey"] = Util.createStringPart("api_key")
baseParams["size"] = Util.createStringPart(file.length().toString())
baseParams["policy"] = Util.createStringPart("my_policy")
baseParams["signature"] = Util.createStringPart("my_signature")
uploadService.complete(baseParams)
val argumentCaptor = ArgumentCaptor.forClass(okhttp3.Request::class.java)
verify(networkClient).call(argumentCaptor.capture(), eq(CompleteResponse::class.java))
val request = argumentCaptor.value
assertEquals(
HttpUrl.get("https://upload.filestackapi.com/multipart/complete"),
request.url()
)
assertEquals("POST", request.method())
val bodyParams = request.bodyParams()
assertEquals("api_key", bodyParams["apikey"])
assertEquals(file.length().toString(), bodyParams["size"])
assertEquals("my_policy", bodyParams["policy"])
assertEquals("my_signature", bodyParams["signature"])
}
private fun Request.bodyParams(): Map<String, String> {
val buffer = Buffer()
body()?.writeTo(buffer)
return buffer.bodyParams()
}
}
| 6
|
Java
|
18
| 18
|
3814ace6b6cbb18c91df5b19c8c5209646623c07
| 6,943
|
filestack-java
|
Apache License 2.0
|
gaia-sdk-java/gaia-sdk-graphql/src/main/kotlin/gaia/sdk/request/type/Conversational.kt
|
leftshiftone
| 218,051,248
| false
|
{"Python": 597076, "TypeScript": 553203, "Kotlin": 517386, "JavaScript": 6976, "ANTLR": 2281}
|
package gaia.sdk.request.type
import gaia.sdk.client.Type
import gaia.sdk.request.intf.*
import gaia.sdk.client.Input
import gaia.sdk.Uuid
import gaia.sdk.ISO8601
import gaia.sdk.Struct
import gaia.sdk.request.input.*
import gaia.sdk.request.enumeration.*
/**
* Type which contains all impulses needed for the maintainence of a conversation
*/
class Conversational: Type() {
/**
* Utterance perception impulse used to send an utterance text to gaia
*/
fun perceiveUtterance(impulse : PerceiveUtteranceImpulse?, config: PerceivedImpulse.() -> Unit) = add {
val name1 = it.register("impulse", impulse)
"perceiveUtterance(impulse:$name1){" + PerceivedImpulse().apply(config).render(it) + "}"
}
/**
* Button perception impulse used to send a button action to gaia
*/
fun perceiveButton(impulse : PerceiveButtonImpulse?, config: PerceivedImpulse.() -> Unit) = add {
val name1 = it.register("impulse", impulse)
"perceiveButton(impulse:$name1){" + PerceivedImpulse().apply(config).render(it) + "}"
}
/**
* Submit perception impulse used to send a submit action to gaia
*/
fun perceiveSubmit(impulse : PerceiveSubmitImpulse?, config: PerceivedImpulse.() -> Unit) = add {
val name1 = it.register("impulse", impulse)
"perceiveSubmit(impulse:$name1){" + PerceivedImpulse().apply(config).render(it) + "}"
}
/**
* Reception perception impulse used to send a reception to gaia
*/
fun perceiveReception(impulse : PerceiveReceptionImpulse?, config: PerceivedImpulse.() -> Unit) = add {
val name1 = it.register("impulse", impulse)
"perceiveReception(impulse:$name1){" + PerceivedImpulse().apply(config).render(it) + "}"
}
/**
* Suggestion perception impulse used to send a suggestion action to gaia
*/
fun perceiveSuggestion(impulse : PerceiveSuggestionImpulse?, config: PerceivedImpulse.() -> Unit) = add {
val name1 = it.register("impulse", impulse)
"perceiveSuggestion(impulse:$name1){" + PerceivedImpulse().apply(config).render(it) + "}"
}
}
| 8
|
Python
|
2
| 1
|
10190c1de4b2b5f1d4a5f014602c4ccc5c11bee4
| 2,129
|
gaia-sdk
|
MIT License
|
library-extensions-swipe/src/main/java/com/mikepenz/fastadapter/swipe/SimpleSwipeDrawerCallback.kt
|
koral--
| 298,616,020
| true
|
{"Kotlin": 629642, "Java": 20690, "Shell": 1061, "Ruby": 26}
|
package com.mikepenz.fastadapter.swipe
import android.graphics.Canvas
import android.graphics.Rect
import android.view.MotionEvent
import android.view.View
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.IItem
/**
* Created by Robb on 2020-07-04.
*/
class SimpleSwipeDrawerCallback @JvmOverloads constructor(private val swipeDirs: Int = ItemTouchHelper.LEFT) : ItemTouchHelper.SimpleCallback(0, swipeDirs) {
// Swipe movement control
private var sensitivityFactor = 1f
// "Drawer width" swipe gesture is allowed to reach before blocking
private var swipeWidthLeftDp = 20
private var swipeWidthRightDp = 20
// Indicates whether the touchTransmitter has been set on the RecyclerView
private var touchTransmitterSet = false
/**
* Enable swipe to the left until the given width has been reached
*/
fun withSwipeLeft(widthDp: Int): SimpleSwipeDrawerCallback {
swipeWidthLeftDp = widthDp
setDefaultSwipeDirs(swipeDirs or ItemTouchHelper.LEFT)
return this
}
/**
* Enable swipe to the right until the given width has been reached
*/
fun withSwipeRight(widthDp: Int): SimpleSwipeDrawerCallback {
swipeWidthRightDp = widthDp
setDefaultSwipeDirs(swipeDirs or ItemTouchHelper.RIGHT)
return this
}
/**
* Control the sensitivity of the swipe gesture
* 0.5 : very sensitive
* 1 : Android default
* 10 : almost insensitive
*/
fun withSensitivity(f: Float): SimpleSwipeDrawerCallback {
sensitivityFactor = f
return this
}
override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val item = FastAdapter.getHolderAdapterItem<IItem<*>>(viewHolder)
return if (item is ISwipeable) {
if ((item as ISwipeable).isSwipeable) {
super.getSwipeDirs(recyclerView, viewHolder)
} else {
0
}
} else {
super.getSwipeDirs(recyclerView, viewHolder)
}
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// Not used
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
// Not enabled
return false
}
override fun getSwipeEscapeVelocity(defaultValue: Float): Float {
return defaultValue * sensitivityFactor
}
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
val itemView = viewHolder.itemView
if (!touchTransmitterSet) {
recyclerView.setOnTouchListener(RecyclerTouchTransmitter())
touchTransmitterSet = true
}
if (viewHolder.adapterPosition == RecyclerView.NO_POSITION) {
return
}
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
val isLeft = dX < 0
var swipeWidthPc = recyclerView.context.resources.displayMetrics.density / itemView.width
swipeWidthPc *= if (isLeft) swipeWidthLeftDp else swipeWidthRightDp
var swipeableView = itemView
if (viewHolder is IDrawerSwipeableViewHolder) swipeableView = viewHolder.swipeableView
swipeableView.translationX = dX * swipeWidthPc
} else super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
/**
* Hack to force-transmit click events to the first visible View at the clicked coordinates
* [< swiped area ] exposed sublayer ]
* Android default touch event mechanisms don't transmit these events to the sublayer :
* any click on the exposed surface just swipe the item back to where it came
*/
class RecyclerTouchTransmitter : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent): Boolean {
if (null == v || v !is ViewGroup) return false
// Get the first visible View under the clicked coordinates
val childView = v.getFirstVisibleViewByCoordinates(event.x, event.y)
// Transmit the ACTION_DOWN and ACTION_UP events to this View
if (childView != null)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
childView.onTouchEvent(event)
}
MotionEvent.ACTION_UP -> {
childView.onTouchEvent(event)
}
}
return false
}
/**
* Return the first visible non-ViewGroup View within the given ViewGroup, at the given coordinates
*/
private fun ViewGroup.getFirstVisibleViewByCoordinates(x: Float, y: Float): View? {
(childCount - 1 downTo 0)
.map { this.getChildAt(it) }
.forEach {
val bounds = Rect()
it.getHitRect(bounds)
if (bounds.contains(x.toInt(), y.toInt()) && VISIBLE == it.visibility) {
return if (it is ViewGroup) it.getFirstVisibleViewByCoordinates(x - bounds.left, y - bounds.top)
else it
}
}
return null
}
}
}
| 0
| null |
0
| 0
|
00713e8e9da3e4debf4b89a7c83915b4c88fd9ca
| 5,648
|
FastAdapter
|
Apache License 2.0
|
subprojects/android-test/ui-testing-core/src/main/kotlin/com/avito/android/test/util/AppendableDescription.kt
|
avito-tech
| 230,265,582
| false
|
{"Kotlin": 3747948, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
|
package com.avito.android.test.util
import org.hamcrest.BaseDescription
internal class AppendableDescription(private val appendable: Appendable) : BaseDescription() {
override fun append(c: Char) {
appendable.append(c)
}
}
| 10
|
Kotlin
|
50
| 414
|
bc94abf5cbac32ac249a653457644a83b4b715bb
| 242
|
avito-android
|
MIT License
|
core/src/main/kotlin/net/rikarin/http/features/DefaultFeatureCollection.kt
|
Rikarin
| 586,107,122
| false
| null |
package net.rikarin.http.features
import kotlin.reflect.KType
import kotlin.reflect.full.withNullability
internal class DefaultFeatureCollection() : FeatureCollection {
private var _features: MutableMap<KType, Any>? = null
private var _defaults: FeatureCollection? = null
private var _containerRevision = 0
constructor(defaults: FeatureCollection) : this() {
_defaults = defaults
}
override val isReadOnly: Boolean
get() = false
override val revision: Int
get() = _containerRevision + (_defaults?.revision ?: 0)
override fun get(key: KType): Any? {
val newKey = key.withNullability(false)
println("get feature by key $key")
return _features?.getOrDefault(newKey, null) ?: _defaults?.get(newKey)
}
override fun set(key: KType, value: Any?) {
println("set feature by key $key")
val newKey = key.withNullability(false)
if (value == null) {
if (_features?.remove(newKey) != null) {
_containerRevision++
}
return
}
if (_features == null) {
_features = mutableMapOf()
}
_features!![newKey] = value
_containerRevision++
}
override fun iterator(): Iterator<Pair<KType, Any?>> {
// return _features?.iterator() ?: _defaults.iterator()
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
ae49fd70b3a46c5e74e161758f6e7eeaed08ed88
| 1,411
|
kotlin
|
MIT License
|
src/main/kotlin/de/hennihaus/routes/mappers/StatisticMapper.kt
|
hennihaus
| 484,714,079
| false
| null |
package de.hennihaus.routes.mappers
import de.hennihaus.bamdatamodel.Statistic
import de.hennihaus.models.generated.rest.StatisticDTO
import java.util.UUID
fun Statistic.toStatisticDTO() = StatisticDTO(
bankId = "$bankId",
teamId = "$teamId",
requestsCount = requestsCount,
)
fun StatisticDTO.toStatistic() = Statistic(
bankId = UUID.fromString(bankId),
teamId = UUID.fromString(teamId),
requestsCount = requestsCount,
)
| 32
|
Kotlin
|
0
| 0
|
d9e57a5ca5f0712671cf4e26c578c1fb22c0262f
| 448
|
bamconfigbackend
|
Apache License 2.0
|
benchmark/common/src/main/java/androidx/benchmark/ResultWriter.kt
|
tikurahul
| 306,333,033
| true
|
{"Java Properties": 20, "Shell": 44, "Markdown": 43, "Java": 4516, "HTML": 17, "Kotlin": 3557, "Python": 28, "Proguard": 37, "Batchfile": 6, "JavaScript": 1, "CSS": 1, "TypeScript": 6, "Gradle Kotlin DSL": 2, "INI": 1, "CMake": 1, "C++": 2}
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark
import android.os.Build
import android.util.JsonWriter
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.test.platform.app.InstrumentationRegistry
import java.io.File
import java.io.IOException
internal object ResultWriter {
@VisibleForTesting
internal val reports = ArrayList<BenchmarkState.Report>()
fun appendReport(report: BenchmarkState.Report) {
reports.add(report)
if (Arguments.outputEnable) {
// Currently, we just overwrite the whole file
// Ideally, append for efficiency
val packageName =
InstrumentationRegistry.getInstrumentation().targetContext!!.packageName
val file = File(Arguments.testOutputDir, "$packageName-benchmarkData.json")
Log.d(
BenchmarkState.TAG,
"writing results to ${file.absolutePath}"
)
writeReport(file, reports)
InstrumentationResults.reportAdditionalFileToCopy(
"results_json",
file.absolutePath,
// since we keep appending the same file, defer reporting path until end of suite
// note: this requires using InstrumentationResultsRunListener
reportOnRunEndOnly = true
)
} else {
Log.d(
BenchmarkState.TAG,
"androidx.benchmark.output.enable not set, not writing results json"
)
}
}
@VisibleForTesting
internal fun writeReport(file: File, reports: List<BenchmarkState.Report>) {
file.run {
if (!exists()) {
parentFile?.mkdirs()
try {
createNewFile()
} catch (exception: IOException) {
throw IOException(
"""
Failed to create file for benchmark report in:
$parent
Make sure the instrumentation argument additionalTestOutputDir is set
to a writable directory on device. If using a version of Android Gradle
Plugin that doesn't support additionalTestOutputDir, ensure your app's
manifest file enables legacy storage behavior by adding the
application attribute: android:requestLegacyExternalStorage="true"
""".trimIndent(),
exception
)
}
}
val writer = JsonWriter(bufferedWriter())
writer.setIndent(" ")
writer.beginObject()
writer.name("context").beginObject()
.name("build").buildInfoObject()
.name("cpuCoreCount").value(CpuInfo.coreDirs.size)
.name("cpuLocked").value(CpuInfo.locked)
.name("cpuMaxFreqHz").value(CpuInfo.maxFreqHz)
.name("memTotalBytes").value(MemInfo.memTotalBytes)
.name("sustainedPerformanceModeEnabled")
.value(IsolationActivity.sustainedPerformanceModeInUse)
writer.endObject()
writer.name("benchmarks").beginArray()
reports.forEach { writer.reportObject(it) }
writer.endArray()
writer.endObject()
writer.flush()
writer.close()
}
}
private fun JsonWriter.buildInfoObject(): JsonWriter {
beginObject()
.name("device").value(Build.DEVICE)
.name("fingerprint").value(Build.FINGERPRINT)
.name("model").value(Build.MODEL)
.name("version").beginObject().name("sdk").value(Build.VERSION.SDK_INT).endObject()
return endObject()
}
private fun JsonWriter.reportObject(report: BenchmarkState.Report): JsonWriter {
beginObject()
.name("name").value(report.testName)
.name("params").paramsObject(report)
.name("className").value(report.className)
.name("totalRunTimeNs").value(report.totalRunTimeNs)
.name("metrics").metricsContainerObject(report.stats, report.data)
.name("warmupIterations").value(report.warmupIterations)
.name("repeatIterations").value(report.repeatIterations)
.name("thermalThrottleSleepSeconds").value(report.thermalThrottleSleepSeconds)
return endObject()
}
private fun JsonWriter.statsObject(
stats: Stats
): JsonWriter {
name("minimum").value(stats.min)
name("maximum").value(stats.max)
name("median").value(stats.median)
return this
}
private fun JsonWriter.metricsContainerObject(
stats: List<Stats>,
data: List<List<Long>>
): JsonWriter {
beginObject()
for (i in 0..stats.lastIndex) {
name(stats[i].name).beginObject()
statsObject(stats[i])
name("runs").beginArray()
data[i].forEach { value(it) }
endArray()
endObject()
}
return endObject()
}
private fun JsonWriter.paramsObject(report: BenchmarkState.Report): JsonWriter {
beginObject()
getParams(report.testName).forEach { name(it.key).value(it.value) }
return endObject()
}
private fun getParams(testName: String): Map<String, String> {
val parameterStrStart = testName.indexOf('[')
val parameterStrEnd = testName.lastIndexOf(']')
val params = HashMap<String, String>()
if (parameterStrStart >= 0 && parameterStrEnd >= 0) {
val paramListString = testName.substring(parameterStrStart + 1, parameterStrEnd)
paramListString.split(",").forEach { paramString ->
val separatorIndex = paramString.indexOfFirst { it == ':' || it == '=' }
if (separatorIndex in 1 until paramString.length - 1) {
val key = paramString.substring(0, separatorIndex)
val value = paramString.substring(separatorIndex + 1)
params[key] = value
}
}
}
return params
}
}
| 1
| null |
1
| 1
|
ccac66729a5e461b3a05944014f42e2dc55337d6
| 6,896
|
androidx
|
Apache License 2.0
|
kcrud-access/src/main/kotlin/kcrud/access/actor/repository/IActorRepository.kt
|
perracodex
| 682,128,013
| false
| null |
/*
* Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license.
*/
package kcrud.access.actor.repository
import kcrud.access.actor.entity.ActorEntity
import kcrud.access.actor.entity.ActorRequest
import java.util.*
/**
* Repository responsible for [ActorEntity] data.
*/
interface IActorRepository {
/**
* Finds the [ActorEntity] for the given username.
*
* @param username The username of the [ActorEntity] to find.
* @return The [ActorEntity] for the given username, or null if it doesn't exist.
*/
suspend fun findByUsername(username: String): ActorEntity?
/**
* Finds all existing [ActorEntity] entries.
* @return A list with all existing [ActorEntity] entries.
*/
suspend fun findAll(): List<ActorEntity>
/**
* Finds the [ActorEntity] for the given id.
*
* @param actorId The id of the [ActorEntity] to find.
* @return The [ActorEntity] for the given id, or null if it doesn't exist.
*/
suspend fun findById(actorId: UUID): ActorEntity?
/**
* Creates a new [ActorEntity].
* @param actorRequest The [ActorRequest] to create.
* @return The id of the [ActorEntity] created.
*/
suspend fun create(actorRequest: ActorRequest): UUID
/**
* Updates an existing [ActorEntity].
*
* @param actorId The id of the actor to update.
* @param actorRequest The new details for the [ActorEntity].
* @return How many records were updated.
*/
suspend fun update(actorId: UUID, actorRequest: ActorRequest): Int
/**
* Sets the lock status for the given [ActorEntity].
*
* @param actorId The id of the [ActorEntity] to lock/unlock.
* @param isLocked Whether the [ActorEntity] should be locked or unlocked.
*/
suspend fun setLockedState(actorId: UUID, isLocked: Boolean)
/**
* Checks if there are any Actor in the database, or if the given usernames exist.
*
* @param usernames The actors usernames to check for. If null, checks for any actors.
* @return True if there are actors for the given usernames in the database, false otherwise.
*/
suspend fun actorsExist(usernames: List<String>? = null): Boolean
}
| 0
| null |
0
| 2
|
7faa3d74588e41a48ac48bb56e80bb02c48f0ba3
| 2,260
|
Kcrud
|
MIT License
|
src/main/kotlin/me/bzvol/fifimod/event/loot/ModClientEvents.kt
|
bzvol
| 508,218,419
| false
|
{"Kotlin": 162220}
|
package me.bzvol.fifimod.event.loot
import me.bzvol.fifimod.FifiMod
import me.bzvol.fifimod.entity.client.armor.FifiArmorRenderer
import me.bzvol.fifimod.item.FifiArmorItem
import net.minecraftforge.api.distmarker.Dist
import net.minecraftforge.client.event.EntityRenderersEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
import net.minecraftforge.fml.common.Mod
import software.bernie.geckolib3.renderers.geo.GeoArmorRenderer
@Mod.EventBusSubscriber(modid = FifiMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = [Dist.CLIENT])
object ModClientEvents {
@SubscribeEvent
fun registerArmorRenderers(event: EntityRenderersEvent.AddLayers) {
GeoArmorRenderer.registerArmorRenderer(FifiArmorItem::class.java, FifiArmorRenderer())
}
}
| 0
|
Kotlin
|
0
| 0
|
95903762a1876342bfeae2b11c272f71d97621a3
| 768
|
FifiMod
|
MIT License
|
vico/core/src/main/java/com/patrykandpatrick/vico/core/component/shape/shader/DynamicShader.kt
|
patrykandpatrick
| 338,848,755
| false
|
{"Kotlin": 730308, "CSS": 166}
|
/*
* Copyright 2023 by <NAME> and <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.patrykandpatrick.vico.core.component.shape.shader
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import com.patrykandpatrick.vico.core.context.DrawContext
import com.patrykandpatrick.vico.core.context.getOrPutExtra
import com.patrykandpatrick.vico.core.util.Point
import kotlin.math.roundToInt
/**
* [DynamicShader] creates [Shader] instances on demand.
*
* @see Shader
*/
public fun interface DynamicShader {
private val bitmapPixelExtractionKey: Any
get() = "bitmapPixelExtractionKey${hashCode()}"
/**
* Creates a [Shader] by using the provided [bounds].
*/
public fun provideShader(
context: DrawContext,
bounds: RectF,
): Shader =
provideShader(
context = context,
left = bounds.left,
top = bounds.top,
right = bounds.right,
bottom = bounds.bottom,
)
/**
* Creates a [Shader] by using the provided [left], [top], [right], and [bottom] bounds.
*/
public fun provideShader(
context: DrawContext,
left: Float,
top: Float,
right: Float,
bottom: Float,
): Shader
/**
* Gets the color of the pixel at the given point. [rectF] specifies the shaded area.
*/
public fun getColorAt(
point: Point,
drawContext: DrawContext,
rectF: RectF,
): Int {
val bitmap =
drawContext.getOrPutExtra(bitmapPixelExtractionKey) {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
getBitmap(drawContext, paint, rectF)
}
return bitmap.getPixel(
(point.x - rectF.left).toInt().coerceIn(0, rectF.width().toInt() - 1),
(point.y - rectF.top).toInt().coerceIn(0, rectF.height().toInt() - 1),
)
}
public companion object {
private fun DynamicShader.getBitmap(
drawContext: DrawContext,
paint: Paint,
rectF: RectF,
): Bitmap {
val width = rectF.width().roundToInt()
val height = rectF.height().roundToInt()
paint.shader = provideShader(drawContext, 0f, 0f, width.toFloat(), height.toFloat())
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
return bitmap
}
}
}
| 8
|
Kotlin
|
89
| 1,465
|
8a4529648b56669dab788e9eeba9fdc4a344268d
| 3,166
|
vico
|
Apache License 2.0
|
bot/src/main/kotlin/com/noahhendrickson/beachbunny/bot/dialogflow/DialogflowClient.kt
|
NoahH99
| 367,918,537
| false
| null |
package com.noahhendrickson.beachbunny.bot.dialogflow
import com.google.cloud.dialogflow.v2.*
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
data class DialogflowClient(
val sessionsClient: SessionsClient?,
val sessionName: SessionName?
) {
suspend fun queryResult(request: DetectIntentRequest): QueryResult? {
return detectIntent(request)?.queryResult
}
private suspend fun detectIntent(request: DetectIntentRequest): DetectIntentResponse? {
return coroutineScope {
async {
sessionsClient?.detectIntent(request)
}
}.await()
}
fun isNotNull() = sessionsClient != null && sessionName != null
override fun toString() = sessionName?.toString() ?: ""
}
| 2
|
Kotlin
|
0
| 0
|
7e401ddf665cb78ffd0c47c1d4cabd2cd9d0bc81
| 777
|
BeachBunny
|
MIT License
|
core/state/src/main/kotlin/br/com/mob1st/core/state/contracts/PaginationManager.kt
|
mob1st
| 526,655,668
| false
| null |
package br.com.mob1st.core.state.contracts
/**
* A standard interface for ViewModels that handle pagination in the UI.
*/
interface PaginationManager {
/**
* Paginates to the next page.
*/
fun next()
}
| 11
|
Kotlin
|
0
| 3
|
d06451b4a3384a757b1b6bae96e85a1874bbc91d
| 223
|
bet-app-android
|
Apache License 2.0
|
core/state/src/main/kotlin/br/com/mob1st/core/state/contracts/PaginationManager.kt
|
mob1st
| 526,655,668
| false
| null |
package br.com.mob1st.core.state.contracts
/**
* A standard interface for ViewModels that handle pagination in the UI.
*/
interface PaginationManager {
/**
* Paginates to the next page.
*/
fun next()
}
| 11
|
Kotlin
|
0
| 3
|
d06451b4a3384a757b1b6bae96e85a1874bbc91d
| 223
|
bet-app-android
|
Apache License 2.0
|
src/main/kotlin/com/codebud7/core/domainobject/CountrySummaryPerCaseStatus.kt
|
codeBud7
| 255,148,881
| false
| null |
package com.codebud7.core.domainobject
class CountrySummaryPerCaseStatus : ArrayList<CountrySummaryPerCaseStatusItem>()
data class CountrySummaryPerCaseStatusItem(
val active: Int,
val admin2: Any,
val combinedKey: String,
val confirmed: Int,
val countryRegion: String,
val deaths: Int,
val fips: Any,
val incidentRate: Double,
val iso3: String,
val lastUpdate: Long,
val lat: Double,
val long: Double,
val peopleHospitalized: Any,
val peopleTested: Any,
val provinceState: Any,
val recovered: Int,
val uid: Int
)
| 0
|
Kotlin
|
0
| 0
|
64745575f97f756b3894f3e5937062b1a9326641
| 584
|
kovid-19-api
|
Apache License 2.0
|
src/test/kotlin/org/intellij/plugin/mdx/MdxParsingTest.kt
|
valentinnodan
| 279,243,243
| false
| null |
package org.intellij.plugin.mdx
import com.intellij.lang.LanguageASTFactory
import com.intellij.lang.javascript.JavascriptASTFactory
import com.intellij.lang.javascript.JavascriptLanguage
import com.intellij.lang.javascript.dialects.ECMA6ParserDefinition
import com.intellij.lang.xml.XMLLanguage
import com.intellij.lang.xml.XmlASTFactory
import com.intellij.psi.LanguageFileViewProviders
import com.intellij.testFramework.ParsingTestCase
import org.intellij.plugin.mdx.js.MdxJSParserDefinition
import org.intellij.plugin.mdx.lang.MdxLanguage
import org.intellij.plugin.mdx.lang.parse.MdxParserDefinition
import org.intellij.plugin.mdx.lang.psi.MdxFileViewProviderFactory
import org.intellij.plugins.markdown.lang.MarkdownFileViewProviderFactory
import org.intellij.plugins.markdown.lang.MarkdownLanguage
import org.intellij.plugins.markdown.lang.parser.MarkdownParserDefinition
import org.intellij.plugins.markdown.lang.psi.MarkdownAstFactory
import org.junit.Test
class MdxParsingTest : ParsingTestCase(
"",
"mdx",
MdxParserDefinition(),
MarkdownParserDefinition(),
MdxJSParserDefinition(),
ECMA6ParserDefinition()
) {
override fun getTestDataPath(): String {
return "src/test/testData/parsing"
}
override fun checkAllPsiRoots(): Boolean {
return false
}
override fun setUp() {
super.setUp()
addExplicitExtension(LanguageFileViewProviders.INSTANCE, MdxLanguage, MdxFileViewProviderFactory())
addExplicitExtension(LanguageFileViewProviders.INSTANCE, MdxLanguage, MarkdownFileViewProviderFactory())
addExplicitExtension(LanguageASTFactory.INSTANCE, MarkdownLanguage.INSTANCE, MarkdownAstFactory())
addExplicitExtension(LanguageASTFactory.INSTANCE, JavascriptLanguage.INSTANCE, JavascriptASTFactory())
addExplicitExtension(LanguageASTFactory.INSTANCE, XMLLanguage.INSTANCE, XmlASTFactory())
}
override fun skipSpaces(): Boolean {
return false
}
override fun includeRanges(): Boolean {
return true
}
@Test
fun testParsingTestData() {
doTest(true)
}
@Test
fun testParsingList() {
doTest(true)
}
@Test
fun testParsingWithNewLines() {
doTest(true)
}
@Test
fun testParsingAlert() {
doTest(true)
}
@Test
fun testParsingEmbedded() {
doTest(true)
}
@Test
fun testParsingPrisma() {
doTest(true)
}
}
| 13
| null |
2
| 8
|
52a51db1e1b6158d52e27f12277f56ca20c228f0
| 2,465
|
mdx-intellij-plugin
|
MIT License
|
korlibs-datastructure/test/korlibs/datastructure/FastRandomTest.kt
|
korlibs
| 80,095,683
| false
|
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
|
package korlibs.datastructure
import korlibs.datastructure.random.FastRandom
import korlibs.datastructure.random.fastRandom
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertTrue
class FastRandomTest {
val random = FastRandom(0L)
@Test
fun testLong() {
assertEquals(
"[512, 774, 807, 39, 6, 289, 517, 769, 807, 32]",
(0 until 10).map { random.nextLong(0L, 1000L) }.toString()
)
}
@Test
fun testInt() {
assertEquals(
"[214, 848, 257, 367, 882, 107, 961, 727, 814, 459]",
(0 until 10).map { random.nextInt(0, 1000) }.toString()
)
}
@Test
fun testFail() {
assertFails { random.nextInt(10, 0) }
assertFails { random.nextLong(10L, 0L) }
}
@Test
fun testGlobal() {
FastRandom.Default.nextBits(0)
FastRandom.nextBits(0)
FastRandom()
assertTrue { (0 until 20).map { FastRandom.nextBits(0) }.distinct().count() > 1 }
assertTrue { (0 until 20).map { FastRandom.Default.nextBits(0) }.distinct().count() > 1 }
assertTrue { (0 until 20).map { FastRandom().nextBits(0) }.distinct().count() > 1 }
}
@Test
fun testArrayExtensionsFail() {
assertFails { listOf<String>().fastRandom() }
assertFails { arrayOfNulls<Int>(0).fastRandom() }
assertFails { arrayOf<String>().fastRandom() }
assertFails { BooleanArray(0).fastRandom() }
assertFails { CharArray(0).fastRandom() }
assertFails { ShortArray(0).fastRandom() }
assertFails { IntArray(0).fastRandom() }
assertFails { LongArray(0).fastRandom() }
assertFails { FloatArray(0).fastRandom() }
assertFails { DoubleArray(0).fastRandom() }
}
@Test
fun testArrayExtensions() {
assertEquals("a", listOf("a").fastRandom())
assertEquals("a", arrayOf("a").fastRandom())
assertEquals(true, booleanArrayOf(true).fastRandom())
assertEquals('a', charArrayOf('a').fastRandom())
assertEquals(-10, shortArrayOf(-10).fastRandom())
assertEquals(-10, intArrayOf(-10).fastRandom())
assertEquals(-10L, longArrayOf(-10L).fastRandom())
assertEquals(3f, floatArrayOf(3f).fastRandom())
assertEquals(7.0, doubleArrayOf(7.0).fastRandom())
}
@Test
fun testArrayExtensions2() {
val random = FastRandom(0L)
assertEquals("a", listOf("a").random(random))
assertEquals("a", arrayOf("a").random(random))
assertEquals(true, booleanArrayOf(true).random(random))
assertEquals('a', charArrayOf('a').random(random))
assertEquals(-10, shortArrayOf(-10).random(random))
assertEquals(-10, intArrayOf(-10).random(random))
assertEquals(-10L, longArrayOf(-10L).random(random))
assertEquals(3f, floatArrayOf(3f).random(random))
assertEquals(7.0, doubleArrayOf(7.0).random(random))
}
@Test
fun testGlobalInstance() {
println((0 until 10).map { FastRandom.nextInt() })
assertTrue { (0 until 10).map { FastRandom.nextInt() }.distinct().size >= 2 }
}
}
| 444
|
WebAssembly
|
121
| 2,207
|
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
| 3,196
|
korge
|
Apache License 2.0
|
TollRoadCalcAndroid/core/src/main/java/ru/andrewkir/core/presentation/presentation/utils/Dimens.kt
|
andrewkir
| 801,831,218
| false
|
{"Kotlin": 163036}
|
package ru.andrewkir.core.presentation.presentation.utils
import androidx.compose.ui.unit.dp
object Dimens {
val MediumPadding = 24.dp
val MediumPadding2 = 30.dp
val IndicatorSize = 14.dp
val PageIndicatorWidth = 52.dp
}
| 0
|
Kotlin
|
0
| 0
|
fea7d491ce0aa2b3adbc277c456e7535c5821e7d
| 240
|
Toll-Price-Diploma
|
MIT License
|
src/main/kotlin/com/colinodell/advent2022/Day24.kt
|
colinodell
| 572,710,708
| false
|
{"Kotlin": 105421}
|
package com.colinodell.advent2022
import java.util.PriorityQueue
class Day24(input: List<String>) {
private val grid = input.toGrid()
private val innerRegion = grid.region().contract(1)
private val start = grid.toList().first { it.first.y == 0 && it.second == '.' }.first
private val goal = grid.toList().first { it.first.y > innerRegion.bottomRight.y && it.second == '.' }.first
private val roundTripEstimate = start.manhattanDistanceTo(goal)
fun solvePart1() = solve(listOf(goal))
fun solvePart2() = solve(listOf(goal, start, goal))
private fun solve(goals: List<Vector2>): Int {
val initialState = State(start, 0, 0)
val queue = PriorityQueue<State>(
compareBy { s ->
// Our heuristic is basically the sum of:
// 1. The time spent so far
// 2. The distance to the current goal
// 3. The distance between any remaining goals
// Parts 2 and 3 of this are multiplied by 2 since there's a higher likelihood of needing to wait or backtrack
s.time + 2 * (s.pos.manhattanDistanceTo(goals[s.goalIndex]) + roundTripEstimate * (goals.size - s.goalIndex - 1))
}
)
queue.add(State(start, 0, 0))
val visited = mutableSetOf(initialState)
while (queue.isNotEmpty()) {
val current = queue.poll()
// Have we reached one of our goals?
if (current.pos == goals[current.goalIndex]) {
if (current.goalIndex == goals.size - 1) {
// We've reached the end!
return current.time
}
// We've reached an intermediate goal
current.goalIndex++
}
// Try moving (or staying put) unless we've previously attempted this state
for (next in current.next().filter { visited.add(it) }) {
// Make sure our move is in bounds
if (!(next.pos in innerRegion || next.pos == start || next.pos == goal)) {
continue
}
// Make sure there's no blizzards in the way
if (next.pos in blizzardsAt(next.time)) {
continue
}
queue.add(next)
}
}
error("No solution found")
}
private data class State(val pos: Vector2, val time: Int, var goalIndex: Int) {
fun next() = setOf(
State(pos + Vector2(1, 0), time + 1, goalIndex), // Right
State(pos + Vector2(-1, 0), time + 1, goalIndex), // Left
State(pos + Vector2(0, 1), time + 1, goalIndex), // Up
State(pos + Vector2(0, -1), time + 1, goalIndex), // Down
State(pos, time + 1, goalIndex) // Wait
)
}
private data class Blizzard(val pos: Vector2, val dir: Direction)
private val blizzardPositionCache = mutableListOf<Set<Vector2>>()
private fun blizzardsAt(time: Int): Set<Vector2> {
while (blizzardPositionCache.size <= time) {
blizzardPositionCache.add(blizzardGenerator.next())
}
return blizzardPositionCache[time]
}
private val blizzardGenerator = sequence {
var blizzards = grid
.filter { it.value in setOf('<', '>', 'v', '^') }
.map { (p, c) -> Blizzard(p, Direction.from(c)) }
while (true) {
yield(blizzards.map { it.pos }.toSet())
blizzards = blizzards.map { b ->
val nextPos = b.pos + b.dir.vector()
when {
nextPos in innerRegion -> Blizzard(nextPos, b.dir)
b.dir == Direction.UP -> Blizzard(nextPos.withY(innerRegion.bottomRight.y), b.dir)
b.dir == Direction.DOWN -> Blizzard(nextPos.withY(innerRegion.topLeft.y), b.dir)
b.dir == Direction.LEFT -> Blizzard(nextPos.withX(innerRegion.bottomRight.x), b.dir)
b.dir == Direction.RIGHT -> Blizzard(nextPos.withX(innerRegion.topLeft.x), b.dir)
else -> error("Invalid direction: ${b.dir}")
}
}
}
}.iterator()
}
| 0
|
Kotlin
|
0
| 1
|
32da24a888ddb8e8da122fa3e3a08fc2d4829180
| 4,235
|
advent-2022
|
MIT License
|
src/commonMain/kotlin/data/items/JusticarGreaves.kt
|
marisa-ashkandi
| 332,658,265
| false
| null |
package `data`.items
import `data`.Constants
import `data`.itemsets.ItemSets
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class JusticarGreaves : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 29074
public override var name: String = "<NAME>"
public override var itemLevel: Int = 120
public override var quality: Int = 4
public override var icon: String = "inv_pants_mail_15.jpg"
public override var inventorySlot: Int = 7
public override var itemSet: ItemSet? = ItemSets.byId(626)
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.PLATE
public override var allowableClasses: Array<Constants.AllowableClass>? = arrayOf(
Constants.AllowableClass.PALADIN
)
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
strength = 53,
agility = 24,
stamina = 34,
intellect = 24,
armor = 1322,
physicalHitRating = 23.0
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override var phase: Int = 1
public override val buffs: List<Buff> by lazy {
listOf()}
}
| 21
| null |
11
| 25
|
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
| 1,688
|
tbcsim
|
MIT License
|
app/src/test/java/ca/on/hojat/gamenews/feature_search/domain/SearchGamesUseCaseImplTest.kt
|
hojat72elect
| 574,228,468
| false
| null |
package ca.on.hojat.gamenews.feature_search.domain
import app.cash.turbine.test
import ca.on.hojat.gamenews.core.providers.NetworkStateProvider
import ca.on.hojat.gamenews.core.domain.games.datastores.GamesDataStores
import ca.on.hojat.gamenews.core.domain.games.datastores.GamesLocalDataStore
import ca.on.hojat.gamenews.core.domain.games.datastores.GamesRemoteDataStore
import ca.on.hojat.gamenews.core.common_testing.domain.DOMAIN_ERROR_UNKNOWN
import ca.on.hojat.gamenews.core.common_testing.domain.DOMAIN_GAMES
import ca.on.hojat.gamenews.core.common_testing.domain.MainCoroutineRule
import ca.on.hojat.gamenews.core.common_testing.domain.PAGINATION
import ca.on.hojat.gamenews.core.common_testing.domain.coVerifyNotCalled
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.get
import com.google.common.truth.Truth.assertThat
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
private val SEARCH_GAMES_USE_CASE_PARAMS = SearchGamesUseCase.Params(
searchQuery = "search_query",
pagination = PAGINATION,
)
internal class SearchGamesUseCaseImplTest {
@get:Rule
val mainCoroutineRule = MainCoroutineRule()
@MockK
private lateinit var gamesLocalDataStore: GamesLocalDataStore
@MockK
private lateinit var gamesRemoteDataStore: GamesRemoteDataStore
@MockK
private lateinit var networkStateProvider: NetworkStateProvider
private lateinit var sut: SearchGamesUseCaseImpl
@Before
fun setup() {
MockKAnnotations.init(this, relaxUnitFun = true)
sut = SearchGamesUseCaseImpl(
gamesDataStores = GamesDataStores(
local = gamesLocalDataStore,
remote = gamesRemoteDataStore,
),
dispatcherProvider = mainCoroutineRule.dispatcherProvider,
networkStateProvider = networkStateProvider,
)
}
@Test
fun `Emits from remote data store when network is on`() {
runTest {
every { networkStateProvider.isNetworkAvailable } returns true
coEvery { gamesRemoteDataStore.searchGames(any(), any()) } returns Ok(DOMAIN_GAMES)
sut.execute(SEARCH_GAMES_USE_CASE_PARAMS).test {
assertThat(awaitItem().get()).isEqualTo(DOMAIN_GAMES)
awaitComplete()
}
}
}
@Test
fun `Saves remote games into local data store when network is on & request succeeds`() {
runTest {
every { networkStateProvider.isNetworkAvailable } returns true
coEvery { gamesRemoteDataStore.searchGames(any(), any()) } returns Ok(DOMAIN_GAMES)
sut.execute(SEARCH_GAMES_USE_CASE_PARAMS).firstOrNull()
coVerify { gamesLocalDataStore.saveGames(DOMAIN_GAMES) }
}
}
@Test
fun `Does not save remote games into local data store when network is on & request fails`() {
runTest {
every { networkStateProvider.isNetworkAvailable } returns true
coEvery { gamesRemoteDataStore.searchGames(any(), any()) } returns Err(
DOMAIN_ERROR_UNKNOWN
)
sut.execute(SEARCH_GAMES_USE_CASE_PARAMS).firstOrNull()
coVerifyNotCalled { gamesLocalDataStore.saveGames(any()) }
}
}
@Test
fun `Emits from local data store when network is off`() {
runTest {
every { networkStateProvider.isNetworkAvailable } returns false
coEvery { gamesLocalDataStore.searchGames(any(), any()) } returns DOMAIN_GAMES
sut.execute(SEARCH_GAMES_USE_CASE_PARAMS).test {
assertThat(awaitItem().get()).isEqualTo(DOMAIN_GAMES)
awaitComplete()
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
80ff667af63e00b09aac129bb1206f520452700a
| 4,003
|
GameHub
|
Apache License 2.0
|
src/main/kotlin/fun/brassicold/brassi/death/project/BrassiDeath.kt
|
BrassiCold
| 594,979,206
| false
| null |
package `fun`.brassicold.brassi.death.project
import `fun`.brassicold.brassi.death.project.internal.BrassiDeathLoader
import org.yaml.snakeyaml.Yaml
import taboolib.common.platform.Plugin
import taboolib.module.configuration.Config
import taboolib.module.configuration.ConfigFile
object BrassiDeath : Plugin() {
@Config("setting.yml", migrate = true)
lateinit var setting: ConfigFile
val yaml = Yaml()
override fun onLoad() {
BrassiDeathLoader.load()
}
override fun onEnable() {
BrassiDeathLoader.enable()
}
override fun onDisable() {
BrassiDeathLoader.disable()
}
}
| 0
|
Kotlin
|
0
| 0
|
1abaad9d0cf8fe8a4d32bb4c4a9a133c0209a3a8
| 633
|
BrassiDeath
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/pl/radoslawdabrowski/admin/modules/root/services/UserService.kt
|
radoslawdabrowski
| 188,028,920
| false
|
{"Kotlin": 18804, "HTML": 4671}
|
package pl.radoslawdabrowski.admin.modules.root.services
import pl.radoslawdabrowski.admin.modules.root.model.User
interface UserService {
fun getUser(username : String) : User
}
| 0
|
Kotlin
|
0
| 1
|
a45e527740089d39fff0f4ab03f281b0ad0cc58f
| 186
|
personal-website-admin-panel-framework
|
Apache License 2.0
|
documents_feature/src/main/java/com/flyview/documents_feature/ui/scan/mark_list/toolbar/RealMarkListToolbarComponent.kt
|
DmiMukh
| 676,402,705
| false
|
{"Kotlin": 288475, "Java": 130379}
|
package com.flyview.documents_feature.ui.scan.mark_list.toolbar
import com.arkivanov.decompose.ComponentContext
class RealMarkListToolbarComponent(
componentContext: ComponentContext,
private val onBack: () -> Unit,
private val onSave: () -> Unit
) : ComponentContext by componentContext, MarkListToolbarComponent {
override fun onBackClick() = this.onBack.invoke()
override fun onSaveClick() = this.onSave.invoke()
}
| 0
|
Kotlin
|
0
| 0
|
5c184121116c08abe217946ba7da27804c232edb
| 440
|
PharmMobile
|
MIT License
|
server/src/main/kotlin/cz/martinforejt/piskvorky/server/core/di/ServerModule.kt
|
MFori
| 323,623,365
| false
| null |
package cz.martinforejt.piskvorky.server.core.di
import cz.martinforejt.piskvorky.domain.repository.*
import cz.martinforejt.piskvorky.domain.service.EmailService
import cz.martinforejt.piskvorky.server.core.service.EmailServiceConfig
import cz.martinforejt.piskvorky.server.core.service.EmailServiceImpl
import cz.martinforejt.piskvorky.server.core.service.SocketService
import cz.martinforejt.piskvorky.server.features.admin.usecase.EditUserUseCase
import cz.martinforejt.piskvorky.server.features.game.repository.GameRepositoryImpl
import cz.martinforejt.piskvorky.server.features.game.usecase.CancelGameInvitationUseCase
import cz.martinforejt.piskvorky.server.features.game.usecase.GiveUpGameUseCase
import cz.martinforejt.piskvorky.server.features.game.usecase.JoinGameUseCase
import cz.martinforejt.piskvorky.server.features.game.usecase.PlayMoveUseCase
import cz.martinforejt.piskvorky.server.features.results.repository.ResultsRepositoryImpl
import cz.martinforejt.piskvorky.server.features.results.usecase.AddGameResultUseCase
import cz.martinforejt.piskvorky.server.features.socket.SocketServiceImpl
import cz.martinforejt.piskvorky.domain.service.HashService
import cz.martinforejt.piskvorky.server.features.users.service.Sha256HashService
import cz.martinforejt.piskvorky.server.features.users.repository.FriendsRepositoryImpl
import cz.martinforejt.piskvorky.server.features.users.repository.LostPasswordRepositoryImpl
import cz.martinforejt.piskvorky.server.features.users.repository.UsersRepositoryImpl
import cz.martinforejt.piskvorky.server.features.users.usecase.*
import cz.martinforejt.piskvorky.server.security.IUserAuthenticator
import cz.martinforejt.piskvorky.server.security.JwtConfig
import cz.martinforejt.piskvorky.server.security.JwtManager
import cz.martinforejt.piskvorky.server.security.UserAuthenticator
import io.ktor.application.*
import io.ktor.util.*
import org.koin.dsl.module
/**
* Created by <NAME> on 23.12.2020.
* <EMAIL>
*
* @author <NAME>
*/
/**
* Koin server module
*
* @param app ktor app
*/
@KtorExperimentalAPI
fun serverModule(app: Application) = module {
/////////// Services & repositories /////////////
single<JwtManager> {
val jwtIssuer = app.property("jwt.domain")
val jwtSecret = app.property("jwt.secret")
val jwtRealm = app.property("jwt.realm")
val jwtValidity = app.property("jwt.validity_ms").toInt()
JwtConfig(jwtIssuer, jwtSecret, jwtRealm, jwtValidity, authenticator = get())
}
single<IUserAuthenticator> {
UserAuthenticator(
usersRepository = get(),
hashService = get()
)
}
single<UsersRepository> {
UsersRepositoryImpl(
socketService = get()
)
}
single<FriendsRepository> {
FriendsRepositoryImpl(
usersRepository = get(),
gameRepository = get()
)
}
single<LostPasswordRepository> {
LostPasswordRepositoryImpl()
}
single<GameRepository> {
GameRepositoryImpl()
}
single<ResultsRepository> {
ResultsRepositoryImpl()
}
single<SocketService> {
SocketServiceImpl(
gameRepository = get()
)
}
single<HashService> {
Sha256HashService()
}
single<EmailService> {
val config = EmailServiceConfig(
hostName = app.property("email.host_name"),
port = app.property("email.port").toInt(),
userName = app.property("email.user_name"),
password = app.property("<PASSWORD>"),
ssl = app.property("email.ssl").toBoolean(),
from = "<EMAIL>"
)
EmailServiceImpl(config)
}
/////////// Use cases /////////////
//---------- Users & security -------------//
factory {
ValidateUserCredentialsUseCase(
authenticator = get()
)
}
factory {
RegisterUserUseCase(
usersRepository = get(),
hashService = get()
)
}
factory {
ChangePasswordUseCase(
usersRepository = get(),
authenticator = get(),
hashService = get()
)
}
factory {
LostPasswordUseCase(
usersRepository = get(),
lostPasswordRepository = get(),
emailService = get()
)
}
factory {
ResetPasswordUseCase(
usersRepository = get(),
lostPasswordRepository = get(),
hashService = get()
)
}
//---------- Friendships -------------//
factory {
AddFriendUseCase(
friendsRepository = get(),
socketService = get()
)
}
factory {
CancelFriendUseCase(
friendsRepository = get(),
socketService = get()
)
}
//---------- Game invitations -------------//
factory {
JoinGameUseCase(
usersRepository = get(),
gameRepository = get(),
socketService = get()
)
}
factory {
CancelGameInvitationUseCase(
gameRepository = get(),
socketService = get()
)
}
//---------- Game -------------//
factory {
PlayMoveUseCase(
gameRepository = get(),
socketService = get(),
addGameResultUseCase = get()
)
}
factory {
GiveUpGameUseCase(
gameRepository = get(),
socketService = get(),
usersRepository = get(),
addGameResultUseCase = get()
)
}
factory {
AddGameResultUseCase(
usersRepository = get(),
resultsRepository = get()
)
}
//---------- Admin -------------//
factory {
EditUserUseCase(
usersRepository = get(),
hashService = get()
)
}
}
@KtorExperimentalAPI
private fun Application.property(name: String) = this.environment.config.property(name).getString()
| 0
|
Kotlin
|
0
| 0
|
8333fa53793a3ea1a9c83cfa821b5c4e8573ec4b
| 6,063
|
Piskvorky
|
Apache License 2.0
|
src/main/kotlin/de/flapdoodle/kfx/layout/decoration/Position.kt
|
flapdoodle-oss
| 451,526,335
| false
| null |
package de.flapdoodle.kfx.layout.decoration
import de.flapdoodle.kfx.types.Direction
import de.flapdoodle.kfx.types.Line2D
import de.flapdoodle.kfx.types.UnitInterval
import de.flapdoodle.kfx.types.to
import javafx.geometry.Bounds
import javafx.geometry.Point2D
data class Position(
val base: Base,
val position: UnitInterval,
val distance: Double,
val offset: Double = 0.0
) {
}
| 0
|
Kotlin
|
1
| 0
|
2407b8c87d62350c6a0bc7f1fbae29afdd830710
| 402
|
de.flapdoodle.kfx
|
Apache License 2.0
|
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/presentation/parachainStaking/start/setup/rewards/ParachainStakingRewardsComponent.kt
|
novasamatech
| 415,834,480
| false
| null |
package io.novafoundation.nova.feature_staking_impl.presentation.parachainStaking.start.setup.rewards
import io.novafoundation.nova.common.utils.firstNotNull
import io.novafoundation.nova.feature_staking_impl.presentation.parachainStaking.start.setup.rewards.ParachainStakingRewardsComponent.Action
import io.novafoundation.nova.feature_staking_impl.presentation.parachainStaking.start.setup.rewards.ParachainStakingRewardsComponent.State
import io.novafoundation.nova.feature_staking_impl.presentation.staking.main.components.StatefullComponent
import io.novafoundation.nova.feature_staking_impl.presentation.staking.main.model.RewardEstimation
import io.novasama.substrate_sdk_android.runtime.AccountId
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.math.BigDecimal
interface ParachainStakingRewardsComponent : StatefullComponent<State, Nothing, Action>, CoroutineScope {
class State(
val rewardsConfiguration: RewardsConfiguration,
val rewardEstimation: RewardEstimation
)
data class RewardsConfiguration(
val collator: AccountId?,
val amount: BigDecimal
)
sealed class Action {
class ConfigurationUpdated(val newConfiguration: RewardsConfiguration) : Action()
}
}
@JvmName("connectWithAmount")
infix fun ParachainStakingRewardsComponent.connectWith(amountFlow: Flow<BigDecimal>) {
amountFlow.onEach { newAmount ->
val rewardsConfiguration = state.firstNotNull().rewardsConfiguration
val newConfiguration = rewardsConfiguration.copy(amount = newAmount)
onAction(Action.ConfigurationUpdated(newConfiguration))
}.launchIn(this)
}
infix fun ParachainStakingRewardsComponent.connectWith(selectedCollatorIdFlow: Flow<AccountId?>) {
selectedCollatorIdFlow.onEach { newCollatorId ->
val rewardsConfiguration = state.firstNotNull().rewardsConfiguration
val newConfiguration = rewardsConfiguration.copy(collator = newCollatorId)
onAction(Action.ConfigurationUpdated(newConfiguration))
}.launchIn(this)
}
| 14
| null |
6
| 9
|
b39307cb56302ce7298582dbd03f33f6b2e2a807
| 2,156
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/jeongg/sanjini_attraction/presentation/navigation/NavGraph.kt
|
sanjini-attraction
| 725,554,254
| false
|
{"Kotlin": 67959}
|
package com.jeongg.sanjini_attraction.presentation.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.jeongg.sanjini_attraction.presentation.view.bluetooth.BluetoothScreen
import com.jeongg.sanjini_attraction.presentation.view.finish_game.FinishGameScreen
import com.jeongg.sanjini_attraction.presentation.view.game.GameScreen
import com.jeongg.sanjini_attraction.presentation.view.ready_game.ReadyForGameScreen
import com.jeongg.sanjini_attraction.presentation.view.splash.SplashScreen
fun NavGraphBuilder.sanjiniAttractionGraph(
navController: NavController
){
composable(route = Screen.SplashScreen.route){
SplashScreen(navController)
}
composable(route = Screen.BluetoothScreen.route) {
BluetoothScreen(navController)
}
composable(route = Screen.ReadyForGameScreen.route) {
ReadyForGameScreen(navController)
}
composable(
route = Screen.GameScreen.route + "?index={index}",
arguments = listOf(
navArgument("index"){
type = NavType.IntType
defaultValue = 0
}
)
){
GameScreen(navController)
}
composable(route = Screen.FinishGameScreen.route){FinishGameScreen(navController)}
}
| 0
|
Kotlin
|
0
| 0
|
031061ecaec9f3cb098b590c967c6a37a4e13934
| 1,412
|
android
|
MIT License
|
domain/src/main/java/com/foobarust/domain/usecases/order/GetArchivedOrdersUseCase.kt
|
foobar-UST
| 285,792,732
| false
| null |
package com.foobarust.domain.usecases.order
import androidx.paging.PagingData
import com.foobarust.domain.di.IoDispatcher
import com.foobarust.domain.models.order.OrderBasic
import com.foobarust.domain.repositories.AuthRepository
import com.foobarust.domain.repositories.OrderRepository
import com.foobarust.domain.usecases.AuthState
import com.foobarust.domain.usecases.PagingUseCase
import com.foobarust.domain.utils.cancelIfActive
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.collect
import javax.inject.Inject
/**
* Created by kevin on 1/30/21
*/
private const val TAG = "GetArchivedOrdersUseCase"
class GetArchivedOrdersUseCase @Inject constructor(
private val authRepository: AuthRepository,
private val orderRepository: OrderRepository,
@IoDispatcher private val coroutineDispatcher: CoroutineDispatcher
) : PagingUseCase<Unit, OrderBasic>(coroutineDispatcher) {
private var producePagingDataJob: Job? = null
private val archivedOrdersFlow: Flow<PagingData<OrderBasic>> = channelFlow {
val coroutineScope = CoroutineScope(currentCoroutineContext())
authRepository.authProfileObservable.collect {
stopProducePagingData()
when (it) {
is AuthState.Authenticated -> {
println("[$TAG] User is signed in. Offered paging data.")
startProducePagingData(coroutineScope, it.data.id)
}
AuthState.Unauthenticated -> {
println("[$TAG] User is signed out. Offered empty paging data.")
channel.offer(PagingData.empty())
}
AuthState.Loading -> {
channel.offer(PagingData.empty())
}
}
}
}
override fun execute(parameters: Unit): Flow<PagingData<OrderBasic>> = archivedOrdersFlow
private fun ProducerScope<PagingData<OrderBasic>>.startProducePagingData(
coroutineScope: CoroutineScope,
userId: String
) {
producePagingDataJob = coroutineScope.launch(coroutineDispatcher) {
orderRepository.getHistoryOrderItemsPagingData(userId).collect {
channel.offer(it)
}
}
}
private fun stopProducePagingData() {
println("[$TAG]: Stop producing paging data.")
producePagingDataJob.cancelIfActive()
}
}
| 0
|
Kotlin
|
2
| 2
|
b4358ef0323a0b7a95483223496164e616a01da5
| 2,523
|
foobar-android
|
MIT License
|
modules/modules_my/src/main/java/com/cl/modules_my/request/MyPlantInfoData.kt
|
aaaaaaaazmx
| 528,318,389
| false
|
{"Kotlin": 3692948, "Java": 1498595}
|
package com.cl.modules_my.request
import com.cl.common_base.BaseBean
data class MyPlantInfoData(
val plantName: String? = null,
var isSelected: Boolean = false
) : BaseBean()
| 0
|
Kotlin
|
0
| 0
|
e010b3e8443e617d72830490b028268476e3e470
| 184
|
abby
|
Apache License 2.0
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/datadonation/safetynet/AttestationContainer.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.datadonation.safetynet
import de.rki.coronawarnapp.appconfig.SafetyNetRequirements
import de.rki.coronawarnapp.datadonation.safetynet.SafetyNetException.Type
import de.rki.coronawarnapp.server.protocols.internal.ppdd.PpacAndroid
import okio.ByteString.Companion.toByteString
internal data class AttestationContainer(
private val ourSalt: ByteArray,
private val report: SafetyNetClientWrapper.Report
) : DeviceAttestation.Result {
override val accessControlProtoBuf: PpacAndroid.PPACAndroid
get() = PpacAndroid.PPACAndroid.newBuilder().apply {
salt = ourSalt.toByteString().base64()
safetyNetJws = report.jwsResult
}.build()
override fun requirePass(reqs: SafetyNetRequirements) {
if (reqs.requireBasicIntegrity && !report.basicIntegrity) {
throw SafetyNetException(
Type.BASIC_INTEGRITY_REQUIRED,
"Requirement 'basicIntegrity' not met (${report.advice})."
)
}
if (reqs.requireCTSProfileMatch && !report.ctsProfileMatch) {
throw SafetyNetException(
Type.CTS_PROFILE_MATCH_REQUIRED,
"Requirement 'ctsProfileMatch' not met (${report.advice})."
)
}
if (reqs.requireBasicIntegrity && !report.evaluationTypes.contains("BASIC")) {
throw SafetyNetException(
Type.EVALUATION_TYPE_BASIC_REQUIRED,
"Evaluation type 'BASIC' not met (${report.advice})."
)
}
if (reqs.requireEvaluationTypeHardwareBacked && !report.evaluationTypes.contains("HARDWARE_BACKED")) {
throw SafetyNetException(
Type.EVALUATION_TYPE_HARDWARE_BACKED_REQUIRED,
"Evaluation type 'HARDWARE_BACKED' not met (${report.advice})."
)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AttestationContainer
if (!ourSalt.contentEquals(other.ourSalt)) return false
if (report != other.report) return false
return true
}
override fun hashCode(): Int {
var result = ourSalt.contentHashCode()
result = 31 * result + report.hashCode()
return result
}
}
| 6
| null |
8
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 2,361
|
cwa-app-android
|
Apache License 2.0
|
Common/src/main/java/dev/aresiel/dohexthewater/common/casting/actions/OpRandInt.kt
|
Aresiel
| 544,412,490
| false
| null |
package dev.aresiel.dohexthewater.common.casting.actions
import at.petrak.hexcasting.api.spell.*
import at.petrak.hexcasting.api.spell.casting.CastingContext
import at.petrak.hexcasting.api.spell.mishaps.MishapInvalidIota
import at.petrak.hexcasting.api.utils.asTranslatedComponent
import kotlin.math.roundToInt
object OpRandInt : ConstManaOperator {
override val argc = 2
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val lowerBound = args.getChecked<Double>(0, argc).roundToInt()
val upperBound = args.getChecked<Double>(1, argc).roundToInt()
if(lowerBound > upperBound) throw MishapInvalidIota(args[0], 0, "dohexthewater.mishap.greater_lower_bound".asTranslatedComponent())
return spellListOf((lowerBound..upperBound).random().toDouble())
}
}
| 0
|
Kotlin
|
0
| 0
|
40fdbab97c38d64fb8e6ad67eacd0ceeec7f4d3e
| 807
|
DoHexTheWater
|
MIT License
|
app/src/main/java/com/example/mykotlinapp/ui/screens/chats/history/group/posts/comments/PostMediasAdapter.kt
|
vbounyasit
| 522,266,559
| false
|
{"Kotlin": 507212}
|
package com.example.mykotlinapp.ui.screens.chats.history.group.posts.comments
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.example.mykotlinapp.databinding.ComponentUserPostMediasBinding
import com.example.mykotlinapp.model.dto.ui.post.PostMediaDTO
import com.example.mykotlinapp.ui.components.recycler_view.AppViewHolder
class PostMediasAdapter(val context: Context, private val medias: List<PostMediaDTO>) :
Adapter<AppViewHolder<ComponentUserPostMediasBinding>>() {
override fun getItemCount(): Int {
return medias.size
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): AppViewHolder<ComponentUserPostMediasBinding> {
return AppViewHolder(
ComponentUserPostMediasBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(
holder: AppViewHolder<ComponentUserPostMediasBinding>,
position: Int
) {
holder.bind {
it.media = medias[position].media
}
}
}
| 0
|
Kotlin
|
0
| 1
|
a9812a061f9214b44ba326b77afe335a003cc22e
| 1,233
|
MyAndroidApp
|
Apache License 2.0
|
app/src/main/java/com/example/metodohoggsimplificado/ui/ui/DataInputScreen.kt
|
Brandon-Meneses
| 832,520,811
| false
|
{"Kotlin": 47699}
|
package com.example.metodohoggsimplificado.ui.ui
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Divider
import androidx.compose.material.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
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.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.font.FontWeight.Companion.Bold
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.metodohoggsimplificado.R
import com.example.metodohoggsimplificado.database.HoggDatabase
import com.example.metodohoggsimplificado.viewModel.HoggViewModel
import kotlin.math.pow
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DataInputScreen(
viewModel: HoggViewModel? = null, // Parámetro opcional
navController: NavController? = null // Parámetro opcional
) {
var d0 by remember { mutableStateOf("") }
var dr by remember { mutableStateOf("") }
var showError by remember { mutableStateOf(false) }
val options = listOf("20", "30", "40", "50", "60", "70", "80", "90", "100")
val coefficient = listOf("90", "100", "120", "130", "140", "150", "160")
var expanded by remember { mutableStateOf(false) }
var expanded2 by remember { mutableStateOf(false) }
var selectedOption by remember { mutableStateOf("30") }
var selectedOption2 by remember { mutableStateOf("100") }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text("Método Hogg Simplificado", style = MaterialTheme.typography.headlineSmall, fontWeight = Bold) },
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = Color(0xFFFFD700) // Amarillo vibrante
),
modifier = Modifier.shadow(8.dp) // Sombra bajo la barra superior
)
},
content = { paddingValues ->
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
colors = listOf(
Color(0xFFFFF8E1), // Fondo amarillo claro
Color(0xFFFFE082)
)
)
)
.padding(paddingValues)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 8.dp) // Espacio horizontal reducido
.clip(RoundedCornerShape(16.dp)) // Bordes redondeados
.shadow(4.dp)
.background(Color.White)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
item {
Box(
modifier = Modifier
.size(250.dp)
.align(Alignment.CenterHorizontally)
) {
Image(
painter = painterResource(id = R.drawable.principal),
contentDescription = null,
modifier = Modifier.fillMaxSize()
)
}
}
item { Spacer(modifier = Modifier.height(20.dp)) }
item {
OutlinedTextField(
value = d0,
onValueChange = {
d0 = it
showError = false
},
label = {
Text(
"Deflexión máxima D0 en mmx10-2",
fontSize = 12.sp,
textAlign = TextAlign.Center,
fontWeight = Bold,
modifier = Modifier.fillMaxWidth()
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp)
.align(Alignment.CenterHorizontally),
textStyle = MaterialTheme.typography.bodyLarge.copy(
fontSize = 24.sp,
textAlign = TextAlign.Center
),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color(0xFF8B4513), // Marrón
unfocusedBorderColor = Color(0xFF8B4513)
),
singleLine = true
)
}
item { Spacer(modifier = Modifier.height(16.dp)) }
item {
OutlinedTextField(
value = dr,
onValueChange = {
dr = it
showError = false
},
label = { Text("Deflexión adicional DR en mmx10-2", fontSize = 12.sp, textAlign = TextAlign.Center, fontWeight = Bold, modifier = Modifier.fillMaxWidth()) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp)
.align(Alignment.CenterHorizontally),
textStyle = MaterialTheme.typography.bodyLarge.copy(fontSize = 24.sp, textAlign = TextAlign.Center),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color(0xFF8B4513),
unfocusedBorderColor = Color(0xFF8B4513)
)
)
}
item { Spacer(modifier = Modifier.height(16.dp)) }
item {
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = { expanded = !expanded }
) {
OutlinedTextField(
readOnly = true,
value = selectedOption,
onValueChange = { },
label = {
Text(
"Distancia radial R en cm",
fontSize = 12.sp,
textAlign = TextAlign.Center,
fontWeight = Bold,
modifier = Modifier.fillMaxWidth()
)
},
modifier = Modifier
.fillMaxWidth()
.menuAnchor()
.padding(horizontal = 8.dp),
textStyle = MaterialTheme.typography.bodyLarge.copy(
fontSize = 24.sp,
textAlign = TextAlign.Center
),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color(0xFF8B4513),
unfocusedBorderColor = Color(0xFF8B4513)
),
trailingIcon = {
Box(
modifier = Modifier.width(24.dp) // Ajustar este ancho según el tamaño del ícono
) {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
}
ExposedDropdownMenu(
expanded = expanded,
modifier = Modifier.width(150.dp),
onDismissRequest = { expanded = false }
) {
options.forEach { selectionOption ->
DropdownMenuItem(
text = {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center // Centra el contenido
) {
Text(
selectionOption,
style = MaterialTheme.typography.bodyLarge.copy(
fontSize = 22.sp,
textAlign = TextAlign.Center
)
)
}
},
onClick = {
selectedOption = selectionOption
expanded = false
}
)
}
}
},
leadingIcon = {
Box(
modifier = Modifier.width(24.dp) // Añadir espacio igual al del trailingIcon para equilibrar
)
},
singleLine = true
)
}
}
item { Spacer(modifier = Modifier.height(16.dp)) }
item {
ExposedDropdownMenuBox(
expanded = expanded2,
onExpandedChange = { expanded2 = !expanded2 }
) {
OutlinedTextField(
readOnly = true,
value = selectedOption2,
onValueChange = { },
label = {
Text(
"Coeficiente k",
fontSize = 12.sp,
textAlign = TextAlign.Center,
fontWeight = Bold,
modifier = Modifier.fillMaxWidth()
)
}, // Aumentar tamaño del texto
modifier = Modifier
.fillMaxWidth()
.menuAnchor()
.padding(horizontal = 8.dp)
.align(Alignment.CenterHorizontally),
textStyle = MaterialTheme.typography.bodyLarge.copy(fontSize = 24.sp, textAlign = TextAlign.Center),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color(0xFF8B4513),
unfocusedBorderColor = Color(0xFF8B4513)
),
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = expanded2
)
ExposedDropdownMenu(
expanded = expanded2,
onDismissRequest = { expanded2 = false },
modifier = Modifier.width(150.dp),
) {
coefficient.forEach { selectionOption2 ->
DropdownMenuItem(
text = {
Text(
selectionOption2,
style = MaterialTheme.typography.bodyLarge.copy(
fontSize = 22.sp,
textAlign = TextAlign.Center
),
modifier = Modifier.fillMaxWidth()
)
},
onClick = {
selectedOption2 = selectionOption2
expanded2 = false
}
)
}
}
},
leadingIcon = {
Box(
modifier = Modifier.width(24.dp) // Añadir espacio igual al del trailingIcon para equilibrar
)
},
)
}
}
item { Spacer(modifier = Modifier.height(24.dp)) }
item {
if (showError) {
Text(
text = "Por favor, ingrese valores válidos.",
color = Color.Red,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(bottom = 8.dp),
textAlign = TextAlign.Center
)
}
Button(
onClick = {
try {
val d0Value = parseScientificNotation(d0)
val drValue = parseScientificNotation(dr)
val rValue = selectedOption.toDouble()
val kValue = selectedOption2.toDouble()
viewModel!!.calculate(d0Value, drValue, rValue, kValue)
navController!!.navigate("ResultScreen")
} catch (e: NumberFormatException) {
showError = true
}
},
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.clip(RoundedCornerShape(12.dp)),
colors = ButtonDefaults.buttonColors(
containerColor = Color(0xFF8B4513),
contentColor = Color.White
)
) {
Text("Calcular", style = MaterialTheme.typography.bodyLarge.copy(fontSize = 20.sp, textAlign = TextAlign.Center))
}
}
}
}
}
}
)
}
@Composable
fun titleBar(name: String) {
Text(
text = name,
fontSize = 30.sp,
color = Color.Black,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
fun parseScientificNotation(input: String): Double {
return if (input.contains("x10")) {
val parts = input.split("x10")
val base = parts[0].toDouble()
val exponent = parts[1].toInt()
base * 10.0.pow(exponent)
} else {
input.toDouble()
}
}
| 0
|
Kotlin
|
0
| 0
|
ee709d34172e056884adc3159cd4a0382d8b66d5
| 21,441
|
MetodoHoggSimplificado
|
MIT License
|
Base/src/main/java/xy/xy/base/widget/text/LinkTextView.kt
|
xiuone
| 291,512,847
| false
|
{"Kotlin": 696966, "Java": 245782}
|
package xy.xy.base.widget.text
import android.content.Context
import android.text.Spannable
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatTextView
open class LinkTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {
override fun onTouchEvent(event: MotionEvent?): Boolean {
var ret = false
val stext = Spannable.Factory.getInstance().newSpannable(text)
val action = event?.action
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
var x = event.x.toInt()
var y = event.y.toInt()
x -= totalPaddingLeft
y -= totalPaddingTop
x += scrollX
y += scrollY
val line: Int = layout.getLineForVertical(y)
val off: Int = layout.getOffsetForHorizontal(line, x.toFloat())
val link = stext.getSpans(off, off, ClickableSpan::class.java)
if (link.isNotEmpty()) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(this)
}
ret = true
}
}
return ret
}
}
| 0
|
Kotlin
|
1
| 2
|
dc9f035dae4c876c6acb3e2e96742d5eb5cebe18
| 1,336
|
ajinlib
|
Apache License 2.0
|
Base/src/main/java/xy/xy/base/widget/text/LinkTextView.kt
|
xiuone
| 291,512,847
| false
|
{"Kotlin": 696966, "Java": 245782}
|
package xy.xy.base.widget.text
import android.content.Context
import android.text.Spannable
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatTextView
open class LinkTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {
override fun onTouchEvent(event: MotionEvent?): Boolean {
var ret = false
val stext = Spannable.Factory.getInstance().newSpannable(text)
val action = event?.action
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
var x = event.x.toInt()
var y = event.y.toInt()
x -= totalPaddingLeft
y -= totalPaddingTop
x += scrollX
y += scrollY
val line: Int = layout.getLineForVertical(y)
val off: Int = layout.getOffsetForHorizontal(line, x.toFloat())
val link = stext.getSpans(off, off, ClickableSpan::class.java)
if (link.isNotEmpty()) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(this)
}
ret = true
}
}
return ret
}
}
| 0
|
Kotlin
|
1
| 2
|
dc9f035dae4c876c6acb3e2e96742d5eb5cebe18
| 1,336
|
ajinlib
|
Apache License 2.0
|
java/com/google/android/libraries/pcc/chronicle/api/ConnectionName.kt
|
google
| 564,990,777
| false
|
{"Kotlin": 1440674, "Starlark": 164409, "Java": 10061, "AIDL": 5852, "Python": 4367, "Dockerfile": 2035, "Shell": 1301}
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.api
/** Used to describe a [Connection], specifying whether it's a Read or Write connection. */
sealed class ConnectionName<T : Connection> {
internal abstract val name: Name
data class Reader<T : Connection>(override val name: Name) : ConnectionName<T>()
data class Writer<T : Connection>(override val name: Name) : ConnectionName<T>()
}
| 0
|
Kotlin
|
7
| 29
|
62efeab0288f39467061c2444549954d0b7137f8
| 994
|
private-compute-libraries
|
Apache License 2.0
|
src/main/kotlin/net/fabricmc/bot/App.kt
|
FabricMC
| 272,279,496
| false
| null |
/*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package net.fabricmc.bot
import com.gitlab.kordlib.gateway.Intents
import com.gitlab.kordlib.gateway.PrivilegedIntent
import com.kotlindiscord.kord.extensions.ExtensibleBot
import mu.KotlinLogging
import net.fabricmc.bot.conf.buildInfo
import net.fabricmc.bot.conf.config
import net.fabricmc.bot.database.Migrator
import net.fabricmc.bot.extensions.*
/** The current instance of the bot. **/
val bot = ExtensibleBot(
prefix = config.prefix,
token = config.token,
guildsToFill = listOf(config.guildSnowflake.value),
fillPresences = true
)
/**
* The main function. Every story has a beginning!
*/
@OptIn(PrivilegedIntent::class)
suspend fun main() {
val logger = KotlinLogging.logger {}
logger.info { "Starting Fabric Discord Bot, version ${buildInfo.version}." }
Migrator.migrate()
bot.addExtension(ActionLogExtension::class)
bot.addExtension(CleanExtension::class)
bot.addExtension(EmojiExtension::class)
bot.addExtension(FilterExtension::class)
bot.addExtension(GitHubExtension::class)
bot.addExtension(InfractionsExtension::class)
bot.addExtension(LoggingExtension::class)
bot.addExtension(ModerationExtension::class)
bot.addExtension(SelfRoleExtension::class)
bot.addExtension(SyncExtension::class)
bot.addExtension(UtilsExtension::class)
bot.addExtension(VersionCheckExtension::class)
bot.start(
presenceBuilder = {
playing("${config.prefix}help for command help")
},
intents = {
+Intents.all
}
)
}
| 20
|
Kotlin
|
10
| 7
|
16622cffbc0622c6ca461bfb887f39849fa2b935
| 1,669
|
kotlin-fabric-discord-bot
|
MIT License
|
kotest-framework/kotest-framework-engine/src/jsMain/kotlin/io/kotest/engine/interceptors.kt
|
IshanKute
| 413,260,612
| true
|
{"Kotlin": 3285660, "CSS": 352, "Java": 145}
|
package io.kotest.engine
import io.kotest.core.config.Configuration
import io.kotest.core.extensions.ProjectExtension
import io.kotest.engine.interceptors.EmptyTestSuiteInterceptor
import io.kotest.engine.interceptors.EngineInterceptor
import io.kotest.engine.interceptors.ProjectExtensionEngineInterceptor
import io.kotest.engine.interceptors.ProjectListenerEngineInterceptor
import io.kotest.engine.interceptors.ProjectTimeoutEngineInterceptor
import io.kotest.engine.interceptors.SpecSortEngineInterceptor
import io.kotest.engine.interceptors.TestDslStateInterceptor
import io.kotest.engine.interceptors.TestEngineListenerStartedFinishedInterceptor
import io.kotest.engine.interceptors.TestEngineStartupShutdownInterceptor
internal actual fun testEngineInterceptors(conf: Configuration): List<EngineInterceptor> {
return listOfNotNull(
TestEngineStartupShutdownInterceptor,
ProjectTimeoutEngineInterceptor,
TestDslStateInterceptor,
SpecSortEngineInterceptor,
ProjectExtensionEngineInterceptor(conf.extensions().filterIsInstance<ProjectExtension>()),
ProjectListenerEngineInterceptor(conf.extensions()),
EmptyTestSuiteInterceptor,
TestEngineListenerStartedFinishedInterceptor,
)
}
| 5
|
Kotlin
|
0
| 0
|
194bdd8f8fcb592a039d8402b8d7ae5a6f77db3c
| 1,239
|
kotest
|
Apache License 2.0
|
k4-core/src/main/kotlin/com/luggsoft/k4/core/sources/iterators/TryConsumeNextDelimited.kt
|
dan-lugg
| 403,714,343
| false
| null |
package com.luggsoft.k4.core.sources.iterators
fun SourceIterator.tryConsumeNextDelimited(delimiter: CharSequence, stringBuilder: StringBuilder): Boolean
{
if (this.peekEquals(delimiter))
{
stringBuilder.append(this.next(delimiter.length))
while (!this.peekEquals(delimiter))
{
stringBuilder.append(this.next())
}
stringBuilder.append(this.next(delimiter.length))
return true
}
return false
}
| 0
| null |
0
| 2
|
7beae2e349492f6c03e8deb96401386e2b7dd29b
| 473
|
luggsoft-k4
|
MIT License
|
src/main/kotlin/ru/quandastudio/lpsclient/model/FriendInfo.kt
|
AlexanderShirokih
| 206,852,922
| false
| null |
package ru.quandastudio.lpsclient.model
data class FriendInfo(
var userId: Int,
var login: String,
var accepted: Boolean,
val pictureHash: String?
)
| 0
|
Kotlin
|
0
| 0
|
228e59c053c7895a22b1a3830a0c07af343733c6
| 166
|
letsplaycities-client-v2
|
MIT License
|
anvil/src/gen-sdk-21/kotlin/dev/inkremental/dsl/android/SdkSetter.kt
|
inkremental
| 205,363,267
| false
| null |
@file:Suppress("DEPRECATION", "UNCHECKED_CAST", "MemberVisibilityCanBePrivate", "unused")
package dev.inkremental.dsl.android
import android.animation.LayoutTransition
import android.animation.ObjectAnimator
import android.animation.StateListAnimator
import android.app.Activity
import android.app.FragmentBreadCrumbs
import android.app.FragmentManager
import android.app.MediaRouteButton
import android.app.SearchableInfo
import android.content.Intent
import android.content.res.ColorStateList
import android.gesture.Gesture
import android.gesture.GestureOverlayView
import android.graphics.Bitmap
import android.graphics.ColorFilter
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.Rect
import android.graphics.SurfaceTexture
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.media.MediaPlayer
import android.media.tv.TvView
import android.net.Uri
import android.opengl.GLSurfaceView
import android.text.Editable
import android.text.InputFilter
import android.text.Spannable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.KeyListener
import android.text.method.MovementMethod
import android.text.method.TransformationMethod
import android.view.ActionMode
import android.view.ContextMenu
import android.view.DragEvent
import android.view.InputEvent
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.MotionEvent
import android.view.SurfaceView
import android.view.TextureView
import android.view.TouchDelegate
import android.view.View
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.view.ViewStub
import android.view.WindowInsets
import android.view.animation.Animation
import android.view.animation.Interpolator
import android.view.animation.LayoutAnimationController
import android.view.inputmethod.ExtractedText
import android.webkit.DownloadListener
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.AbsListView
import android.widget.AbsSeekBar
import android.widget.ActionMenuView
import android.widget.Adapter
import android.widget.AdapterView
import android.widget.AdapterViewAnimator
import android.widget.AdapterViewFlipper
import android.widget.AutoCompleteTextView
import android.widget.CalendarView
import android.widget.CheckedTextView
import android.widget.Chronometer
import android.widget.CompoundButton
import android.widget.CursorAdapter
import android.widget.DatePicker
import android.widget.DialerFilter
import android.widget.EditText
import android.widget.ExpandableListAdapter
import android.widget.ExpandableListView
import android.widget.FrameLayout
import android.widget.Gallery
import android.widget.GridLayout
import android.widget.GridView
import android.widget.HorizontalScrollView
import android.widget.ImageSwitcher
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.MediaController
import android.widget.MultiAutoCompleteTextView
import android.widget.NumberPicker
import android.widget.ProgressBar
import android.widget.QuickContactBadge
import android.widget.RadioGroup
import android.widget.RatingBar
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.Scroller
import android.widget.SearchView
import android.widget.SeekBar
import android.widget.SlidingDrawer
import android.widget.Spinner
import android.widget.Switch
import android.widget.TabHost
import android.widget.TabWidget
import android.widget.TableLayout
import android.widget.TextClock
import android.widget.TextSwitcher
import android.widget.TextView
import android.widget.TimePicker
import android.widget.ToggleButton
import android.widget.Toolbar
import android.widget.VideoView
import android.widget.ViewAnimator
import android.widget.ViewFlipper
import android.widget.ViewSwitcher
import android.widget.ZoomButton
import android.widget.ZoomControls
import dev.inkremental.Inkremental
import dev.inkremental.dip
import java.util.Locale
import kotlin.Any
import kotlin.Array
import kotlin.Boolean
import kotlin.CharSequence
import kotlin.Float
import kotlin.Function
import kotlin.Int
import kotlin.IntArray
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
/**
* DSL for creating views and settings their attributes.
* This file has been generated by
* {@code gradle SdkSetter}
* It contains views and their setters for Android SDK (API level 21).
* Please, don't edit it manually unless for debugging.
*/
object SdkSetter : Inkremental.AttributeSetter<Any> {
override fun set(
v: View,
name: String,
arg: Any?,
old: Any?
): Boolean = when (name) {
"activity" -> when {
v is FragmentBreadCrumbs && arg is Activity -> {
v.setActivity(arg)
true
}
else -> false
}
"maxVisible" -> when {
v is FragmentBreadCrumbs && arg is Int -> {
v.setMaxVisible(arg)
true
}
else -> false
}
"onBreadCrumbClick" -> when {
v is FragmentBreadCrumbs -> when {
arg == null -> {
v.setOnBreadCrumbClickListener(null as? FragmentBreadCrumbs.OnBreadCrumbClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: FragmentManager.BackStackEntry, arg1: Int) -> Boolean)?
v.setOnBreadCrumbClickListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"extendedSettingsClickListener" -> when {
v is MediaRouteButton && arg is View.OnClickListener -> {
v.setExtendedSettingsClickListener(arg)
true
}
else -> false
}
"routeTypes" -> when {
v is MediaRouteButton && arg is Int -> {
v.setRouteTypes(arg)
true
}
else -> false
}
"eventsInterceptionEnabled" -> when {
v is GestureOverlayView && arg is Boolean -> {
v.setEventsInterceptionEnabled(arg)
true
}
else -> false
}
"fadeEnabled" -> when {
v is GestureOverlayView && arg is Boolean -> {
v.setFadeEnabled(arg)
true
}
else -> false
}
"fadeOffset" -> when {
v is GestureOverlayView && arg is Long -> {
v.setFadeOffset(arg)
true
}
else -> false
}
"gesture" -> when {
v is GestureOverlayView && arg is Gesture -> {
v.setGesture(arg)
true
}
else -> false
}
"gestureColor" -> when {
v is GestureOverlayView && arg is Int -> {
v.setGestureColor(arg)
true
}
else -> false
}
"gestureStrokeAngleThreshold" -> when {
v is GestureOverlayView && arg is Float -> {
v.setGestureStrokeAngleThreshold(arg)
true
}
else -> false
}
"gestureStrokeLengthThreshold" -> when {
v is GestureOverlayView && arg is Float -> {
v.setGestureStrokeLengthThreshold(arg)
true
}
else -> false
}
"gestureStrokeSquarenessTreshold" -> when {
v is GestureOverlayView && arg is Float -> {
v.setGestureStrokeSquarenessTreshold(arg)
true
}
else -> false
}
"gestureStrokeType" -> when {
v is GestureOverlayView && arg is Int -> {
v.setGestureStrokeType(arg)
true
}
else -> false
}
"gestureStrokeWidth" -> when {
v is GestureOverlayView && arg is Float -> {
v.setGestureStrokeWidth(arg)
true
}
else -> false
}
"gestureVisible" -> when {
v is GestureOverlayView && arg is Boolean -> {
v.setGestureVisible(arg)
true
}
else -> false
}
"orientation" -> when {
v is GestureOverlayView && arg is Int -> {
v.setOrientation(arg)
true
}
v is GridLayout && arg is Int -> {
v.setOrientation(arg)
true
}
v is LinearLayout && arg is Int -> {
v.setOrientation(arg)
true
}
else -> false
}
"uncertainGestureColor" -> when {
v is GestureOverlayView && arg is Int -> {
v.setUncertainGestureColor(arg)
true
}
else -> false
}
"keyboard" -> when {
v is KeyboardView && arg is Keyboard -> {
v.setKeyboard(arg)
true
}
else -> false
}
"onKeyboardAction" -> when {
v is KeyboardView -> when {
arg == null -> {
v.setOnKeyboardActionListener(null as? KeyboardView.OnKeyboardActionListener?)
true
}
arg is KeyboardView.OnKeyboardActionListener -> {
v.setOnKeyboardActionListener(object : KeyboardView.OnKeyboardActionListener {
override fun onKey(arg0: Int, arg1: IntArray): Unit = arg.onKey(arg0, arg1).also {
Inkremental.render() }
override fun onPress(arg0: Int): Unit = arg.onPress(arg0).also { Inkremental.render() }
override fun onRelease(arg0: Int): Unit = arg.onRelease(arg0).also {
Inkremental.render() }
override fun onText(arg0: CharSequence): Unit = arg.onText(arg0).also {
Inkremental.render() }
override fun swipeDown(): Unit = arg.swipeDown().also { Inkremental.render() }
override fun swipeLeft(): Unit = arg.swipeLeft().also { Inkremental.render() }
override fun swipeRight(): Unit = arg.swipeRight().also { Inkremental.render() }
override fun swipeUp(): Unit = arg.swipeUp().also { Inkremental.render() }
})
true
}
else -> false
}
else -> false
}
"popupParent" -> when {
v is KeyboardView && arg is View -> {
v.setPopupParent(arg)
true
}
else -> false
}
"previewEnabled" -> when {
v is KeyboardView && arg is Boolean -> {
v.setPreviewEnabled(arg)
true
}
else -> false
}
"proximityCorrectionEnabled" -> when {
v is KeyboardView && arg is Boolean -> {
v.setProximityCorrectionEnabled(arg)
true
}
else -> false
}
"shifted" -> when {
v is KeyboardView && arg is Boolean -> {
v.setShifted(arg)
true
}
else -> false
}
"verticalCorrection" -> when {
v is KeyboardView && arg is Int -> {
v.setVerticalCorrection(arg)
true
}
else -> false
}
"callback" -> when {
v is TvView && arg is TvView.TvInputCallback? -> {
v.setCallback(arg)
true
}
else -> false
}
"captionEnabled" -> when {
v is TvView && arg is Boolean -> {
v.setCaptionEnabled(arg)
true
}
else -> false
}
"onUnhandledInputEvent" -> when {
v is TvView -> when {
arg == null -> {
v.setOnUnhandledInputEventListener(null as? TvView.OnUnhandledInputEventListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: InputEvent) -> Boolean)?
v.setOnUnhandledInputEventListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"streamVolume" -> when {
v is TvView && arg is Float -> {
v.setStreamVolume(arg)
true
}
else -> false
}
"debugFlags" -> when {
v is GLSurfaceView && arg is Int -> {
v.setDebugFlags(arg)
true
}
else -> false
}
"eGLConfigChooser" -> when {
v is GLSurfaceView && arg is GLSurfaceView.EGLConfigChooser -> {
v.setEGLConfigChooser(arg)
true
}
v is GLSurfaceView && arg is Boolean -> {
v.setEGLConfigChooser(arg)
true
}
else -> false
}
"eGLContextClientVersion" -> when {
v is GLSurfaceView && arg is Int -> {
v.setEGLContextClientVersion(arg)
true
}
else -> false
}
"eGLContextFactory" -> when {
v is GLSurfaceView && arg is GLSurfaceView.EGLContextFactory -> {
v.setEGLContextFactory(arg)
true
}
else -> false
}
"eGLWindowSurfaceFactory" -> when {
v is GLSurfaceView && arg is GLSurfaceView.EGLWindowSurfaceFactory -> {
v.setEGLWindowSurfaceFactory(arg)
true
}
else -> false
}
"gLWrapper" -> when {
v is GLSurfaceView && arg is GLSurfaceView.GLWrapper -> {
v.setGLWrapper(arg)
true
}
else -> false
}
"preserveEGLContextOnPause" -> when {
v is GLSurfaceView && arg is Boolean -> {
v.setPreserveEGLContextOnPause(arg)
true
}
else -> false
}
"renderMode" -> when {
v is GLSurfaceView && arg is Int -> {
v.setRenderMode(arg)
true
}
else -> false
}
"renderer" -> when {
v is GLSurfaceView && arg is GLSurfaceView.Renderer -> {
v.setRenderer(arg)
true
}
else -> false
}
"secure" -> when {
v is SurfaceView && arg is Boolean -> {
v.setSecure(arg)
true
}
else -> false
}
"zOrderMediaOverlay" -> when {
v is SurfaceView && arg is Boolean -> {
v.setZOrderMediaOverlay(arg)
true
}
else -> false
}
"zOrderOnTop" -> when {
v is SurfaceView && arg is Boolean -> {
v.setZOrderOnTop(arg)
true
}
else -> false
}
"opaque" -> when {
v is TextureView && arg is Boolean -> {
v.setOpaque(arg)
true
}
else -> false
}
"surfaceTexture" -> when {
v is TextureView && arg is SurfaceTexture -> {
v.setSurfaceTexture(arg)
true
}
else -> false
}
"surfaceTextureListener" -> when {
v is TextureView && arg is TextureView.SurfaceTextureListener -> {
v.setSurfaceTextureListener(arg)
true
}
else -> false
}
"transform" -> when {
v is TextureView && arg is Matrix -> {
v.setTransform(arg)
true
}
else -> false
}
"accessibilityDelegate" -> when {
arg is View.AccessibilityDelegate? -> {
v.setAccessibilityDelegate(arg)
true
}
else -> false
}
"accessibilityLiveRegion" -> when {
arg is Int -> {
v.setAccessibilityLiveRegion(arg)
true
}
else -> false
}
"activated" -> when {
arg is Boolean -> {
v.setActivated(arg)
true
}
else -> false
}
"alpha" -> when {
arg is Float -> {
v.setAlpha(arg)
true
}
else -> false
}
"animation" -> when {
arg is Animation -> {
v.setAnimation(arg)
true
}
else -> false
}
"background" -> when {
arg is Drawable -> {
v.setBackground(arg)
true
}
else -> false
}
"backgroundColor" -> when {
arg is Int -> {
v.setBackgroundColor(arg)
true
}
else -> false
}
"backgroundResource" -> when {
arg is Int -> {
v.setBackgroundResource(arg)
true
}
else -> false
}
"backgroundTintList" -> when {
arg is ColorStateList? -> {
v.setBackgroundTintList(arg)
true
}
else -> false
}
"backgroundTintMode" -> when {
arg is PorterDuff.Mode? -> {
v.setBackgroundTintMode(arg)
true
}
else -> false
}
"bottom" -> when {
arg is Int -> {
v.setBottom(arg)
true
}
else -> false
}
"cameraDistance" -> when {
arg is Float -> {
v.setCameraDistance(arg)
true
}
else -> false
}
"clickable" -> when {
arg is Boolean -> {
v.setClickable(arg)
true
}
else -> false
}
"clipBounds" -> when {
arg is Rect -> {
v.setClipBounds(arg)
true
}
else -> false
}
"clipToOutline" -> when {
arg is Boolean -> {
v.setClipToOutline(arg)
true
}
else -> false
}
"contentDescription" -> when {
arg is CharSequence -> {
v.setContentDescription(arg)
true
}
else -> false
}
"drawingCacheBackgroundColor" -> when {
arg is Int -> {
v.setDrawingCacheBackgroundColor(arg)
true
}
else -> false
}
"drawingCacheEnabled" -> when {
arg is Boolean -> {
v.setDrawingCacheEnabled(arg)
true
}
else -> false
}
"drawingCacheQuality" -> when {
arg is Int -> {
v.setDrawingCacheQuality(arg)
true
}
else -> false
}
"duplicateParentStateEnabled" -> when {
arg is Boolean -> {
v.setDuplicateParentStateEnabled(arg)
true
}
else -> false
}
"enabled" -> when {
arg is Boolean -> {
v.setEnabled(arg)
true
}
else -> false
}
"fadingEdgeLength" -> when {
arg is Int -> {
v.setFadingEdgeLength(arg)
true
}
else -> false
}
"filterTouchesWhenObscured" -> when {
arg is Boolean -> {
v.setFilterTouchesWhenObscured(arg)
true
}
else -> false
}
"fitsSystemWindows" -> when {
arg is Boolean -> {
v.setFitsSystemWindows(arg)
true
}
else -> false
}
"focusable" -> when {
arg is Boolean -> {
v.setFocusable(arg)
true
}
else -> false
}
"focusableInTouchMode" -> when {
arg is Boolean -> {
v.setFocusableInTouchMode(arg)
true
}
else -> false
}
"hapticFeedbackEnabled" -> when {
arg is Boolean -> {
v.setHapticFeedbackEnabled(arg)
true
}
else -> false
}
"hasTransientState" -> when {
arg is Boolean -> {
v.setHasTransientState(arg)
true
}
else -> false
}
"horizontalFadingEdgeEnabled" -> when {
arg is Boolean -> {
v.setHorizontalFadingEdgeEnabled(arg)
true
}
else -> false
}
"horizontalScrollBarEnabled" -> when {
arg is Boolean -> {
v.setHorizontalScrollBarEnabled(arg)
true
}
else -> false
}
"hovered" -> when {
arg is Boolean -> {
v.setHovered(arg)
true
}
else -> false
}
"id" -> when {
arg is Int -> {
v.setId(arg)
true
}
else -> false
}
"importantForAccessibility" -> when {
arg is Int -> {
v.setImportantForAccessibility(arg)
true
}
else -> false
}
"keepScreenOn" -> when {
arg is Boolean -> {
v.setKeepScreenOn(arg)
true
}
else -> false
}
"labelFor" -> when {
arg is Int -> {
v.setLabelFor(arg)
true
}
else -> false
}
"layerPaint" -> when {
arg is Paint? -> {
v.setLayerPaint(arg)
true
}
else -> false
}
"layoutDirection" -> when {
arg is Int -> {
v.setLayoutDirection(arg)
true
}
else -> false
}
"layoutParams" -> when {
arg is ViewGroup.LayoutParams -> {
v.setLayoutParams(arg)
true
}
else -> false
}
"left" -> when {
arg is Int -> {
v.setLeft(arg)
true
}
else -> false
}
"longClickable" -> when {
arg is Boolean -> {
v.setLongClickable(arg)
true
}
else -> false
}
"minimumHeight" -> when {
arg is Int -> {
v.setMinimumHeight(dip(arg))
true
}
else -> false
}
"minimumWidth" -> when {
arg is Int -> {
v.setMinimumWidth(dip(arg))
true
}
else -> false
}
"nestedScrollingEnabled" -> when {
arg is Boolean -> {
v.setNestedScrollingEnabled(arg)
true
}
else -> false
}
"nextFocusDownId" -> when {
arg is Int -> {
v.setNextFocusDownId(arg)
true
}
else -> false
}
"nextFocusForwardId" -> when {
arg is Int -> {
v.setNextFocusForwardId(arg)
true
}
else -> false
}
"nextFocusLeftId" -> when {
arg is Int -> {
v.setNextFocusLeftId(arg)
true
}
else -> false
}
"nextFocusRightId" -> when {
arg is Int -> {
v.setNextFocusRightId(arg)
true
}
else -> false
}
"nextFocusUpId" -> when {
arg is Int -> {
v.setNextFocusUpId(arg)
true
}
else -> false
}
"onApplyWindowInsets" -> when {
arg == null -> {
v.setOnApplyWindowInsetsListener(null as? View.OnApplyWindowInsetsListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: WindowInsets) -> WindowInsets)?
v.setOnApplyWindowInsetsListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
"onClick" -> when {
arg == null -> {
v.setOnClickListener(null as? View.OnClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View) -> Unit)?
v.setOnClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
"onCreateContextMenu" -> when {
arg == null -> {
v.setOnCreateContextMenuListener(null as? View.OnCreateContextMenuListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: ContextMenu,
arg1: View,
arg2: ContextMenu.ContextMenuInfo
) -> Unit)?
v.setOnCreateContextMenuListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
"onDrag" -> when {
arg == null -> {
v.setOnDragListener(null as? View.OnDragListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: DragEvent) -> Boolean)?
v.setOnDragListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
"onFocusChange" -> when {
arg == null -> {
v.setOnFocusChangeListener(null as? View.OnFocusChangeListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: Boolean) -> Unit)?
v.setOnFocusChangeListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
"onGenericMotion" -> when {
arg == null -> {
v.setOnGenericMotionListener(null as? View.OnGenericMotionListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: MotionEvent) -> Boolean)?
v.setOnGenericMotionListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
"onHover" -> when {
arg == null -> {
v.setOnHoverListener(null as? View.OnHoverListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: MotionEvent) -> Boolean)?
v.setOnHoverListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
"onKey" -> when {
arg == null -> {
v.setOnKeyListener(null as? View.OnKeyListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: View,
arg1: Int,
arg2: KeyEvent
) -> Boolean)?
v.setOnKeyListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
"onLongClick" -> when {
arg == null -> {
v.setOnLongClickListener(null as? View.OnLongClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View) -> Boolean)?
v.setOnLongClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
"onSystemUiVisibilityChange" -> when {
arg == null -> {
v.setOnSystemUiVisibilityChangeListener(null as? View.OnSystemUiVisibilityChangeListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: Int) -> Unit)?
v.setOnSystemUiVisibilityChangeListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
"onTouch" -> when {
arg == null -> {
v.setOnTouchListener(null as? View.OnTouchListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: MotionEvent) -> Boolean)?
v.setOnTouchListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
"outlineProvider" -> when {
arg is ViewOutlineProvider -> {
v.setOutlineProvider(arg)
true
}
else -> false
}
"overScrollMode" -> when {
arg is Int -> {
v.setOverScrollMode(arg)
true
}
else -> false
}
"pivotX" -> when {
arg is Float -> {
v.setPivotX(arg)
true
}
else -> false
}
"pivotY" -> when {
arg is Float -> {
v.setPivotY(arg)
true
}
else -> false
}
"pressed" -> when {
arg is Boolean -> {
v.setPressed(arg)
true
}
else -> false
}
"right" -> when {
arg is Int -> {
v.setRight(arg)
true
}
else -> false
}
"rotation" -> when {
arg is Float -> {
v.setRotation(arg)
true
}
else -> false
}
"rotationX" -> when {
arg is Float -> {
v.setRotationX(arg)
true
}
else -> false
}
"rotationY" -> when {
arg is Float -> {
v.setRotationY(arg)
true
}
else -> false
}
"saveEnabled" -> when {
arg is Boolean -> {
v.setSaveEnabled(arg)
true
}
else -> false
}
"saveFromParentEnabled" -> when {
arg is Boolean -> {
v.setSaveFromParentEnabled(arg)
true
}
else -> false
}
"scaleX" -> when {
arg is Float -> {
v.setScaleX(arg)
true
}
else -> false
}
"scaleY" -> when {
arg is Float -> {
v.setScaleY(arg)
true
}
else -> false
}
"scrollBarDefaultDelayBeforeFade" -> when {
arg is Int -> {
v.setScrollBarDefaultDelayBeforeFade(arg)
true
}
else -> false
}
"scrollBarFadeDuration" -> when {
arg is Int -> {
v.setScrollBarFadeDuration(arg)
true
}
else -> false
}
"scrollBarSize" -> when {
arg is Int -> {
v.setScrollBarSize(arg)
true
}
else -> false
}
"scrollBarStyle" -> when {
arg is Int -> {
v.setScrollBarStyle(arg)
true
}
else -> false
}
"scrollContainer" -> when {
arg is Boolean -> {
v.setScrollContainer(arg)
true
}
else -> false
}
"scrollX" -> when {
arg is Int -> {
v.setScrollX(arg)
true
}
else -> false
}
"scrollY" -> when {
arg is Int -> {
v.setScrollY(arg)
true
}
else -> false
}
"scrollbarFadingEnabled" -> when {
arg is Boolean -> {
v.setScrollbarFadingEnabled(arg)
true
}
else -> false
}
"selected" -> when {
arg is Boolean -> {
v.setSelected(arg)
true
}
else -> false
}
"soundEffectsEnabled" -> when {
arg is Boolean -> {
v.setSoundEffectsEnabled(arg)
true
}
else -> false
}
"stateListAnimator" -> when {
arg is StateListAnimator -> {
v.setStateListAnimator(arg)
true
}
else -> false
}
"systemUiVisibility" -> when {
arg is Int -> {
v.setSystemUiVisibility(arg)
true
}
else -> false
}
"tag" -> when {
arg is Any -> {
v.setTag(arg)
true
}
else -> false
}
"textAlignment" -> when {
arg is Int -> {
v.setTextAlignment(arg)
true
}
else -> false
}
"textDirection" -> when {
arg is Int -> {
v.setTextDirection(arg)
true
}
else -> false
}
"top" -> when {
arg is Int -> {
v.setTop(arg)
true
}
else -> false
}
"touchDelegate" -> when {
arg is TouchDelegate -> {
v.setTouchDelegate(arg)
true
}
else -> false
}
"transitionName" -> when {
arg is String -> {
v.setTransitionName(arg)
true
}
else -> false
}
"translationX" -> when {
arg is Float -> {
v.setTranslationX(arg)
true
}
else -> false
}
"translationY" -> when {
arg is Float -> {
v.setTranslationY(arg)
true
}
else -> false
}
"translationZ" -> when {
arg is Float -> {
v.setTranslationZ(arg)
true
}
else -> false
}
"verticalFadingEdgeEnabled" -> when {
arg is Boolean -> {
v.setVerticalFadingEdgeEnabled(arg)
true
}
else -> false
}
"verticalScrollBarEnabled" -> when {
arg is Boolean -> {
v.setVerticalScrollBarEnabled(arg)
true
}
else -> false
}
"verticalScrollbarPosition" -> when {
arg is Int -> {
v.setVerticalScrollbarPosition(arg)
true
}
else -> false
}
"visibility" -> when {
arg is Int -> {
v.setVisibility(arg)
true
}
else -> false
}
"willNotCacheDrawing" -> when {
arg is Boolean -> {
v.setWillNotCacheDrawing(arg)
true
}
else -> false
}
"willNotDraw" -> when {
arg is Boolean -> {
v.setWillNotDraw(arg)
true
}
else -> false
}
"x" -> when {
arg is Float -> {
v.setX(arg)
true
}
else -> false
}
"y" -> when {
arg is Float -> {
v.setY(arg)
true
}
else -> false
}
"z" -> when {
arg is Float -> {
v.setZ(arg)
true
}
else -> false
}
"addStatesFromChildren" -> when {
v is ViewGroup && arg is Boolean -> {
v.setAddStatesFromChildren(arg)
true
}
else -> false
}
"alwaysDrawnWithCacheEnabled" -> when {
v is ViewGroup && arg is Boolean -> {
v.setAlwaysDrawnWithCacheEnabled(arg)
true
}
else -> false
}
"animationCacheEnabled" -> when {
v is ViewGroup && arg is Boolean -> {
v.setAnimationCacheEnabled(arg)
true
}
else -> false
}
"clipChildren" -> when {
v is ViewGroup && arg is Boolean -> {
v.setClipChildren(arg)
true
}
else -> false
}
"clipToPadding" -> when {
v is ViewGroup && arg is Boolean -> {
v.setClipToPadding(arg)
true
}
else -> false
}
"descendantFocusability" -> when {
v is ViewGroup && arg is Int -> {
v.setDescendantFocusability(arg)
true
}
else -> false
}
"layoutAnimation" -> when {
v is ViewGroup && arg is LayoutAnimationController -> {
v.setLayoutAnimation(arg)
true
}
else -> false
}
"layoutAnimationListener" -> when {
v is ViewGroup && arg is Animation.AnimationListener -> {
v.setLayoutAnimationListener(arg)
true
}
else -> false
}
"layoutMode" -> when {
v is ViewGroup && arg is Int -> {
v.setLayoutMode(arg)
true
}
else -> false
}
"layoutTransition" -> when {
v is ViewGroup && arg is LayoutTransition -> {
v.setLayoutTransition(arg)
true
}
else -> false
}
"motionEventSplittingEnabled" -> when {
v is ViewGroup && arg is Boolean -> {
v.setMotionEventSplittingEnabled(arg)
true
}
else -> false
}
"onHierarchyChange" -> when {
v is ViewGroup -> when {
arg == null -> {
v.setOnHierarchyChangeListener(null as? ViewGroup.OnHierarchyChangeListener?)
true
}
arg is ViewGroup.OnHierarchyChangeListener -> {
v.setOnHierarchyChangeListener(object : ViewGroup.OnHierarchyChangeListener {
override fun onChildViewAdded(arg0: View, arg1: View): Unit = arg.onChildViewAdded(arg0,
arg1).also { Inkremental.render() }
override fun onChildViewRemoved(arg0: View, arg1: View): Unit =
arg.onChildViewRemoved(arg0, arg1).also { Inkremental.render() }
})
true
}
else -> false
}
else -> false
}
"persistentDrawingCache" -> when {
v is ViewGroup && arg is Int -> {
v.setPersistentDrawingCache(arg)
true
}
else -> false
}
"touchscreenBlocksFocus" -> when {
v is ViewGroup && arg is Boolean -> {
v.setTouchscreenBlocksFocus(arg)
true
}
else -> false
}
"transitionGroup" -> when {
v is ViewGroup && arg is Boolean -> {
v.setTransitionGroup(arg)
true
}
else -> false
}
"inflatedId" -> when {
v is ViewStub && arg is Int -> {
v.setInflatedId(arg)
true
}
else -> false
}
"layoutInflater" -> when {
v is ViewStub && arg is LayoutInflater -> {
v.setLayoutInflater(arg)
true
}
else -> false
}
"layoutResource" -> when {
v is ViewStub && arg is Int -> {
v.setLayoutResource(arg)
true
}
else -> false
}
"onInflate" -> when {
v is ViewStub -> when {
arg == null -> {
v.setOnInflateListener(null as? ViewStub.OnInflateListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: ViewStub, arg1: View) -> Unit)?
v.setOnInflateListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"downloadListener" -> when {
v is WebView && arg is DownloadListener -> {
v.setDownloadListener(arg)
true
}
else -> false
}
"findListener" -> when {
v is WebView && arg is WebView.FindListener -> {
v.setFindListener(arg)
true
}
else -> false
}
"horizontalScrollbarOverlay" -> when {
v is WebView && arg is Boolean -> {
v.setHorizontalScrollbarOverlay(arg)
true
}
else -> false
}
"initialScale" -> when {
v is WebView && arg is Int -> {
v.setInitialScale(arg)
true
}
else -> false
}
"networkAvailable" -> when {
v is WebView && arg is Boolean -> {
v.setNetworkAvailable(arg)
true
}
else -> false
}
"verticalScrollbarOverlay" -> when {
v is WebView && arg is Boolean -> {
v.setVerticalScrollbarOverlay(arg)
true
}
else -> false
}
"webChromeClient" -> when {
v is WebView && arg is WebChromeClient -> {
v.setWebChromeClient(arg)
true
}
else -> false
}
"webViewClient" -> when {
v is WebView && arg is WebViewClient -> {
v.setWebViewClient(arg)
true
}
else -> false
}
"cacheColorHint" -> when {
v is AbsListView && arg is Int -> {
v.setCacheColorHint(arg)
true
}
else -> false
}
"choiceMode" -> when {
v is AbsListView && arg is Int -> {
v.setChoiceMode(arg)
true
}
else -> false
}
"drawSelectorOnTop" -> when {
v is AbsListView && arg is Boolean -> {
v.setDrawSelectorOnTop(arg)
true
}
else -> false
}
"fastScrollAlwaysVisible" -> when {
v is AbsListView && arg is Boolean -> {
v.setFastScrollAlwaysVisible(arg)
true
}
else -> false
}
"fastScrollEnabled" -> when {
v is AbsListView && arg is Boolean -> {
v.setFastScrollEnabled(arg)
true
}
else -> false
}
"fastScrollStyle" -> when {
v is AbsListView && arg is Int -> {
v.setFastScrollStyle(arg)
true
}
else -> false
}
"filterText" -> when {
v is AbsListView && arg is String -> {
v.setFilterText(arg)
true
}
else -> false
}
"friction" -> when {
v is AbsListView && arg is Float -> {
v.setFriction(arg)
true
}
else -> false
}
"multiChoiceModeListener" -> when {
v is AbsListView && arg is AbsListView.MultiChoiceModeListener -> {
v.setMultiChoiceModeListener(arg)
true
}
else -> false
}
"onScroll" -> when {
v is AbsListView -> when {
arg == null -> {
v.setOnScrollListener(null as? AbsListView.OnScrollListener?)
true
}
arg is AbsListView.OnScrollListener -> {
v.setOnScrollListener(object : AbsListView.OnScrollListener {
override fun onScroll(
arg0: AbsListView,
arg1: Int,
arg2: Int,
arg3: Int
): Unit = arg.onScroll(arg0, arg1, arg2, arg3).also { Inkremental.render() }
override fun onScrollStateChanged(arg0: AbsListView, arg1: Int): Unit =
arg.onScrollStateChanged(arg0, arg1).also { Inkremental.render() }
})
true
}
else -> false
}
v is NumberPicker -> when {
arg == null -> {
v.setOnScrollListener(null as? NumberPicker.OnScrollListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: NumberPicker, arg1: Int) -> Unit)?
v.setOnScrollListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"recyclerListener" -> when {
v is AbsListView && arg is AbsListView.RecyclerListener -> {
v.setRecyclerListener(arg)
true
}
else -> false
}
"remoteViewsAdapter" -> when {
v is AbsListView && arg is Intent -> {
v.setRemoteViewsAdapter(arg)
true
}
v is AdapterViewAnimator && arg is Intent -> {
v.setRemoteViewsAdapter(arg)
true
}
else -> false
}
"scrollingCacheEnabled" -> when {
v is AbsListView && arg is Boolean -> {
v.setScrollingCacheEnabled(arg)
true
}
else -> false
}
"selector" -> when {
v is AbsListView && arg is Drawable -> {
v.setSelector(arg)
true
}
v is AbsListView && arg is Int -> {
v.setSelector(arg)
true
}
else -> false
}
"smoothScrollbarEnabled" -> when {
v is AbsListView && arg is Boolean -> {
v.setSmoothScrollbarEnabled(arg)
true
}
else -> false
}
"stackFromBottom" -> when {
v is AbsListView && arg is Boolean -> {
v.setStackFromBottom(arg)
true
}
else -> false
}
"textFilterEnabled" -> when {
v is AbsListView && arg is Boolean -> {
v.setTextFilterEnabled(arg)
true
}
else -> false
}
"transcriptMode" -> when {
v is AbsListView && arg is Int -> {
v.setTranscriptMode(arg)
true
}
else -> false
}
"velocityScale" -> when {
v is AbsListView && arg is Float -> {
v.setVelocityScale(arg)
true
}
else -> false
}
"keyProgressIncrement" -> when {
v is AbsSeekBar && arg is Int -> {
v.setKeyProgressIncrement(arg)
true
}
else -> false
}
"splitTrack" -> when {
v is AbsSeekBar && arg is Boolean -> {
v.setSplitTrack(arg)
true
}
v is Switch && arg is Boolean -> {
v.setSplitTrack(arg)
true
}
else -> false
}
"thumb" -> when {
v is AbsSeekBar && arg is Drawable -> {
v.setThumb(arg)
true
}
else -> false
}
"thumbOffset" -> when {
v is AbsSeekBar && arg is Int -> {
v.setThumbOffset(arg)
true
}
else -> false
}
"thumbTintList" -> when {
v is AbsSeekBar && arg is ColorStateList? -> {
v.setThumbTintList(arg)
true
}
else -> false
}
"thumbTintMode" -> when {
v is AbsSeekBar && arg is PorterDuff.Mode? -> {
v.setThumbTintMode(arg)
true
}
else -> false
}
"onMenuItemClick" -> when {
v is ActionMenuView -> when {
arg == null -> {
v.setOnMenuItemClickListener(null as? ActionMenuView.OnMenuItemClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: MenuItem) -> Boolean)?
v.setOnMenuItemClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
v is Toolbar -> when {
arg == null -> {
v.setOnMenuItemClickListener(null as? Toolbar.OnMenuItemClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: MenuItem) -> Boolean)?
v.setOnMenuItemClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"popupTheme" -> when {
v is ActionMenuView && arg is Int -> {
v.setPopupTheme(arg)
true
}
v is Toolbar && arg is Int -> {
v.setPopupTheme(arg)
true
}
else -> false
}
"adapter" -> when {
v is AdapterView<*> && arg is Adapter -> {
(v as android.widget.AdapterView<android.widget.Adapter>).setAdapter(arg)
true
}
v is ExpandableListView && arg is ExpandableListAdapter -> {
v.setAdapter(arg)
true
}
else -> false
}
"emptyView" -> when {
v is AdapterView<*> && arg is View -> {
(v as android.widget.AdapterView<android.widget.Adapter>).setEmptyView(arg)
true
}
else -> false
}
"onItemClick" -> when {
v is AdapterView<*> -> when {
arg == null -> {
(v as android.widget.AdapterView<android.widget.Adapter>).setOnItemClickListener(null as?
AdapterView.OnItemClickListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: AdapterView<*>,
arg1: View,
arg2: Int,
arg3: Long
) -> Unit)?
v.setOnItemClickListener { arg0, arg1, arg2, arg3 ->
arg(arg0, arg1, arg2, arg3).also { Inkremental.render() }
}
true
}
else -> false
}
v is AutoCompleteTextView -> when {
arg == null -> {
v.setOnItemClickListener(null as? AdapterView.OnItemClickListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: AdapterView<*>,
arg1: View,
arg2: Int,
arg3: Long
) -> Unit)?
v.setOnItemClickListener { arg0, arg1, arg2, arg3 ->
arg(arg0, arg1, arg2, arg3).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onItemLongClick" -> when {
v is AdapterView<*> -> when {
arg == null -> {
(v as android.widget.AdapterView<android.widget.Adapter>).setOnItemLongClickListener(null
as? AdapterView.OnItemLongClickListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: AdapterView<*>,
arg1: View,
arg2: Int,
arg3: Long
) -> Boolean)?
v.setOnItemLongClickListener { arg0, arg1, arg2, arg3 ->
arg(arg0, arg1, arg2, arg3).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onItemSelected" -> when {
v is AdapterView<*> -> when {
arg == null -> {
(v as android.widget.AdapterView<android.widget.Adapter>).setOnItemSelectedListener(null
as? AdapterView.OnItemSelectedListener?)
true
}
arg is AdapterView.OnItemSelectedListener -> {
v.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
arg0: AdapterView<*>,
arg1: View,
arg2: Int,
arg3: Long
): Unit = arg.onItemSelected(arg0, arg1, arg2, arg3).also { Inkremental.render() }
override fun onNothingSelected(arg0: AdapterView<*>): Unit =
arg.onNothingSelected(arg0).also { Inkremental.render() }
})
true
}
else -> false
}
v is AutoCompleteTextView -> when {
arg == null -> {
v.setOnItemSelectedListener(null as? AdapterView.OnItemSelectedListener?)
true
}
arg is AdapterView.OnItemSelectedListener -> {
v.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
arg0: AdapterView<*>,
arg1: View,
arg2: Int,
arg3: Long
): Unit = arg.onItemSelected(arg0, arg1, arg2, arg3).also { Inkremental.render() }
override fun onNothingSelected(arg0: AdapterView<*>): Unit =
arg.onNothingSelected(arg0).also { Inkremental.render() }
})
true
}
else -> false
}
else -> false
}
"selection" -> when {
v is AdapterView<*> && arg is Int -> {
(v as android.widget.AdapterView<android.widget.Adapter>).setSelection(arg)
true
}
v is EditText && arg is Int -> {
v.setSelection(arg)
true
}
else -> false
}
"animateFirstView" -> when {
v is AdapterViewAnimator && arg is Boolean -> {
v.setAnimateFirstView(arg)
true
}
v is ViewAnimator && arg is Boolean -> {
v.setAnimateFirstView(arg)
true
}
else -> false
}
"displayedChild" -> when {
v is AdapterViewAnimator && arg is Int -> {
v.setDisplayedChild(arg)
true
}
v is ViewAnimator && arg is Int -> {
v.setDisplayedChild(arg)
true
}
else -> false
}
"inAnimation" -> when {
v is ViewAnimator && arg is Animation -> {
v.setInAnimation(arg)
true
}
v is AdapterViewAnimator && arg is ObjectAnimator -> {
v.setInAnimation(arg)
true
}
else -> false
}
"outAnimation" -> when {
v is ViewAnimator && arg is Animation -> {
v.setOutAnimation(arg)
true
}
v is AdapterViewAnimator && arg is ObjectAnimator -> {
v.setOutAnimation(arg)
true
}
else -> false
}
"autoStart" -> when {
v is AdapterViewFlipper && arg is Boolean -> {
v.setAutoStart(arg)
true
}
v is ViewFlipper && arg is Boolean -> {
v.setAutoStart(arg)
true
}
else -> false
}
"flipInterval" -> when {
v is AdapterViewFlipper && arg is Int -> {
v.setFlipInterval(arg)
true
}
v is ViewFlipper && arg is Int -> {
v.setFlipInterval(arg)
true
}
else -> false
}
"completionHint" -> when {
v is AutoCompleteTextView && arg is CharSequence -> {
v.setCompletionHint(arg)
true
}
else -> false
}
"dropDownAnchor" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setDropDownAnchor(arg)
true
}
else -> false
}
"dropDownBackgroundDrawable" -> when {
v is AutoCompleteTextView && arg is Drawable -> {
v.setDropDownBackgroundDrawable(arg)
true
}
else -> false
}
"dropDownBackgroundResource" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setDropDownBackgroundResource(arg)
true
}
else -> false
}
"dropDownHeight" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setDropDownHeight(arg)
true
}
else -> false
}
"dropDownHorizontalOffset" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setDropDownHorizontalOffset(arg)
true
}
v is Spinner && arg is Int -> {
v.setDropDownHorizontalOffset(arg)
true
}
else -> false
}
"dropDownVerticalOffset" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setDropDownVerticalOffset(arg)
true
}
v is Spinner && arg is Int -> {
v.setDropDownVerticalOffset(arg)
true
}
else -> false
}
"dropDownWidth" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setDropDownWidth(arg)
true
}
v is Spinner && arg is Int -> {
v.setDropDownWidth(arg)
true
}
else -> false
}
"listSelection" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setListSelection(arg)
true
}
else -> false
}
"onDismiss" -> when {
v is AutoCompleteTextView -> when {
arg == null -> {
v.setOnDismissListener(null as? AutoCompleteTextView.OnDismissListener?)
true
}
arg is Function<*> -> {
arg as (() -> Unit)?
v.setOnDismissListener { ->
arg().also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"threshold" -> when {
v is AutoCompleteTextView && arg is Int -> {
v.setThreshold(arg)
true
}
else -> false
}
"validator" -> when {
v is AutoCompleteTextView && arg is AutoCompleteTextView.Validator -> {
v.setValidator(arg)
true
}
else -> false
}
"date" -> when {
v is CalendarView && arg is Long -> {
v.setDate(arg)
true
}
else -> false
}
"dateTextAppearance" -> when {
v is CalendarView && arg is Int -> {
v.setDateTextAppearance(arg)
true
}
else -> false
}
"firstDayOfWeek" -> when {
v is CalendarView && arg is Int -> {
v.setFirstDayOfWeek(arg)
true
}
v is DatePicker && arg is Int -> {
v.setFirstDayOfWeek(arg)
true
}
else -> false
}
"focusedMonthDateColor" -> when {
v is CalendarView && arg is Int -> {
v.setFocusedMonthDateColor(arg)
true
}
else -> false
}
"maxDate" -> when {
v is CalendarView && arg is Long -> {
v.setMaxDate(arg)
true
}
v is DatePicker && arg is Long -> {
v.setMaxDate(arg)
true
}
else -> false
}
"minDate" -> when {
v is CalendarView && arg is Long -> {
v.setMinDate(arg)
true
}
v is DatePicker && arg is Long -> {
v.setMinDate(arg)
true
}
else -> false
}
"onDateChange" -> when {
v is CalendarView -> when {
arg == null -> {
v.setOnDateChangeListener(null as? CalendarView.OnDateChangeListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: CalendarView,
arg1: Int,
arg2: Int,
arg3: Int
) -> Unit)?
v.setOnDateChangeListener { arg0, arg1, arg2, arg3 ->
arg(arg0, arg1, arg2, arg3).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"selectedDateVerticalBar" -> when {
v is CalendarView && arg is Drawable -> {
v.setSelectedDateVerticalBar(arg)
true
}
v is CalendarView && arg is Int -> {
v.setSelectedDateVerticalBar(arg)
true
}
else -> false
}
"selectedWeekBackgroundColor" -> when {
v is CalendarView && arg is Int -> {
v.setSelectedWeekBackgroundColor(arg)
true
}
else -> false
}
"showWeekNumber" -> when {
v is CalendarView && arg is Boolean -> {
v.setShowWeekNumber(arg)
true
}
else -> false
}
"shownWeekCount" -> when {
v is CalendarView && arg is Int -> {
v.setShownWeekCount(arg)
true
}
else -> false
}
"unfocusedMonthDateColor" -> when {
v is CalendarView && arg is Int -> {
v.setUnfocusedMonthDateColor(arg)
true
}
else -> false
}
"weekDayTextAppearance" -> when {
v is CalendarView && arg is Int -> {
v.setWeekDayTextAppearance(arg)
true
}
else -> false
}
"weekNumberColor" -> when {
v is CalendarView && arg is Int -> {
v.setWeekNumberColor(arg)
true
}
else -> false
}
"weekSeparatorLineColor" -> when {
v is CalendarView && arg is Int -> {
v.setWeekSeparatorLineColor(arg)
true
}
else -> false
}
"checkMarkDrawable" -> when {
v is CheckedTextView && arg is Drawable? -> {
v.setCheckMarkDrawable(arg)
true
}
v is CheckedTextView && arg is Int -> {
v.setCheckMarkDrawable(arg)
true
}
else -> false
}
"checkMarkTintList" -> when {
v is CheckedTextView && arg is ColorStateList? -> {
v.setCheckMarkTintList(arg)
true
}
else -> false
}
"checkMarkTintMode" -> when {
v is CheckedTextView && arg is PorterDuff.Mode? -> {
v.setCheckMarkTintMode(arg)
true
}
else -> false
}
"checked" -> when {
v is CheckedTextView && arg is Boolean -> {
v.setChecked(arg)
true
}
v is CompoundButton && arg is Boolean -> {
v.setChecked(arg)
true
}
else -> false
}
"base" -> when {
v is Chronometer && arg is Long -> {
v.setBase(arg)
true
}
else -> false
}
"format" -> when {
v is Chronometer && arg is String -> {
v.setFormat(arg)
true
}
else -> false
}
"onChronometerTick" -> when {
v is Chronometer -> when {
arg == null -> {
v.setOnChronometerTickListener(null as? Chronometer.OnChronometerTickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: Chronometer) -> Unit)?
v.setOnChronometerTickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"buttonDrawable" -> when {
v is CompoundButton && arg is Drawable? -> {
v.setButtonDrawable(arg)
true
}
v is CompoundButton && arg is Int -> {
v.setButtonDrawable(arg)
true
}
else -> false
}
"buttonTintList" -> when {
v is CompoundButton && arg is ColorStateList? -> {
v.setButtonTintList(arg)
true
}
else -> false
}
"buttonTintMode" -> when {
v is CompoundButton && arg is PorterDuff.Mode? -> {
v.setButtonTintMode(arg)
true
}
else -> false
}
"onCheckedChange" -> when {
v is CompoundButton -> when {
arg == null -> {
v.setOnCheckedChangeListener(null as? CompoundButton.OnCheckedChangeListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: CompoundButton, arg1: Boolean) -> Unit)?
v.setOnCheckedChangeListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
v is RadioGroup -> when {
arg == null -> {
v.setOnCheckedChangeListener(null as? RadioGroup.OnCheckedChangeListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: RadioGroup, arg1: Int) -> Unit)?
v.setOnCheckedChangeListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"calendarViewShown" -> when {
v is DatePicker && arg is Boolean -> {
v.setCalendarViewShown(arg)
true
}
else -> false
}
"spinnersShown" -> when {
v is DatePicker && arg is Boolean -> {
v.setSpinnersShown(arg)
true
}
else -> false
}
"digitsWatcher" -> when {
v is DialerFilter && arg is TextWatcher -> {
v.setDigitsWatcher(arg)
true
}
else -> false
}
"filterWatcher" -> when {
v is DialerFilter && arg is TextWatcher -> {
v.setFilterWatcher(arg)
true
}
else -> false
}
"lettersWatcher" -> when {
v is DialerFilter && arg is TextWatcher -> {
v.setLettersWatcher(arg)
true
}
else -> false
}
"mode" -> when {
v is DialerFilter && arg is Int -> {
v.setMode(arg)
true
}
v is QuickContactBadge && arg is Int -> {
v.setMode(arg)
true
}
else -> false
}
"childDivider" -> when {
v is ExpandableListView && arg is Drawable -> {
v.setChildDivider(arg)
true
}
else -> false
}
"childIndicator" -> when {
v is ExpandableListView && arg is Drawable -> {
v.setChildIndicator(arg)
true
}
else -> false
}
"groupIndicator" -> when {
v is ExpandableListView && arg is Drawable -> {
v.setGroupIndicator(arg)
true
}
else -> false
}
"onChildClick" -> when {
v is ExpandableListView -> when {
arg == null -> {
v.setOnChildClickListener(null as? ExpandableListView.OnChildClickListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: ExpandableListView,
arg1: View,
arg2: Int,
arg3: Int,
arg4: Long
) -> Boolean)?
v.setOnChildClickListener { arg0, arg1, arg2, arg3, arg4 ->
arg(arg0, arg1, arg2, arg3, arg4).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onGroupClick" -> when {
v is ExpandableListView -> when {
arg == null -> {
v.setOnGroupClickListener(null as? ExpandableListView.OnGroupClickListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: ExpandableListView,
arg1: View,
arg2: Int,
arg3: Long
) -> Boolean)?
v.setOnGroupClickListener { arg0, arg1, arg2, arg3 ->
arg(arg0, arg1, arg2, arg3).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onGroupCollapse" -> when {
v is ExpandableListView -> when {
arg == null -> {
v.setOnGroupCollapseListener(null as? ExpandableListView.OnGroupCollapseListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: Int) -> Unit)?
v.setOnGroupCollapseListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onGroupExpand" -> when {
v is ExpandableListView -> when {
arg == null -> {
v.setOnGroupExpandListener(null as? ExpandableListView.OnGroupExpandListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: Int) -> Unit)?
v.setOnGroupExpandListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"selectedGroup" -> when {
v is ExpandableListView && arg is Int -> {
v.setSelectedGroup(arg)
true
}
else -> false
}
"foreground" -> when {
v is FrameLayout && arg is Drawable -> {
v.setForeground(arg)
true
}
else -> false
}
"foregroundGravity" -> when {
v is FrameLayout && arg is Int -> {
v.setForegroundGravity(arg)
true
}
else -> false
}
"foregroundTintList" -> when {
v is FrameLayout && arg is ColorStateList -> {
v.setForegroundTintList(arg)
true
}
else -> false
}
"foregroundTintMode" -> when {
v is FrameLayout && arg is PorterDuff.Mode -> {
v.setForegroundTintMode(arg)
true
}
else -> false
}
"measureAllChildren" -> when {
v is FrameLayout && arg is Boolean -> {
v.setMeasureAllChildren(arg)
true
}
else -> false
}
"animationDuration" -> when {
v is Gallery && arg is Int -> {
v.setAnimationDuration(arg)
true
}
else -> false
}
"callbackDuringFling" -> when {
v is Gallery && arg is Boolean -> {
v.setCallbackDuringFling(arg)
true
}
else -> false
}
"gravity" -> when {
v is Gallery && arg is Int -> {
v.setGravity(arg)
true
}
v is GridView && arg is Int -> {
v.setGravity(arg)
true
}
v is LinearLayout && arg is Int -> {
v.setGravity(arg)
true
}
v is RelativeLayout && arg is Int -> {
v.setGravity(arg)
true
}
v is Spinner && arg is Int -> {
v.setGravity(arg)
true
}
v is TextView && arg is Int -> {
v.setGravity(arg)
true
}
else -> false
}
"spacing" -> when {
v is Gallery && arg is Int -> {
v.setSpacing(arg)
true
}
else -> false
}
"unselectedAlpha" -> when {
v is Gallery && arg is Float -> {
v.setUnselectedAlpha(arg)
true
}
else -> false
}
"alignmentMode" -> when {
v is GridLayout && arg is Int -> {
v.setAlignmentMode(arg)
true
}
else -> false
}
"columnCount" -> when {
v is GridLayout && arg is Int -> {
v.setColumnCount(arg)
true
}
else -> false
}
"columnOrderPreserved" -> when {
v is GridLayout && arg is Boolean -> {
v.setColumnOrderPreserved(arg)
true
}
else -> false
}
"rowCount" -> when {
v is GridLayout && arg is Int -> {
v.setRowCount(arg)
true
}
else -> false
}
"rowOrderPreserved" -> when {
v is GridLayout && arg is Boolean -> {
v.setRowOrderPreserved(arg)
true
}
else -> false
}
"useDefaultMargins" -> when {
v is GridLayout && arg is Boolean -> {
v.setUseDefaultMargins(arg)
true
}
else -> false
}
"columnWidth" -> when {
v is GridView && arg is Int -> {
v.setColumnWidth(arg)
true
}
else -> false
}
"horizontalSpacing" -> when {
v is GridView && arg is Int -> {
v.setHorizontalSpacing(arg)
true
}
else -> false
}
"numColumns" -> when {
v is GridView && arg is Int -> {
v.setNumColumns(arg)
true
}
else -> false
}
"stretchMode" -> when {
v is GridView && arg is Int -> {
v.setStretchMode(arg)
true
}
else -> false
}
"verticalSpacing" -> when {
v is GridView && arg is Int -> {
v.setVerticalSpacing(arg)
true
}
else -> false
}
"fillViewport" -> when {
v is HorizontalScrollView && arg is Boolean -> {
v.setFillViewport(arg)
true
}
v is ScrollView && arg is Boolean -> {
v.setFillViewport(arg)
true
}
else -> false
}
"smoothScrollingEnabled" -> when {
v is HorizontalScrollView && arg is Boolean -> {
v.setSmoothScrollingEnabled(arg)
true
}
v is ScrollView && arg is Boolean -> {
v.setSmoothScrollingEnabled(arg)
true
}
else -> false
}
"imageDrawable" -> when {
v is ImageSwitcher && arg is Drawable -> {
v.setImageDrawable(arg)
true
}
v is ImageView && arg is Drawable? -> {
v.setImageDrawable(arg)
true
}
else -> false
}
"imageResource" -> when {
v is ImageSwitcher && arg is Int -> {
v.setImageResource(arg)
true
}
v is ImageView && arg is Int -> {
v.setImageResource(arg)
true
}
else -> false
}
"imageURI" -> when {
v is ImageSwitcher && arg is Uri -> {
v.setImageURI(arg)
true
}
v is ImageView && arg is Uri? -> {
v.setImageURI(arg)
true
}
else -> false
}
"adjustViewBounds" -> when {
v is ImageView && arg is Boolean -> {
v.setAdjustViewBounds(arg)
true
}
else -> false
}
"baseline" -> when {
v is ImageView && arg is Int -> {
v.setBaseline(arg)
true
}
else -> false
}
"baselineAlignBottom" -> when {
v is ImageView && arg is Boolean -> {
v.setBaselineAlignBottom(arg)
true
}
else -> false
}
"colorFilter" -> when {
v is ImageView && arg is ColorFilter -> {
v.setColorFilter(arg)
true
}
v is ImageView && arg is Int -> {
v.setColorFilter(arg)
true
}
else -> false
}
"cropToPadding" -> when {
v is ImageView && arg is Boolean -> {
v.setCropToPadding(arg)
true
}
else -> false
}
"imageAlpha" -> when {
v is ImageView && arg is Int -> {
v.setImageAlpha(arg)
true
}
else -> false
}
"imageBitmap" -> when {
v is ImageView && arg is Bitmap -> {
v.setImageBitmap(arg)
true
}
else -> false
}
"imageLevel" -> when {
v is ImageView && arg is Int -> {
v.setImageLevel(arg)
true
}
else -> false
}
"imageMatrix" -> when {
v is ImageView && arg is Matrix -> {
v.setImageMatrix(arg)
true
}
else -> false
}
"imageTintList" -> when {
v is ImageView && arg is ColorStateList? -> {
v.setImageTintList(arg)
true
}
else -> false
}
"imageTintMode" -> when {
v is ImageView && arg is PorterDuff.Mode? -> {
v.setImageTintMode(arg)
true
}
else -> false
}
"maxHeight" -> when {
v is ImageView && arg is Int -> {
v.setMaxHeight(arg)
true
}
v is TextView && arg is Int -> {
v.setMaxHeight(arg)
true
}
else -> false
}
"maxWidth" -> when {
v is ImageView && arg is Int -> {
v.setMaxWidth(arg)
true
}
v is SearchView && arg is Int -> {
v.setMaxWidth(arg)
true
}
v is TextView && arg is Int -> {
v.setMaxWidth(arg)
true
}
else -> false
}
"scaleType" -> when {
v is ImageView && arg is ImageView.ScaleType -> {
v.setScaleType(arg)
true
}
else -> false
}
"baselineAligned" -> when {
v is LinearLayout && arg is Boolean -> {
v.setBaselineAligned(arg)
true
}
else -> false
}
"baselineAlignedChildIndex" -> when {
v is LinearLayout && arg is Int -> {
v.setBaselineAlignedChildIndex(arg)
true
}
else -> false
}
"dividerDrawable" -> when {
v is LinearLayout && arg is Drawable -> {
v.setDividerDrawable(arg)
true
}
v is TabWidget && arg is Int -> {
v.setDividerDrawable(arg)
true
}
else -> false
}
"dividerPadding" -> when {
v is LinearLayout && arg is Int -> {
v.setDividerPadding(arg)
true
}
else -> false
}
"horizontalGravity" -> when {
v is LinearLayout && arg is Int -> {
v.setHorizontalGravity(arg)
true
}
v is RelativeLayout && arg is Int -> {
v.setHorizontalGravity(arg)
true
}
else -> false
}
"measureWithLargestChildEnabled" -> when {
v is LinearLayout && arg is Boolean -> {
v.setMeasureWithLargestChildEnabled(arg)
true
}
else -> false
}
"showDividers" -> when {
v is LinearLayout && arg is Int -> {
v.setShowDividers(arg)
true
}
else -> false
}
"verticalGravity" -> when {
v is LinearLayout && arg is Int -> {
v.setVerticalGravity(arg)
true
}
v is RelativeLayout && arg is Int -> {
v.setVerticalGravity(arg)
true
}
else -> false
}
"weightSum" -> when {
v is LinearLayout && arg is Float -> {
v.setWeightSum(arg)
true
}
else -> false
}
"divider" -> when {
v is ListView && arg is Drawable? -> {
v.setDivider(arg)
true
}
else -> false
}
"dividerHeight" -> when {
v is ListView && arg is Int -> {
v.setDividerHeight(arg)
true
}
else -> false
}
"footerDividersEnabled" -> when {
v is ListView && arg is Boolean -> {
v.setFooterDividersEnabled(arg)
true
}
else -> false
}
"headerDividersEnabled" -> when {
v is ListView && arg is Boolean -> {
v.setHeaderDividersEnabled(arg)
true
}
else -> false
}
"itemsCanFocus" -> when {
v is ListView && arg is Boolean -> {
v.setItemsCanFocus(arg)
true
}
else -> false
}
"overscrollFooter" -> when {
v is ListView && arg is Drawable -> {
v.setOverscrollFooter(arg)
true
}
else -> false
}
"overscrollHeader" -> when {
v is ListView && arg is Drawable -> {
v.setOverscrollHeader(arg)
true
}
else -> false
}
"anchorView" -> when {
v is MediaController && arg is View -> {
v.setAnchorView(arg)
true
}
else -> false
}
"mediaPlayer" -> when {
v is MediaController && arg is MediaController.MediaPlayerControl -> {
v.setMediaPlayer(arg)
true
}
else -> false
}
"tokenizer" -> when {
v is MultiAutoCompleteTextView && arg is MultiAutoCompleteTextView.Tokenizer -> {
v.setTokenizer(arg)
true
}
else -> false
}
"displayedValues" -> when {
v is NumberPicker && arg is Array<*> -> {
v.setDisplayedValues(arg as? Array<String>)
true
}
else -> false
}
"formatter" -> when {
v is NumberPicker && arg is NumberPicker.Formatter -> {
v.setFormatter(arg)
true
}
else -> false
}
"maxValue" -> when {
v is NumberPicker && arg is Int -> {
v.setMaxValue(arg)
true
}
else -> false
}
"minValue" -> when {
v is NumberPicker && arg is Int -> {
v.setMinValue(arg)
true
}
else -> false
}
"onLongPressUpdateInterval" -> when {
v is NumberPicker && arg is Long -> {
v.setOnLongPressUpdateInterval(arg)
true
}
else -> false
}
"onValueChanged" -> when {
v is NumberPicker -> when {
arg == null -> {
v.setOnValueChangedListener(null as? NumberPicker.OnValueChangeListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: NumberPicker,
arg1: Int,
arg2: Int
) -> Unit)?
v.setOnValueChangedListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"value" -> when {
v is NumberPicker && arg is Int -> {
v.setValue(arg)
true
}
else -> false
}
"wrapSelectorWheel" -> when {
v is NumberPicker && arg is Boolean -> {
v.setWrapSelectorWheel(arg)
true
}
else -> false
}
"indeterminate" -> when {
v is ProgressBar && arg is Boolean -> {
v.setIndeterminate(arg)
true
}
else -> false
}
"indeterminateDrawable" -> when {
v is ProgressBar && arg is Drawable -> {
v.setIndeterminateDrawable(arg)
true
}
else -> false
}
"indeterminateDrawableTiled" -> when {
v is ProgressBar && arg is Drawable -> {
v.setIndeterminateDrawableTiled(arg)
true
}
else -> false
}
"indeterminateTintList" -> when {
v is ProgressBar && arg is Int? -> {
if(arg != null) {
v.setIndeterminateTintList(ColorStateList.valueOf(v.resources.getColor(arg)))
} else {
v.setIndeterminateTintList(null)
}
true
}
else -> false
}
"indeterminateTintMode" -> when {
v is ProgressBar && arg is PorterDuff.Mode? -> {
v.setIndeterminateTintMode(arg)
true
}
else -> false
}
"interpolator" -> when {
v is ProgressBar && arg is Interpolator -> {
v.setInterpolator(arg)
true
}
else -> false
}
"max" -> when {
v is ProgressBar && arg is Int -> {
v.setMax(arg)
true
}
else -> false
}
"progress" -> when {
v is ProgressBar && arg is Int -> {
v.setProgress(arg)
true
}
else -> false
}
"progressBackgroundTintList" -> when {
v is ProgressBar && arg is Int? -> {
if(arg != null) {
v.setProgressBackgroundTintList(ColorStateList.valueOf(v.resources.getColor(arg)))
} else {
v.setProgressBackgroundTintList(null)
}
true
}
else -> false
}
"progressBackgroundTintMode" -> when {
v is ProgressBar && arg is PorterDuff.Mode? -> {
v.setProgressBackgroundTintMode(arg)
true
}
else -> false
}
"progressDrawable" -> when {
v is ProgressBar && arg is Drawable -> {
v.setProgressDrawable(arg)
true
}
else -> false
}
"progressDrawableTiled" -> when {
v is ProgressBar && arg is Drawable -> {
v.setProgressDrawableTiled(arg)
true
}
else -> false
}
"progressTintList" -> when {
v is ProgressBar && arg is Int? -> {
if(arg != null) {
v.setProgressTintList(ColorStateList.valueOf(v.resources.getColor(arg)))
} else {
v.setProgressTintList(null)
}
true
}
else -> false
}
"progressTintMode" -> when {
v is ProgressBar && arg is PorterDuff.Mode? -> {
v.setProgressTintMode(arg)
true
}
else -> false
}
"secondaryProgress" -> when {
v is ProgressBar && arg is Int -> {
v.setSecondaryProgress(arg)
true
}
else -> false
}
"secondaryProgressTintList" -> when {
v is ProgressBar && arg is Int? -> {
if(arg != null) {
v.setSecondaryProgressTintList(ColorStateList.valueOf(v.resources.getColor(arg)))
} else {
v.setSecondaryProgressTintList(null)
}
true
}
else -> false
}
"secondaryProgressTintMode" -> when {
v is ProgressBar && arg is PorterDuff.Mode? -> {
v.setSecondaryProgressTintMode(arg)
true
}
else -> false
}
"excludeMimes" -> when {
v is QuickContactBadge && arg is Array<*> -> {
v.setExcludeMimes(arg as? Array<String>)
true
}
else -> false
}
"overlay" -> when {
v is QuickContactBadge && arg is Drawable -> {
v.setOverlay(arg)
true
}
else -> false
}
"isIndicator" -> when {
v is RatingBar && arg is Boolean -> {
v.setIsIndicator(arg)
true
}
else -> false
}
"numStars" -> when {
v is RatingBar && arg is Int -> {
v.setNumStars(arg)
true
}
else -> false
}
"onRatingBarChange" -> when {
v is RatingBar -> when {
arg == null -> {
v.setOnRatingBarChangeListener(null as? RatingBar.OnRatingBarChangeListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: RatingBar,
arg1: Float,
arg2: Boolean
) -> Unit)?
v.setOnRatingBarChangeListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"rating" -> when {
v is RatingBar && arg is Float -> {
v.setRating(arg)
true
}
else -> false
}
"stepSize" -> when {
v is RatingBar && arg is Float -> {
v.setStepSize(arg)
true
}
else -> false
}
"ignoreGravity" -> when {
v is RelativeLayout && arg is Int -> {
v.setIgnoreGravity(arg)
true
}
else -> false
}
"iconified" -> when {
v is SearchView && arg is Boolean -> {
v.setIconified(arg)
true
}
else -> false
}
"iconifiedByDefault" -> when {
v is SearchView && arg is Boolean -> {
v.setIconifiedByDefault(arg)
true
}
else -> false
}
"imeOptions" -> when {
v is SearchView && arg is Int -> {
v.setImeOptions(arg)
true
}
v is TextView && arg is Int -> {
v.setImeOptions(arg)
true
}
else -> false
}
"inputType" -> when {
v is SearchView && arg is Int -> {
v.setInputType(arg)
true
}
v is TextView && arg is Int -> {
v.setInputType(arg)
true
}
else -> false
}
"onClose" -> when {
v is SearchView -> when {
arg == null -> {
v.setOnCloseListener(null as? SearchView.OnCloseListener?)
true
}
arg is Function<*> -> {
arg as (() -> Boolean)?
v.setOnCloseListener { ->
arg().also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onQueryText" -> when {
v is SearchView -> when {
arg == null -> {
v.setOnQueryTextListener(null as? SearchView.OnQueryTextListener?)
true
}
arg is SearchView.OnQueryTextListener -> {
v.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(arg0: String): Boolean =
arg.onQueryTextChange(arg0).also { Inkremental.render() }
override fun onQueryTextSubmit(arg0: String): Boolean =
arg.onQueryTextSubmit(arg0).also { Inkremental.render() }
})
true
}
else -> false
}
else -> false
}
"onQueryTextFocusChange" -> when {
v is SearchView -> when {
arg == null -> {
v.setOnQueryTextFocusChangeListener(null as? View.OnFocusChangeListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View, arg1: Boolean) -> Unit)?
v.setOnQueryTextFocusChangeListener { arg0, arg1 ->
arg(arg0, arg1).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onSearchClick" -> when {
v is SearchView -> when {
arg == null -> {
v.setOnSearchClickListener(null as? View.OnClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View) -> Unit)?
v.setOnSearchClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onSuggestion" -> when {
v is SearchView -> when {
arg == null -> {
v.setOnSuggestionListener(null as? SearchView.OnSuggestionListener?)
true
}
arg is SearchView.OnSuggestionListener -> {
v.setOnSuggestionListener(object : SearchView.OnSuggestionListener {
override fun onSuggestionClick(arg0: Int): Boolean = arg.onSuggestionClick(arg0).also {
Inkremental.render() }
override fun onSuggestionSelect(arg0: Int): Boolean =
arg.onSuggestionSelect(arg0).also { Inkremental.render() }
})
true
}
else -> false
}
else -> false
}
"queryHint" -> when {
v is SearchView && arg is CharSequence? -> {
v.setQueryHint(arg)
true
}
else -> false
}
"queryRefinementEnabled" -> when {
v is SearchView && arg is Boolean -> {
v.setQueryRefinementEnabled(arg)
true
}
else -> false
}
"searchableInfo" -> when {
v is SearchView && arg is SearchableInfo -> {
v.setSearchableInfo(arg)
true
}
else -> false
}
"submitButtonEnabled" -> when {
v is SearchView && arg is Boolean -> {
v.setSubmitButtonEnabled(arg)
true
}
else -> false
}
"suggestionsAdapter" -> when {
v is SearchView && arg is CursorAdapter -> {
v.setSuggestionsAdapter(arg)
true
}
else -> false
}
"onSeekBarChange" -> when {
v is SeekBar -> when {
arg == null -> {
v.setOnSeekBarChangeListener(null as? SeekBar.OnSeekBarChangeListener?)
true
}
arg is SeekBar.OnSeekBarChangeListener -> {
v.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
arg0: SeekBar,
arg1: Int,
arg2: Boolean
): Unit = arg.onProgressChanged(arg0, arg1, arg2).also { Inkremental.render() }
override fun onStartTrackingTouch(arg0: SeekBar): Unit =
arg.onStartTrackingTouch(arg0).also { Inkremental.render() }
override fun onStopTrackingTouch(arg0: SeekBar): Unit =
arg.onStopTrackingTouch(arg0).also { Inkremental.render() }
})
true
}
else -> false
}
else -> false
}
"onDrawerClose" -> when {
v is SlidingDrawer -> when {
arg == null -> {
v.setOnDrawerCloseListener(null as? SlidingDrawer.OnDrawerCloseListener?)
true
}
arg is Function<*> -> {
arg as (() -> Unit)?
v.setOnDrawerCloseListener { ->
arg().also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onDrawerOpen" -> when {
v is SlidingDrawer -> when {
arg == null -> {
v.setOnDrawerOpenListener(null as? SlidingDrawer.OnDrawerOpenListener?)
true
}
arg is Function<*> -> {
arg as (() -> Unit)?
v.setOnDrawerOpenListener { ->
arg().also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onDrawerScroll" -> when {
v is SlidingDrawer -> when {
arg == null -> {
v.setOnDrawerScrollListener(null as? SlidingDrawer.OnDrawerScrollListener?)
true
}
arg is SlidingDrawer.OnDrawerScrollListener -> {
v.setOnDrawerScrollListener(object : SlidingDrawer.OnDrawerScrollListener {
override fun onScrollEnded(): Unit = arg.onScrollEnded().also { Inkremental.render() }
override fun onScrollStarted(): Unit = arg.onScrollStarted().also { Inkremental.render()
}
})
true
}
else -> false
}
else -> false
}
"popupBackgroundDrawable" -> when {
v is Spinner && arg is Drawable -> {
v.setPopupBackgroundDrawable(arg)
true
}
else -> false
}
"popupBackgroundResource" -> when {
v is Spinner && arg is Int -> {
v.setPopupBackgroundResource(arg)
true
}
else -> false
}
"prompt" -> when {
v is Spinner && arg is CharSequence -> {
v.setPrompt(arg)
true
}
else -> false
}
"promptId" -> when {
v is Spinner && arg is Int -> {
v.setPromptId(arg)
true
}
else -> false
}
"showText" -> when {
v is Switch && arg is Boolean -> {
v.setShowText(arg)
true
}
else -> false
}
"switchPadding" -> when {
v is Switch && arg is Int -> {
v.setSwitchPadding(arg)
true
}
else -> false
}
"switchTypeface" -> when {
v is Switch && arg is Typeface -> {
v.setSwitchTypeface(arg)
true
}
else -> false
}
"textOff" -> when {
v is Switch && arg is CharSequence -> {
v.setTextOff(arg)
true
}
v is ToggleButton && arg is CharSequence -> {
v.setTextOff(arg)
true
}
else -> false
}
"textOn" -> when {
v is Switch && arg is CharSequence -> {
v.setTextOn(arg)
true
}
v is ToggleButton && arg is CharSequence -> {
v.setTextOn(arg)
true
}
else -> false
}
"thumbDrawable" -> when {
v is Switch && arg is Drawable -> {
v.setThumbDrawable(arg)
true
}
else -> false
}
"thumbResource" -> when {
v is Switch && arg is Int -> {
v.setThumbResource(arg)
true
}
else -> false
}
"thumbTextPadding" -> when {
v is Switch && arg is Int -> {
v.setThumbTextPadding(arg)
true
}
else -> false
}
"trackDrawable" -> when {
v is Switch && arg is Drawable -> {
v.setTrackDrawable(arg)
true
}
else -> false
}
"trackResource" -> when {
v is Switch && arg is Int -> {
v.setTrackResource(arg)
true
}
else -> false
}
"currentTab" -> when {
v is TabHost && arg is Int -> {
v.setCurrentTab(arg)
true
}
v is TabWidget && arg is Int -> {
v.setCurrentTab(arg)
true
}
else -> false
}
"currentTabByTag" -> when {
v is TabHost && arg is String -> {
v.setCurrentTabByTag(arg)
true
}
else -> false
}
"onTabChanged" -> when {
v is TabHost -> when {
arg == null -> {
v.setOnTabChangedListener(null as? TabHost.OnTabChangeListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: String) -> Unit)?
v.setOnTabChangedListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"leftStripDrawable" -> when {
v is TabWidget && arg is Drawable? -> {
v.setLeftStripDrawable(arg)
true
}
v is TabWidget && arg is Int -> {
v.setLeftStripDrawable(arg)
true
}
else -> false
}
"rightStripDrawable" -> when {
v is TabWidget && arg is Drawable? -> {
v.setRightStripDrawable(arg)
true
}
v is TabWidget && arg is Int -> {
v.setRightStripDrawable(arg)
true
}
else -> false
}
"stripEnabled" -> when {
v is TabWidget && arg is Boolean -> {
v.setStripEnabled(arg)
true
}
else -> false
}
"shrinkAllColumns" -> when {
v is TableLayout && arg is Boolean -> {
v.setShrinkAllColumns(arg)
true
}
else -> false
}
"stretchAllColumns" -> when {
v is TableLayout && arg is Boolean -> {
v.setStretchAllColumns(arg)
true
}
else -> false
}
"format12Hour" -> when {
v is TextClock && arg is CharSequence -> {
v.setFormat12Hour(arg)
true
}
else -> false
}
"format24Hour" -> when {
v is TextClock && arg is CharSequence -> {
v.setFormat24Hour(arg)
true
}
else -> false
}
"timeZone" -> when {
v is TextClock && arg is String -> {
v.setTimeZone(arg)
true
}
else -> false
}
"currentText" -> when {
v is TextSwitcher && arg is CharSequence -> {
v.setCurrentText(arg)
true
}
else -> false
}
"text" -> when {
v is TextSwitcher && arg is CharSequence -> {
v.setText(arg)
true
}
v is TextView && arg is Int -> {
v.setText(arg)
true
}
else -> false
}
"allCaps" -> when {
v is TextView && arg is Boolean -> {
v.setAllCaps(arg)
true
}
else -> false
}
"autoLinkMask" -> when {
v is TextView && arg is Int -> {
v.setAutoLinkMask(arg)
true
}
else -> false
}
"compoundDrawablePadding" -> when {
v is TextView && arg is Int -> {
v.setCompoundDrawablePadding(arg)
true
}
else -> false
}
"cursorVisible" -> when {
v is TextView && arg is Boolean -> {
v.setCursorVisible(arg)
true
}
else -> false
}
"customSelectionActionModeCallback" -> when {
v is TextView && arg is ActionMode.Callback -> {
v.setCustomSelectionActionModeCallback(arg)
true
}
else -> false
}
"editableFactory" -> when {
v is TextView && arg is Editable.Factory -> {
v.setEditableFactory(arg)
true
}
else -> false
}
"elegantTextHeight" -> when {
v is TextView && arg is Boolean -> {
v.setElegantTextHeight(arg)
true
}
else -> false
}
"ellipsize" -> when {
v is TextView && arg is TextUtils.TruncateAt -> {
v.setEllipsize(arg)
true
}
else -> false
}
"ems" -> when {
v is TextView && arg is Int -> {
v.setEms(arg)
true
}
else -> false
}
"error" -> when {
v is TextView && arg is CharSequence -> {
v.setError(arg)
true
}
else -> false
}
"extractedText" -> when {
v is TextView && arg is ExtractedText -> {
v.setExtractedText(arg)
true
}
else -> false
}
"filters" -> when {
v is TextView && arg is Array<*> -> {
v.setFilters(arg as? Array<InputFilter>)
true
}
else -> false
}
"fontFeatureSettings" -> when {
v is TextView && arg is String? -> {
v.setFontFeatureSettings(arg)
true
}
else -> false
}
"freezesText" -> when {
v is TextView && arg is Boolean -> {
v.setFreezesText(arg)
true
}
else -> false
}
"height" -> when {
v is TextView && arg is Int -> {
v.setHeight(arg)
true
}
else -> false
}
"highlightColor" -> when {
v is TextView && arg is Int -> {
v.setHighlightColor(arg)
true
}
else -> false
}
"hint" -> when {
v is TextView && arg is CharSequence -> {
v.setHint(arg)
true
}
v is TextView && arg is Int -> {
v.setHint(arg)
true
}
else -> false
}
"hintTextColor" -> when {
v is TextView && arg is ColorStateList -> {
v.setHintTextColor(arg)
true
}
v is TextView && arg is Int -> {
v.setHintTextColor(arg)
true
}
else -> false
}
"horizontallyScrolling" -> when {
v is TextView && arg is Boolean -> {
v.setHorizontallyScrolling(arg)
true
}
else -> false
}
"includeFontPadding" -> when {
v is TextView && arg is Boolean -> {
v.setIncludeFontPadding(arg)
true
}
else -> false
}
"keyListener" -> when {
v is TextView && arg is KeyListener -> {
v.setKeyListener(arg)
true
}
else -> false
}
"letterSpacing" -> when {
v is TextView && arg is Float -> {
v.setLetterSpacing(arg)
true
}
else -> false
}
"lines" -> when {
v is TextView && arg is Int -> {
v.setLines(arg)
true
}
else -> false
}
"linkTextColor" -> when {
v is TextView && arg is ColorStateList -> {
v.setLinkTextColor(arg)
true
}
v is TextView && arg is Int -> {
v.setLinkTextColor(arg)
true
}
else -> false
}
"linksClickable" -> when {
v is TextView && arg is Boolean -> {
v.setLinksClickable(arg)
true
}
else -> false
}
"marqueeRepeatLimit" -> when {
v is TextView && arg is Int -> {
v.setMarqueeRepeatLimit(arg)
true
}
else -> false
}
"maxEms" -> when {
v is TextView && arg is Int -> {
v.setMaxEms(arg)
true
}
else -> false
}
"maxLines" -> when {
v is TextView && arg is Int -> {
v.setMaxLines(arg)
true
}
else -> false
}
"minEms" -> when {
v is TextView && arg is Int -> {
v.setMinEms(arg)
true
}
else -> false
}
"minHeight" -> when {
v is TextView && arg is Int -> {
v.setMinHeight(arg)
true
}
else -> false
}
"minLines" -> when {
v is TextView && arg is Int -> {
v.setMinLines(arg)
true
}
else -> false
}
"movementMethod" -> when {
v is TextView && arg is MovementMethod -> {
v.setMovementMethod(arg)
true
}
else -> false
}
"onEditorAction" -> when {
v is TextView -> when {
arg == null -> {
v.setOnEditorActionListener(null as? TextView.OnEditorActionListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: TextView,
arg1: Int,
arg2: KeyEvent
) -> Boolean)?
v.setOnEditorActionListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"paintFlags" -> when {
v is TextView && arg is Int -> {
v.setPaintFlags(arg)
true
}
else -> false
}
"privateImeOptions" -> when {
v is TextView && arg is String -> {
v.setPrivateImeOptions(arg)
true
}
else -> false
}
"rawInputType" -> when {
v is TextView && arg is Int -> {
v.setRawInputType(arg)
true
}
else -> false
}
"scroller" -> when {
v is TextView && arg is Scroller -> {
v.setScroller(arg)
true
}
else -> false
}
"selectAllOnFocus" -> when {
v is TextView && arg is Boolean -> {
v.setSelectAllOnFocus(arg)
true
}
else -> false
}
"showSoftInputOnFocus" -> when {
v is TextView && arg is Boolean -> {
v.setShowSoftInputOnFocus(arg)
true
}
else -> false
}
"singleLine" -> when {
v is TextView && arg is Boolean -> {
v.setSingleLine(arg)
true
}
else -> false
}
"spannableFactory" -> when {
v is TextView && arg is Spannable.Factory -> {
v.setSpannableFactory(arg)
true
}
else -> false
}
"textColor" -> when {
v is TextView && arg is ColorStateList -> {
v.setTextColor(arg)
true
}
v is TextView && arg is Int -> {
v.setTextColor(arg)
true
}
else -> false
}
"textIsSelectable" -> when {
v is TextView && arg is Boolean -> {
v.setTextIsSelectable(arg)
true
}
else -> false
}
"textKeepState" -> when {
v is TextView && arg is CharSequence -> {
v.setTextKeepState(arg)
true
}
else -> false
}
"textLocale" -> when {
v is TextView && arg is Locale -> {
v.setTextLocale(arg)
true
}
else -> false
}
"textScaleX" -> when {
v is TextView && arg is Float -> {
v.setTextScaleX(arg)
true
}
else -> false
}
"transformationMethod" -> when {
v is TextView && arg is TransformationMethod -> {
v.setTransformationMethod(arg)
true
}
else -> false
}
"typeface" -> when {
v is TextView && arg is Typeface? -> {
v.setTypeface(arg)
true
}
else -> false
}
"width" -> when {
v is TextView && arg is Int -> {
v.setWidth(arg)
true
}
else -> false
}
"currentHour" -> when {
v is TimePicker && arg is Int -> {
v.setCurrentHour(arg)
true
}
else -> false
}
"currentMinute" -> when {
v is TimePicker && arg is Int -> {
v.setCurrentMinute(arg)
true
}
else -> false
}
"is24HourView" -> when {
v is TimePicker && arg is Boolean -> {
v.setIs24HourView(arg)
true
}
else -> false
}
"onTimeChanged" -> when {
v is TimePicker -> when {
arg == null -> {
v.setOnTimeChangedListener(null as? TimePicker.OnTimeChangedListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: TimePicker,
arg1: Int,
arg2: Int
) -> Unit)?
v.setOnTimeChangedListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"logo" -> when {
v is Toolbar && arg is Drawable -> {
v.setLogo(arg)
true
}
v is Toolbar && arg is Int -> {
v.setLogo(arg)
true
}
else -> false
}
"logoDescription" -> when {
v is Toolbar && arg is CharSequence -> {
v.setLogoDescription(arg)
true
}
v is Toolbar && arg is Int -> {
v.setLogoDescription(arg)
true
}
else -> false
}
"navigationContentDescription" -> when {
v is Toolbar && arg is CharSequence? -> {
v.setNavigationContentDescription(arg)
true
}
v is Toolbar && arg is Int -> {
v.setNavigationContentDescription(arg)
true
}
else -> false
}
"navigationIcon" -> when {
v is Toolbar && arg is Drawable? -> {
v.setNavigationIcon(arg)
true
}
v is Toolbar && arg is Int -> {
v.setNavigationIcon(arg)
true
}
else -> false
}
"navigationOnClickListener" -> when {
v is Toolbar && arg is View.OnClickListener -> {
v.setNavigationOnClickListener(arg)
true
}
else -> false
}
"subtitle" -> when {
v is Toolbar && arg is CharSequence -> {
v.setSubtitle(arg)
true
}
v is Toolbar && arg is Int -> {
v.setSubtitle(arg)
true
}
else -> false
}
"subtitleTextColor" -> when {
v is Toolbar && arg is Int -> {
v.setSubtitleTextColor(arg)
true
}
else -> false
}
"title" -> when {
v is Toolbar && arg is CharSequence -> {
v.setTitle(arg)
true
}
v is Toolbar && arg is Int -> {
v.setTitle(arg)
true
}
else -> false
}
"titleTextColor" -> when {
v is Toolbar && arg is Int -> {
v.setTitleTextColor(arg)
true
}
else -> false
}
"mediaController" -> when {
v is VideoView && arg is MediaController -> {
v.setMediaController(arg)
true
}
else -> false
}
"onCompletion" -> when {
v is VideoView -> when {
arg == null -> {
v.setOnCompletionListener(null as? MediaPlayer.OnCompletionListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: MediaPlayer) -> Unit)?
v.setOnCompletionListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onError" -> when {
v is VideoView -> when {
arg == null -> {
v.setOnErrorListener(null as? MediaPlayer.OnErrorListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: MediaPlayer,
arg1: Int,
arg2: Int
) -> Boolean)?
v.setOnErrorListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onInfo" -> when {
v is VideoView -> when {
arg == null -> {
v.setOnInfoListener(null as? MediaPlayer.OnInfoListener?)
true
}
arg is Function<*> -> {
arg as ((
arg0: MediaPlayer,
arg1: Int,
arg2: Int
) -> Boolean)?
v.setOnInfoListener { arg0, arg1, arg2 ->
arg(arg0, arg1, arg2).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onPrepared" -> when {
v is VideoView -> when {
arg == null -> {
v.setOnPreparedListener(null as? MediaPlayer.OnPreparedListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: MediaPlayer) -> Unit)?
v.setOnPreparedListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"videoPath" -> when {
v is VideoView && arg is String -> {
v.setVideoPath(arg)
true
}
else -> false
}
"videoURI" -> when {
v is VideoView && arg is Uri -> {
v.setVideoURI(arg)
true
}
else -> false
}
"factory" -> when {
v is ViewSwitcher && arg is ViewSwitcher.ViewFactory -> {
v.setFactory(arg)
true
}
else -> false
}
"zoomSpeed" -> when {
v is ZoomButton && arg is Long -> {
v.setZoomSpeed(arg)
true
}
v is ZoomControls && arg is Long -> {
v.setZoomSpeed(arg)
true
}
else -> false
}
"isZoomInEnabled" -> when {
v is ZoomControls && arg is Boolean -> {
v.setIsZoomInEnabled(arg)
true
}
else -> false
}
"isZoomOutEnabled" -> when {
v is ZoomControls && arg is Boolean -> {
v.setIsZoomOutEnabled(arg)
true
}
else -> false
}
"onZoomInClick" -> when {
v is ZoomControls -> when {
arg == null -> {
v.setOnZoomInClickListener(null as? View.OnClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View) -> Unit)?
v.setOnZoomInClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
"onZoomOutClick" -> when {
v is ZoomControls -> when {
arg == null -> {
v.setOnZoomOutClickListener(null as? View.OnClickListener?)
true
}
arg is Function<*> -> {
arg as ((arg0: View) -> Unit)?
v.setOnZoomOutClickListener { arg0 ->
arg(arg0).also { Inkremental.render() }
}
true
}
else -> false
}
else -> false
}
else -> false
}
}
| 20
| null |
5
| 58
|
6e6241a0e9ac80a1edd1f0e100ad6bf0c4f8175e
| 106,443
|
inkremental
|
MIT License
|
core/src/main/java/ee/solarlabs/community/core/model/subscriptions/response/QuotaResponse.kt
|
sentinel-official
| 578,087,836
| false
| null |
package ee.solarlabs.community.core.model.subscriptions.response
data class QuotaResponse(val address: String, val consumed: String, val allocated: String)
| 1
| null |
4
| 4
|
58b79967924e5049397c5297bb9b2aefe98060f0
| 157
|
sentinel-dvpn-for-android
|
MIT License
|
src/main/kotlin/com/hades/example/leankotlin/concepts/_4_class_and_object/_13_inline_value_classes/InlineValueClassesExample.kt
|
YingVickyCao
| 557,306,875
| false
|
{"Kotlin": 402357, "Java": 2079}
|
package com.hades.example.leankotlin.concepts._4_class_and_object._13_inline_value_classes
// 内联类
// https://book.kotlincn.net/text/inline-classes.html
// https://kotlinlang.org/docs/inline-classes.html
fun main() {
/**
* Example 1 : Inline value classes
* 内联类
*/
run {
test1()
}
/**
* Example 2 : Members
*/
run {
test2()
}
/**
* Example 3 : Inheritance
*/
run {
test3()
}
/**
* Example 4 : Representation
*/
test4_1()
/**
* Example 4 : Representation - Mangling
*/
test4_2()
/**
* Example 4 : Representation - Calling from Java code
*/
test4_3()
/**
* Example 5 : Inline classes vs type aliases
*/
test5()
/**
* Example 6 : Inline classes and delegation
*/
test6()
}
/**
* Example 1 : Inline value classes
* 内联类
*/
// value 和 @JvmInline 来表示标识一个内联类
@JvmInline
value class Password(private val s: String)
// 内联类必须含有唯一的一个属性在主构造器中初始化。在运行时,将使用这个唯一属性来表示内联类的实例。
fun test1() {
// 内联类的使用场景:wrap a value in a class to create a more domain-specific type. 若被包装的是原生类型,那么同时又不会丧失运行时对原始类型的优化因此不会有性能损失。
// 在运行时,不存在Password类的真实实例对象,securePassword仅仅包含 string
val securePassword = Password("<PASSWORD>")
println(securePassword)
// 内联类的主要特性:类的数据被内联到该类使用的地方。类似于内联函数中的代码被内联到该函数调用的地方。
}
/**
* Example 2 : Members
*/
// 内联类支持普通类中的一些功能,比如属性、函数、init block、secondary constructors
// Inline class properties cannot have backing fields. They can only have simple computable properties (no lateinit/delegated properties).
@JvmInline
value class Person(private val fullName: String) {
init {
require(fullName.isNotEmpty()) {
"Full name should not be empty"
}
}
constructor(firstName: String, lastName: String) : this("$firstName $lastName") {
require(lastName.isNotEmpty()) {
"Last name should not be empty"
}
}
val length: Int
get() = fullName.length
fun greet() {
println("Hi, $fullName")
}
}
fun test2() {
val name1 = Person("Kotlin", "Mascot")
val name2 = Person("Kode")
name1.greet()
println(name2.length)
}
/**
* Example 3 : Inheritance
* 继承
*/
// 内联类允许去继承接口
interface Printable {
fun prettyPrint(): String
}
@JvmInline
value class Name(val s: String) : Printable {
override fun prettyPrint(): String {
return "Let's $s!"
}
}
//final class A :Name(){ // 内联类是final类,不能被其他类继承。
//
//}
fun test3() {
val name = Name("Kotlin")
println(name.prettyPrint())
}
/**
* Example 4 : Representation
* 表示方式
*/
// In generated code, the Kotlin compiler keeps a wrapper for each inline class.
// 内联类的实例在运行时表示为wrappers或者基础类型。类似与Int可以表示为原生类型int或wrapper Integer
// 为了生成性能最优的代码,Kotlin 编译更倾向于使用基础类型而不是包装器。 然而,有时候使用包装器是必要的。一般来说,只要将内联类用作另一种类型, 它们就会被装箱。
interface I
@JvmInline
value class Foo(val i: Int) : I {
}
fun asInline(f: Foo) {
}
fun <T> asGeneric(x: T) {
}
fun asInterface(i: I) {
}
fun asNullable(i: Foo?) {
}
fun <T> id(x: T): T = x
fun test4_1() {
val f = Foo(42)
asInline(f) // 拆箱:用作Foo本身
asGeneric(f) // 装箱:用作泛型类型T
asInterface(f) // 装箱:用作泛型类型I
asNullable(f) // 装箱: 用作不同Foo的可空类型 Foo?
// 'f' 首先会被装箱(当它作为参数传递给 'id' 函数时)然后又被拆箱(当它从'id'函数中被返回时)
// 最后, 'c' 中就包含了被拆箱后的内部表达(也就是 '42'), 和 'f' 一样
val c = id(f)
}
// 因为内联类既可以表示为基础类型有可以表示为包装器,引用相等(===/!==)对于内联类而言毫无意义,因此这也是被禁止的。
// https://book.kotlincn.net/text/equality.html
// Inline classes can also have a generic type parameter as the underlying type. In this case, the compiler maps it to Any? or, generally, to the upper bound of the type parameter.
@JvmInline
value class UserId<T>(val value: T)
fun compute(s: UserId<String>) {} // compiler generates fun compute-<hashcode>(s: Any?)
/**
* Example 4 : Representation - Mangling
* 名字修饰
*/
// 由于内联类被编译为其基础类型,因此可能会导致各种模糊的错误,例如意想不到的平台签名冲突:
@JvmInline
value class UInt(val x: Int)
// 在 JVM 平台上被表示为'public final void compute(int x)'
fun compute(x: Int) {}
// 同理,在 JVM 平台上也被表示为'public final void compute(int x)'!
fun compute(x: UInt) {}
// 为了缓解这种问题,一般会通过在函数名后面拼接一些稳定的哈希码来修饰函数名。 因此,fun compute(x: UInt) 将会被表示为 public final void compute-<hashcode>(int x),以此来解决冲突的问题。
fun test4_2() {
}
/**
* Example 4 : Representation - Calling from Java code
*/
// You can call functions that accept inline classes from Java code. To do so, you should manually disable mangling: add the @JvmName annotation before the function declaration:
@JvmInline
value class UInt2(val x: Int)
// Java : :InlineValueClassesExampleKt.compute2(10);
fun compute2(x: Int) {}
// InlineValueClassesExampleKt.computeUInt(10);
@JvmName("computeUInt") // 如果不加@JvmName,那么,Java能看到两个compute2,Java不能match到底是调用哪一个。
fun compute2(x: UInt2) {
// 相当于因为Java看到重复的函数签名,然后用@JvmName给其中一个指定一个别的名字。
}
fun test4_3() {
compute2(10)
val value = UInt2(10)
compute2(value)
}
/**
* Example 5 : Inline classes vs type aliases
* 内联类与类型别名
*/
// 内联类 vs 类型别名(https://book.kotlincn.net/text/type-aliases.html)
// 内联类是引入了一个真实的新类型
// 类型别名是为现有的类型取了一个新的替代名称(别名)
typealias NameTypeAlias = String
@JvmInline
value class NameInlineClass(val s: String)
fun acceptString(s: String) {
}
fun acceptNameTypeAlias(n: NameTypeAlias) {
}
fun acceptNameInlineClass(p: NameInlineClass) {}
fun test5() {
val nameTypeAlias: NameTypeAlias = "abc"
val nameInlineClass: NameInlineClass = NameInlineClass("abc")
val string: String = "abc"
acceptString(nameTypeAlias) // ok
// acceptString(nameInlineClass) // error
acceptString(string) // ok
acceptNameTypeAlias(string) // ok
acceptNameTypeAlias(nameTypeAlias) // ok
// acceptNameTypeAlias(nameInlineClass) // error
// acceptNameInlineClass(nameTypeAlias) // error
acceptNameInlineClass(nameInlineClass) // ok
// acceptNameInlineClass(string) // error
}
/**
* Example 6 : Inline classes and delegation
* TODO: Inline classes and delegation
*/
// Implementation by delegation to inlined value of inlined class is allowed with interfaces:
interface MyInterface {
fun bar()
fun foo() = "f00"
}
@JvmInline
value class MyInterfaceWrapper(private val myInterface: MyInterface) : MyInterface by myInterface // TODO: by
fun test6() {
val my = MyInterfaceWrapper(object : MyInterface {
override fun bar() {
println("bar")
}
})
println(my.foo())
}
| 0
|
Kotlin
|
0
| 0
|
e82a3d4b3c88f4b3cbeda71f2876a68d172c96d9
| 6,449
|
LeanKotlin
|
Apache License 2.0
|
app/src/main/java/com/valerityoss/randomuserinfo/ui/data/GitRepoRemoteDataSource.kt
|
shvets-denis
| 207,673,191
| false
| null |
package com.valerityoss.randomuserinfo.ui.data
import com.valerityoss.randomuserinfo.ui.ui.ui_model.Repository
import io.reactivex.Observable
import java.util.concurrent.TimeUnit
class GitRepoRemoteDataSource {
fun getRepositories(): Observable<ArrayList<Repository>> {
var arrayList = ArrayList<Repository>()
with(arrayList) {
add(
Repository(
"First from remote",
"Owner remote 1",
100,
false
)
)
add(
Repository(
"Second from remote",
"Owner remote 2",
30,
true
)
)
add(
Repository(
"Third from remote",
"Owner remote 3",
430,
false
)
)
}
return Observable.just(arrayList).delay(2, TimeUnit.SECONDS)
}
}
| 0
|
Kotlin
|
0
| 0
|
ea21c46bbdb95bfe3ed6ab70d5f504e3416112ac
| 1,056
|
RandomUserInfo
|
Apache License 2.0
|
app/src/main/java/com/uxstate/skycast/presentation/home/components/EmptyWeatherBox.kt
|
Tonnie-Dev
| 698,802,033
| false
|
{"Kotlin": 169908}
|
package com.uxstate.skycast.presentation.home.components
import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.uxstate.skycast.R
import com.uxstate.skycast.ui.theme.LocalSpacing
import com.uxstate.skycast.ui.theme.SkyCastTheme
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun EmptyWeatherBox( onGetLocation:()-> Unit) {
val spacing = LocalSpacing.current
Box(
modifier = Modifier
.fillMaxSize()
.padding(spacing.spaceSmall),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
painter = painterResource(id = R.drawable.ic_no_weather_info),
contentDescription = null,
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary),
)
Text(
text = stringResource(id = R.string.location_permission_msg),
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.bodyMedium
)
Button(onClick = { onGetLocation() }) {
Text("Try Again")
}
}
}
}
@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_NO)
@Composable
fun EmptyWeatherBoxPreviewLight() {
SkyCastTheme {
EmptyWeatherBox(){}
}
}
@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_YES)
@Composable
fun EmptyWeatherBoxPreviewDark() {
SkyCastTheme {
EmptyWeatherBox(){}
}
}
| 0
|
Kotlin
|
0
| 0
|
1bf6826fb3d0ec9c6decf54d6e1176211bf7f3e2
| 2,538
|
SkyCast
|
The Unlicense
|
feature-themes-impl/src/main/kotlin/com/blacksquircle/ui/feature/themes/ui/mvi/ThemesViewState.kt
|
massivemadness
| 100,590,072
| false
| null |
/*
* Copyright 2022 Squircle CE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blacksquircle.ui.feature.themes.ui.viewstate
import com.blacksquircle.ui.core.ui.viewstate.ViewState
import com.blacksquircle.ui.feature.themes.domain.model.ThemeModel
sealed class ThemesViewState : ViewState() {
abstract val query: String
object Loading : ThemesViewState() {
override val query: String = ""
}
data class Empty(
override val query: String,
) : ThemesViewState()
data class Data(
override val query: String,
val themes: List<ThemeModel>,
) : ThemesViewState()
}
| 74
| null |
75
| 708
|
2622fcc49a1d71ea1dec87c460d4586d671646c0
| 1,165
|
Squircle-CE
|
Apache License 2.0
|
app/src/main/java/com/example/savemeal/reservations/consumer/ReservationDetailFragment.kt
|
UTN-FRBA-Mobile
| 410,448,464
| false
| null |
package com.example.savemeal.reservations.consumer
import android.app.AlertDialog
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewModelScope
import com.example.savemeal.CodeDialogFragment
import com.example.savemeal.databinding.FragmentReservationDetailBinding
import com.example.savemeal.domain.reservation.ReservationViewModel
import com.google.android.gms.common.util.Base64Utils
import com.squareup.picasso.Picasso
import kotlinx.coroutines.launch
class ReservationDetailFragment : Fragment() {
private var _binding: FragmentReservationDetailBinding? = null
private val binding get() = _binding!!
private var reservationId = 0
private val viewModel: ReservationViewModel by viewModels()
private var reservationCode: String = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentReservationDetailBinding.inflate(inflater, container, false)
reservationId = arguments?.getInt("reservationId")!!
bindUI(reservationId)
return binding.root
}
private fun bindUI(reservationId: Int) {
val reservation = viewModel.getReservationDetail(reservationId)
reservationCode = reservation.token
_binding?.apply {
expirationDate.text = reservation.comida.expiracion
title.text = reservation.comida.nombre
businessHours.text = reservation.business.businessHours
businessAddress.text = reservation.business.address
businessName.text = reservation.business.businessName
availables.text = reservation.comida.disponibles.toString()
detail.text = reservation.comida.detalle
val imageAsBytes: ByteArray = Base64Utils.decode(reservation.comida.imagen)
photo.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.size))
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonObtainCode.setOnClickListener {
val dialog = CodeDialogFragment(reservationCode)
dialog.show(parentFragmentManager, "No se que es el tag")
}
binding.buttonCancelar.setOnClickListener {
val warning_dialog = AlertDialog.Builder(context)
warning_dialog.setMessage("¿Desea cancelar la reserva?")
.setNegativeButton("No"){ _, _->}
.setPositiveButton("Si"){dialog, which ->
cancelReservation()
fragmentManager?.popBackStack()
Toast.makeText(context, "Reserva cancelada", Toast.LENGTH_LONG).show()
}
.show()
}
}
private fun cancelReservation() {
viewModel.viewModelScope.launch {
viewModel.cancelReservation(reservationId)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
f25767e3d59b145d67d972b134f2b42b09798ca8
| 3,289
|
SaveMeal
|
MIT License
|
valentine-starter/src/main/kotlin/org/springframework/core/task/VirtualThreadDelegate.kt
|
lWoHvYe
| 350,562,833
| false
|
{"Java": 1215811, "Kotlin": 159066, "PLpgSQL": 71478, "FreeMarker": 34581, "HTML": 13706, "Shell": 4000}
|
/*
* Copyright 2002-2023 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.task
import java.util.concurrent.ThreadFactory
/**
* Internal delegate for virtual thread handling on JDK 21.
* This is the actual version compiled against JDK 21.
* [...](https://github.com/spring-projects/spring-framework/blob/main/spring-core/src/main/java21/org/springframework/core/task/VirtualThreadDelegate.java)
*
* @author <NAME>
* @see VirtualThreadTaskExecutor
*
* @since 6.1
*/
internal class VirtualThreadDelegate {
private val threadBuilder: Thread.Builder = Thread.ofVirtual()
fun virtualThreadFactory(): ThreadFactory {
return threadBuilder.name("Virtual-Delegate").factory()
}
fun virtualThreadFactory(threadNamePrefix: String?): ThreadFactory {
return threadBuilder.name(threadNamePrefix, 0).factory()
}
fun newVirtualThread(name: String?, task: Runnable?): Thread {
return threadBuilder.name(name).unstarted(task)
}
}
| 3
|
Java
|
20
| 40
|
40ef54a8529fc5cdc1e8d5551bc236aa4efac98f
| 1,557
|
unicorn
|
Apache License 2.0
|
app/src/main/java/com/naver/maps/map/compose/demo/location/CustomLocationSourceScreen.kt
|
fornewid
| 492,204,824
| false
|
{"Kotlin": 431651, "Shell": 2924}
|
/*
* Copyright 2022 SOUP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.naver.maps.map.compose.demo.location
import android.graphics.PointF
import android.location.Location
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.naver.maps.geometry.LatLng
import com.naver.maps.map.LocationSource
import com.naver.maps.map.compose.ExperimentalNaverMapApi
import com.naver.maps.map.compose.LocationTrackingMode
import com.naver.maps.map.compose.MapProperties
import com.naver.maps.map.compose.NaverMap
import com.naver.maps.map.compose.demo.R
import com.naver.maps.map.compose.demo.common.DefaultTopAppBar
import com.naver.maps.map.compose.demo.common.showToast
@OptIn(ExperimentalNaverMapApi::class)
@Composable
fun CustomLocationSourceScreen(upPress: () -> Unit) {
Scaffold(
topBar = {
DefaultTopAppBar(
text = stringResource(R.string.name_custom_location_source),
upPress = upPress
)
}
) { contentPadding ->
Box(modifier = Modifier.padding(contentPadding)) {
val context = LocalContext.current
val locationSource = remember { CustomLocationSource() }
NaverMap(
locationSource = locationSource,
properties = MapProperties(
locationTrackingMode = LocationTrackingMode.NoFollow
),
onMapClick = locationSource::onMapClick,
onLocationChange = {
context.showToast(
R.string.format_location_changed,
it.latitude,
it.longitude
)
}
)
}
}
}
private class CustomLocationSource : LocationSource {
private var listener: LocationSource.OnLocationChangedListener? = null
override fun activate(listener: LocationSource.OnLocationChangedListener) {
this.listener = listener
}
override fun deactivate() {
listener = null
}
fun onMapClick(point: PointF, coord: LatLng) {
listener?.onLocationChanged(
Location("CustomLocationSource").apply {
latitude = coord.latitude
longitude = coord.longitude
accuracy = 100f
}
)
}
}
| 8
|
Kotlin
|
6
| 99
|
2fcbd5f18a69d58717c84e8a7367f702531f4e24
| 3,153
|
naver-map-compose
|
Apache License 2.0
|
calendar/src/main/java/com/jonaswanke/calendar/CalendarView.kt
|
TrendingTechnology
| 143,161,660
| true
|
{"Kotlin": 60480, "Java": 1120}
|
package com.jonaswanke.calendar
import android.content.Context
import android.gesture.GestureOverlayView
import android.os.Parcel
import android.os.Parcelable
import android.support.annotation.AttrRes
import android.support.annotation.IntDef
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.util.SparseArray
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import kotlinx.android.synthetic.main.view_calendar.view.*
import kotlin.properties.Delegates
/**
* TODO: document your custom view class.
*/
class CalendarView @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null,
@AttrRes defStyleAttr: Int = R.attr.calendarViewStyle)
: GestureOverlayView(context, attrs, defStyleAttr) {
companion object {
const val RANGE_DAY = 1
const val RANGE_3_DAYS = 3
const val RANGE_WEEK = 7
val RANGE_VALUES = intArrayOf(RANGE_DAY, RANGE_3_DAYS, RANGE_WEEK)
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(RANGE_DAY, RANGE_3_DAYS, RANGE_WEEK)
annotation class Range
var onEventClickListener: ((Event) -> Unit)?
by Delegates.observable<((Event) -> Unit)?>(null) { _, _, new ->
updateListeners(new, onEventLongClickListener)
}
var onEventLongClickListener: ((Event) -> Unit)?
by Delegates.observable<((Event) -> Unit)?>(null) { _, _, new ->
updateListeners(onEventClickListener, new)
}
var eventRequestCallback: (Week) -> Unit = {}
@get: Range
var range: Int by Delegates.observable(RANGE_WEEK) { _, old, new ->
if (old == new)
return@observable
if (new !in RANGE_VALUES)
throw UnsupportedOperationException()
onRangeUpdated()
}
var hourHeight: Float by Delegates.vetoable(0f) { _, old, new ->
if ((hourHeightMin > 0 && new < hourHeightMin)
|| (hourHeightMax > 0 && new > hourHeightMax))
return@vetoable false
if (old == new)
return@vetoable true
hours.hourHeight = new
for (week in weekViews.values)
week.hourHeight = new
return@vetoable true
}
var hourHeightMin: Float by Delegates.observable(0f) { _, _, new ->
if (new > 0 && hourHeight < new)
hourHeight = new
hours.hourHeightMin = new
for (week in weekViews.values)
week.hourHeightMin = new
}
var hourHeightMax: Float by Delegates.observable(0f) { _, _, new ->
if (new > 0 && hourHeight > new)
hourHeight = new
hours.hourHeightMax = new
for (week in weekViews.values)
week.hourHeightMax = new
}
var scrollPosition: Int by Delegates.observable(0) { _, _, new ->
hoursScroll.scrollY = new
for (week in weekViews.values)
week.scrollTo(new)
}
private val events: MutableMap<Week, List<Event>> = mutableMapOf()
private val weekViews: MutableMap<Week, WeekView> = mutableMapOf()
private val scaleDetector: ScaleGestureDetector
private var _currentWeek: Week = Week()
var currentWeek: Week
get() = _currentWeek
set(value) {
if (_currentWeek == value)
return
_currentWeek = value
hoursHeader.week = value
pager.setCurrentIndicator<Week, WeekView>(value)
}
private val pagerAdapter: InfinitePagerAdapter<Week, WeekView>
init {
View.inflate(context, R.layout.view_calendar, this)
val a = context.obtainStyledAttributes(
attrs, R.styleable.CalendarView, defStyleAttr, R.style.Calendar_CalendarViewStyle)
range = a.getInteger(R.styleable.CalendarView_range, RANGE_WEEK)
hourHeightMin = a.getDimension(R.styleable.CalendarView_hourHeightMin, 0f)
hourHeightMax = a.getDimension(R.styleable.CalendarView_hourHeightMax, 0f)
hourHeight = a.getDimension(R.styleable.CalendarView_hourHeight, 100f)
a.recycle()
isGestureVisible = false
gestureStrokeLengthThreshold = 10f
scaleDetector = ScaleGestureDetector(context, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector?): Boolean {
if (detector == null)
return false
val foc = (detector.focusY + scrollPosition) / hourHeight
hourHeight *= detector.currentSpanY / detector.previousSpanY
scrollPosition = (foc * hourHeight - detector.focusY).toInt() // (beginFocus * hourHeight - detector.focusY).toInt()
return true
}
})
pagerAdapter = object : InfinitePagerAdapter<Week, WeekView>(currentWeek, 2) {
override fun nextIndicator(current: Week) = current.nextWeek
override fun previousIndicator(current: Week) = current.prevWeek
override var currentIndicatorString: String
get() = currentIndicator.toString()
set(value) {
currentIndicator = value.toWeek()!!
}
override fun instantiateItem(indicator: Week, oldView: WeekView?): WeekView {
val view = if (oldView == null)
WeekView(context, _week = indicator).also {
it.events = events[indicator] ?: emptyList()
it.onEventClickListener = onEventClickListener
it.onEventLongClickListener = onEventLongClickListener
it.onScrollChangeListener = { scrollPosition = it }
it.hourHeightMin = hourHeightMin
it.hourHeightMax = hourHeightMax
it.hourHeight = hourHeight
doOnLayout { _ -> it.scrollTo(scrollPosition) }
}
else {
if (weekViews[oldView.week] == oldView)
weekViews.remove(oldView.week)
oldView.also {
it.setWeek(indicator, events[indicator] ?: emptyList())
}
}
weekViews[indicator] = view
eventRequestCallback(indicator)
return view
}
}
hoursScroll.onScrollChangeListener = { scrollPosition = it }
hoursHeader.week = pagerAdapter.currentIndicator
pager.adapter = pagerAdapter
pager.listener = object : InfiniteViewPager.OnInfinitePageChangeListener {
override fun onPageScrolled(indicator: Any?, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(indicator: Any?) {
}
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
_currentWeek = pagerAdapter.currentIndicator
hoursHeader.week = _currentWeek
}
}
}
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
scaleDetector.onTouchEvent(event)
return super.dispatchTouchEvent(event)
}
fun setEventsForWeek(week: Week, events: List<Event>) {
this.events[week] = events
weekViews[week]?.events = events
}
private fun onRangeUpdated() {
when (range) {
RANGE_DAY -> TODO()
RANGE_3_DAYS -> TODO()
RANGE_WEEK -> {
}
else -> throw UnsupportedOperationException()
}
}
private fun updateListeners(onEventClickListener: ((Event) -> Unit)?,
onEventLongClickListener: ((Event) -> Unit)?) {
for (view in weekViews.values) {
view.onEventClickListener = onEventClickListener
view.onEventLongClickListener = onEventLongClickListener
}
}
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>?) {
dispatchFreezeSelfOnly(container)
}
override fun onSaveInstanceState(): Parcelable {
return SavedState(super.onSaveInstanceState()).also {
it.week = currentWeek
it.range = range
it.hourHeight = hourHeight
it.hourHeightMin = hourHeightMin
it.hourHeightMax = hourHeightMax
it.scrollPosition = scrollPosition
}
}
override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>?) {
dispatchThawSelfOnly(container)
}
override fun onRestoreInstanceState(state: Parcelable?) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
// firstDayOfWeek not updated on restore automatically
state.week?.also { currentWeek = Week(it.year, it.week) }
state.range?.also { range = it }
state.hourHeightMin?.also { hourHeightMin = it }
state.hourHeightMax?.also { hourHeightMax = it }
state.hourHeight?.also { hourHeight = it }
state.scrollPosition?.also { scrollPosition = it }
}
internal class SavedState : View.BaseSavedState {
companion object {
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel?) = SavedState(source)
override fun newArray(size: Int) = arrayOfNulls<SavedState>(size)
}
}
var week: Week? = null
@get: Range
var range: Int? = null
var hourHeight: Float? = null
var hourHeightMin: Float? = null
var hourHeightMax: Float? = null
var scrollPosition: Int? = null
constructor(source: Parcel?) : super(source) {
if (source == null)
return
fun readInt(): Int? {
val value = source.readInt()
return if (value == Int.MIN_VALUE) null else value
}
fun readFloat(): Float? {
val value = source.readFloat()
return if (value == Float.NaN) null else value
}
week = source.readString()?.toWeek()
range = readInt()
hourHeight = readFloat()
hourHeightMin = readFloat()
hourHeightMax = readFloat()
scrollPosition = readInt()
}
constructor(superState: Parcelable) : super(superState)
override fun writeToParcel(out: Parcel?, flags: Int) {
super.writeToParcel(out, flags)
out?.writeString(week?.toString())
out?.writeInt(range ?: Int.MIN_VALUE)
out?.writeFloat(hourHeight ?: Float.NaN)
out?.writeFloat(hourHeightMin ?: Float.NaN)
out?.writeFloat(hourHeightMax ?: Float.NaN)
out?.writeInt(scrollPosition ?: Int.MIN_VALUE)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8ac6b11b372a929517190a16edf931a3737e620e
| 11,277
|
com.jonaswanke.calendar
|
Apache License 2.0
|
nba/app/src/main/java/com/tyhoo/android/nba/ui/player/PlayersFragment.kt
|
cnwutianhao
| 600,592,169
| false
| null |
package com.tyhoo.android.nba.ui.player
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import com.tyhoo.android.nba.adapter.PlayersAdapter
import com.tyhoo.android.nba.databinding.FragmentPlayersBinding
import com.tyhoo.android.nba.viewmodel.PlayersViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
@AndroidEntryPoint
class PlayersFragment : Fragment() {
private lateinit var binding: FragmentPlayersBinding
private var job: Job? = null
private val viewModel: PlayersViewModel by viewModels()
private lateinit var adapter: PlayersAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentPlayersBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initUI()
requestData()
}
override fun onDestroyView() {
job?.cancel()
super.onDestroyView()
}
private fun initUI() {
adapter = PlayersAdapter()
binding.playerList.addItemDecoration(
DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
)
binding.playerList.adapter = adapter
}
private fun requestData() {
job?.cancel()
job = lifecycleScope.launchWhenResumed {
viewModel.requestData(viewLifecycleOwner, adapter)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
90797aa1c354092b72ed5fc910f2c4838f1e0577
| 1,804
|
android
|
MIT License
|
compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyScriptClassMemberScope.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.lazy.descriptors
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.ClassConstructorDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider
class LazyScriptClassMemberScope(
resolveSession: ResolveSession,
declarationProvider: ClassMemberDeclarationProvider,
private val scriptDescriptor: LazyScriptDescriptor,
trace: BindingTrace)
: LazyClassMemberScope(resolveSession, declarationProvider, scriptDescriptor, trace) {
override fun resolvePrimaryConstructor(): ClassConstructorDescriptor? {
val constructor = ClassConstructorDescriptorImpl.create(
scriptDescriptor,
Annotations.EMPTY,
true,
SourceElement.NO_SOURCE
)
constructor.initialize(
createScriptParameters(constructor),
Visibilities.PUBLIC
)
setDeferredReturnType(constructor)
return constructor
}
private fun createScriptParameters(constructor: ClassConstructorDescriptorImpl): List<ValueParameterDescriptor> {
return scriptDescriptor.scriptDefinition.getScriptParameters(scriptDescriptor).mapIndexed { index, scriptParameter ->
ValueParameterDescriptorImpl(
constructor, null, index, Annotations.EMPTY, scriptParameter.name, scriptParameter.type,
/* declaresDefaultValue = */ false,
/* isCrossinline = */ false,
/* isNoinline = */ false,
/* isCoroutine = */ false,
null, SourceElement.NO_SOURCE
)
}
}
override fun createPropertiesFromPrimaryConstructorParameters(name: Name, result: MutableSet<PropertyDescriptor>) {
}
}
| 1
| null |
4
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 2,746
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/yzq/kotlincommon/view_model/MoshiViewModel.kt
|
yuzhiqiang1993
| 140,548,996
| false
|
{"Kotlin": 368226, "Java": 153913, "CSS": 3721, "JavaScript": 3215, "HTML": 2415}
|
package com.yzq.kotlincommon.view_model
import androidx.lifecycle.viewModelScope
import com.yzq.base.utils.MoshiUtils
import com.yzq.base.view_model.BaseViewModel
import com.yzq.common.api.BaseResp
import com.yzq.common.data.moshi.User
import com.yzq.common.ext.dataConvert
import com.yzq.common.net.RetrofitFactory
import com.yzq.common.net.api.ApiService
import com.yzq.common.net.constants.ResponseCode
import com.yzq.coroutine.safety_coroutine.launchSafety
import com.yzq.logger.Logger
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
class MoshiViewModel : BaseViewModel() {
private lateinit var jsonStr: String
fun serialize() {
/*生成数据 */
viewModelScope.launchSafety {
val userList = mutableListOf<User>()
for (it in 1..3) {
userList.add(
User(
"喻志强$it",
it,
arrayListOf(User.Hobby("type$it", "爱好$it"))
)
)
}
val baseResp = BaseResp<List<User>>(ResponseCode.SUCCESS, userList, "ok")
jsonStr = MoshiUtils.toJson(baseResp) ?: ""
Logger.i(jsonStr)
}
}
fun deserialize() {
viewModelScope.launchSafety {
if (jsonStr.isNotEmpty()) {
val genericType = MoshiUtils.getGenericType<BaseResp<List<User>>>()
Logger.i("genericType==========:$genericType")
val userList = MoshiUtils.fromJson<BaseResp<List<User>>>(jsonStr).dataConvert()
userList?.forEach {
Logger.i(MoshiUtils.toJson(it, " ") ?: "")
}
}
}
}
fun requestData() {
viewModelScope.launchSafety {
supervisorScope {
launch {
val userList =
RetrofitFactory.instance.getService(ApiService::class.java).listLocalUser()
.dataConvert()
userList?.forEach {
Logger.i("${it.name}--${it.age}")
}
}
launch {
delay(4000)
val userInfo =
RetrofitFactory.instance.getService(ApiService::class.java).userInfo()
Logger.i("userInfo:$userInfo")
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f65f96b72df77536925e6f0ef56aa27d404ce206
| 2,492
|
kotlinCommon
|
MIT License
|
fuzzer/api/src/commonMain/kotlin/com/github/jcornaz/kwik/fuzzer/api/FuzzerFactory.kt
|
ProdigSun
| 391,233,716
| true
|
{"Kotlin": 237632}
|
package com.github.jcornaz.kwik.fuzzer.api
import com.github.jcornaz.kwik.ExperimentalKwikApi
import com.github.jcornaz.kwik.fuzzer.api.simplifier.Simplifier
import com.github.jcornaz.kwik.fuzzer.api.simplifier.pair
import com.github.jcornaz.kwik.fuzzer.api.simplifier.triple
import com.github.jcornaz.kwik.generator.api.combineWith
import kotlin.random.Random
/**
* Returns a [Fuzzer] for pair of [A] and [B].
*
* @param first Fuzzer for the first element of the pairs
* @param second Fuzzer for the second element of the pairs
*/
@ExperimentalKwikApi
public fun <A, B> Arbitrary.pair(first: Fuzzer<A>, second: Fuzzer<B>): Fuzzer<Pair<A, B>> =
Fuzzer(
generator = first.generator.combineWith(second.generator),
simplifier = Simplifier.pair(first.simplifier, second.simplifier)
)
/**
* Returns a [Fuzzer] for pair, using [fuzzer] to fuzz both elements of the pair.
*/
@ExperimentalKwikApi
public fun <T> Arbitrary.pair(fuzzer: Fuzzer<T>): Fuzzer<Pair<T, T>> =
pair(fuzzer, fuzzer)
/**
* Returns a [Fuzzer] for triple of [A], [B] and [C].
*
* @param first Fuzzer for the first element of the pairs
* @param second Fuzzer for the second element of the pairs
* @param third Fuzzer for the third element of the pairs
*/
@ExperimentalKwikApi
public fun <A, B, C> Arbitrary.triple(first: Fuzzer<A>, second: Fuzzer<B>, third: Fuzzer<C>): Fuzzer<Triple<A, B, C>> =
Fuzzer(
generator = { random: Random ->
Triple(
first.generator.generate(random),
second.generator.generate(random),
third.generator.generate(random)
)
},
simplifier = Simplifier.triple(first.simplifier, second.simplifier, third.simplifier)
)
/**
* Returns a [Fuzzer] for triple, using [fuzzer] for all elements.
*/
@ExperimentalKwikApi
public fun <T> Arbitrary.triple(fuzzer: Fuzzer<T>): Fuzzer<Triple<T, T, T>> =
triple(fuzzer, fuzzer, fuzzer)
| 0
| null |
0
| 0
|
60d3c48838520e592ed9047fb5edd397f7f8e85c
| 1,959
|
kwik
|
Apache License 2.0
|
plugins/net/src/main/kotlin/org/rsmod/plugins/net/login/downstream/ConnectOkCodec.kt
|
rsmod
| 293,875,986
| false
|
{"Kotlin": 812861}
|
package org.rsmod.plugins.net.login.downstream
import io.netty.buffer.ByteBuf
import org.openrs2.crypto.StreamCipher
import org.rsmod.protocol.packet.VariableByteLengthPacketCodec
import javax.inject.Singleton
@Singleton
class ConnectOkCodec : VariableByteLengthPacketCodec<LoginResponse.ConnectOk>(
type = LoginResponse.ConnectOk::class.java,
opcode = 2
) {
override fun decode(buf: ByteBuf, cipher: StreamCipher): LoginResponse.ConnectOk {
val decodeDeviceIdentifier = buf.readBoolean()
val deviceIdentifier = if (decodeDeviceIdentifier) {
var identifier = 0
identifier = identifier or (((buf.readUnsignedByte() - cipher.nextInt()) and 0xFF) shl 24)
identifier = identifier or (((buf.readUnsignedByte() - cipher.nextInt()) and 0xFF) shl 16)
identifier = identifier or (((buf.readUnsignedByte() - cipher.nextInt()) and 0xFF) shl 8)
identifier = identifier or ((buf.readUnsignedByte() - cipher.nextInt()) and 0xFF)
identifier
} else {
buf.skipBytes(Int.SIZE_BYTES)
null
}
val playerModLevel = buf.readByte().toInt()
val playerMod = buf.readBoolean()
val playerIndex = buf.readUnsignedShort()
val playerMember = buf.readBoolean()
val accountHash = buf.readLong()
return LoginResponse.ConnectOk(
deviceLinkIdentifier = deviceIdentifier,
playerModLevel = playerModLevel,
playerMod = playerMod,
playerIndex = playerIndex,
playerMember = playerMember,
accountHash = accountHash,
cipher = cipher
)
}
override fun encode(packet: LoginResponse.ConnectOk, buf: ByteBuf, cipher: StreamCipher) {
buf.writeBoolean(packet.deviceLinkIdentifier != null)
if (packet.deviceLinkIdentifier != null) {
val identifier = IntArray(4)
identifier[0] = packet.deviceLinkIdentifier shr 24
identifier[1] = packet.deviceLinkIdentifier shr 16
identifier[2] = packet.deviceLinkIdentifier shr 8
identifier[3] = packet.deviceLinkIdentifier
for (byte in identifier) {
buf.writeByte(byte + packet.cipher.nextInt())
}
} else {
buf.writeInt(0)
}
buf.writeByte(packet.playerModLevel)
buf.writeBoolean(packet.playerMod)
buf.writeShort(packet.playerIndex)
buf.writeBoolean(packet.playerMember)
buf.writeLong(packet.accountHash)
}
}
| 2
|
Kotlin
|
63
| 79
|
e1e1a85d7a4d1840ca0738e3401d18ee40424860
| 2,572
|
rsmod
|
ISC License
|
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/TaskNodeCodec.kt
|
gradle
| 302,322
| false
| null |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.codecs
import org.gradle.api.Task
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.GeneratedSubclasses
import org.gradle.api.internal.TaskInputsInternal
import org.gradle.api.internal.TaskInternal
import org.gradle.api.internal.TaskOutputsInternal
import org.gradle.api.internal.provider.Providers
import org.gradle.api.internal.tasks.TaskDestroyablesInternal
import org.gradle.api.internal.tasks.TaskLocalStateInternal
import org.gradle.api.internal.tasks.properties.InputFilePropertyType
import org.gradle.api.internal.tasks.properties.InputParameterUtils
import org.gradle.api.internal.tasks.properties.OutputFilePropertyType
import org.gradle.api.internal.tasks.properties.PropertyValue
import org.gradle.api.internal.tasks.properties.PropertyVisitor
import org.gradle.api.specs.Spec
import org.gradle.api.tasks.FileNormalizer
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.problems.PropertyKind
import org.gradle.configurationcache.problems.PropertyTrace
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.IsolateContext
import org.gradle.configurationcache.serialization.IsolateOwner
import org.gradle.configurationcache.serialization.MutableIsolateContext
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.beans.BeanPropertyWriter
import org.gradle.configurationcache.serialization.beans.readPropertyValue
import org.gradle.configurationcache.serialization.beans.writeNextProperty
import org.gradle.configurationcache.serialization.readClassOf
import org.gradle.configurationcache.serialization.readCollection
import org.gradle.configurationcache.serialization.readCollectionInto
import org.gradle.configurationcache.serialization.readEnum
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.withDebugFrame
import org.gradle.configurationcache.serialization.withIsolate
import org.gradle.configurationcache.serialization.withPropertyTrace
import org.gradle.configurationcache.serialization.writeCollection
import org.gradle.configurationcache.serialization.writeEnum
import org.gradle.execution.plan.LocalTaskNode
import org.gradle.execution.plan.TaskNodeFactory
import org.gradle.internal.fingerprint.DirectorySensitivity
import org.gradle.internal.fingerprint.LineEndingSensitivity
import org.gradle.util.internal.DeferredUtil
class TaskNodeCodec(
private val userTypesCodec: Codec<Any?>,
private val taskNodeFactory: TaskNodeFactory
) : Codec<LocalTaskNode> {
override suspend fun WriteContext.encode(value: LocalTaskNode) {
val task = value.task
writeTask(task)
}
override suspend fun ReadContext.decode(): LocalTaskNode {
val task = readTask()
val node = taskNodeFactory.getOrCreateNode(task) as LocalTaskNode
node.isolated()
return node
}
private
suspend fun WriteContext.writeTask(task: TaskInternal) {
withDebugFrame({ task.path }) {
val taskType = GeneratedSubclasses.unpackType(task)
val projectPath = task.project.path
val taskName = task.name
writeClass(taskType)
writeString(projectPath)
writeString(taskName)
withDebugFrame({ taskType.name }) {
withTaskOf(taskType, task, userTypesCodec) {
writeUpToDateSpec(task)
writeCollection(task.outputs.cacheIfSpecs)
writeCollection(task.outputs.doNotCacheIfSpecs)
writeReasonNotToTrackState(task)
beanStateWriterFor(task.javaClass).run {
writeStateOf(task)
writeRegisteredPropertiesOf(
task,
this as BeanPropertyWriter
)
}
writeDestroyablesOf(task)
writeLocalStateOf(task)
writeRegisteredServicesOf(task)
}
}
}
}
private
suspend fun ReadContext.readTask(): Task {
val taskType = readClassOf<Task>()
val projectPath = readString()
val taskName = readString()
val task = createTask(projectPath, taskName, taskType)
withTaskOf(taskType, task, userTypesCodec) {
readUpToDateSpec(task)
readCollectionInto { task.outputs.cacheIfSpecs.uncheckedCast() }
readCollectionInto { task.outputs.doNotCacheIfSpecs.uncheckedCast() }
readReasonNotToTrackState(task)
beanStateReaderFor(task.javaClass).run {
readStateOf(task)
}
readRegisteredPropertiesOf(task)
readDestroyablesOf(task)
readLocalStateOf(task)
readRegisteredServicesOf(task)
}
return task
}
private
suspend fun WriteContext.writeUpToDateSpec(task: TaskInternal) {
// TODO - should just write this as a bean field of the outputs object, and also do this for the registered properties above
if (task.outputs.upToDateSpec.isEmpty) {
writeBoolean(false)
} else {
writeBoolean(true)
write(task.outputs.upToDateSpec)
}
}
private
suspend fun ReadContext.readUpToDateSpec(task: TaskInternal) {
if (readBoolean()) {
task.outputs.upToDateWhen(readNonNull<Spec<Task>>())
}
}
private
suspend fun WriteContext.writeReasonNotToTrackState(task: TaskInternal) {
writeNullableString(task.reasonNotToTrackState.orElse(null))
}
private
fun ReadContext.readReasonNotToTrackState(task: TaskInternal) {
val reasonNotToTrackState = readNullableString()
if (reasonNotToTrackState != null) {
task.doNotTrackState(reasonNotToTrackState)
}
}
private
suspend fun WriteContext.writeRegisteredServicesOf(task: TaskInternal) {
writeCollection(task.requiredServices)
}
private
suspend fun ReadContext.readRegisteredServicesOf(task: TaskInternal) {
readCollection {
task.usesService(readNonNull())
}
}
private
suspend fun WriteContext.writeDestroyablesOf(task: TaskInternal) {
val destroyables = (task.destroyables as TaskDestroyablesInternal).registeredFiles
if (destroyables.isEmpty) {
writeBoolean(false)
} else {
writeBoolean(true)
write(destroyables)
}
}
private
suspend fun ReadContext.readDestroyablesOf(task: TaskInternal) {
if (readBoolean()) {
task.destroyables.register(readNonNull<FileCollection>())
}
}
private
suspend fun WriteContext.writeLocalStateOf(task: TaskInternal) {
val localState = (task.localState as TaskLocalStateInternal).registeredFiles
if (localState.isEmpty) {
writeBoolean(false)
} else {
writeBoolean(true)
write(localState)
}
}
private
suspend fun ReadContext.readLocalStateOf(task: TaskInternal) {
if (readBoolean()) {
task.localState.register(readNonNull<FileCollection>())
}
}
}
private
suspend fun <T> T.withTaskOf(
taskType: Class<*>,
task: TaskInternal,
codec: Codec<Any?>,
action: suspend () -> Unit
) where T : IsolateContext, T : MutableIsolateContext {
withIsolate(IsolateOwner.OwnerTask(task), codec) {
withPropertyTrace(PropertyTrace.Task(taskType, task.path)) {
if (!task.isCompatibleWithConfigurationCache) {
forIncompatibleType(action)
} else {
action()
}
}
}
}
private
sealed class RegisteredProperty {
data class Input(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean
) : RegisteredProperty()
data class InputFile(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean,
val filePropertyType: InputFilePropertyType,
val skipWhenEmpty: Boolean,
val incremental: Boolean,
val fileNormalizer: Class<out FileNormalizer>?,
val directorySensitivity: DirectorySensitivity,
val lineEndingSensitivity: LineEndingSensitivity
) : RegisteredProperty()
data class OutputFile(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean,
val filePropertyType: OutputFilePropertyType
) : RegisteredProperty()
}
private
suspend fun WriteContext.writeRegisteredPropertiesOf(
task: Task,
propertyWriter: BeanPropertyWriter
) = propertyWriter.run {
suspend fun writeProperty(propertyName: String, propertyValue: Any?, kind: PropertyKind) {
writeString(propertyName)
writeNextProperty(propertyName, propertyValue, kind)
}
suspend fun writeInputProperty(propertyName: String, propertyValue: Any?) =
writeProperty(propertyName, propertyValue, PropertyKind.InputProperty)
suspend fun writeOutputProperty(propertyName: String, propertyValue: Any?) =
writeProperty(propertyName, propertyValue, PropertyKind.OutputProperty)
val inputProperties = collectRegisteredInputsOf(task)
writeCollection(inputProperties) { property ->
property.run {
when (this) {
is RegisteredProperty.InputFile -> {
val finalValue = DeferredUtil.unpackOrNull(propertyValue)
writeInputProperty(propertyName, finalValue)
writeBoolean(optional)
writeBoolean(true)
writeEnum(filePropertyType)
writeBoolean(skipWhenEmpty)
writeClass(fileNormalizer!!)
writeEnum(directorySensitivity)
writeEnum(lineEndingSensitivity)
}
is RegisteredProperty.Input -> {
val finalValue = InputParameterUtils.prepareInputParameterValue(propertyValue)
writeInputProperty(propertyName, finalValue)
writeBoolean(optional)
writeBoolean(false)
}
else -> throw IllegalStateException()
}
}
}
val outputProperties = collectRegisteredOutputsOf(task)
writeCollection(outputProperties) { property ->
property.run {
val finalValue = DeferredUtil.unpackOrNull(propertyValue)
writeOutputProperty(propertyName, finalValue)
writeBoolean(optional)
writeEnum(filePropertyType)
}
}
}
private
fun collectRegisteredOutputsOf(task: Task): List<RegisteredProperty.OutputFile> {
val properties = mutableListOf<RegisteredProperty.OutputFile>()
(task.outputs as TaskOutputsInternal).visitRegisteredProperties(object : PropertyVisitor.Adapter() {
override fun visitOutputFileProperty(
propertyName: String,
optional: Boolean,
value: PropertyValue,
filePropertyType: OutputFilePropertyType
) {
properties.add(
RegisteredProperty.OutputFile(
propertyName,
value,
optional,
filePropertyType
)
)
}
})
return properties
}
private
fun collectRegisteredInputsOf(task: Task): List<RegisteredProperty> {
val properties = mutableListOf<RegisteredProperty>()
(task.inputs as TaskInputsInternal).visitRegisteredProperties(object : PropertyVisitor.Adapter() {
override fun visitInputFileProperty(
propertyName: String,
optional: Boolean,
skipWhenEmpty: Boolean,
directorySensitivity: DirectorySensitivity,
lineEndingSensitivity: LineEndingSensitivity,
incremental: Boolean,
fileNormalizer: Class<out FileNormalizer>?,
propertyValue: PropertyValue,
filePropertyType: InputFilePropertyType
) {
properties.add(
RegisteredProperty.InputFile(
propertyName,
propertyValue,
optional,
filePropertyType,
skipWhenEmpty,
incremental,
fileNormalizer,
directorySensitivity,
lineEndingSensitivity
)
)
}
override fun visitInputProperty(
propertyName: String,
propertyValue: PropertyValue,
optional: Boolean
) {
properties.add(
RegisteredProperty.Input(
propertyName,
propertyValue,
optional
)
)
}
})
return properties
}
private
suspend fun ReadContext.readRegisteredPropertiesOf(task: Task) {
readInputPropertiesOf(task)
readOutputPropertiesOf(task)
}
private
suspend fun ReadContext.readInputPropertiesOf(task: Task) =
readCollection {
val propertyName = readString()
readPropertyValue(PropertyKind.InputProperty, propertyName) { propertyValue ->
val optional = readBoolean()
val isFileInputProperty = readBoolean()
when {
isFileInputProperty -> {
val filePropertyType = readEnum<InputFilePropertyType>()
val skipWhenEmpty = readBoolean()
val normalizer = readClass()
val directorySensitivity = readEnum<DirectorySensitivity>()
val lineEndingNormalization = readEnum<LineEndingSensitivity>()
task.inputs.run {
when (filePropertyType) {
InputFilePropertyType.FILE -> file(pack(propertyValue))
InputFilePropertyType.DIRECTORY -> dir(pack(propertyValue))
InputFilePropertyType.FILES -> files(pack(propertyValue))
}
}.run {
withPropertyName(propertyName)
optional(optional)
skipWhenEmpty(skipWhenEmpty)
withNormalizer(normalizer.uncheckedCast())
ignoreEmptyDirectories(directorySensitivity == DirectorySensitivity.IGNORE_DIRECTORIES)
normalizeLineEndings(lineEndingNormalization == LineEndingSensitivity.NORMALIZE_LINE_ENDINGS)
}
}
else -> {
task.inputs
.property(propertyName, propertyValue)
.optional(optional)
}
}
}
}
private
fun pack(value: Any?) = value ?: Providers.notDefined<Any>()
private
suspend fun ReadContext.readOutputPropertiesOf(task: Task) =
readCollection {
val propertyName = readString()
readPropertyValue(PropertyKind.OutputProperty, propertyName) { propertyValue ->
val optional = readBoolean()
val filePropertyType = readEnum<OutputFilePropertyType>()
task.outputs.run {
when (filePropertyType) {
OutputFilePropertyType.DIRECTORY -> dir(pack(propertyValue))
OutputFilePropertyType.DIRECTORIES -> dirs(pack(propertyValue))
OutputFilePropertyType.FILE -> file(pack(propertyValue))
OutputFilePropertyType.FILES -> files(pack(propertyValue))
}
}.run {
withPropertyName(propertyName)
optional(optional)
}
}
}
private
fun ReadContext.createTask(projectPath: String, taskName: String, taskClass: Class<out Task>) =
getProject(projectPath).tasks.createWithoutConstructor(taskName, taskClass) as TaskInternal
| 2,095
| null |
3792
| 13,076
|
c1b02a85c1d02816ba0c59fd02b656f6187a4472
| 17,037
|
gradle
|
Apache License 2.0
|
BazaarPay/src/main/java/ir/cafebazaar/bazaarpay/screens/payment/paymentmethods/PaymentMethodsType.kt
|
cafebazaar
| 489,705,723
| false
| null |
package ir.cafebazaar.bazaarpay.screens.payment.paymentmethods
internal enum class PaymentMethodsType(val value: String) {
INCREASE_BALANCE("increase_balance"),
ENOUGH_BALANCE("enough_balance"),
DIRECT_DEBIT_ACTIVATION("direct_debit_activation"),
DIRECT_DEBIT("direct_debit"),
POSTPAID_CREDIT_ACTIVATION("postpaid_credit_activation"),
POSTPAID_CREDIT("postpaid_credit");
}
| 5
|
Kotlin
|
1
| 8
|
99ad2be78716bd24b4c025bfbe1b12303d0b72c3
| 397
|
BazaarPay
|
Apache License 2.0
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultCheckBox.kt
|
Xanik
| 282,687,897
| false
| null |
package org.hexworks.zircon.internal.component.impl
import org.hexworks.zircon.api.behavior.Selectable
import org.hexworks.zircon.api.behavior.TextHolder
import org.hexworks.zircon.api.component.CheckBox
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.data.ComponentMetadata
import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy
import org.hexworks.zircon.api.extensions.whenEnabled
import org.hexworks.zircon.api.extensions.whenEnabledRespondWith
import org.hexworks.zircon.api.uievent.MouseEvent
import org.hexworks.zircon.api.uievent.UIEventPhase
import org.hexworks.zircon.internal.component.impl.DefaultCheckBox.CheckBoxState.*
import kotlin.jvm.Synchronized
@Suppress("DuplicatedCode")
class DefaultCheckBox(
componentMetadata: ComponentMetadata,
initialText: String,
renderingStrategy: ComponentRenderingStrategy<CheckBox>
) : CheckBox, DefaultComponent(
componentMetadata = componentMetadata,
renderer = renderingStrategy),
Selectable by Selectable.create(),
TextHolder by TextHolder.create(initialText) {
override var checkBoxState = UNCHECKED
private set
private var pressing = false
init {
render()
textProperty.onChange {
render()
}
selectedProperty.onChange {
this.checkBoxState = if (it.newValue) CHECKED else UNCHECKED
render()
}
}
@Synchronized
override fun mouseExited(event: MouseEvent, phase: UIEventPhase) = whenEnabledRespondWith {
if (phase == UIEventPhase.TARGET) {
pressing = false
this.checkBoxState = if (isSelected) CHECKED else UNCHECKED
}
super.mouseExited(event, phase)
}
@Synchronized
override fun activated() = whenEnabled {
pressing = true
this.checkBoxState = if (isSelected) UNCHECKING else CHECKING
render()
super.activated()
}
@Synchronized
override fun deactivated() = whenEnabled {
pressing = false
isSelected = isSelected.not()
this.checkBoxState = if (isSelected) CHECKED else UNCHECKED
super.deactivated()
}
@Synchronized
override fun focusTaken() = whenEnabled {
pressing = false
super.focusTaken()
}
override fun convertColorTheme(colorTheme: ColorTheme) = colorTheme.toInteractableStyle()
enum class CheckBoxState {
CHECKING,
CHECKED,
UNCHECKING,
UNCHECKED
}
}
| 1
| null |
1
| 2
|
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
| 2,561
|
zircon
|
Apache License 2.0
|
rendering/src/com/android/tools/rendering/HtmlLinkManager.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
|
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.rendering
import com.android.ide.common.repository.GoogleMavenArtifactId
import com.android.utils.SdkUtils
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiFile
import java.io.File
import java.net.MalformedURLException
interface HtmlLinkManager {
/** Handles a click in the [HtmlLinkManager]. */
fun interface Action {
/**
* Called when the action is clicked. If available, the [module] will be passed as a parameter.
*/
fun actionPerformed(module: Module?)
}
fun showNotification(content: String) = Unit
fun handleUrl(
url: String,
module: Module,
file: PsiFile,
hasRenderResult: Boolean,
surface: RefreshableSurface,
)
fun createBuildModuleUrl(): String = URL_BUILD_FOR_RENDERING
fun createBuildProjectUrl(): String = URL_BUILD
fun createSyncProjectUrl(): String = URL_SYNC
fun createEditClassPathUrl(): String = URL_EDIT_CLASSPATH
fun createOpenClassUrl(className: String): String = "$URL_OPEN_CLASS$className"
fun createCommandLink(command: CommandLink): String
fun createActionLink(action: Action): String
fun createShowTagUrl(tag: String): String = "$URL_SHOW_TAG$tag"
fun createNewClassUrl(className: String): String = "$URL_CREATE_CLASS$className"
fun createOpenStackUrl(
className: String,
methodName: String,
fileName: String,
lineNumber: Int,
): String = "$URL_OPEN$className#$methodName;$fileName:$lineNumber"
fun createReplaceTagsUrl(from: String, to: String): String = "$URL_REPLACE_TAGS$from/$to"
fun createEditAttributeUrl(attribute: String, value: String): String =
"$URL_EDIT_ATTRIBUTE$attribute/$value"
fun createDisableSandboxUrl(): String = URL_DISABLE_SANDBOX
fun createRefreshRenderUrl(): String = URL_REFRESH_RENDER
fun createClearCacheUrl(): String = URL_CLEAR_CACHE_AND_NOTIFY
fun createAddDependencyUrl(artifactId: GoogleMavenArtifactId): String =
"$URL_ADD_DEPENDENCY$artifactId"
fun createAddDebugDependencyUrl(artifactId: GoogleMavenArtifactId): String =
"$URL_ADD_DEBUG_DEPENDENCY$artifactId"
fun createReplaceAttributeValueUrl(
attribute: String,
oldValue: String,
newValue: String,
): String = "$URL_REPLACE_ATTRIBUTE_VALUE$attribute/$oldValue/$newValue"
fun createIgnoreFragmentsUrl(): String = URL_ACTION_IGNORE_FRAGMENTS
fun createAssignFragmentUrl(id: String?): String = "$URL_ASSIGN_FRAGMENT_URL${(id ?: "")}"
fun createPickLayoutUrl(activityName: String): String = "$URL_ASSIGN_LAYOUT_URL$activityName"
fun createAssignLayoutUrl(activityName: String, layout: String): String =
"$URL_ASSIGN_LAYOUT_URL$activityName:$layout"
companion object {
/**
* Creates a file url for the given file and line position
*
* @param file the file
* @param line the line, or -1 if not known
* @param column the column, or 0 if not known
* @return a URL which points to a given position in a file
*/
@JvmStatic
fun createFilePositionUrl(file: File, line: Int, column: Int): String? {
return try {
val fileUrl = SdkUtils.fileToUrlString(file)
if (line != -1) {
return if (column > 0) {
"$fileUrl:$line:$column"
} else {
"$fileUrl:$line"
}
}
fileUrl
} catch (e: MalformedURLException) {
// Ignore
Logger.getInstance(HtmlLinkManager::class.java).error(e)
null
}
}
@JvmField
val NOOP_LINK_MANAGER =
object : HtmlLinkManager {
override fun handleUrl(
url: String,
module: Module,
file: PsiFile,
hasRenderResult: Boolean,
surface: RefreshableSurface,
) {}
override fun createCommandLink(command: CommandLink): String = ""
override fun createActionLink(action: Action): String = ""
}
@JvmField
val NOOP_SURFACE =
object : RefreshableSurface {
override fun handleRefreshRenderUrl() {}
override fun requestRender() {}
}
}
interface RefreshableSurface {
fun handleRefreshRenderUrl()
fun requestRender()
}
interface CommandLink : Runnable {
fun executeCommand()
}
}
const val URL_BUILD = "action:build"
const val URL_BUILD_FOR_RENDERING = "action:buildForRendering"
const val URL_SYNC = "action:sync"
const val URL_EDIT_CLASSPATH = "action:classpath"
const val URL_OPEN_CLASS = "openClass:"
const val URL_REPLACE_TAGS = "replaceTags:"
const val URL_SHOW_TAG = "showTag:"
const val URL_CREATE_CLASS = "createClass:"
const val URL_OPEN = "open:"
const val URL_EDIT_ATTRIBUTE = "editAttribute:"
const val URL_DISABLE_SANDBOX = "disableSandbox:"
const val URL_REFRESH_RENDER = "refreshRender"
const val URL_CLEAR_CACHE_AND_NOTIFY = "clearCacheAndNotify"
const val URL_ADD_DEPENDENCY = "addDependency:"
const val URL_ADD_DEBUG_DEPENDENCY = "addDebugDependency:"
const val URL_ACTION_IGNORE_FRAGMENTS = "action:ignoreFragment"
const val URL_ASSIGN_FRAGMENT_URL = "assignFragmentUrl:"
const val URL_ASSIGN_LAYOUT_URL = "assignLayoutUrl:"
const val URL_REPLACE_ATTRIBUTE_VALUE = "replaceAttributeValue:"
| 5
|
Kotlin
|
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 5,835
|
android
|
Apache License 2.0
|
app/src/main/java/com/kylecorry/procamera/ui/MainFragment.kt
|
kylecorry31
| 782,928,235
| false
|
{"Kotlin": 42618}
|
package com.kylecorry.procamera.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.OptIn
import androidx.camera.core.ExperimentalZeroShutterLag
import androidx.camera.core.ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY
import androidx.core.view.isVisible
import com.kylecorry.andromeda.camera.ImageCaptureSettings
import com.kylecorry.andromeda.core.math.DecimalFormatter
import com.kylecorry.andromeda.core.time.CoroutineTimer
import com.kylecorry.andromeda.core.ui.setOnProgressChangeListener
import com.kylecorry.andromeda.files.IFileSystem
import com.kylecorry.andromeda.fragments.BoundFragment
import com.kylecorry.andromeda.fragments.inBackground
import com.kylecorry.andromeda.haptics.HapticFeedbackType
import com.kylecorry.andromeda.haptics.IHapticMotor
import com.kylecorry.andromeda.pickers.Pickers
import com.kylecorry.luna.coroutines.CoroutineQueueRunner
import com.kylecorry.luna.coroutines.onIO
import com.kylecorry.luna.coroutines.onMain
import com.kylecorry.procamera.R
import com.kylecorry.procamera.databinding.FragmentMainBinding
import com.kylecorry.procamera.infrastructure.camera.SensitivityProvider
import com.kylecorry.procamera.infrastructure.io.FileNameGenerator
import com.kylecorry.procamera.infrastructure.io.MediaStoreSaver
import dagger.hilt.android.AndroidEntryPoint
import java.time.Duration
import javax.inject.Inject
@AndroidEntryPoint
class MainFragment : BoundFragment<FragmentMainBinding>() {
// DI
@Inject
lateinit var formatter: FormatService
@Inject
lateinit var files: IFileSystem
@Inject
lateinit var haptics: IHapticMotor
@Inject
lateinit var fileNameGenerator: FileNameGenerator
@Inject
lateinit var mediaStoreSaver: MediaStoreSaver
// State
private var focusPercent by state<Float?>(null)
private var iso by state<Int?>(null)
private var shutterSpeed by state<Duration?>(null)
private var interval by state<Duration?>(null)
private var isCapturing by state(false)
private var zoomRatio by state(1f)
private var sensitivities by state(emptyList<Int>())
private var cameraStartCounter by state(0)
private var previousShutterSpeed by state<Duration?>(null)
private var isCameraRunning by state(false)
private val queue = CoroutineQueueRunner(1)
private var hasPendingPhoto = false
private var turnOffDuringInterval = false
private val intervalometer = CoroutineTimer {
if (turnOffDuringInterval) {
println("INTERVAL")
hasPendingPhoto = true
onMain {
restartCamera()
}
} else {
takePhoto()
}
}
private val delayedPhotoTimer = CoroutineTimer {
takePhoto()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.focus.setOnProgressChangeListener { progress, _ ->
focusPercent = progress / 100f
}
binding.captureButton.setOnClickListener {
takePhoto()
}
binding.iso.setOnClickListener {
val sensitivityNames =
listOf(getString(R.string.auto)) + sensitivities.map { it.toString() }
Pickers.item(
requireContext(),
getString(R.string.iso),
sensitivityNames,
sensitivities.indexOf(iso) + 1,
) {
it ?: return@item
iso = if (it == 0) {
null
} else {
sensitivities[it - 1]
}
}
}
binding.shutterSpeed.setOnClickListener {
Pickers.number(
requireContext(),
getString(R.string.shutter_speed),
default = shutterSpeed?.toMillis()?.div(1000f),
allowDecimals = true,
allowNegative = false,
hint = getString(R.string.shutter_speed)
) {
if (it != null) {
shutterSpeed = Duration.ofMillis((it.toFloat() * 1000).toLong())
}
}
}
binding.interval.setOnClickListener {
CustomUiUtils.pickDuration(
requireContext(),
interval,
getString(R.string.interval),
showSeconds = true
) {
interval = it
}
}
binding.camera.setOnZoomChangeListener {
zoomRatio = binding.camera.camera?.zoom?.ratio ?: 1f
}
}
@OptIn(ExperimentalZeroShutterLag::class)
override fun onResume() {
super.onResume()
// TODO: Adjust for sensor rotation + display rotation
binding.camera.setOnReadyListener {
val camera = binding.camera.camera ?: return@setOnReadyListener
val sensitivityProvider = SensitivityProvider()
sensitivities = sensitivityProvider.getValues(camera)
cameraStartCounter++
if (hasPendingPhoto) {
delayedPhotoTimer.once(Duration.ofMillis(500))
}
}
startCamera()
}
override fun onPause() {
super.onPause()
intervalometer.stop()
delayedPhotoTimer.stop()
haptics.off()
stopCamera()
isCapturing = false
}
override fun onUpdate() {
super.onUpdate()
effect("focus", focusPercent, cameraStartCounter) {
val pct = focusPercent
binding.focusLabel.text = getString(
R.string.focus_amount, if (pct == null) {
getString(R.string.auto)
} else {
DecimalFormatter.format(pct * 100, 0)
}
)
binding.camera.camera?.setFocusDistancePercentage(pct)
}
effect("iso", iso, cameraStartCounter) {
val iso = iso
binding.iso.text = iso?.toString() ?: getString(R.string.auto)
binding.camera.camera?.setSensitivity(iso)
}
effect("shutter_speed", shutterSpeed, cameraStartCounter) {
val shutterSpeed = shutterSpeed
binding.shutterSpeed.text =
shutterSpeed?.let { DecimalFormatter.format(shutterSpeed.toMillis() / 1000f, 2) }
?: getString(R.string.auto)
binding.camera.camera?.setExposureTime(shutterSpeed)
val previous = previousShutterSpeed
previousShutterSpeed = shutterSpeed
if (shutterSpeed != previous && previous != null && previous > Duration.ofMillis(250)) {
restartCamera()
}
}
effect("interval", interval, lifecycleHookTrigger.onResume()) {
val interval = interval
binding.interval.text =
interval?.let { DecimalFormatter.format(it.toMillis() / 1000f, 2) }
?: getString(R.string.off)
if (interval != null) {
turnOffDuringInterval = interval > Duration.ofSeconds(2)
intervalometer.interval(interval)
} else {
val wasRunning = turnOffDuringInterval
intervalometer.stop()
hasPendingPhoto = false
turnOffDuringInterval = false
if (wasRunning) {
restartCamera()
}
}
}
effect("capture_button", isCapturing) {
val isCapturing = isCapturing
binding.captureButton.isVisible = !isCapturing
binding.loadingIndicator.isVisible = isCapturing
}
effect("zoom", zoomRatio, cameraStartCounter) {
val zoomRatio = zoomRatio
binding.zoom.text = DecimalFormatter.format(zoomRatio, 2) + "x"
// binding.camera.camera?.setZoomRatio(zoomRatio)
}
effect("blackout", isCameraRunning, cameraStartCounter) {
val isCameraRunning = isCameraRunning
binding.blackout.isVisible = !isCameraRunning
}
}
fun takePhoto() {
inBackground {
queue.enqueue {
val fileName = fileNameGenerator.generate()
val file = files.getFile(fileName, true)
isCapturing = true
onIO {
binding.camera.capture(file)
mediaStoreSaver.copyToMediaStore(file)
file.delete()
}
haptics.feedback(HapticFeedbackType.Click)
isCapturing = false
hasPendingPhoto = false
if (turnOffDuringInterval) {
onMain {
stopCamera()
}
}
}
}
}
private fun startCamera() {
binding.camera.start(
readFrames = false,
captureSettings = ImageCaptureSettings(
quality = 100,
captureMode = CAPTURE_MODE_MAXIMIZE_QUALITY,
rotation = requireActivity().windowManager.defaultDisplay.rotation
)
)
isCameraRunning = true
}
private fun stopCamera() {
binding.camera.stop()
isCameraRunning = false
}
private fun restartCamera() {
stopCamera()
startCamera()
}
override fun generateBinding(
layoutInflater: LayoutInflater,
container: ViewGroup?
): FragmentMainBinding {
return FragmentMainBinding.inflate(layoutInflater, container, false)
}
}
| 29
|
Kotlin
|
0
| 1
|
14774132efecdaacb2ab6c724986f4b0a4f21489
| 9,733
|
Pro-Camera
|
MIT License
|
extensions/rx/src/main/java/com/extensions/rx/functions/Disposable.kt
|
VitaliyDoskoch
| 263,280,184
| false
| null |
package com.extensions.rx.functions
import io.reactivex.disposables.Disposable
/**
* Recreates [Disposable] on trigger function invocation.
* @param [create] function, which gets called instantly and creates [Disposable],
* providing trigger function.
* When consumer calls that trigger function, [create] function is invoked again.
*/
fun recreateOnEvent(create: (() -> Unit) -> Disposable) {
fun newEventHandler(): () -> Unit = { create(newEventHandler()) }
create(newEventHandler())
}
| 0
|
Kotlin
|
0
| 0
|
9de9670b1b24934a39122b58517d026569cea1d3
| 504
|
Movies
|
MIT License
|
src/main/kotlin/com/github/kerubistan/kerub/network/SimpleInterface.kt
|
fossabot
| 226,186,649
| true
|
{"Kotlin": 2261401, "Gherkin": 81712, "HTML": 74339, "JavaScript": 54476, "CSS": 754}
|
package com.github.kerubistan.kerub.network
import com.fasterxml.jackson.annotation.JsonTypeName
@JsonTypeName("simple")
data class SimpleInterface(
override val name: String,
override val portSpeedPerSec: Int,
val device : String
) : NetworkInterface
| 0
|
Kotlin
|
0
| 0
|
50ac690f71b018f3db60c6b44f203902baecf50a
| 259
|
kerub
|
Apache License 2.0
|
src/main/kotlin/com/andrejusti/example/kotlin/springboot/graphql/domain/controller/graphql/config/CustomGraphQlErrorHandler.kt
|
justiandre
| 145,351,118
| false
| null |
package com.andrejusti.example.kotlin.springboot.graphql.domain.controller.graphql.config
import com.fasterxml.jackson.annotation.JsonIgnore
import graphql.ErrorType
import graphql.ExceptionWhileDataFetching
import graphql.GraphQLError
import graphql.servlet.GraphQLErrorHandler
import org.apache.commons.lang3.exception.ExceptionUtils
import org.springframework.stereotype.Component
import com.andrejusti.example.kotlin.springboot.graphql.infrastructure.exception.ValidationException
@Component
class CustomGraphQlErrorHandler : GraphQLErrorHandler {
companion object {
const val KEY_ERRO_VALIDATION = "ItemValidationErrors"
}
override fun processErrors(errors: List<GraphQLError>): List<GraphQLError> {
val erros = errors.filter { !isServerError(it) }
val errosException = errors
.filter { isServerError(it) }
.map { parseGraphQLErrorAdapterException(it) }
return erros + errosException
}
private fun isServerError(error: GraphQLError) = error is ExceptionWhileDataFetching
private fun parseGraphQLErrorAdapterException(graphQLError: GraphQLError) =
if (isValidationException(graphQLError))
GraphQLErrorAdapterExceptionValidation(graphQLError)
else
GraphQLErrorAdapterException(graphQLError)
private fun isValidationException(graphQLError: GraphQLError) =
(graphQLError as ExceptionWhileDataFetching).exception is ValidationException
private open class GraphQLErrorAdapterException(@JsonIgnore val graphQLError: GraphQLError) : GraphQLError by graphQLError {
override fun getMessage() = getExceptionWhileDataFetching().exception.message
override fun getExtensions(): Map<String, Any> =
getExceptionWhileDataFetching().exception
.let { mapOf(it.javaClass.simpleName to ExceptionUtils.getRootCauseMessage(it)) }
protected fun getExceptionWhileDataFetching() = graphQLError as ExceptionWhileDataFetching
}
private class GraphQLErrorAdapterExceptionValidation(@JsonIgnore val graphQLErrorValidation: GraphQLError) : GraphQLErrorAdapterException(graphQLErrorValidation) {
override fun getExtensions() = mapOf(KEY_ERRO_VALIDATION to getValidationException().itemValidationErrors)
override fun getErrorType() = ErrorType.ValidationError
private fun getValidationException() = getExceptionWhileDataFetching().exception as ValidationException
}
}
| 0
|
Kotlin
|
4
| 33
|
e81a9c6daff1c2372cd27aecbe97545a4b7f24fc
| 2,521
|
example-kotlin-springboot-graphql
|
MIT License
|
petcare-sample/b2c/mobile-app/petcare-with-sdk/app/src/main/java/com/wso2_sample/api_auth_sample/features/home/presentation/screens/profile/ProfileScreenViewModel.kt
|
wso2
| 113,807,615
| false
|
{"JavaScript": 4542969, "TypeScript": 1704847, "Java": 1619866, "CSS": 774091, "Kotlin": 346914, "Shell": 339125, "Ballerina": 176145, "C#": 170551, "Batchfile": 156676, "HTML": 57598, "Swift": 40860, "Objective-C": 39341, "ASP.NET": 23571, "PHP": 11361, "Python": 10018, "TSQL": 5305, "Less": 2625, "Dockerfile": 1701, "Hack": 919, "Ruby": 464}
|
/*
* Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.wso2_sample.api_auth_sample.features.home.presentation.screens.profile
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wso2_sample.api_auth_sample.features.home.domain.models.UserDetails
import com.wso2_sample.api_auth_sample.features.home.domain.repository.PetRepository
import com.wso2_sample.api_auth_sample.features.login.domain.repository.AsgardeoAuthRepository
import com.wso2_sample.api_auth_sample.util.navigation.NavigationViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import io.asgardeo.android.core_auth_direct.provider.providers.authentication.AuthenticationProvider
import io.asgardeo.android.core_auth_direct.provider.providers.token.TokenProvider
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProfileScreenViewModel @Inject constructor(
@ApplicationContext private val applicationContext: Context,
asgardeoAuthRepository: AsgardeoAuthRepository,
private val petRepository: PetRepository
) : ViewModel() {
companion object {
const val TAG = "ProfileScreen"
}
private val _state = MutableStateFlow(ProfileScreenState())
val state = _state
private var authenticationProvider: AuthenticationProvider
private var tokenProvider: TokenProvider
init {
authenticationProvider = asgardeoAuthRepository.getAuthenticationProvider()
tokenProvider = asgardeoAuthRepository.getTokenProvider()
_state.update {
it.copy(isLoading = false)
}
}
init {
getBasicUserInfo()
getDecodedIdToken()
}
fun navigateToHome() {
viewModelScope.launch {
NavigationViewModel.navigationEvents.emit(
NavigationViewModel.Companion.NavigationEvent.NavigateToHome
)
}
}
private fun getBasicUserInfo() {
_state.update {
it.copy(
isLoading = true
)
}
viewModelScope.launch {
runCatching {
authenticationProvider.getBasicUserInfo(applicationContext)
}.onSuccess { userDetails ->
_state.update {
it.copy(
user = UserDetails(
username = userDetails?.get("sub").toString(),
firstName = userDetails?.get("given_name").toString(),
lastName = userDetails?.get("family_name").toString(),
email = userDetails?.get("email").toString()
),
isLoading = false
)
}
_state.update {
it.copy(
isLoading = false
)
}
}.onFailure { e ->
_state.update {
it.copy(
error = e.message!!,
isLoading = false
)
}
}
}
}
private fun getDecodedIdToken() {
viewModelScope.launch {
tokenProvider.getDecodedIDToken(applicationContext)
}
}
fun logout() {
viewModelScope.launch {
_state.update {
it.copy(
isLoading = true
)
}
try {
authenticationProvider.logout(applicationContext)
NavigationViewModel.navigationEvents.emit(
NavigationViewModel.Companion.NavigationEvent.NavigateToLanding
)
} catch (e: Exception) {
_state.update {
it.copy(
error = e.message!!,
isLoading = false
)
}
}
}
}
}
| 46
|
JavaScript
|
226
| 77
|
df5f0d37169fd966cbc0c4c68a47f11ebec77a77
| 4,746
|
samples-is
|
Apache License 2.0
|
src/main/kotlin/nl/deltadak/plep/ui/settingspane/colors/ColorsList.kt
|
deltadak
| 79,740,220
| false
| null |
package nl.deltadak.plep.ui.settingspane.colors
import javafx.scene.control.ColorPicker
import nl.deltadak.plep.database.tables.Colors
import nl.deltadak.plep.ui.util.converters.toColor
import nl.deltadak.plep.ui.util.converters.toHex
/**
* This class represents the few color pickers with which the user can change the colors to color a HomeworkTask with.
*/
class ColorsList(
/** A list of FXML references to the ColorPickers to set up. */
private val colorPickers: List<ColorPicker>) {
/**
* Set up the color pickers given.
*
* @param refreshUI Should refresh UI when called.
*/
fun setup(refreshUI: () -> Unit) {
// Get the colors from the database, so the colorpickers can be set to those colors.
Colors.getAll().mapIndexed { index, color ->
colorPickers[index].styleClass.add("button")
// Set the color in the database on the color picker.
colorPickers[index].value = color.toColor()
}
@Suppress("RedundantLambdaArrow") // Needed to have type inference for 'it'
colorPickers.forEach { it.setOnAction{ _ -> editColor(it, refreshUI) }}
}
/**
* Updates the value of the color in the database.
*
* @param colorPicker The ColorPicker that is edited.
* @param refreshUI Should refresh UI when called.
*/
private fun editColor(colorPicker: ColorPicker, refreshUI: () -> Unit) {
val id = colorPickers.indexOf(colorPicker)
Colors.update(id, colorPicker.value.toHex())
refreshUI()
}
}
| 26
| null |
1
| 2
|
a5ee4e8f389bfa5c312eea3589b877c5cd468877
| 1,575
|
plep
|
MIT License
|
src/main/kotlin/nl/deltadak/plep/ui/settingspane/colors/ColorsList.kt
|
deltadak
| 79,740,220
| false
| null |
package nl.deltadak.plep.ui.settingspane.colors
import javafx.scene.control.ColorPicker
import nl.deltadak.plep.database.tables.Colors
import nl.deltadak.plep.ui.util.converters.toColor
import nl.deltadak.plep.ui.util.converters.toHex
/**
* This class represents the few color pickers with which the user can change the colors to color a HomeworkTask with.
*/
class ColorsList(
/** A list of FXML references to the ColorPickers to set up. */
private val colorPickers: List<ColorPicker>) {
/**
* Set up the color pickers given.
*
* @param refreshUI Should refresh UI when called.
*/
fun setup(refreshUI: () -> Unit) {
// Get the colors from the database, so the colorpickers can be set to those colors.
Colors.getAll().mapIndexed { index, color ->
colorPickers[index].styleClass.add("button")
// Set the color in the database on the color picker.
colorPickers[index].value = color.toColor()
}
@Suppress("RedundantLambdaArrow") // Needed to have type inference for 'it'
colorPickers.forEach { it.setOnAction{ _ -> editColor(it, refreshUI) }}
}
/**
* Updates the value of the color in the database.
*
* @param colorPicker The ColorPicker that is edited.
* @param refreshUI Should refresh UI when called.
*/
private fun editColor(colorPicker: ColorPicker, refreshUI: () -> Unit) {
val id = colorPickers.indexOf(colorPicker)
Colors.update(id, colorPicker.value.toHex())
refreshUI()
}
}
| 26
| null |
1
| 2
|
a5ee4e8f389bfa5c312eea3589b877c5cd468877
| 1,575
|
plep
|
MIT License
|
Xmusic/src/main/java/com/nct/xmusicstation/event/PlayingSongEvent.kt
|
ToanMobile
| 584,599,884
| false
| null |
package com.nct.xmusicstation.event
import com.nct.xmusicstation.data.model.song.SongDetail
import com.toan_itc.core.base.event.Event
/**
* Created by Toan.IT on 12/20/17.
* Email:<EMAIL>
*/
class PlayingSongEvent(val song: SongDetail?, val isDownload : Boolean = false):Event()
| 0
|
Kotlin
|
0
| 0
|
8dd243dbd3d849260988b3887dcf5d14ea462b39
| 286
|
skymusic.xms.box.app
|
Apache License 2.0
|
app/src/main/java/co/gov/isabu/showcase/tasks/CacheUpdateTask.kt
|
AzaelDragon
| 216,564,766
| false
| null |
package co.gov.isabu.showcase.tasks
import android.app.ProgressDialog
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import co.gov.isabu.showcase.helpers.NetworkHelper
import co.gov.isabu.showcase.helpers.StorageHelper
import java.lang.ref.WeakReference
/**
* Asynchronous Worker Task for refreshing the System's Internal Storage cache.
*/
class CacheUpdateTask internal constructor(activity: AppCompatActivity) : AsyncTask<Unit, CacheUpdateTask.Progress, Unit>() {
private val activityReference: WeakReference<AppCompatActivity> = WeakReference(activity)
private lateinit var mProgressDialog: ProgressDialog
/**
* Simple class to create dynamic progress dialogs based on title.
*/
class Progress(val title: String, val showFlag: Boolean)
/**
* Instantiate dynamic progress dialog
*/
override fun onPreExecute() {
this.mProgressDialog = ProgressDialog(activityReference.get())
this.mProgressDialog.setTitle("Realizando actividad de refresco de caché")
this.mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER)
this.mProgressDialog.isIndeterminate = true
this.mProgressDialog.setCancelable(false)
}
/**
* Completely downloads again the JSON resource map from the remote URL.
*/
override fun doInBackground(vararg params: Unit?) {
val activity = activityReference.get()!!
publishProgress(Progress("Reconstruyendo mapa desde localización remota...", true))
NetworkHelper.fetchMapFromRemote(activity)
publishProgress(Progress("Refrescando cache...", true))
}
/**
* Refreshes the progress dialog with the provided title, and verifies if it needs to be shown
* in screen.
*/
override fun onProgressUpdate(vararg values: Progress?) {
val progressObj = values[0]!!
this.mProgressDialog.setTitle(progressObj.title)
if (!mProgressDialog.isShowing && progressObj.showFlag) this.mProgressDialog.show()
}
/**
* Verifies and downloads (if required) all the required files pending update that get detected
* on the restart of the application.
*/
override fun onPostExecute(result: Unit?) {
val activity = activityReference.get()!!
if (mProgressDialog.isShowing) mProgressDialog.dismiss()
StorageHelper(activity)
}
}
| 0
|
Kotlin
|
0
| 0
|
30253e5cc75f06c43329316e2f0892022d5aacb2
| 2,411
|
isabu-showcase-app
|
MIT License
|
year2019/day04/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day04/part2/Year2019Day04Part2.kt
|
curtislb
| 226,797,689
| false
| null |
/*
--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching digits are not part of a
larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the following are now true:
- 112233 meets these criteria because the digits never decrease and all repeated digits are exactly
two digits long.
- 123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444).
- 111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double
22).
How many different passwords within the range given in your puzzle input meet all of the criteria?
*/
package com.curtislb.adventofcode.year2019.day04.part2
import com.curtislb.adventofcode.common.io.readIntRange
import com.curtislb.adventofcode.year2019.day04.password.ExactLengthGenerator
import com.curtislb.adventofcode.year2019.day04.password.ExactRepeatCountDigitGenerator
import com.curtislb.adventofcode.year2019.day04.password.InRangeGenerator
import com.curtislb.adventofcode.year2019.day04.password.NonDecreasingGenerator
import com.curtislb.adventofcode.year2019.day04.password.SatisfiesAllGenerator
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2019, day 4, part 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param passwordLength The number of digits in a valid password.
* @param repeatCount The exact number of times a digit must be repeated in a valid password.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
passwordLength: Int = 6,
repeatCount: Int = 2
): Int {
val passwordRange = inputPath.toFile().readIntRange()
val generator = SatisfiesAllGenerator(
ExactLengthGenerator(passwordLength),
InRangeGenerator(passwordRange.first, passwordRange.last),
NonDecreasingGenerator(),
ExactRepeatCountDigitGenerator(repeatCount)
)
return generator.countPasswords()
}
fun main() {
println(solve())
}
| 0
|
Kotlin
|
1
| 1
|
e9ef1f42e245d730edeb0ebec57de515992d84e5
| 2,054
|
AdventOfCode
|
MIT License
|
app/src/main/java/com/fxn/bubbletabbarapp/MainActivity.kt
|
changefouk
| 337,042,273
| true
|
{"Kotlin": 26067}
|
package com.fxn.bubbletabbarapp
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.fxn.OnBubbleClickListener
import com.fxn.ariana.ArianaBackgroundListener
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val height = displayMetrics.heightPixels
val width = displayMetrics.widthPixels
Log.e("height", "-> " + height)
Log.e("width", "-> " + width)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
/*bubbleTabBar.addBubbleListener(object : OnBubbleClickListener {
override fun onBubbleClick(id: Int) {
when (id) {
R.id.home -> viewpager.currentItem = 0
R.id.log -> viewpager.currentItem = 1
R.id.doc -> viewpager.currentItem = 2
R.id.setting -> viewpager.currentItem = 3
}
}
})*/
// The second lambda parameter is not used here since it is the menu item index
bubbleTabBar.addBubbleListener(object : OnBubbleClickListener {
override fun onBubbleClick(id: Int, position: Int) {
when (id) {
R.id.home -> {
viewpager.currentItem = 0
bubbleTabBar.addDotBadge(R.id.doc)
}
R.id.log -> viewpager.currentItem = 1
R.id.doc -> {
viewpager.currentItem = 2
bubbleTabBar.removeDotBadges(R.id.doc)
}
R.id.setting -> viewpager.currentItem = 3
}
}
})
bubbleTabBar.setupBubbleTabBar(viewpager)
viewpager.setDurationScroll(1000)
viewpager.adapter = ViewPagerAdapter(supportFragmentManager).apply {
list = ArrayList<String>().apply {
add("Home")
add("Logger")
add("Documents")
add("Settings")
}
}
viewpager.addOnPageChangeListener(
ArianaBackgroundListener(
getColors(),
iv,
viewpager
)
)
bubbleTabBar.addDotBadge(R.id.doc)
}
private fun getColors(): IntArray {
return intArrayOf(
ContextCompat.getColor(this, R.color.home),
ContextCompat.getColor(this, R.color.logger),
ContextCompat.getColor(this, R.color.documents),
ContextCompat.getColor(this, R.color.settings),
ContextCompat.getColor(this, R.color.home)
)
}
}
| 0
|
Kotlin
|
1
| 0
|
f55b7d1cc877a9b967ad9e77ff75fec17f2328b1
| 3,082
|
BubbleTabBar
|
Apache License 2.0
|
sample/src/main/java/com/readdle/swiftjava/sample/asbtracthierarhy/AbstractType.kt
|
readdle
| 116,164,472
| false
|
{"Gradle": 7, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 9, "Kotlin": 29, "Java": 46, "Swift": 22, "YAML": 2}
|
package com.readdle.swiftjava.sample.asbtracthierarhy
import com.readdle.codegen.anotation.SwiftValue
@SwiftValue(hasSubclasses = true)
open class AbstractType protected constructor() {
external fun basicMethod(): String
}
| 4
|
Java
|
12
| 28
|
b2c263239055b4224ea1c1dcd0afa99e294b0a1d
| 231
|
swift-java-codegen
|
MIT License
|
cams/src/main/java/com/linwei/cams/http/repository/IDataRepository.kt
|
WeiShuaiDev
| 390,686,269
| false
| null |
package com.linwei.cams.http.repository
import android.app.Application
/**
* ---------------------------------------------------------------------
* @Author: WeiShuai
* @Time: 2020/7/14
* @Contact: <EMAIL>
* @Github: https://github.com/WeiShuaiDev
* @Description:
*-----------------------------------------------------------------------
*/
interface IDataRepository {
/**
* 根据 [serviceClass] 从 `Cache` 获取 `Retrofit` 接口对象
* @param serviceClass [Class]
* @return [T]
*/
fun <T> obtainRetrofitService(serviceClass: Class<T>): T
/**
* 根据 [serviceClass] 从 `RxCache` 获取 `Retrofit` 接口对象
* @param serviceClass [Class]
* @return [T]
*/
fun <T> obtainRxCacheService(serviceClass: Class<T>): T
/**
* 清除 `RxCache` 中数据
*/
fun clearAllRxCache()
/**
* 返回 [Application]
*/
fun fetchApplication(): Application
}
| 1
|
Kotlin
|
1
| 1
|
3c7289aae35551ee53284d91e96ad5f24c21eb50
| 902
|
Cams
|
Apache License 2.0
|
common/build/generated/ksp/main/kotlin/dev/kord/common/entity/TeamMembershipState.kt
|
kordlib
| 202,856,399
| false
| null |
// THIS FILE IS AUTO-GENERATED BY KordEnumProcessor.kt, DO NOT EDIT!
@file:Suppress(names = arrayOf("RedundantVisibilityModifier", "IncorrectFormatting",
"ReplaceArrayOfWithLiteral", "SpellCheckingInspection", "GrazieInspection"))
package dev.kord.common.entity
import kotlin.Any
import kotlin.Boolean
import kotlin.Deprecated
import kotlin.DeprecationLevel
import kotlin.Int
import kotlin.LazyThreadSafetyMode.PUBLICATION
import kotlin.ReplaceWith
import kotlin.String
import kotlin.Suppress
import kotlin.collections.List
import kotlin.jvm.JvmField
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
/**
* See [TeamMembershipState]s in the
* [Discord Developer Documentation](https://discord.com/developers/docs/topics/teams#data-models-membership-state-enum).
*/
@Serializable(with = TeamMembershipState.Serializer::class)
public sealed class TeamMembershipState(
/**
* The raw value used by Discord.
*/
public val `value`: Int,
) {
public final override fun equals(other: Any?): Boolean = this === other ||
(other is TeamMembershipState && this.value == other.value)
public final override fun hashCode(): Int = value.hashCode()
public final override fun toString(): String =
"TeamMembershipState.${this::class.simpleName}(value=$value)"
/**
* An unknown [TeamMembershipState].
*
* This is used as a fallback for [TeamMembershipState]s that haven't been added to Kord yet.
*/
public class Unknown(
`value`: Int,
) : TeamMembershipState(value)
public object Invited : TeamMembershipState(1)
public object Accepted : TeamMembershipState(2)
internal object Serializer : KSerializer<TeamMembershipState> {
public override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("dev.kord.common.entity.TeamMembershipState",
PrimitiveKind.INT)
public override fun serialize(encoder: Encoder, `value`: TeamMembershipState) =
encoder.encodeInt(value.value)
public override fun deserialize(decoder: Decoder) = when (val value = decoder.decodeInt()) {
1 -> Invited
2 -> Accepted
else -> Unknown(value)
}
}
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Use 'TeamMembershipState.serializer()' instead.",
replaceWith = ReplaceWith(expression = "TeamMembershipState.serializer()", imports =
arrayOf("dev.kord.common.entity.TeamMembershipState")),
)
public object TeamMembershipStateSerializer : KSerializer<TeamMembershipState> by Serializer {
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Use 'TeamMembershipState.serializer()' instead.",
replaceWith = ReplaceWith(expression = "TeamMembershipState.serializer()", imports =
arrayOf("dev.kord.common.entity.TeamMembershipState")),
)
public fun serializer(): KSerializer<TeamMembershipState> = this
}
public companion object {
/**
* A [List] of all known [TeamMembershipState]s.
*/
public val entries: List<TeamMembershipState> by lazy(mode = PUBLICATION) {
listOf(
Invited,
Accepted,
)
}
@Suppress(names = arrayOf("DEPRECATION_ERROR"))
@Deprecated(
level = DeprecationLevel.HIDDEN,
message = "Binary compatibility",
)
@JvmField
public val TeamMembershipStateSerializer: TeamMembershipStateSerializer =
TeamMembershipStateSerializer
}
}
| 54
| null |
66
| 689
|
2b12ba28ec50140286e38db2223cdcfd5a6166eb
| 3,995
|
kord
|
MIT License
|
core/src/main/java/com/jtuffery/mealmanager/core/randomrecipes/domain/model/RandomRecipesEntity.kt
|
TufferyJordan
| 395,443,919
| false
| null |
package com.jtuffery.mealmanager.core.randomrecipes.domain.model
import com.jtuffery.mealmanager.core.shared.domain.model.RecipeEntity
data class RandomRecipesEntity(val recipeList: List<RecipeEntity>)
| 0
|
Kotlin
|
0
| 1
|
289ce167f229ae466898c8c1322f461eae669190
| 203
|
MealManager
|
MIT License
|
src/main/kotlin/de/smoofy/eurocup/tournament/match/MatchesInventory.kt
|
Smoofy19
| 816,489,200
| false
|
{"Kotlin": 97974}
|
package de.smoofy.eurocup.tournament.match
import de.smoofy.eurocup.EuroCup
import de.smoofy.eurocup.builder.InventoryBuilder
import de.smoofy.eurocup.builder.ItemBuilder
import de.smoofy.eurocup.builder.SkullBuilder
import de.smoofy.eurocup.fan.Team
import de.smoofy.eurocup.utils.Keys
import de.smoofy.eurocup.utils.Skulls
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
import org.bukkit.persistence.PersistentDataType
/*
* Copyright ©
* @author - Smoofy
* @GitHub - https://github.com/Smoofy19
* @Twitter - https://twitter.com/Smoofy19
* Created - 18.06.2024 - 12:49
*/
/**
*/
class MatchesInventory(private val id: Int) {
fun groupInventory(): Inventory {
val inventory = InventoryBuilder(Holder(), 9*5, "<yellow>All matches")
val group = this.group(id)
inventory.fill(ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).noName())
inventory.set(Team.Cache.group(group), 4)
this.setMatches(inventory, group)
if (id != 1) {
inventory.set(ItemBuilder(Material.RED_STAINED_GLASS_PANE)
.name("<red>Previous page")
.data(Keys.PREVIOUS_PAGE, PersistentDataType.INTEGER, id - 1), 36
)
}
if (id != 6) {
inventory.set(ItemBuilder(Material.LIME_STAINED_GLASS_PANE)
.name("<green>Next page")
.data(Keys.NEXT_PAGE, PersistentDataType.INTEGER, id + 1), 44
)
}
return inventory.build()
}
private fun setMatches(inventory: InventoryBuilder, group: Team.Group) {
val slots = listOf(9, 14, 18, 23, 27, 32)
var currentSlot = 0
EuroCup.tournamentAPI.matchesCache.filter { match -> match.teamOne.group == group }.forEach { match ->
var slot = slots[currentSlot++]
inventory.set(this.matchDayItem(match), slot++)
inventory.set(Team.Cache.skull(match.teamOne), slot++)
inventory.set(Team.Cache.skull(match.teamTwo), slot++)
inventory.set(ItemBuilder(Material.PAPER).name("<green>To the game")
.data(Keys.MATCH, PersistentDataType.INTEGER, match.matchId), slot)
}
}
private fun matchDayItem(match: Match): SkullBuilder {
val item = SkullBuilder(Skulls.FOOTBALL.texture)
.name("<green>${this.matchDay(match.phase)}")
.lore("<gold>${match.time}")
return item
}
private fun matchDay(name: String): String {
return if (name.startsWith("1. Runde")) {
"Matchday 1"
} else if (name.startsWith("2. Runde")) {
"Matchday 2"
} else if (name.startsWith("3. Runde")) {
"Matchday 3"
} else if (name.startsWith("Achtelfinale")) {
"Round of sixteen"
} else if (name.startsWith("Viertelfinale")) {
"Quarterfinals"
} else if (name.startsWith("Halbfinale")) {
"Semifinal"
} else {
"Final"
}
}
private fun group(id: Int): Team.Group {
return when (id) {
1 -> Team.Group.A
2 -> Team.Group.B
3 -> Team.Group.C
4 -> Team.Group.D
5 -> Team.Group.E
6 -> Team.Group.F
else -> Team.Group.A
}
}
class Holder : InventoryHolder {
override fun getInventory(): Inventory {
return Bukkit.createInventory(null, 9)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
694ed3e3433ef68c59f196c5522a01f80b8c7059
| 3,550
|
EuroCup24
|
MIT License
|
app/src/main/java/com/pajokka/githubuser/utils/ZoomOutPageTransformer.kt
|
rrdhoi
| 425,407,913
| false
|
{"Kotlin": 62493}
|
package com.pajokka.githubuser.utils
import android.view.View
import androidx.viewpager2.widget.ViewPager2
private const val MIN_SCALE = 0.85f
private const val MIN_ALPHA = 0.5f
class ZoomOutPageTransformer : ViewPager2.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
val pageHeight = height
when {
position < -1 -> {
alpha = 0f
}
position <= 1 -> {
val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position))
val vertMargin = pageHeight * (1 - scaleFactor) / 2
val horzMargin = pageWidth * (1 - scaleFactor) / 2
translationX = if (position < 0) {
horzMargin - vertMargin / 2
} else {
horzMargin + vertMargin / 2
}
scaleX = scaleFactor
scaleY = scaleFactor
alpha = (MIN_ALPHA +
(((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA)))
}
else -> {
alpha = 0f
}
}
}
}
}
| 1
|
Kotlin
|
1
| 5
|
7907b152c52a27d7c85986319e006fa57bb87a4c
| 1,312
|
Jithapp
|
Apache License 2.0
|
deprecated/sample-xml/app/src/main/java/co/nimblehq/sample/xml/di/modules/NavigatorModule.kt
|
nimblehq
| 101,353,301
| false
|
{"Kotlin": 387666, "Ruby": 5344, "XSLT": 1824}
|
package co.nimblehq.sample.xml.di.modules
import co.nimblehq.sample.xml.ui.screens.MainNavigator
import co.nimblehq.sample.xml.ui.screens.MainNavigatorImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.FragmentComponent
@Module
@InstallIn(FragmentComponent::class)
abstract class NavigatorModule {
@Binds
abstract fun mainNavigator(mainNavigator: MainNavigatorImpl): MainNavigator
}
| 31
|
Kotlin
|
23
| 94
|
f07941499a70b6144f4280c233edba542ab3e516
| 456
|
android-templates
|
MIT License
|
app/src/main/kotlin/com/github/typ0520/codee/network/Github.kt
|
typ0520
| 115,848,990
| false
| null |
package com.github.typ0520.codee.network
import com.github.typ0520.codee.BuildConfig
import com.github.typ0520.codee.base.DEFAULT_PER_PAGE
import com.github.typ0520.codee.mvp.bean.*
import com.github.typ0520.codee.network.route.Scope
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
/**
* Created by tong on 2017/12/21.
*/
interface Github {
companion object {
const val BASE_URL_GITHUB = "https://github.com/"
const val BASE_URL_API = "https://api.github.com/"
const val BASE_URL_TRENDING = "http://trending.codehub-app.com/"
}
@Scope(BASE_URL_GITHUB)
@POST("login/oauth/access_token")
fun requestAccessToken(@Query("code") code: String,
@Query("client_id") clientId: String = BuildConfig.CLIENT_ID,
@Query("client_secret") clientSecret: String = BuildConfig.CLIENT_SECRET): Observable<String>
@GET("user")
fun getUserInfoByAccessToken(@Query("access_token") accessToken: String): Observable<User>
@GET("users/{ownerName}")
fun getUserInfo(@Path("ownerName") username: String): Observable<User>
@GET("users/{ownerName}/followers")
fun getFollowers(@Path("ownerName") username: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<User>>
@GET("users/{ownerName}/following")
fun getFollowing(@Path("ownerName") username: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<User>>
//https://api.github.com/repos/typ0520/fastdex/watchers
@GET("repos/{ownerName}/{repoName}/watchers")
fun getWatchers(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<User>>
//https://api.github.com/repos/typ0520/bizsocket/stargazers
@GET("repos/{ownerName}/{repoName}/stargazers")
fun getStargazers(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<User>>
//https://api.github.com/users/typ0520/received_events/public?page=1&per_page=1000
@GET("users/{ownerName}/received_events/public")
fun getReceivedEvents(@Path("ownerName") username: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE)
: Observable<EventList>
@GET("users/{ownerName}/events/public")
fun getUserEvents(@Path("ownerName") username: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE)
: Observable<EventList>
@GET("repos/{ownerName}/{repoName}/events")
fun getRepoEvents(@Path("ownerName") username: String,
@Path("repoName") repoName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<EventList>
//https://api.github.com/repos/typ0520/fastdex
@GET("repos/{ownerName}/{repoName}")
fun getRepository(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String): Observable<Repository>
@GET("repos/{ownerName}/{repoName}/forks")
fun getForks(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<Repository>>
@GET("users/{ownerName}/repos")
fun getUserRepos(@Path("ownerName") ownerName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<Repository>>
@GET("users/{ownerName}/starred")
fun getStarredRepos(@Path("ownerName") ownerName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<Repository>>
//http://trending.codehub-app.com/v2/
@Scope(BASE_URL_TRENDING)
@GET("/v2/trending")
fun getTrendingRepos(@Query("since") since: String,
@Query("language") language: String): Observable<List<Repository>>
@GET("repos/{ownerName}/{repoName}/branches")
fun getBranches(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<Branche>>
@GET("repos/{ownerName}/{repoName}/issues")
fun getIssues(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String,
@Query("state") state: String = "all",
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<Issue>>
@GET("repos/{ownerName}/{repoName}/issues")
fun getUserIssues(@Path("ownerName") ownerName: String,
@Path("repoName") repoName: String,
@Query("state") state: String = "all",
@Query("creator") creator: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<List<Issue>>
//https://api.github.com/search/repositories?q=typ0520&page=1&per_page=1
@GET("search/repositories")
fun searchRepositories(@Query("q") keyword: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<SearchResponse<Repository>>
//https://api.github.com/search/users?q=typ0520&page=1&per_page=1
@GET("search/users")
fun searchUsers(@Query("q") keyword: String,
@Query("page") page: Int = 1,
@Query("per_page") per_page: Int = DEFAULT_PER_PAGE): Observable<SearchResponse<User>>
}
| 1
|
Kotlin
|
1
| 4
|
8fde9be47123528a4bfdf09a78f9a2264dea6900
| 6,474
|
Codee
|
Apache License 2.0
|
data/src/test/java/com/github/albertopeam/data/ArtistsDataSourceImplementationTests.kt
|
albertopeam
| 294,799,044
| false
| null |
package com.github.albertopeam.data
import com.github.albertopeam.data.artists.ArtistDataSourceImplementation
import com.github.albertopeam.data.artists.ArtistService
import com.github.albertopeam.data.service.ServiceBuilder
import com.github.albertopeam.data.utils.MockResponseFileReader
import com.github.albertopeam.domain.getOrThrow
import com.github.albertopeam.domain.models.Artist
import com.github.albertopeam.data.auth.AuthenticationDataSource
import com.github.albertopeam.usecases.auth.UnauthorizedChallenge
import junit.framework.TestCase
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
class ArtistsDataSourceImplementationTests: TestCase() {
private lateinit var sut: ArtistDataSourceImplementation
private lateinit var server: MockWebServer
private lateinit var unauthorizedChallengeSpy: UnauthorizedChallenge
private lateinit var authenticationDataSourceMock: AuthenticationDataSource
override fun setUp() {
super.setUp()
unauthorizedChallengeSpy = Mockito.spy(UnauthorizedChallenge::class.java)
authenticationDataSourceMock = Mockito.mock(AuthenticationDataSource::class.java)
server = MockWebServer()
server.start()
val service = ServiceBuilder(server.url("/v1/").toString(), unauthorizedChallengeSpy, authenticationDataSourceMock, useLoginInterceptor = false)
.build(ArtistService::class.java)
sut = ArtistDataSourceImplementation(service)
}
override fun tearDown() {
super.tearDown()
server.shutdown()
}
@Test
fun `test given authenticated when get artist for id then match success data`() = runBlocking {
Mockito.`when`(authenticationDataSourceMock.get()).thenReturn("app_token")
server.enqueue(MockResponse()
.setResponseCode(200)
.setBody(MockResponseFileReader("api_artist_by_id_success.json").read()))
val result = sut.artist("1").getOrThrow()
val expected = Artist(id = "1", name = "Band of Horses", image = "https://i.scdn.co/image/0f9a5013134de288af7d49a962417f4200539b47")
assertEquals(result, expected)
verify(unauthorizedChallengeSpy, never()).challenge()
}
}
| 0
|
Kotlin
|
0
| 2
|
23e02f627a81d90b85eb03ab22824c56ff99c4ab
| 2,389
|
spoktify
|
MIT License
|
easylauncher/src/test/kotlin/com/project/starter/easylauncher/plugin/EasyLauncherConfigTest.kt
|
mhelder
| 292,776,545
| true
|
{"Kotlin": 50116}
|
package com.project.starter.easylauncher.plugin
import com.project.starter.easylauncher.plugin.utils.WithGradleProjectTest
import com.project.starter.easylauncher.plugin.utils.buildScript
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class EasyLauncherConfigTest : WithGradleProjectTest() {
@BeforeEach
fun setUp() {
rootDirectory.resolve("src/main/AndroidManifest.xml") {
writeText(
"""
<manifest package="com.example.app" />
""".trimIndent()
)
}
}
@Test
fun `custom ribbon`() {
rootDirectory.resolve("build.gradle").buildScript(
androidBlock = {
"""
buildTypes {
debug { }
release { }
}
""".trimIndent()
},
easylauncherBlock = {
"""
buildTypes {
debug {
filters customRibbon(
label: "bitcoin",
ribbonColor: "#8A123456",
labelColor: "#654321",
fontName: "Arial-Black"
)
}
}
""".trimIndent()
}
)
runTask("assembleDebug", "--stacktrace")
}
@Test
fun `chrome like ribbon`() {
rootDirectory.resolve("build.gradle").buildScript(
androidBlock = {
"""
buildTypes {
debug { }
release { }
}
""".trimIndent()
},
easylauncherBlock = {
"""
buildTypes {
debug {
filters chromeLike(
label: "bitcoin",
ribbonColor: "#8A123456",
labelColor: "#654321",
fontName: "Tahoma"
)
}
}
""".trimIndent()
}
)
runTask("assembleDebug", "--stacktrace")
}
}
| 0
| null |
0
| 0
|
46cdbb58b0521d7e6596bb81c1df9d3119258640
| 2,495
|
easylauncher-gradle-plugin
|
MIT License
|
SS-W-Discord/src/main/kotlin/com/github/syari/ss/wplugins/discord/api/handle/MessageCreateHandler.kt
|
SecondStoryServer
| 314,996,172
| false
| null |
package com.github.syari.ss.wplugins.discord.api.handle
import com.github.syari.ss.wplugins.discord.api.DiscordAPI
import com.github.syari.ss.wplugins.discord.api.entity.Emoji
import com.github.syari.ss.wplugins.discord.api.entity.Guild
import com.github.syari.ss.wplugins.discord.api.entity.Member
import com.github.syari.ss.wplugins.discord.api.entity.Message
import com.github.syari.ss.wplugins.discord.api.entity.Role
import com.github.syari.ss.wplugins.discord.api.entity.TextChannel
import com.github.syari.ss.wplugins.discord.api.util.json.getArrayOrNull
import com.github.syari.ss.wplugins.discord.api.util.json.getOrNull
import com.google.gson.JsonObject
import java.util.regex.Pattern
internal object MessageCreateHandler : GatewayHandler {
override fun handle(json: JsonObject) {
handleGuild(json)
}
private fun handleGuild(json: JsonObject) {
val guildId = json.getOrNull("guild_id")?.asLong ?: return
val guild = Guild.get(guildId) ?: return
val channelId = json["channel_id"].asLong
val channel = guild.getTextChannel(channelId) ?: return
val userJson = json["author"].asJsonObject
val memberJson = json.getOrNull("member")?.asJsonObject
val member = Member.from(memberJson, userJson)
val content = json["content"].asString
val mentionMembers = getMentionMembers(json)
val mentionRoles = getMentionRoles(guild, json)
val mentionChannels = getMentionChannels(guild, content)
val mentionEmojis = getMentionEmojis(guild, content)
val message = Message(channel, member, content, mentionMembers, mentionRoles, mentionChannels, mentionEmojis)
DiscordAPI.messageReceiveEvent.invoke(message)
}
private fun getMentionMembers(parent: JsonObject): List<Member> {
val array = parent.getArrayOrNull("mentions")
return array?.map {
val child = it.asJsonObject
val memberJson = child["member"].asJsonObject
Member.from(memberJson, child)
} ?: emptyList()
}
private fun getMentionRoles(guild: Guild, parent: JsonObject): List<Role> {
return parent.getArrayOrNull("mention_roles")?.mapNotNull {
guild.getRole(it.asLong)
} ?: emptyList()
}
private fun getMentionChannels(guild: Guild, content: String): List<TextChannel> {
val pattern = Pattern.compile(TextChannel.REGEX)
val matcher = pattern.matcher(content)
return mutableListOf<TextChannel>().apply {
while (matcher.find()) {
val channelId = matcher.group(1).toLongOrNull() ?: continue
val channel = guild.getTextChannel(channelId) ?: continue
add(channel)
}
}
}
private fun getMentionEmojis(guild: Guild, content: String): List<Emoji> {
val pattern = Pattern.compile(Emoji.REGEX)
val matcher = pattern.matcher(content)
return mutableListOf<Emoji>().apply {
while (matcher.find()) {
val emojiId = matcher.group(2).toLongOrNull() ?: continue
val emoji = guild.getEmoji(emojiId) ?: continue
add(emoji)
}
}
}
}
| 25
|
Kotlin
|
1
| 2
|
9af898e4eef290b8a2e4c0f75e3f99afb0b19e57
| 3,229
|
SS-Plugins
|
Apache License 2.0
|
app/src/main/java/com/m2mmusic/android/logic/network/service/SongService.kt
|
guosuweidev
| 259,247,961
| false
|
{"Kotlin": 308044, "JavaScript": 90327}
|
package com.m2mmusic.android.logic.network.service
import com.m2mmusic.android.logic.model.SongResponse
import com.m2mmusic.android.logic.model.UrlOfSongResponse
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.Call
interface SongService {
/**
* 获取歌曲URL
*/
@GET("song/url")
fun getUrlOfSong(
@Query("id")ids: String,
@Query("timestamp") timestamp: Long
): Call<UrlOfSongResponse>
/**
* 获取歌曲详情
*/
@GET("song/detail")
fun getDetailOfSong(
@Query("ids")ids: String,
@Query("timestamp") timestamp: Long
): Call<SongResponse>
/**
* 获取歌曲URL
*/
@GET("song/url")
fun getUrlOfSong(
@Query("id")ids: String,
@Query("cookie") cookie: String,
@Query("timestamp") timestamp: Long
): Call<UrlOfSongResponse>
/**
* 获取歌曲详情
*/
@GET("song/detail")
fun getDetailOfSong(
@Query("ids")ids: String,
@Query("cookie") cookie: String,
@Query("timestamp") timestamp: Long
): Call<SongResponse>
}
| 0
|
Kotlin
|
0
| 1
|
3a246d68421cbde0a3c241b7864b9139c43fd56d
| 1,082
|
M2M-Music
|
Apache License 2.0
|
src/main/kotlin/com/github/iambaljeet/templater/services/MyProjectService.kt
|
iambaljeet
| 301,542,094
| false
| null |
package com.github.iambaljeet.templater.services
import com.intellij.openapi.project.Project
import com.github.iambaljeet.templater.MyBundle
class MyProjectService(project: Project) {
init {
println(MyBundle.message("projectService", project.name))
}
}
| 0
|
Kotlin
|
0
| 0
|
fc0ffd8e00d65978b8ec9912f633cea16d1a3ef7
| 272
|
templater
|
Apache License 2.0
|
app/src/main/java/com/ohuji/cardsNmonsters/screens/augmented_reality/ARScreen.kt
|
ohuji
| 598,587,284
| false
| null |
package com.ohuji.cardsNmonsters.screens.augmented_reality
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateListOf
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.ohuji.cardsNmonsters.R
import com.ohuji.cardsNmonsters.database.FullDeck
import com.ohuji.cardsNmonsters.screens.collectables.CollectablesViewModel
import com.ohuji.cardsNmonsters.screens.deck_building.DeckViewModel
import io.github.sceneview.ar.ARScene
import io.github.sceneview.ar.node.ArModelNode
import io.github.sceneview.ar.node.ArNode
import io.github.sceneview.ar.node.PlacementMode
import io.github.sceneview.math.Position
/**
* Main play screen. Features an AR screen with other elements.
* Top bar that displays turn counter, monster status, monster health points and element icon.
*
* @param navController The navigation controller for the screen.
* @param viewModel ViewModel that is used to get deck and cards
* @param monsterViewModel ViewModel that used to get monster
* @param gameLogicViewModel ViewModel that handles the game logic
* @param monsterId monster that we get from map screen. Used to fetch monster that the player fights
* @param deckId used to fetch the deck that the player is using in the fight
*/
@Composable
fun ARScreen(
navController: NavController,
viewModel: DeckViewModel,
monsterViewModel: CollectablesViewModel,
gameLogicViewModel: GameLogicViewModel,
monsterId: Long,
deckId: Long
) {
val nodes = remember { mutableStateListOf<ArNode>() }
val context = LocalContext.current
val monster = monsterViewModel.findMonsterById(monsterId).observeAsState().value
val cardsState = viewModel.getDeckWithCards(deckId).observeAsState()
val cards: FullDeck? = cardsState.value
val playerStats = monsterViewModel.getPlayerStats().observeAsState().value
var showVictoryDialog by remember { mutableStateOf(false) }
var showDefeatDialog by remember { mutableStateOf(false) }
var health by remember {
mutableStateOf(gameLogicViewModel.getStartingHealth(monsterId))
}
var stateDazed by remember { mutableStateOf(false) }
var turn by remember { mutableStateOf(0) }
fun expRequired(): Int {
val expReq = playerStats?.expRequirement ?: 1
val currentExp = playerStats?.currentLvlExp ?: 2
return expReq - currentExp
}
fun stateAndDamage(i: Int) {
val card = cards!!.cards[i]
health -= gameLogicViewModel.doDamage(
card.cardDamage,
stateDazed,
card.cardElement,
monster?.monsterElement
)
val isPhysicalCard = card.cardElement == "Phys"
stateDazed = isPhysicalCard
}
fun battleConclusion(): String {
if (health <= 0) {
gameLogicViewModel.updateCollectableTypeKill("Kill")
gameLogicViewModel.updatePlayerStats(
monster?.monsterHealth ?: 800
)
showVictoryDialog = true
} else if (turn >= 4) {
showDefeatDialog = true
}
return health.toString()
}
/**
* Create ARModelNode and load GLB model for it asynchronously
* Set BEST_AVAILABLE placement mode for auto refining accuracy placement of the node.
* Set instantAnchor set as false in order to not set anchor when node is placed.
* Set Float3 hitPosition coordinates and set followHitPosition as true in order to make node follow it.
* Set autoAnimate as true for using GLB models animation.
* Set centerOrigin Float3 Position for model.
*/
val model = ArModelNode(
placementMode = PlacementMode.BEST_AVAILABLE,
instantAnchor = false,
hitPosition = Position(0.0f, 0.0f, -2.0f),
followHitPosition = true,
).apply {
loadModelGlbAsync(
context = context,
glbFileLocation = "models/${monster?.monsterModel}",
autoAnimate = true,
centerOrigin = Position(x = 0.0f, y = -1.0f, z = 0.0f),
)
}
val healthBar = HealthBarNode (
context = context,
lifecycle = null,
)
if (cards != null) {
Column {
AR(
model,
nodes,
turn,
stateDazed,
monster?.monsterName,
health,
monster?.monsterElement
)
Box(
modifier = Modifier
.fillMaxSize()
.clip(RoundedCornerShape(20.dp))
) {
Image(
painter = painterResource(R.drawable.wood_background),
contentDescription = stringResource(id = R.string.wood_background_desc),
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
Column {
Row(
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
for (i in cards.cards.indices) {
val image = cards.cards[i].cardModel
val context = LocalContext.current
val resId = context.resources.getIdentifier(
image,
"drawable",
context.packageName
)
Image(
painter = painterResource(resId),
contentDescription = cards.cards[i].cardName,
modifier = Modifier
.padding(start = 8.dp, end = 8.dp)
.clickable {
stateAndDamage(i)
turn += 1
healthBar.text = battleConclusion()
},
contentScale = ContentScale.Fit
)
}
}
}
}
}
}
BattleReport(
showVictoryDialog,
showDefeatDialog,
navController,
monster?.monsterName,
playerStats?.playerLevel,
expRequired()
)
}
@Composable
fun AR(
model: io.github.sceneview.node.Node,
nodes: List<io.github.sceneview.node.Node>,
turn: Int,
stateDazed: Boolean,
monsterName: String?,
health: Int?,
monsterElement: String?
) {
Box(
modifier = Modifier
.fillMaxHeight(0.75f)
.fillMaxWidth()
) {
ARScene(
nodes = nodes,
planeRenderer = true,
onCreate = { arSceneView ->
// Apply configuration
arSceneView.addChild(model)
},
onSessionCreate = { session ->
// Configure the ARCore session
},
onFrame = { arFrame ->
// Retrieve ARCore frame update
},
onTap = { hitResult ->
// User tapped in the AR view
}
)
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.05f)
) {
Image(
painter = painterResource(R.drawable.wood_background),
contentDescription = stringResource(id = R.string.wood_background_desc),
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
TurnComposable(
turn = turn,
stateDazed = stateDazed,
monsterName = monsterName,
health,
monsterElement
)
}
}
}
/**
* Handles the alert that pops up when battle ends. Displays message depending on the battle result.
*
* @param showVictoryDialog if true displays victory dialog
* @param showDefeatDialog if true displays defeat dialog
* @param navController the NavController that handles navigation
* @param monsterName used to display correct monster name
* @param playerLevel used to display player level
* @param expRequired used to display the exp player needs to level up
*/
@Composable
fun BattleReport(
showVictoryDialog: Boolean,
showDefeatDialog: Boolean,
navController: NavController,
monsterName: String?,
playerLevel: Int?,
expRequired: Int
) {
var showVictoryDialog = showVictoryDialog
var showDefeatDialog = showDefeatDialog
fun victoryDialogDismiss() {
showVictoryDialog = false
navController.navigate("map_screen")
}
fun defeatDialogDismiss() {
showDefeatDialog= false
navController.navigate("map_screen")
}
if (showVictoryDialog) {
ShowDialog(
title = stringResource(R.string.battle_victory),
message = "${stringResource(R.string.battle_victory_message1)} $monsterName ${stringResource(R.string.battle_victory_message2)}\n" +
"${stringResource(R.string.battle_victory_message3)} $playerLevel\n" +
"${stringResource(R.string.battle_victory_message4)} $expRequired",
onDismiss = { victoryDialogDismiss()}
)
}
if (showDefeatDialog) {
ShowDialog(
title = stringResource(R.string.battle_defeat),
message = "${stringResource(R.string.battle_defeat_message1)} $monsterName ${stringResource(R.string.battle_defeat_message2)}",
onDismiss = { defeatDialogDismiss()}
)
}
}
@Composable
fun ShowDialog(
title: String,
message: String,
onDismiss: () -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
title = {Column(modifier = Modifier.padding(10.dp)) {
Text(title, fontSize = 24.sp, color = White)
}},
text = {
Column(modifier = Modifier.padding(10.dp)) {
Text(message, fontSize = 16.sp, color = White)
}
},
confirmButton = {
Button(onClick = onDismiss) {
androidx.compose.material3.Text("OK")
}
}
)
}
/**
* In the top of the screen. Displays data the player needs in battle
*
* @param turn show what turn is
* @param stateDazed when true displays to user that the monster is dazed
* @param monsterName used to display correct monster name
* @param health shows monsters health points
* @param monsterElement used to get correct element icon
*/
@Composable
fun TurnComposable(
turn: Int,
stateDazed: Boolean,
monsterName: String?,
health: Int?,
monsterElement: String?
) {
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = "${stringResource(R.string.battle_turn)} $turn/4",
textAlign = TextAlign.Left,
fontSize = 16.sp,
color = White,
modifier = Modifier
.padding(start = 8.dp, end = 0.dp, top = 0.dp, bottom = 0.dp)
.weight(1f)
)
if (stateDazed) {
Text(
text = "$monsterName ${stringResource(R.string.battle_status)}",
textAlign = TextAlign.Center,
fontSize = 12.sp,
color = White,
modifier = Modifier.weight(1f)
)
}
Text(
text = "${stringResource(R.string.battle_hp)} ${if (health != null && health < 0) { "0" } else { health }}",
color = White,
textAlign = TextAlign.Right,
fontSize = 16.sp,
modifier = Modifier
.padding(start = 0.dp, end = 2.dp, top = 0.dp, bottom = 0.dp)
.weight(1f)
)
val image = monsterElement?.lowercase() + "_icon"
val context = LocalContext.current
val resId = context.resources.getIdentifier(
image,
"drawable",
context.packageName
)
Image(
painter = painterResource(resId),
contentDescription = "Element icon",
modifier = Modifier
.padding(start = 0.dp, end = 5.dp, top = 0.dp, bottom = 0.dp)
.size(20.dp)
)
}
}
| 0
|
Kotlin
|
1
| 3
|
41f7c3e794d73b28582e3d0fde36f353083003ef
| 14,069
|
Cards-Monsters
|
MIT License
|
inference/src/main/kotlin/io/kinference/operators/tensor/Slice.kt
|
cybernetics
| 324,970,047
| true
|
{"Kotlin": 461291, "PureBasic": 24490}
|
package io.kinference.operators.tensor
import io.kinference.attributes.Attribute
import io.kinference.data.tensors.Tensor
import io.kinference.data.tensors.asTensor
import io.kinference.graph.Context
import io.kinference.ndarray.arrays.IntNDArray
import io.kinference.ndarray.arrays.LongNDArray
import io.kinference.ndarray.toIntArray
import io.kinference.onnx.TensorProto
import io.kinference.operators.*
import io.kinference.primitives.types.DataType
class Slice(attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>)
: Operator<Tensor, Tensor>(INFO, attributes, inputs, outputs) {
companion object {
private val DATA_TYPE_CONSTRAINTS = ALL_DATA_TYPES
private val INDEX_TYPE_CONSTRAINTS = setOf(TensorProto.DataType.INT64, TensorProto.DataType.INT32)
private val INPUTS_INFO = listOf(
IOInfo(0, DATA_TYPE_CONSTRAINTS, "data", optional = false, differentiable = true),
IOInfo(1, INDEX_TYPE_CONSTRAINTS, "starts", optional = false, differentiable = false),
IOInfo(2, INDEX_TYPE_CONSTRAINTS, "ends", optional = false, differentiable = false),
IOInfo(3, INDEX_TYPE_CONSTRAINTS, "axes", optional = true, differentiable = false),
IOInfo(4, INDEX_TYPE_CONSTRAINTS, "steps", optional = true, differentiable = false)
)
private val OUTPUTS_INFO = listOf(
IOInfo(0, DATA_TYPE_CONSTRAINTS, "output", optional = false, differentiable = true)
)
private val INFO = OperatorInfo("Slice", emptyMap(), INPUTS_INFO, OUTPUTS_INFO)
}
override fun apply(context: Context, inputs: List<Tensor?>): List<Tensor?> {
val data = inputs[0]!!
val shape = data.data.shape
val incompleteAxes = inputs.getOrNull(3)?.let {
if (it.data.type == DataType.LONG) {
val pointer = (it.data as LongNDArray).array.pointer()
IntArray(it.data.linearSize) {
val axis = pointer.getAndIncrement().toInt()
if (axis < 0) shape.size + axis else axis
}
} else {
val pointer = (it.data as IntNDArray).array.pointer()
IntArray(it.data.linearSize) {
val axis = pointer.getAndIncrement()
if (axis < 0) shape.size + axis else axis
}
}
} ?: shape.indices.toIntArray()
val incompleteSteps = inputs.getOrNull(4)?.let {
require(it.data.linearSize == incompleteAxes.size) { "Input 'steps' must be same size as 'axes'" }
if (it.data.type == DataType.LONG) {
val pointer = (it.data as LongNDArray).array.pointer()
IntArray(incompleteAxes.size) {
val step = pointer.getAndIncrement().toInt()
require(step != 0) { "Input 'steps' must not contains zeros " }
step
}
} else {
val pointer = (it.data as IntNDArray).array.pointer()
IntArray(incompleteAxes.size) {
val step = pointer.getAndIncrement()
require(step != 0) { "Input 'steps' must not contains zeros " }
step
}
}
} ?: IntArray(shape.size) { 1 }
val incompleteStarts = inputs[1]!!.data.let {
require(it.linearSize == incompleteAxes.size) { "Input 'starts' must be same size as 'axes'" }
if (it.type == DataType.LONG) {
val pointer = (it as LongNDArray).array.pointer()
IntArray(incompleteAxes.size) { index ->
var start = pointer.getAndIncrement()
val dim = shape[incompleteAxes[index]].toLong()
start = if (start < 0) dim + start else start
start = if (start >= dim) (if (incompleteSteps[index] > 0) dim else dim - 1) else start
if (start < 0) 0 else start.toInt()
}
} else {
val pointer = (it as IntNDArray).array.pointer()
IntArray(incompleteAxes.size) { index ->
var start = pointer.getAndIncrement().toLong()
val dim = shape[incompleteAxes[index]].toLong()
start = if (start < 0) dim + start else start
start = if (start >= dim) (if (incompleteSteps[index] > 0) dim else dim - 1) else start
if (start < 0) 0 else start.toInt()
}
}
}
val incompleteEnds = inputs[2]!!.data.let {
require(it.linearSize == incompleteAxes.size) { "Input 'ends' must be same size as 'axes'" }
if (it.type == DataType.LONG) {
val pointer = (it as LongNDArray).array.pointer()
IntArray(incompleteAxes.size) { index ->
var end = pointer.getAndIncrement()
val dim = shape[incompleteAxes[index]].toLong()
end = if (end < 0) dim + end else end
end = if (end > dim) dim else end
if (end < 0) (if (incompleteSteps[index] > 0) 0 else -1) else end.toInt()
}
} else {
val pointer = (it as IntNDArray).array.pointer()
IntArray(incompleteAxes.size) { index ->
var end = pointer.getAndIncrement().toLong()
val dim = shape[incompleteAxes[index]].toLong()
end = if (end < 0) dim + end else end
end = if (end > dim) dim else end
if (end < 0) (if (incompleteSteps[index] > 0) 0 else -1) else end.toInt()
}
}
}
val starts = IntArray(shape.size)
val ends = IntArray(shape.size)
val steps = IntArray(shape.size)
for (axis in shape.indices) {
val index = incompleteAxes.indexOf(axis)
if (index == -1) {
starts[axis] = 0
ends[axis] = shape[axis]
steps[axis] = 1
} else {
starts[axis] = incompleteStarts[index]
ends[axis] = incompleteEnds[index]
steps[axis] = incompleteSteps[index]
}
}
return listOf(data.data.slice(starts, ends, steps).asTensor("output"))
}
}
| 0
| null |
0
| 0
|
8aa3295f112353949562750b83991b7ea8b83cf2
| 6,441
|
kinference
|
Apache License 2.0
|
plugins/src/main/kotlin/com/freeletics/gradle/monorepo/tasks/ComputeVersionCodeTask.kt
|
freeletics
| 611,205,691
| false
|
{"Kotlin": 158054, "Shell": 2852}
|
package com.freeletics.gradle.tasks
import com.freeletics.gradle.util.RealGit
import com.freeletics.gradle.util.computeInfoFromGit
import java.io.File
import java.time.LocalDate
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
public abstract class ComputeVersionCodeTask : DefaultTask() {
@get:Input
public abstract val computeFromGit: Property<Boolean>
@get:Input
public abstract val gitTagName: Property<String>
@get:Input
public abstract val gitRootDirectory: Property<File>
@get:OutputFile
public abstract val outputFile: RegularFileProperty
@TaskAction
public fun action() {
val versionCode = if (computeFromGit.get()) {
val git = RealGit(gitRootDirectory.get())
computeVersionCode(git, gitTagName.get(), LocalDate.now())
} else {
Int.MAX_VALUE
}
outputFile.get().asFile.writeText(versionCode.toString())
}
internal companion object {
fun Project.registerComputeVersionCodeTask(gitTagName: String): TaskProvider<ComputeVersionCodeTask> {
return tasks.register("computeVersionCode", ComputeVersionCodeTask::class.java) { task ->
task.computeFromGit.set(computeInfoFromGit)
task.gitTagName.set(gitTagName)
task.gitRootDirectory.set(rootDir)
task.outputFile.set(layout.buildDirectory.file("intermediates/git/version-code.txt"))
}
}
fun TaskProvider<ComputeVersionCodeTask>.mapOutput(): Provider<Int> {
return flatMap { task ->
task.outputFile.map { it.asFile.readText().toInt() }
}
}
}
}
| 7
|
Kotlin
|
1
| 9
|
d5d74c8e0f6c05f37edf6af7b4658e31e894de00
| 1,975
|
freeletics-gradle-plugins
|
Apache License 2.0
|
uix-pages/src/main/java/me/shouheng/uix/pages/image/Glide4Engine.kt
|
fg2q1q3q
| 375,986,738
| false
|
{"C++": 4855567, "CMake": 538827, "Kotlin": 359069, "C": 295144, "Java": 56875, "Objective-C": 7348, "Makefile": 5336}
|
package me.shouheng.uix.pages.image
import android.content.Context
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.request.RequestOptions
import com.zhihu.matisse.engine.ImageEngine
/**
* Created WngShhng on 2018/12/10.
*/
class Glide4Engine : ImageEngine {
override fun loadThumbnail(context: Context, resize: Int, placeholder: Drawable, imageView: ImageView, uri: Uri) {
Glide.with(context)
.asBitmap() // some .jpeg uix_files are actually gif
.load(uri)
.apply(
RequestOptions()
.override(resize, resize)
.placeholder(placeholder)
.centerCrop()
)
.into(imageView)
}
override fun loadGifThumbnail(
context: Context,
resize: Int,
placeholder: Drawable,
imageView: ImageView,
uri: Uri
) {
Glide.with(context)
.asBitmap() // some .jpeg uix_files are actually gif
.load(uri)
.apply(
RequestOptions()
.override(resize, resize)
.placeholder(placeholder)
.centerCrop()
)
.into(imageView)
}
override fun loadImage(context: Context, resizeX: Int, resizeY: Int, imageView: ImageView, uri: Uri) {
Glide.with(context)
.load(uri)
.apply(
RequestOptions()
.override(resizeX, resizeY)
.priority(Priority.HIGH)
.fitCenter()
)
.into(imageView)
}
override fun loadGifImage(context: Context, resizeX: Int, resizeY: Int, imageView: ImageView, uri: Uri) {
Glide.with(context)
.asGif()
.load(uri)
.apply(
RequestOptions()
.override(resizeX, resizeY)
.priority(Priority.HIGH)
.fitCenter()
)
.into(imageView)
}
override fun supportAnimatedGif(): Boolean {
return true
}
}
| 0
|
C++
|
0
| 0
|
0549366a465e038ab6288ed910b2f74128669ef6
| 2,256
|
Android-uix
|
Apache License 2.0
|
app/src/main/java/ru/zavedyaev/fillme/primitive/Triangle.kt
|
zavedyaev
| 181,200,666
| false
| null |
package ru.zavedyaev.fillme.primitive
import android.opengl.GLES31
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
/**
* Represents triangle
* a
* / \
* / \
* b----c
*/
open class Triangle(
val a: Point,
val b: Point,
val c: Point
) {
private val ab = Line(a, b)
private val ac = Line(a, c)
private val bc = Line(b, c)
val lines = listOf(ab, ac, bc)
fun getSquare(): Float {
val abLength = ab.getLength()
val acLength = ac.getLength()
val bcLength = bc.getLength()
val perimeter = abLength + acLength + bcLength
val perimeterHalf = perimeter / 2
return Math.sqrt(
(perimeterHalf *
(perimeterHalf - abLength) *
(perimeterHalf - acLength) *
(perimeterHalf - bcLength)).toDouble()
).toFloat()
}
val vertexBuffer: FloatBuffer =
ByteBuffer.allocateDirect(COORDS_COUNT * Point.BYTES_PER_FLOAT).run {
// use the device hardware's native byte order
order(ByteOrder.nativeOrder())
// create a floating point buffer from the ByteBuffer
asFloatBuffer().apply {
// add the coordinates to the FloatBuffer
put(floatArrayOf(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z))
// set the buffer to read the first coordinate
position(0)
}
}
fun draw(positionHandle: Int, colorHandle: Int, textureHandle: Int, color: FloatArray) {
draw(positionHandle, colorHandle, textureHandle, color, color, color)
}
fun draw(positionHandle: Int, colorHandle: Int, textureHandle: Int, colorA: FloatArray, colorB: FloatArray, colorC: FloatArray) {
// Prepare the triangle coordinate data
GLES31.glVertexAttribPointer(
positionHandle,
Point.COORDS_PER_POINT,
GLES31.GL_FLOAT,
false,
Point.BYTES_PER_POINT,
vertexBuffer
)
GLES31.glEnableVertexAttribArray(positionHandle)
// Set color for drawing the triangle
val colorBuffer: FloatBuffer =
ByteBuffer.allocateDirect(COLOR_COORDS_COUNT * Point.BYTES_PER_FLOAT).run {
// use the device hardware's native byte order
order(ByteOrder.nativeOrder())
// create a floating point buffer from the ByteBuffer
asFloatBuffer().apply {
// add the coordinates to the FloatBuffer
put(colorA + colorB + colorC)
// set the buffer to read the first coordinate
position(0)
}
}
GLES31.glVertexAttribPointer(
colorHandle,
4, //color components per vertex
GLES31.GL_FLOAT,
false,
VERTEX_COLOR_STRIDE,
colorBuffer
)
GLES31.glEnableVertexAttribArray(colorHandle)
// Set texture coords for drawing the triangle
val texBuffer: FloatBuffer =
ByteBuffer.allocateDirect(POINT_COUNT * 2 * Point.BYTES_PER_FLOAT).run {
// use the device hardware's native byte order
order(ByteOrder.nativeOrder())
// create a floating point buffer from the ByteBuffer
asFloatBuffer().apply {
// add the coordinates to the FloatBuffer
put(floatArrayOf((a.x+4.5f)/14, (a.y + 7)/14, (b.x+4.5f)/14, (b.y + 7)/14, (c.x+4.5f)/14, (c.y+7)/14))
// set the buffer to read the first coordinate
position(0)
}
}
GLES31.glVertexAttribPointer(
textureHandle,
2, //texture coords per vertex
GLES31.GL_FLOAT,
false,
2 * Point.BYTES_PER_FLOAT,
texBuffer
)
GLES31.glEnableVertexAttribArray(textureHandle)
// Draw the triangle
GLES31.glDrawArrays(GLES31.GL_TRIANGLES, 0, Triangle.POINT_COUNT)
}
/**
* Applicable only for 2D triangles
*/
fun containsPoint2D(point: Point2D): Boolean {
val result1 = (a.x - point.x) * (c.y - a.y) - (c.x - a.x) * (a.y - point.y)
val result2 = (c.x - point.x) * (b.y - c.y) - (b.x - c.x) * (c.y - point.y)
val result3 = (b.x - point.x) * (a.y - b.y) - (a.x - b.x) * (b.y - point.y)
return (result1 <= 0 && result2 <= 0 && result3 <= 0) || (result1 >= 0 && result2 >= 0 && result3 >= 0)
}
companion object {
const val POINT_COUNT = 3
const val COORDS_COUNT = POINT_COUNT * Point.COORDS_PER_POINT
const val COLOR_SIZE_PER_VERTEX = 4
const val COLOR_COORDS_COUNT = POINT_COUNT * COLOR_SIZE_PER_VERTEX
const val VERTEX_COLOR_STRIDE = COLOR_SIZE_PER_VERTEX * Point.BYTES_PER_FLOAT
}
}
| 1
|
Kotlin
|
0
| 0
|
3354a03d590f51e2bc7f3296a9e0c5968ec5d991
| 4,987
|
fill_me
|
Open Market License
|
app/src/main/java/com/example/simplewishlist/WishItem.kt
|
Shady-Rouk
| 689,070,541
| false
|
{"Kotlin": 5162}
|
package com.example.simplewishlist
class WishItem(
val itemName: String,
val itemPrice: Double,
val itemLink: String) {}
| 0
|
Kotlin
|
0
| 0
|
3957e659f31eeb250baf343a982a90e2e9b1a6b5
| 133
|
SimpleWishlist
|
Apache License 2.0
|
app/src/main/java/com/example/android/ballBounce/view/CanvasDrawView.kt
|
trlaw
| 330,268,031
| false
| null |
package com.example.android.ballBounce.view
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.example.android.ballBounce.utility.Rectangle
import com.example.android.ballBounce.utility.Vector
import com.example.android.ballBounce.view.canvasPainter.CanvasPainter
class CanvasDrawView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
var framePainter: CanvasPainter? = null
var touchEventHandler: ((MotionEvent) -> Unit)? = null
var sizeChangeCallback: ((Int, Int) -> Unit)? = null
var drawingSpace = Rectangle(Vector.zero(), Vector.zero())
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
drawingSpace = Rectangle(Vector.zero(),Vector(w.toDouble(),h.toDouble()))
sizeChangeCallback?.invoke(w, h)
}
override fun onTouchEvent(e: MotionEvent): Boolean {
super.onTouchEvent(e)
touchEventHandler?.invoke(e)
return true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (framePainter != null) {
framePainter!!.paintViewCanvas(canvas,this)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
eaa330713095bca6f90cd068201b4ffdad9984ab
| 1,354
|
BallBounce
|
MIT License
|
app/src/main/java/xyz/teamgravity/kichkinashahzoda/core/service/SongNotificationManager.kt
|
raheemadamboev
| 527,998,459
| false
| null |
package xyz.teamgravity.kichkinashahzoda.core.service
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import xyz.teamgravity.kichkinashahzoda.R
class SongNotificationManager(
private val context: Context,
private val token: MediaSessionCompat.Token,
private val listener: PlayerNotificationManager.NotificationListener,
private val onSongChange: () -> Unit,
) {
companion object {
const val CHANNEL_ID = "crybaby_music"
const val NOTIFICATION_ID = 0x5454
}
private var manager: PlayerNotificationManager? = null
init {
initializeManager()
}
fun show(player: Player) {
manager?.setPlayer(player)
}
private fun initializeManager() {
manager = PlayerNotificationManager.Builder(context, NOTIFICATION_ID, CHANNEL_ID)
.setChannelNameResourceId(R.string.notification_channel_player)
.setChannelDescriptionResourceId(R.string.notification_channel_description_player)
.setMediaDescriptionAdapter(DescriptionAdapter(MediaControllerCompat(context, token)))
.setNotificationListener(listener)
.build().apply {
setSmallIcon(R.drawable.ic_music)
setMediaSessionToken(token)
}
}
private inner class DescriptionAdapter(
private val controller: MediaControllerCompat,
) : PlayerNotificationManager.MediaDescriptionAdapter {
override fun getCurrentContentTitle(player: Player): CharSequence {
onSongChange()
return controller.metadata.description.title.toString()
}
override fun createCurrentContentIntent(player: Player): PendingIntent? {
return controller.sessionActivity
}
override fun getCurrentContentText(player: Player): CharSequence {
return controller.metadata.description.subtitle.toString()
}
override fun getCurrentLargeIcon(player: Player, callback: PlayerNotificationManager.BitmapCallback): Bitmap? {
return BitmapFactory.decodeResource(context.resources, R.drawable.icon)
}
}
}
| 0
|
Kotlin
|
1
| 3
|
37a7349e32693e2ad956db6bee262556b60ba504
| 2,444
|
kichkina-shahzoda
|
Apache License 2.0
|
app/src/main/java/us/ihmc/android/nats/NATSActivity.kt
|
icochico
| 75,347,938
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Proguard": 1, "Java": 3, "XML": 7, "Kotlin": 2}
|
package us.ihmc.android.nats
import android.Manifest
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import android.widget.ToggleButton
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.reflect.Field
/**
* NATSActivity.kt
*
*
* Simple gNATSd server for Android, written in Kotlin.
* Creates and handles interactions of UI elements.
* A click on each of the following buttons will enable the specific setting associated
* with the button. The setting will override the NATS default setting.
*
*
* HOST Bind to HOST address (default: 0.0.0.0)
* PORT Use PORT for clients (default: 4222)
* LOG File to redirect log output
* CONFIG Configuration File
*
* @author <NAME> (<EMAIL>)
*/
class NATSActivity : AppCompatActivity() {
private val natsAssetsExecutablePath: String
get() = getString(R.string.nats_release) + File.separator +
getString(R.string.nats_executable)
private//same directory structure
val natsLocalDirPath: String
get() = "/data/data/" +
getString(R.string.app_package) + File.separator +
getString(R.string.nats_release)
private val natsLocalExecutable: String
get() = natsLocalDirPath + File.separator + getString(R.string.nats_executable)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//copy NATS executable from assets to local directory
copyNATSExecutable()
setContentView(R.layout.activity_main)
//set default status for UI elements
setDefaultUI()
//disable extra settings by default
val btnHost = findViewById<View>(R.id.btnHost) as ToggleButton
btnHost.setOnClickListener { modifyHost(btnHost.isChecked) }
val btnPort = findViewById<View>(R.id.btnPort) as ToggleButton
btnPort.setOnClickListener { modifyPort(btnPort.isChecked) }
val btnLog = findViewById<View>(R.id.btnLog) as ToggleButton
btnLog.setOnClickListener {
ActivityCompat.requestPermissions(this@NATSActivity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
1)
modifyLog(btnLog.isChecked)
}
val btnConfig = findViewById<View>(R.id.btnConfig) as ToggleButton
btnConfig.setOnClickListener {
ActivityCompat.requestPermissions(this@NATSActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
2)
modifyConfig(btnConfig.isChecked)
Toast.makeText(baseContext,
getString(R.string.toast_config),
Toast.LENGTH_SHORT).show()
}
//get EditText elements to retrieve values
val etHost = findViewById<View>(R.id.etHost) as EditText
val etPort = findViewById<View>(R.id.etPort) as EditText
val etLog = findViewById<View>(R.id.etLog) as EditText
val etConfig = findViewById<View>(R.id.etConfig) as EditText
val btnStartStop = findViewById<View>(R.id.btnStartStop) as ToggleButton
btnStartStop.setOnClickListener(View.OnClickListener {
if (btnStartStop.isChecked) {
var host: String? = if (btnHost.isChecked) etHost.text.toString() else null
if (!Utils.isValidIPv4(host)) {
//if IP not valid, don't use as argument
host = null
}
var port: String? = if (btnPort.isChecked) etPort.text.toString() else null
if (!Utils.isValidPort(port)) {
//if port not valid, don't use as argument
port = null
}
var log: String? = if (btnLog.isChecked) etLog.text.toString() else null
if (log != null) {
log = (Utils.externalStorageDirectory
+ File.separator + log)
}
var config: String? = if (btnConfig.isChecked) etConfig.text.toString() else null
//check if provided config file exists
if (config != null) {
val fileConfig = File(Utils.externalStorageDirectory
+ File.separator + config)
if (!fileConfig.exists()) {
//if file doesn't exist, don't use as option
Toast.makeText(this@NATSActivity,
getString(R.string.toast_config_not_found), Toast.LENGTH_SHORT).show()
btnStartStop.isChecked = false
return@OnClickListener
}
config = (Utils.externalStorageDirectory
+ File.separator + config)
}
RunNATSTask().execute(host, port, log, config)
modifyUI(true)
Toast.makeText(baseContext,
getString(R.string.toast_start),
Toast.LENGTH_LONG).show()
} else {
//should be checked because running, then decide what to do after alert dialog
btnStartStop.isChecked = true
//ask user if he's sure to stop NATS Server
AlertDialog.Builder(this@NATSActivity)
.setTitle(getString(R.string.alert_stop_title))
.setMessage(getString(R.string.alert_stop_message))
.setPositiveButton(android.R.string.yes) { _, _ ->
// continue with stop
if (killNATS()) {
setDefaultUI()
Toast.makeText(baseContext,
getString(R.string.toast_stop),
Toast.LENGTH_LONG).show()
}
}
.setNegativeButton(android.R.string.no) { _, _ ->
// do nothing
}
.setIcon(android.R.drawable.ic_dialog_alert)
.show()
}
})
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
//log case
1 -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this@NATSActivity,
getString(R.string.toast_permission_denied), Toast.LENGTH_SHORT).show()
//show evidence to the user that log option was disabled
val btnLog = findViewById<View>(R.id.btnLog) as ToggleButton
btnLog.isChecked = false
}
return
}
//config case
2 -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(this@NATSActivity,
getString(R.string.toast_permission_denied), Toast.LENGTH_SHORT).show()
//show evidence to the user that config option was disabled
val btnConfig = findViewById<View>(R.id.btnConfig) as ToggleButton
btnConfig.isChecked = false
}
return
}
}
}
private fun copyNATSExecutable() {
val NATSExecutable = File("/data/data/" +
getString(R.string.app_package) + File.separator +
getString(R.string.nats_release) + File.separator +
getString(R.string.nats_executable))
if (!NATSExecutable.exists()) {
Log.d(TAG, "Copying asset: " + natsAssetsExecutablePath
+ " to " + natsLocalDirPath)
copyFile(natsAssetsExecutablePath, natsLocalDirPath, baseContext)
}
}
private fun modifyHost(isChecked: Boolean) {
val tb = findViewById<View>(R.id.btnHost) as ToggleButton
tb.isChecked = isChecked
findViewById<View>(R.id.etHost).isEnabled = isChecked
}
private fun modifyPort(isChecked: Boolean) {
val tb = findViewById<View>(R.id.btnPort) as ToggleButton
tb.isChecked = isChecked
findViewById<View>(R.id.etPort).isEnabled = isChecked
}
private fun modifyLog(isChecked: Boolean) {
val tb = findViewById<View>(R.id.btnLog) as ToggleButton
tb.isChecked = isChecked
findViewById<View>(R.id.etLog).isEnabled = isChecked
}
private fun modifyConfig(isChecked: Boolean) {
val tb = findViewById<View>(R.id.btnConfig) as ToggleButton
tb.isChecked = isChecked
findViewById<View>(R.id.etConfig).isEnabled = isChecked
//disable others
modifyHost(false)
modifyPort(false)
modifyLog(false)
findViewById<View>(R.id.btnHost).isEnabled = !isChecked
findViewById<View>(R.id.btnPort).isEnabled = !isChecked
findViewById<View>(R.id.btnLog).isEnabled = !isChecked
}
private fun setDefaultUI() {
val btnStartStop = findViewById<View>(R.id.btnStartStop) as ToggleButton
btnStartStop.isEnabled = true
btnStartStop.isChecked = false
findViewById<View>(R.id.pbRunning).visibility = View.INVISIBLE
val btnHost = findViewById<View>(R.id.btnHost) as ToggleButton
btnHost.isEnabled = true
btnHost.isChecked = false
val btnPort = findViewById<View>(R.id.btnPort) as ToggleButton
btnPort.isEnabled = true
btnPort.isChecked = false
val btnLog = findViewById<View>(R.id.btnLog) as ToggleButton
btnLog.isEnabled = true
btnLog.isChecked = false
val btnConfig = findViewById<View>(R.id.btnConfig) as ToggleButton
btnConfig.isEnabled = true
btnConfig.isChecked = false
findViewById<View>(R.id.etHost).isEnabled = false
findViewById<View>(R.id.etPort).isEnabled = false
findViewById<View>(R.id.etLog).isEnabled = false
findViewById<View>(R.id.etConfig).isEnabled = false
}
private fun modifyUI(isNATSRunning: Boolean) {
findViewById<View>(R.id.pbRunning).visibility = if (isNATSRunning) View.VISIBLE else View.INVISIBLE
//Button elements
findViewById<View>(R.id.btnHost).isEnabled = !isNATSRunning
findViewById<View>(R.id.btnPort).isEnabled = !isNATSRunning
findViewById<View>(R.id.btnLog).isEnabled = !isNATSRunning
findViewById<View>(R.id.btnConfig).isEnabled = !isNATSRunning
//EditText elements
findViewById<View>(R.id.etHost).isEnabled = !isNATSRunning
findViewById<View>(R.id.etPort).isEnabled = !isNATSRunning
findViewById<View>(R.id.etLog).isEnabled = !isNATSRunning
findViewById<View>(R.id.etConfig).isEnabled = !isNATSRunning
}
private inner class RunNATSTask : AsyncTask<String, Void, Boolean>() {
override fun doInBackground(vararg params: String): Boolean? =
runNATS(params[0], params[1], params[2], params[3])
override fun onPostExecute(result: Boolean?) {
if (result != null && !result) {
//disable running notification if false
modifyUI(false)
}
}
}
private fun killNATS(): Boolean {
return try {
val kill = "kill -9 " + _natsProcessPID
Log.d(TAG, "Executing: " + kill)
Runtime.getRuntime().exec(kill)
true
} catch (e: IOException) {
Log.e(TAG, "Unable to kill NATS: ", e)
false
}
}
private fun runNATS(host: String?, port: String?, log: String?, config: String?): Boolean {
try {
val args = StringBuilder()
if (host != null) {
args.append(" -a ").append(host)
}
if (port != null) {
args.append(" -p ").append(port)
}
if (log != null) {
args.append(" -l ").append(log)
}
if (config != null) {
args.append(" -c ").append(config)
}
Log.d(TAG, "Executing: " + natsLocalExecutable + args.toString())
val natsProcess = Runtime.getRuntime().exec(
natsLocalExecutable + args.toString())
//use reflection to extract PID
val f = natsProcess.javaClass.getDeclaredField("pid")
f.isAccessible = true
_natsProcessPID = f.getInt(natsProcess)
Log.d(TAG, "NATS PID is: " + _natsProcessPID)
val reader = BufferedReader(InputStreamReader(natsProcess.inputStream))
// var read: Int
// val buffer = CharArray(4096)
// val output = StringBuffer()
reader.use { it.readText() }
// while ((read = reader.read(buffer)) > 0) {
// output.append(buffer, 0, read)
// }
// reader.close()
// Waits for the command to finish.
natsProcess.waitFor()
//String nativeOutput = output.toString();
//Log.d(TAG, "Output: " + nativeOutput);
} catch (e: InterruptedException) {
Log.e(TAG, "Unable to run NATS: ", e)
return false
} catch (e: IOException) {
Log.e(TAG, "Unable to run NATS: ", e)
return false
} catch (e: NoSuchFieldException) {
Log.e(TAG, "Unable to extract field ", e)
return false
} catch (e: IllegalAccessException) {
Log.e(TAG, "Unable to access field ", e)
}
return true
}
companion object {
// private fun copyFile(assetPath: String, localDirPath: String, context: Context) {
// try {
// val inputStream = context.assets.open(assetPath)
//
// val localDir = File(localDirPath)
// if (!localDir.exists()) {
// val success = localDir.mkdir()
// if (!success) {
// throw RuntimeException("Unable to create directory: " + localDirPath)
// }
// }
//
// val assetsFile = File(assetPath)
//
// val outFilePath = localDirPath + File.separator + assetsFile.name
// val out = FileOutputStream(outFilePath)
// Log.d(TAG, "Copying file to: " + outFilePath)
// var read: Int
// val buffer = ByteArray(4096)
// while ((read = inputStream.read(buffer)) > 0) {
// out.write(buffer, 0, read)
// }
// out.close()
// inputStream.close()
//
// //set executable
// val bin = File(localDirPath + File.separator + assetsFile.name)
// bin.setExecutable(true)
// } catch (e: IOException) {
// throw RuntimeException(e)
// }
// }
private fun copyFile(assetFilePath: String, localDirPath: String, context: Context) {
val assetsFile = File(assetFilePath)
val localDir = File(localDirPath)
if (!localDir.exists() && !localDir.mkdir()) {
throw RuntimeException("Unable to create directory: " + localDirPath)
}
val outputFilePath = localDirPath + File.separator + assetsFile.name
val inputStream = context.assets.open(assetFilePath)
val outputStream = FileOutputStream(outputFilePath)
try {
inputStream.copyTo(outputStream)
//set executable
val bin = File(outputFilePath)
bin.setExecutable(true)
} finally {
inputStream.close()
outputStream.close()
}
}
private var _natsProcessPID: Int = 0
private val TAG = "NATSActivity"
}
}
| 0
|
Kotlin
|
1
| 10
|
8e8f9615d4a0e41737509ec36ac1ac99f14cf001
| 17,096
|
nats-android
|
MIT License
|
Tabuada_Refatorada/app/src/main/java/com/cassio/tabuada_refatorada/MainActivity.kt
|
cassiofm
| 382,967,684
| false
| null |
package com.cassio.tabuada_app3
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
//import kotlinx.android.synthetic.main.activity_main.*
//import kotlinx.android.synthetic.main.activity_main.view.*
import java.util.*
class MainActivity : AppCompatActivity () {
lateinit var resultadoTabuada: TextView
lateinit var botaoCalcular: Button
var numeroTabuada: Int? = null
override fun onCreate ( savedInstanceState : Bundle? ) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
resultadoTabuada = findViewById(R.id.txtResultado)
botaoCalcular = findViewById(R.id.btnSortear)
botaoCalcular.setOnClickListener {
numeroTabuada = findViewById<EditText>(R.id.txtNumero).text.toString().toIntOrNull()
CalcularTabuada()
}
}
fun CalcularTabuada (){
var calculo = 0
var resultado = ""
numeroTabuada?.let{
for (i in 1..10) {
calculo = it * i
resultado += "$numeroTabuada X $i = $calculo \n"
}
}
resultadoTabuada.text = resultado
}
}
| 0
|
Kotlin
|
0
| 0
|
ee75a080ae06c2ddd4ab1a0ed26bed81c08dc293
| 1,312
|
mobile
|
MIT License
|
android-base/basektlib/src/main/java/com/kangraoo/basektlib/tools/store/DiskCacheStore.kt
|
smartbackme
| 390,677,125
| false
| null |
package com.kangraoo.basektlib.tools.store
import android.text.TextUtils
import com.jakewharton.disklrucache.DiskLruCache
import com.kangraoo.basektlib.app.SApplication
import com.kangraoo.basektlib.data.model.SExpModel
import com.kangraoo.basektlib.exception.LibPermissionException
import com.kangraoo.basektlib.exception.LibStorageException
import com.kangraoo.basektlib.exception.LibStorageNoEnoughSpaceException
import com.kangraoo.basektlib.tools.SSystem
import com.kangraoo.basektlib.tools.encryption.MessageDigestUtils
import com.kangraoo.basektlib.tools.log.ULog
import com.kangraoo.basektlib.tools.store.filestorage.StorageType
import com.kangraoo.basektlib.tools.store.filestorage.UStorage
import com.kangraoo.basektlib.tools.store.filestorage.UStorage.getWritePath
import com.kangraoo.basektlib.tools.store.filestorage.UStorage.storageCheck
import java.io.*
import kotlin.jvm.Throws
/**
* author : WaTaNaBe
* e-mail : <EMAIL>
* time : 2019/07/23
* desc : 文件缓存类
*/
class DiskCacheStore private constructor() {
companion object {
private const val DISK_CACHE = "disk_cache"
@JvmStatic
val instance: DiskCacheStore by lazy {
DiskCacheStore()
}
}
@Volatile
private var cache: DiskLruCache? = null
private fun checkEnable() {
if (cache == null || cache!!.isClosed) {
val path = getWritePath(
DISK_CACHE,
StorageType.TYPE_CACHE
)
if (path != null) {
cache = DiskLruCache.open(File(path), version, 1, 10 * UStorage.M) // 10M
}
}
}
@Throws(LibPermissionException::class, LibStorageException::class)
private fun checkStorage() {
storageCheck(StorageType.TYPE_CACHE)
}
// 每当版本号改变,缓存路径下存储的所有数据都会被清除掉
private val version: Int
private get() {
// 每当版本号改变,缓存路径下存储的所有数据都会被清除掉
return if (SApplication.instance().sConfiger.diskCacheVersion != null) {
SApplication.instance().sConfiger.diskCacheVersion!!
} else {
SSystem.getVersionCode(SApplication.context())!!.toInt()
}
}
@Synchronized
@Throws(LibPermissionException::class, LibStorageException::class)
fun put(key: String, value: Any?) {
checkStorage()
checkEnable()
if (TextUtils.isEmpty(key)) return
if (cache != null) {
var editor = cache!!.edit(MessageDigestUtils.md5(key))
if (value != null) {
ObjectOutputStream(editor.newOutputStream(0)).use {
it.writeObject(value)
editor.commit()
}
}
cache!!.flush()
}
}
@Throws(LibPermissionException::class, LibStorageException::class)
fun put(map: Map<String, Any?>) {
for ((key, value) in map) {
put(key, value)
}
}
@Throws(LibPermissionException::class, LibStorageException::class)
fun put(map: Map<String, Any?>, expireMills: Long) {
for ((key, value) in map) {
put(key, value, expireMills)
}
}
@Throws(LibPermissionException::class, LibStorageException::class)
fun put(key: String, value: Any?, expireMills: Long) {
put(key, SExpModel(value, expireMills))
}
@Synchronized
@Throws(LibPermissionException::class, LibStorageException::class)
fun <T> get(key: String, defaultValue: T?): T? {
try {
checkStorage()
} catch (e: LibStorageNoEnoughSpaceException) {
ULog.e(e)
}
checkEnable()
if (cache != null) {
val snapshot =
cache!![MessageDigestUtils.md5(key)]
if (snapshot != null) {
ObjectInputStream(snapshot.getInputStream(0)).use {
return getModel(key, it.readObject(), defaultValue)
}
}
}
return defaultValue
}
@Synchronized
@Throws(LibPermissionException::class, LibStorageException::class)
fun remove(key: String) {
try {
checkStorage()
} catch (e: LibStorageNoEnoughSpaceException) {
ULog.e(e)
}
checkEnable()
if (cache != null) {
cache!!.remove(MessageDigestUtils.md5(key))
}
}
@Synchronized
@Throws(LibPermissionException::class, LibStorageException::class)
fun contains(key: String): Boolean {
try {
checkStorage()
} catch (e: LibStorageNoEnoughSpaceException) {
ULog.e(e)
}
checkEnable()
if (cache != null) {
val snapshot =
cache!![MessageDigestUtils.md5(key)]
return snapshot != null
}
return false
}
@Synchronized
@Throws(LibPermissionException::class, LibStorageException::class)
fun clear() {
try {
checkStorage()
} catch (e: LibStorageNoEnoughSpaceException) {
ULog.e(e)
}
checkEnable()
if (cache != null) {
cache!!.delete()
}
}
private fun <T> getModel(key: String, o: Any?, defaultValue: T?): T? {
return if (o != null) {
if (o is SExpModel) {
if (o.isExpire()) {
remove(key)
defaultValue
} else {
o.value as T?
}
} else o as T
} else defaultValue
}
}
| 0
|
Kotlin
|
1
| 2
|
39b595a9a7a8bf5176022a51bc3fd63fa536414d
| 5,592
|
Creative-Challenge-DrawingBoard
|
MIT License
|
examplemodule/src/main/kotlin/com/example/examplemodule/routing/Route.kt
|
teambankrupt
| 292,100,358
| false
|
{"Kotlin": 13084, "HTML": 3849, "Java": 586}
|
package com.example.examplemodule.routing
class Route {
class V1 {
companion object {
private const val API = "/api"
private const val VERSION = "/v1"
private const val ADMIN = "/admin"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e1656ff77d6e60bc0aabc00dad5701af2a96f8aa
| 255
|
examples
|
Apache License 2.0
|
2023/src/test/kotlin/Day08Test.kt
|
dlew
| 498,498,097
| false
|
{"Kotlin": 331659, "TypeScript": 69253, "Python": 25458, "JavaScript": 262}
|
import org.junit.jupiter.api.Test
import utils.getResourceAsString
import kotlin.test.assertEquals
class Day08Test {
@Test
fun part1_sample1() {
assertEquals(2, Day08.part1(getResourceAsString("day08-sample1.txt")))
}
@Test
fun part1_sample2() {
assertEquals(6, Day08.part1(getResourceAsString("day08-sample2.txt")))
}
@Test
fun part1() {
assertEquals(12599, Day08.part1(getResourceAsString("day08.txt")))
}
@Test
fun part2_sample() {
assertEquals(6L, Day08.part2(getResourceAsString("day08-sample3.txt")))
}
@Test
fun part2() {
assertEquals(8245452805243L, Day08.part2(getResourceAsString("day08.txt")))
}
}
| 0
|
Kotlin
|
0
| 0
|
dda4127d9d622c321917370b38fe59e4ae09d565
| 663
|
advent-of-code
|
MIT License
|
app/src/main/java/com/mjkim/infinityviewpager/InfinityViewPagerAdapter.kt
|
mjkim737
| 331,807,297
| false
| null |
package com.mjkim.infinityviewpagerlib
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class InfinityViewPagerAdapter(private val list : ArrayList<Any>, private val layout: Int) : RecyclerView.Adapter<InfinityViewPagerAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val imageView: ImageView = view.findViewById(R.id.imageview_glide)
}
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(
LayoutInflater.from(parent.context).inflate(layout, parent, false)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Glide.with(holder.itemView.context)
.load(list[position])
.into(holder.imageView)
}
}
| 0
|
Kotlin
|
0
| 0
|
62b1e0cf2bc6e83390e02c8a81f62365ce101eb4
| 969
|
InfinityViewPager
|
Apache License 2.0
|
app/src/test/java/kasem/sm/delightplayground/datasource/cache/RocketDatabaseFake.kt
|
kasem-sm
| 408,881,519
| false
|
{"Kotlin": 105619}
|
/*
Copyright (c) 2021 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kasem.sm.delightplayground.datasource.cache
import kasem.sm.delightplayground.datasource.Rocket
class RocketDatabaseFake {
/**
* We would use a mutable list as our fake Database because
* we need to mock our Database and list would be a good replacement for it.
*/
val rocket: MutableList<Rocket> = mutableListOf()
}
| 0
|
Kotlin
|
4
| 40
|
0ff3f4ba8c40985da8283c681e9e4193f2cf4b60
| 917
|
RocketXDelight-Playground
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.