path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
app/src/main/java/com/home/nainpainter/Multipart.kt
majidmobini
644,927,553
false
null
package com.home.nainpainter import android.util.Log import java.io.* import java.net.HttpURLConnection import java.net.URL /** * Created by tarek on 9/13/17. */ class Multipart /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * @param url * * * @throws IOException */ @Throws(IOException::class) constructor(url: URL , outFile: File) { companion object { private val LINE_FEED = "\r\n" private val maxBufferSize = 1024 * 1024 private val charset = "UTF-8" } // creates a unique boundary based on time stamp private val boundary: String = "===" + System.currentTimeMillis() + "===" private val httpConnection: HttpURLConnection = url.openConnection() as HttpURLConnection private val outputStream: OutputStream private val writer: PrintWriter private val loutFile = outFile init { httpConnection.setRequestProperty("Accept-Charset", "UTF-8") httpConnection.setRequestProperty("Connection", "Keep-Alive") httpConnection.setRequestProperty("Cache-Control", "no-cache") httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary) httpConnection.setChunkedStreamingMode(maxBufferSize) httpConnection.doInput = true httpConnection.doOutput = true // indicates POST method httpConnection.useCaches = false outputStream = httpConnection.outputStream writer = PrintWriter(OutputStreamWriter(outputStream, charset), true) } /** * Adds a form field to the request * @param name field name * * * @param value field value */ fun addFormField(name: String, value: String) { writer.append("--").append(boundary).append(LINE_FEED) writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"") .append(LINE_FEED) writer.append(LINE_FEED) writer.append(value).append(LINE_FEED) writer.flush() } /** * Adds a upload file section to the request * @param fieldName - name attribute in <input type="file" name="..."></input> * * * @param uploadFile - a File to be uploaded * * * @throws IOException */ @Throws(IOException::class) fun addFilePart(fieldName: String, uploadFile: File, fileName: String, fileType: String) { writer.append("--").append(boundary).append(LINE_FEED) writer.append("Content-Disposition: file; name=\"").append(fieldName) .append("\"; filename=\"").append(fileName).append("\"").append(LINE_FEED) writer.append("Content-Type: ").append(fileType).append(LINE_FEED) writer.append(LINE_FEED) writer.flush() val inputStream = FileInputStream(uploadFile) inputStream.copyTo(outputStream, maxBufferSize) outputStream.flush() inputStream.close() writer.append(LINE_FEED) writer.flush() } /** * Adds a header field to the request. * @param name - name of the header field * * * @param value - value of the header field */ fun addHeaderField(name: String, value: String) { writer.append(name + ": " + value).append(LINE_FEED) writer.flush() } /** * Upload the file and receive a response from the server. * @param onFileUploadedListener * * * @throws IOException */ @Throws(IOException::class) fun upload(onFileUploadedListener: OnFileUploadedListener?) { writer.append(LINE_FEED).flush() writer.append("--").append(boundary).append("--") .append(LINE_FEED) writer.close() try { // checks server's status code first val status = httpConnection.responseCode if (status == HttpURLConnection.HTTP_OK) { val reader = BufferedReader(InputStreamReader(httpConnection .inputStream)) val inputStream = httpConnection.inputStream inputStream.use { input -> loutFile.outputStream().use { output -> input.copyTo(output) } } //val response = reader.use(BufferedReader::readText) //Log.d("response",response) httpConnection.disconnect() onFileUploadedListener?.onFileUploadingSuccess(loutFile) } else { onFileUploadedListener?.onFileUploadingFailed(status) } } catch (e: IOException) { e.printStackTrace() } } interface OnFileUploadedListener { fun onFileUploadingSuccess(response: File) fun onFileUploadingFailed(responseCode: Int) } }
0
Kotlin
0
0
4aa6bf21732dbebcefbf76261dc8ce2425b432aa
4,830
Nail_painter
Apache License 2.0
src/main/kotlin/com/aphisiit/springkafka/service/KafkaProducer.kt
aphisiit
744,406,846
false
{"Kotlin": 20431, "Dockerfile": 267}
package com.aphisiit.springkafka.service import org.springframework.stereotype.Service @Service class KafkaProducer { fun send() { } }
0
Kotlin
0
0
2545d30f5507cc3d29c70d36173b8d38d63e648b
140
spring-kafka-producer
MIT License
compiler/testData/writeSignature/declarationSiteVariance/wildcardOptimization/finalReturnType.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
class Out<out T> class OutPair<out X, out Y> class In<in Z> class Inv<E> open class Open class Final fun skipAllOutInvWildcards(): Inv<OutPair<Open, Out<Out<Open>>>> = null!! // method: FinalReturnTypeKt::skipAllOutInvWildcards // generic signature: ()LInv<LOutPair<LOpen;LOut<LOut<LOpen;>;>;>;>; fun skipAllInvWildcards(): Inv<In<Out<Open>>> = null!! // method: FinalReturnTypeKt::skipAllInvWildcards // generic signature: ()LInv<LIn<LOut<+LOpen;>;>;>; fun notDeepIn(): In<Final> = null!! // method: FinalReturnTypeKt::notDeepIn // generic signature: ()LIn<LFinal;>; fun skipWildcardsUntilIn0(): Out<In<Out<Open>>> = null!! // method: FinalReturnTypeKt::skipWildcardsUntilIn0 // generic signature: ()LOut<LIn<LOut<+LOpen;>;>;>; fun skipWildcardsUntilIn1(): Out<In<Out<Final>>> = null!! // method: FinalReturnTypeKt::skipWildcardsUntilIn1 // generic signature: ()LOut<LIn<LOut<LFinal;>;>;>; fun skipWildcardsUntilIn2(): Out<In<OutPair<Final, Out<Open>>>> = null!! // method: FinalReturnTypeKt::skipWildcardsUntilIn2 // generic signature: ()LOut<LIn<LOutPair<LFinal;+LOut<+LOpen;>;>;>;>; fun skipWildcardsUntilInProjection(): Inv<in Out<Open>> = null!! // method: FinalReturnTypeKt::skipWildcardsUntilInProjection // generic signature: ()LInv<-LOut<+LOpen;>;>;
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,268
kotlin
Apache License 2.0
BinaryTree.kt
HKhademian
279,499,193
false
{"Python": 38437, "JavaScript": 16936, "Kotlin": 11381}
package tree.bin class BinaryTree( var value: String = "", var parent: BinaryTree? = null, var left: BinaryTree? = null, var right: BinaryTree? = null, var tag: Any? = null, //use in AVL and RB init: BinaryTree.() -> Unit = {} ) { init { left?.parent = this right?.parent = this init() } override fun toString() = write().toString() } /// create bintree and insert it fun BinaryTree.print() = print(this) val BinaryTree.hasParent get() = parent != null val BinaryTree.hasLeft get() = left != null val BinaryTree.hasRight get() = right != null val BinaryTree.hasChild get() = hasLeft or hasRight val BinaryTree.isLeaf get() = !hasChild val BinaryTree.isRoot get() = !hasParent val BinaryTree.isLeft get() = this == parent?.left val BinaryTree.isRight get() = this == parent?.right val BinaryTree.grand get() = parent?.parent val BinaryTree.uncle get() = parent?.sibling val BinaryTree.sibling get() = if (isLeft) parent!!.right else if (isRight) parent!!.right else null /// get bintree min valuable element before /// sorted: { [target] ... this ... } val BinaryTree.min get():BinaryTree { var node = this while (node.hasLeft) node = node.left!! return node } /// get bintree max valuable element after /// sorted: { a b c ... this ... [target] } val BinaryTree.max get():BinaryTree { var node = this while (node.hasRight) node = node.right!! return node } /// get bintree least valuable element after /// sorted: { a b c ... this [target] ... } val BinaryTree.successor get():BinaryTree { if (hasRight) return right!!.min var node = this // not this.parent while (node.isRight) node = node.parent!! return node.parent ?: node } /// get bintree most valuable element before /// sorted: { a b c ... [target] this ... } val BinaryTree.proccessor get():BinaryTree { if (hasLeft) return right!!.max var node = this // not this.parent while (node.isLeft) node = node.parent!! return node.parent ?: node } /// pretty write bintree in buffer fun BinaryTree.write( buffer: StringBuffer = StringBuffer(), prefix: String = "", childrenPrefix: String = "" ): StringBuffer { buffer.append(prefix) buffer.append(value) buffer.append("\n") fun writeChild(child: BinaryTree?, hasNext: Boolean, childrenPrefix: String): StringBuffer { val pref = childrenPrefix + if (hasNext) "├─── " else "└─── " return if (child != null) { val childPref = childrenPrefix + if (hasNext) "│ " else " " child.write(buffer, pref, childPref) } else { buffer.append(pref) buffer.append("{null}") buffer.append('\n') buffer } } if (hasChild) { // //first left //writeChild(this.left, hasRight, childrenPrefix) //writeChild(this.right, false, childrenPrefix) // first right writeChild(this.right, hasLeft, childrenPrefix) writeChild(this.left, false, childrenPrefix) } return buffer } /// rotate bintree to left fun BinaryTree.rotateLeft() { //if(BST.DEBUG) console.log("RotateLeft("+this.key+")") val other = this.right ?: return val alpha = this.left val beta = other.left val gama = other.right this.right = beta beta?.parent = this other.parent = this.parent if (!this.hasParent) { this.parent = other } else if (this.isLeft) { this.parent!!.left = other } else if (this.isRight) { this.parent!!.right = other } other.left = this this.parent = other } /// rotate bintree to right fun BinaryTree.rotateRight() { // if(BST.DEBUG) console.log("RotateRight("+this.key+")") val other = this.left ?: return val alpha = other.left val beta = other.right val gama = this.right this.left = beta; beta?.parent = this other.parent = this.parent if (!this.hasParent) { this.parent = other } else if (this.isLeft) { this.parent!!.left = other } else if (this.isRight) { this.parent!!.right = other } other.right = this this.parent = other } /// visit bintree PreOrder fun BinaryTree?.preOrder(action: (BinaryTree) -> Unit) { if (this == null) return action(this) left.preOrder(action) right.preOrder(action) } /// visit bintree inOrder fun BinaryTree?.inOrder(action: (BinaryTree) -> Unit) { if (this == null) return left.preOrder(action) action(this) right.preOrder(action) } /// visit bintree PostOrder fun BinaryTree?.postOrder(action: (BinaryTree) -> Unit) { if (this == null) return action(this) left.preOrder(action) right.preOrder(action) } /// create bintree as root node fun binaryTree(value: String = "", init: BinaryTree.() -> Unit = {}) = BinaryTree(value).also { it.init() } /// create bintree as left node of current bintree /// better to use insert instead fun BinaryTree.left(value: String = "", init: BinaryTree.() -> Unit = {}) = BinaryTree(value, this, init = init).also { this.left = it; } /// create bintree as right node of current bintree /// better to use insert instead fun BinaryTree.right(value: String = "", init: BinaryTree.() -> Unit = {}) = BinaryTree(value, this, init = init).also { this.right = it; } /// insert new node fun BinaryTree.bstInsert(newNode: BinaryTree, init: BinaryTree.() -> Unit = {}): BinaryTree { val cmp = { a: BinaryTree?, b: BinaryTree? -> when { a == null -> (if (b == null) 0 else -1) b == null -> 1 else -> a.value.compareTo(b.value) } } val left = this.left val right = this.right if (cmp(this, newNode) > 0) { if (right == null) { this.right = newNode newNode.parent = this } else { right.bstInsert(newNode) } } else { if (left == null) { this.left = newNode newNode.parent = this } else { left.bstInsert(newNode) } } return newNode.also(init) } /// create bintree and insert it fun BinaryTree.bstInsert(value: String = "", init: BinaryTree.() -> Unit = {}) = bstInsert(BinaryTree(value, this), init)
0
Python
0
0
151c1aabf648f8d356eeb858fad40ec24acfad50
5,780
QuickDS
The Unlicense
app/src/main/java/dubizzle/android/com/moviedb/modules/ViewModelKey.kt
alaa7731
166,552,388
false
null
package dubizzle.android.com.moviedb.modules import androidx.lifecycle.ViewModel import dagger.MapKey import kotlin.reflect.KClass @MapKey @Target(AnnotationTarget.FUNCTION) internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
0
Kotlin
0
0
7133e8084051937030ffc994b7b2f05957b0de8b
250
MyMoviesDB
MIT License
src/main/kotlin/de/apps_roters/tesla_for_kotlin/web/AuthRestRequest.kt
oMtQB4
693,307,692
false
{"Kotlin": 61546, "Shell": 147}
package de.apps_roters.tesla_for_kotlin.web import de.apps_roters.tesla_for_kotlin.tesla.TeslaAuth import org.apache.logging.log4j.LogManager class AuthRestRequest(private val restRequest: RestRequest, teslaAuth: TeslaAuth) { private val teslaAuth: TeslaAuth init { this.teslaAuth = teslaAuth } @Throws(Exception::class) operator fun get(getURL: String?, headers: Map<String?, String?>?): String? { return restRequest[getURL, headers] } @Throws(Exception::class) fun post(postURL: String?, body: String?, headers: Map<String?, String?>?): String? { return restRequest.post(postURL, body, headers) } fun setBearer(b: String?) { restRequest.setBearer(b) } @Throws(Exception::class) fun <T : Any?> getJSON(getURL: String?, clazz: Class<T>?): T? { return try { restRequest.getJSON(getURL, clazz) } catch (e: AuthenticationException) { teslaAuth.refreshTokens() restRequest.getJSON(getURL, clazz) } } @Throws(Exception::class) fun <T : Any?> postJson(postURL: String?, body: Any?, clazz: Class<T>?): T? { return try { restRequest.postJson(postURL, body, clazz) } catch (e: AuthenticationException) { teslaAuth.refreshTokens() restRequest.postJson(postURL, body, clazz) } } companion object { val logger = LogManager.getLogger(AuthRestRequest::class.java) } }
0
Kotlin
0
0
be89c084123cc40d4075b61102fc475a45b12b48
1,499
tesla4kotlin
Apache License 2.0
kofu/src/test/kotlin/org/springframework/boot/kofu/samples/logging.kt
ksvasan
151,100,484
true
{"Kotlin": 227981, "Java": 58894, "Shell": 1265, "HTML": 15}
package org.springframework.boot.kofu.samples import org.springframework.boot.kofu.application import org.springframework.boot.logging.LogLevel private fun loggingDsl() { application(false) { logging { level = LogLevel.INFO level("org.springframework", LogLevel.DEBUG) level<ApiHandler>(LogLevel.WARN) } } }
0
Kotlin
0
0
a747b8ac4d224ca598398ae834eac53d15c2d895
324
spring-fu
Apache License 2.0
document-server/src/main/kotlin/com/github/chaitan64arun/documentserver/DocumentServerApplication.kt
chaitan64arun
309,894,949
false
null
package com.github.chaitan64arun.documentserver import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.runApplication @SpringBootApplication @ConfigurationPropertiesScan class DocumentServerApplication fun main(args: Array<String>) { runApplication<DocumentServerApplication>(*args) }
0
Kotlin
0
0
815809ef9e2d9e3533a35985ff1055d2c3c05418
414
quick-start
MIT License
filesave/build.gradle.kts
drahovac
342,925,986
false
null
plugins { id("com.android.library") kotlin("android") kotlin("android.extensions") } extra.apply { set("PUBLISH_GROUP_ID", "io.github.drahovac") set("PUBLISH_VERSION", "0.0.3") set("PUBLISH_ARTIFACT_ID", "file-save") } apply(from = "${rootProject.projectDir}/scripts/publish-module.gradle") android { compileSdkVersion(Versions.compileSdkVersion) defaultConfig { minSdkVersion(Versions.minSdkVersion) targetSdkVersion(Versions.compileSdkVersion) versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles("consumer-rules.pro") } buildTypes { getByName("release") { isMinifyEnabled = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" languageVersion = "1.5" } } dependencies { implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) implementation(KotlinDependencies.kotlin) implementation(KotlinDependencies.coroutines) implementation(AndroidDependencies.androidxCore) implementation(AndroidDependencies.appCompat) testImplementation(TestDependencies.junit) testImplementation(TestDependencies.mockito) testImplementation(TestDependencies.mockitoKotlin) androidTestImplementation(TestDependencies.androidxTest) androidTestImplementation(TestDependencies.espresso) }
0
Kotlin
1
2
ac490dd099347183345e420e1f45a473cb5bde71
1,729
android-file-save
Apache License 2.0
app/demo/src/main/kotlin/com/example/demo/book/Book.kt
sabercon
609,417,032
false
null
package com.example.demo.book import com.example.util.EPOCH import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.Id import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.relational.core.mapping.Table import java.time.LocalDateTime @Table data class Book( @Id val id: Long = 0, val title: String, val author: String, val price: Long, @CreatedDate val createdAt: LocalDateTime = EPOCH, @LastModifiedDate val updatedAt: LocalDateTime = EPOCH, )
0
Kotlin
0
0
7cac98655913f04b2c396387f801a539b321ecb5
551
gksr-monorepo
MIT License
app/src/main/java/com/crossbowffs/quotelock/app/settings/DarkModeViewModel.kt
Yubyf
60,074,817
false
null
package com.crossbowffs.quotelock.app.settings import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate.NightMode import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.crossbowffs.quotelock.data.ConfigurationRepository import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject data class DarkModeUiState(@NightMode val nightMode: Int) /** * @author Yubyf */ @HiltViewModel class DarkModeViewModel @Inject constructor( private val configurationRepository: ConfigurationRepository, ) : ViewModel() { private val _uiState = mutableStateOf(DarkModeUiState(configurationRepository.nightMode)) val uiState: State<DarkModeUiState> = _uiState fun setNightMode(@NightMode nightMode: Int) { configurationRepository.nightMode = nightMode _uiState.value = DarkModeUiState(nightMode) AppCompatDelegate.setDefaultNightMode(nightMode) } }
2
Kotlin
3
53
7e82ba2c535ed6f68a81c762805038f2b8bf0e4f
1,019
QuoteLockX
MIT License
messaging-core/src/test/java/com/nabla/sdk/messaging/core/data/apollo/SubscriptionExtKtTest.kt
nabla
478,468,099
false
{"Kotlin": 1146406, "Java": 20507}
package com.nabla.sdk.messaging.core.data.apollo import app.cash.turbine.test import com.nabla.sdk.core.data.stubs.TestClock import com.nabla.sdk.core.data.stubs.fake import com.nabla.sdk.core.domain.entity.Provider import com.nabla.sdk.messaging.core.domain.entity.ProviderInConversation import com.nabla.sdk.tests.common.BaseCoroutineTest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import org.junit.Test import kotlin.test.assertFalse import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) internal class SubscriptionExtKtTest : BaseCoroutineTest() { @Test fun `notifyTypingUpdates() notifies typing updates`() = runTest { val clock = TestClock(this) val typingProvider = ProviderInConversation( Provider.fake(), clock.now(), null, ) val eventFlowWithProviders = flow { emit(typingProvider) }.notifyTypingUpdates(clock, coroutineContext) { listOf(it) } eventFlowWithProviders.test { assertTrue(awaitItem().isTyping(clock)) assertFalse(awaitItem().isTyping(clock)) awaitComplete() } } }
0
Kotlin
2
17
363c71b71f7902cea04529fa2b052f93aa8abb47
1,223
nabla-android
MIT License
imagepicker/src/main/java/com/esafirm/imagepicker/features/imageloader/ImageType.kt
esafirm
70,986,819
false
{"Kotlin": 88895, "Shell": 162}
package com.esafirm.imagepicker.features.imageloader enum class ImageType { FOLDER, GALLERY }
55
Kotlin
318
1,057
13e3bea95828150901cf7cc43d9f045dbe23bda5
98
android-image-picker
MIT License
app/src/main/java/com/etasdemir/ethinspector/data/remote/service/BlockService.kt
etasdemir
584,191,764
false
null
package com.etasdemir.ethinspector.data.remote.service import com.etasdemir.ethinspector.data.remote.dto.etherscan.* import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface BlockService { @GET("/api?module=proxy&action=eth_getBlockByNumber") suspend fun getBlockInfoByHash( @Query("tag") blockHash: String, @Query("boolean") getTransactionsAsObject: Boolean ): Response<EtherscanRPCResponse<BlockResponse>> }
0
Kotlin
0
3
b71cf963b6265f9c1a3d8aa74cdf79398a5d91b8
474
eth-inspector
MIT License
pack/tester/src/main/kotlin/voodoo/tester/AbstractTester.kt
DaemonicLabs
119,208,408
false
{"Kotlin": 561752, "Java": 13063, "Shell": 2818}
package voodoo.tester import com.eyeem.watchadoin.Stopwatch import voodoo.data.lock.LockPack import voodoo.util.Directories /** * Created by nikky on 30/03/18. * @author Nikky */ abstract class AbstractTester { abstract val label: String abstract suspend fun execute(stopwatch: Stopwatch, modpack: LockPack, clean: Boolean = true) val directories = Directories.get() }
4
Kotlin
8
28
8e4a0643edf10d39335ea084d00d036606901fd4
388
Voodoo
MIT License
kaspresso/src/main/kotlin/com/kaspersky/kaspresso/interceptors/tolibrary/kautomator/KautomatorDeviceInterceptor.kt
KasperskyLab
208,070,025
false
{"Kotlin": 725146, "Java": 10748, "Shell": 1880, "Makefile": 387}
package com.kaspersky.kaspresso.interceptors.tolibrary.kautomator import com.kaspersky.components.kautomator.intercept.interaction.UiDeviceInteraction import com.kaspersky.components.kautomator.intercept.operation.UiDeviceAction import com.kaspersky.components.kautomator.intercept.operation.UiDeviceAssertion import com.kaspersky.kaspresso.interceptors.behaviorkautomator.DeviceBehaviorInterceptor import com.kaspersky.kaspresso.interceptors.tolibrary.LibraryInterceptor import com.kaspersky.kaspresso.interceptors.watcher.kautomator.DeviceWatcherInterceptor /** * Kaspresso's implementation of Kautomator's UiDeviceInteraction interceptor. */ internal class KautomatorDeviceInterceptor( private val deviceBehaviorInterceptors: List<DeviceBehaviorInterceptor>, private val deviceWatcherInterceptors: List<DeviceWatcherInterceptor> ) : LibraryInterceptor<UiDeviceInteraction, UiDeviceAssertion, UiDeviceAction> { /** * Folds all [DeviceBehaviorInterceptor]'s one into another in the order from the first to the last with the actual * [UiDeviceInteraction.check] call as the initial, and invokes the resulting lambda. * Also, adds a call of all [DeviceWatcherInterceptor] in the initial lambda */ override fun interceptCheck(interaction: UiDeviceInteraction, assertion: UiDeviceAssertion) { deviceBehaviorInterceptors.fold( initial = { deviceWatcherInterceptors.forEach { it.interceptCheck(interaction, assertion) } interaction.check(assertion) }, operation = { acc, deviceBehaviorInterceptor -> { deviceBehaviorInterceptor.interceptCheck(interaction, assertion, acc) } } ).invoke() } /** * Folds all [DeviceBehaviorInterceptor]'s one into another in the order from the first to the last with the actual * [UiDeviceInteraction.perform] call as the initial, and invokes the resulting lambda. * Also, adds a call of [DeviceWatcherInterceptor] in the initial lambda */ override fun interceptPerform(interaction: UiDeviceInteraction, action: UiDeviceAction) { deviceBehaviorInterceptors.fold( initial = { deviceWatcherInterceptors.forEach { it.interceptPerform(interaction, action) } interaction.perform(action) }, operation = { acc, deviceBehaviorInterceptor -> { deviceBehaviorInterceptor.interceptPerform(interaction, action, acc) } } ).invoke() } }
44
Kotlin
146
1,716
391e197745ad7d22fd113630fa9dabbdb1d03613
2,662
Kaspresso
Apache License 2.0
src/main/kotlin/org/philips/arcson/bcoder/utils/UnsupportedTypeException.kt
Und97n
513,674,141
false
{"Kotlin": 53179}
package org.philips.arcson.bcoder.utils import org.philips.arcson.type.ArcsonType class UnsupportedTypeException(_scope: String, _type: ArcsonType): BCoderException("Element type $_type is not supported in $_scope")
0
Kotlin
0
0
1b6bfc774e11b77b2b745e0b0fb3bfcba6626fee
221
arcson
Apache License 2.0
src/main/kotlin/ru/kotlin/bankservice/model/dto/RequestDTO.kt
never-sleeps
289,792,976
false
null
package ru.kotlin.bankservice.model.dto import java.math.BigDecimal data class UserRequestDTO( val id: Long? = null, val fullName: String? = null, val passport: String? = null ) data class AccountRequestDTO( val id: Long? = null, val number: Number? = null, val balance: BigDecimal = BigDecimal.ZERO, val currency: String? = null, val userId: Long? = null ) data class TransferRequestDTO( val senderAccountNumber: Number? = null, val receiverAccountNumber: Number? = null, val amount: BigDecimal? = null, val operation: String? = null )
0
Kotlin
0
0
7ced30e18a07d9f3a97b6d6cccf488e26ca6fd3f
589
kotlin-bank-service
Apache License 2.0
app/src/main/java/com/example/footballleaguelocalstorage/presenter/match/DetailsMatchPresenter.kt
maulanarasoky
220,818,120
false
{"Kotlin": 84623}
package com.example.footballleaguelocalstorage.presenter.match import com.example.footballleaguelocalstorage.api.ApiRepository import com.example.footballleaguelocalstorage.api.TheSportDBApi import com.example.footballleaguelocalstorage.coroutines.CoroutineContextProvider import com.example.footballleaguelocalstorage.interfaces.match.DetailsMatchView import com.example.footballleaguelocalstorage.response.match.DetailsResponse import com.google.gson.Gson import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class DetailsMatchPresenter (private val view : DetailsMatchView, private val apiRepository : ApiRepository, private val gson : Gson, private val context: CoroutineContextProvider = CoroutineContextProvider()) { fun getDetailsMatch(idMatch : String?) { view.showLoading() GlobalScope.launch(context.main) { val data = gson.fromJson(apiRepository .doRequest(TheSportDBApi.getDetailsMatch(idMatch)).await(), DetailsResponse:: class.java) view.hideLoading() view.showDetailsMatch(data.detailsMatch) } } }
0
Kotlin
0
0
680f17059d29bac841239ff157e972a5dae19be3
1,134
Football-League-Local-Storage
MIT License
src/main/kotlin/com/sourcegraph/cody/agent/protocol/PanelNotFoundError.kt
sourcegraph
702,947,607
false
{"Kotlin": 466313, "Java": 238892, "Shell": 4321, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294}
package com.sourcegraph.cody.agent.protocol data class PanelNotFoundError(val message: String)
230
Kotlin
6
22
6f75c53354eddb882e15e985ebabc711c5f2e3d2
96
jetbrains
Apache License 2.0
app/src/main/java/xyz/savvamirzoyan/eposea/domain/interactor/RegisterInteractor.kt
eposea
456,247,050
false
{"Kotlin": 156958}
package xyz.savvamirzoyan.eposea.domain.interactor import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import xyz.savvamirzoyan.eposea.R import xyz.savvamirzoyan.eposea.data.repository.AuthRepository import xyz.savvamirzoyan.eposea.domain.mapper.RegistrationConfirmDataToDomainMapper import xyz.savvamirzoyan.eposea.domain.mapper.RegistrationConfirmDomainToAuthStatusDomainMapper import xyz.savvamirzoyan.eposea.domain.mapper.RegistrationDataToDomainMapper import xyz.savvamirzoyan.eposea.domain.model.AuthStatusDomain import xyz.savvamirzoyan.eposea.domain.model.EditTextStatusDomain import xyz.savvamirzoyan.eposea.domain.model.RegistrationConfirmDomain import xyz.savvamirzoyan.eposea.domain.model.RegistrationDomain interface RegisterInteractor { val emailStatusFlow: StateFlow<EditTextStatusDomain> val passwordStatusFlow: StateFlow<EditTextStatusDomain> val passwordRepeatStatusFlow: StateFlow<EditTextStatusDomain> val isSignUpButtonEnabledFlow: StateFlow<Boolean> val isConfirmationBlockVisibleFlow: StateFlow<Boolean> val isSignUpButtonVisibleFlow: StateFlow<Boolean> val isProgressSignUpVisibleFlow: StateFlow<Boolean> val errorMessageIdFlow: SharedFlow<Int> val resultStatusFlow: SharedFlow<AuthStatusDomain> suspend fun validateCredentials(email: String, password: String, passwordRepeat: String) suspend fun signUp(email: String, password: String) suspend fun sendVerificationCode(verificationCode: String) class Base( private val authRepository: AuthRepository, private val registrationDataToDomainMapper: RegistrationDataToDomainMapper, private val registrationConfirmDataToDomainMapper: RegistrationConfirmDataToDomainMapper, private val registrationConfirmDomainToAuthStatusDomainMapper: RegistrationConfirmDomainToAuthStatusDomainMapper ) : RegisterInteractor { private val emailStandardStatus = EditTextStatusDomain() private val passwordStandardStatus = EditTextStatusDomain() private val passwordRepeatStandardStatus = EditTextStatusDomain() private val _emailStatusFlow = MutableStateFlow(emailStandardStatus) override val emailStatusFlow: StateFlow<EditTextStatusDomain> = _emailStatusFlow private val _passwordStatusFlow = MutableStateFlow(passwordStandardStatus) override val passwordStatusFlow: StateFlow<EditTextStatusDomain> = _passwordStatusFlow private val _passwordRepeatStatusFlow = MutableStateFlow(passwordRepeatStandardStatus) override val passwordRepeatStatusFlow: StateFlow<EditTextStatusDomain> = _passwordRepeatStatusFlow private val _isSignUpButtonEnabledFlow = MutableStateFlow(false) override val isSignUpButtonEnabledFlow: StateFlow<Boolean> = _isSignUpButtonEnabledFlow private val _isConfirmationBlockVisibleFlow = MutableStateFlow(false) override val isConfirmationBlockVisibleFlow: StateFlow<Boolean> = _isConfirmationBlockVisibleFlow private val _isSignUpButtonVisibleFlow = MutableStateFlow(true) override val isSignUpButtonVisibleFlow: StateFlow<Boolean> = _isSignUpButtonVisibleFlow private val _isProgressSignUpVisibleFlow = MutableStateFlow(false) override val isProgressSignUpVisibleFlow: StateFlow<Boolean> = _isProgressSignUpVisibleFlow private val _errorMessageIdFlow = MutableSharedFlow<Int>() override val errorMessageIdFlow: SharedFlow<Int> = _errorMessageIdFlow private val _resultStatusFlow = MutableSharedFlow<AuthStatusDomain>() override val resultStatusFlow: SharedFlow<AuthStatusDomain> = _resultStatusFlow override suspend fun validateCredentials(email: String, password: String, passwordRepeat: String) { val isEmailInvalid = !authRepository.isEmailValid(email) val isPasswordInvalid = !authRepository.isPasswordValid(password) val isPasswordRepeatInvalid = isPasswordRepeatInvalid(passwordRepeat, password) // Email if (isEmailInvalid) { _emailStatusFlow.emit(EditTextStatusDomain(error = R.string.email_field_error)) } else { _emailStatusFlow.emit(emailStandardStatus) } // Password if (isPasswordInvalid) { _passwordStatusFlow.emit(EditTextStatusDomain(error = R.string.password_field_error)) } else { _passwordStatusFlow.emit(passwordStandardStatus) } // Password repeat if (isPasswordRepeatInvalid) { _passwordRepeatStatusFlow.emit(EditTextStatusDomain(error = R.string.password_error_dont_match)) } else { _passwordRepeatStatusFlow.emit(passwordRepeatStandardStatus) } _isConfirmationBlockVisibleFlow.emit(false) _isSignUpButtonVisibleFlow.emit(true) _isSignUpButtonEnabledFlow.emit( !isEmailInvalid && !isPasswordInvalid && !isPasswordRepeatInvalid && password.isNotEmpty() && passwordRepeat.isNotEmpty() ) } override suspend fun signUp(email: String, password: String) { _isSignUpButtonVisibleFlow.emit(false) _isProgressSignUpVisibleFlow.emit(true) val registrationDomain: RegistrationDomain = registrationDataToDomainMapper.map(authRepository.sendRegisterCredentials(email, password)) _isProgressSignUpVisibleFlow.emit(false) when (registrationDomain) { RegistrationDomain.Base -> { _isConfirmationBlockVisibleFlow.emit(true) } is RegistrationDomain.Error -> { _isSignUpButtonVisibleFlow.emit(true) _errorMessageIdFlow.emit(registrationDomain.message) } } } override suspend fun sendVerificationCode(verificationCode: String) { val registrationConfirmDomain: RegistrationConfirmDomain = registrationConfirmDataToDomainMapper .map(authRepository.sendConfirmationCode(verificationCode)) val authStatusDomain = registrationConfirmDomainToAuthStatusDomainMapper.map(registrationConfirmDomain) _resultStatusFlow.emit(authStatusDomain) } private fun isPasswordRepeatInvalid(passwordRepeat: String, password: String) = (passwordRepeat.isBlank() && passwordRepeat.isNotEmpty()) || (passwordRepeat.isNotEmpty() && passwordRepeat != password) } }
0
Kotlin
0
0
b451400b4af641053040e0d913bb081fd5510b89
6,800
android-client
MIT License
MyApplication2/app/src/main/java/com/github/peep/PickPeepActivity.kt
KPUCE2021SP
387,675,142
false
null
package com.github.peep import android.app.Activity import android.content.Intent import android.graphics.drawable.AnimationDrawable import android.os.Bundle import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.github.peep.databinding.ActivityPickPeepBinding import kotlinx.android.synthetic.main.fragment_home.* import org.jetbrains.anko.toast class PickPeepActivity : AppCompatActivity() { private lateinit var mBinding : ActivityPickPeepBinding private lateinit var anim_out : AnimationDrawable private lateinit var anim_in : AnimationDrawable // picked값 0: 선택 안함 // 1:red peep 2:yellow 3: blue // 4: green 5:pigeon 6: w(뱁새) private var picked = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = ActivityPickPeepBinding.inflate(layoutInflater) setContentView(mBinding.root) mBinding.redPeepLayout.setOnClickListener { picked =1 val anim_out = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_out) val anim_in = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_in) mBinding.redPeepLayout.startAnimation(anim_in) mBinding.yellowPeepLayout.startAnimation(anim_out) mBinding.bluePeepLayout.startAnimation(anim_out) mBinding.greenPeepLayout.startAnimation(anim_out) mBinding.wPeepLayout.startAnimation(anim_out) mBinding.pigeonLayout.startAnimation(anim_out) } mBinding.yellowPeepLayout.setOnClickListener { picked =2 val anim_out = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_out) val anim_in = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_in) mBinding.redPeepLayout.startAnimation(anim_out) mBinding.yellowPeepLayout.startAnimation(anim_in) mBinding.bluePeepLayout.startAnimation(anim_out) mBinding.greenPeepLayout.startAnimation(anim_out) mBinding.wPeepLayout.startAnimation(anim_out) mBinding.pigeonLayout.startAnimation(anim_out) } mBinding.bluePeepLayout.setOnClickListener { picked =3 val anim_out = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_out) val anim_in = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_in) mBinding.redPeepLayout.startAnimation(anim_out) mBinding.yellowPeepLayout.startAnimation(anim_out) mBinding.bluePeepLayout.startAnimation(anim_in) mBinding.greenPeepLayout.startAnimation(anim_out) mBinding.wPeepLayout.startAnimation(anim_out) mBinding.pigeonLayout.startAnimation(anim_out) } mBinding.greenPeepLayout.setOnClickListener { picked =4 val anim_out = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_out) val anim_in = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_in) mBinding.redPeepLayout.startAnimation(anim_out) mBinding.yellowPeepLayout.startAnimation(anim_out) mBinding.bluePeepLayout.startAnimation(anim_out) mBinding.greenPeepLayout.startAnimation(anim_in) mBinding.wPeepLayout.startAnimation(anim_out) mBinding.pigeonLayout.startAnimation(anim_out) } mBinding.pigeonLayout.setOnClickListener { picked =5 val anim_out = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_out) val anim_in = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_in) mBinding.redPeepLayout.startAnimation(anim_out) mBinding.yellowPeepLayout.startAnimation(anim_out) mBinding.bluePeepLayout.startAnimation(anim_out) mBinding.greenPeepLayout.startAnimation(anim_out) mBinding.wPeepLayout.startAnimation(anim_out) mBinding.pigeonLayout.startAnimation(anim_in) } mBinding.wPeepLayout.setOnClickListener { picked =6 val anim_out = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_out) val anim_in = AnimationUtils.loadAnimation(applicationContext, com.github.peep.R.anim.alpha_anim_fade_in) mBinding.redPeepLayout.startAnimation(anim_out) mBinding.yellowPeepLayout.startAnimation(anim_out) mBinding.bluePeepLayout.startAnimation(anim_out) mBinding.greenPeepLayout.startAnimation(anim_out) mBinding.wPeepLayout.startAnimation(anim_in) mBinding.pigeonLayout.startAnimation(anim_out) } mBinding.nextBtn.setOnClickListener { when(picked){ //red 1 ->{ var intent = Intent(this, MainActivity::class.java) intent.putExtra("nextPeep","red") startActivity(intent) finish() } //yellow 2 ->{ var intent = Intent(this, MainActivity::class.java) intent.putExtra("nextPeep","yellow") startActivity(intent) finish() } //blue 3 ->{ var intent = Intent(this, MainActivity::class.java) intent.putExtra("nextPeep","blue") startActivity(intent) finish() } //green 4 ->{ var intent = Intent(this, MainActivity::class.java) intent.putExtra("nextPeep","green") startActivity(intent) finish() } //pigeon 5 ->{ var intent = Intent(this, MainActivity::class.java) intent.putExtra("nextPeep","pigeon") startActivity(intent) finish() } //뱁새 6 ->{ var intent = Intent(this, MainActivity::class.java) intent.putExtra("nextPeep","white") startActivity(intent) finish() } } } } }
40
Kotlin
1
9
10cc6793adbb2aff5d43e8c64e5cb18abc45ff86
6,829
hummingbird
MIT License
core/src/main/java/com/dicoding/dummyfilmapp/core/domain/repository/IFilmRepository.kt
r3dz0n3-plysafe
391,220,918
false
null
package com.dicoding.dummyfilmapp.core.domain.repository import com.dicoding.dummyfilmapp.core.data.Resource import com.dicoding.dummyfilmapp.core.domain.model.Movie import com.dicoding.dummyfilmapp.core.domain.model.TvShow import kotlinx.coroutines.flow.Flow interface IFilmRepository { fun getAllMovie(): Flow<Resource<List<Movie>>> fun getAllFavMovie(): Flow<List<Movie>> fun setMovieFav(movie: Movie, state: Boolean) fun getAllTvShow(): Flow<Resource<List<TvShow>>> fun getAllFavTvShow(): Flow<List<TvShow>> fun setTvShowFav(tvShow: TvShow, state: Boolean) }
0
Kotlin
0
0
e60dc3657296f4e1e8d705d1543f110dc644e27f
589
Sub2-Expert-DummyFilmApp
The Unlicense
src/main/kotlin/org/arend/module/config/ArendModuleConfigService.kt
JetBrains
96,068,447
false
{"Kotlin": 2445799, "Lex": 14516, "Java": 4637, "HTML": 1695, "CSS": 1108, "JavaScript": 713}
package org.arend.module.config import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleServiceManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import org.arend.ext.module.ModulePath import org.arend.library.LibraryDependency import org.arend.module.* import org.arend.settings.ArendProjectSettings import org.arend.typechecking.ArendTypechecking import org.arend.typechecking.TypeCheckingService import org.arend.util.* import org.arend.yaml.* import org.jetbrains.yaml.psi.YAMLFile class ArendModuleConfigService(val module: Module) : LibraryConfig(module.project), ArendModuleConfiguration { private var synchronized = false var isInitialized = ApplicationManager.getApplication().isUnitTestMode fun synchronize() = synchronized(this) { val result = !synchronized synchronized = true result } private val libraryManager = project.service<TypeCheckingService>().libraryManager override var librariesRoot = project.service<ArendProjectSettings>().librariesRoot set(value) { field = value project.service<ArendProjectSettings>().librariesRoot = value } override var sourcesDir = "" override var withBinaries = false override var binariesDirectory = "" override var testsDir = "" override var withExtensions = false override var extensionsDirectory = "" override var extensionMainClassData = "" override var modules: List<ModulePath>? = null override var dependencies: List<LibraryDependency> = emptyList() override var versionString: String = "" override var langVersionString: String = "" override val binariesDir: String? get() = flaggedBinariesDir override val extensionsDir: String? get() = flaggedExtensionsDir override val extensionMainClass: String? get() = flaggedExtensionMainClass override val version: Version? get() = Version.fromString(versionString) override val langVersion: Range<Version> get() = VersionRange.parseVersionRange(langVersionString) ?: Range.unbound() override val root: VirtualFile? get() = if (module.isDisposed) null else ModuleRootManager.getInstance(module).contentEntries.firstOrNull()?.file override val name get() = module.name private val yamlFile get() = root?.findChild(FileUtils.LIBRARY_CONFIG_FILE)?.let { PsiManager.getInstance(project).findFile(it) as? YAMLFile } val librariesRootDef: String? get() = librariesRoot.ifEmpty { root?.parent?.path?.let { FileUtil.toSystemDependentName(it) } } val library = ArendRawLibrary(this) private fun updateDependencies(newDependencies: List<LibraryDependency>, reload: Boolean, callback: () -> Unit) { val oldDependencies = dependencies dependencies = ArrayList(newDependencies) synchronized = false if (!reload) { return } var reloadLib = false for (dependency in oldDependencies) { if (!newDependencies.contains(dependency) && libraryManager.getRegisteredLibrary(dependency.name) != null) { reloadLib = true break } } if (reloadLib) { refreshLibrariesDirectory(project.service<ArendProjectSettings>().librariesRoot) project.service<TypeCheckingService>().reload(true) callback() } else ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Loading Arend libraries", false) { override fun run(indicator: ProgressIndicator) { refreshLibrariesDirectory(project.service<ArendProjectSettings>().librariesRoot) runReadAction { val typechecking = ArendTypechecking.create(project) for (dependency in newDependencies) { if (!oldDependencies.contains(dependency)) { var depLibrary = libraryManager.getRegisteredLibrary(dependency.name) if (depLibrary == null) { depLibrary = libraryManager.loadDependency(library, dependency.name, typechecking) } if (depLibrary != null) { libraryManager.registerDependency(library, depLibrary) } } } } callback() } }) } fun synchronizeDependencies(reload: Boolean) { synchronized = false ModuleSynchronizer.synchronizeModule(this, reload) } fun copyFromYAML(yaml: YAMLFile, update: Boolean) { val newDependencies = yaml.dependencies if (dependencies != newDependencies) { updateDependencies(newDependencies, update) { ModuleSynchronizer.synchronizeModule(this, false) } } modules = yaml.modules flaggedBinariesDir = yaml.binariesDir testsDir = yaml.testsDir val extDir = yaml.extensionsDir val extMain = yaml.extensionMainClass withExtensions = extDir != null && extMain != null if (extDir != null) { extensionsDirectory = extDir } if (extMain != null) { extensionMainClassData = extMain } sourcesDir = yaml.sourcesDir ?: "" versionString = yaml.version langVersionString = yaml.langVersion } fun copyFromYAML(update: Boolean) { copyFromYAML(yamlFile ?: return, update) } fun updateFromIDEA(config: ArendModuleConfiguration) { val newLibrariesRoot = config.librariesRoot val reload = librariesRoot != newLibrariesRoot var updateYAML = false val newDependencies = config.dependencies if (dependencies != newDependencies) { updateDependencies(newDependencies, !reload) {} updateYAML = true } val newSourcesDir = config.sourcesDir if (sourcesDir != newSourcesDir) { sourcesDir = newSourcesDir updateYAML = true } val newBinariesDir = config.flaggedBinariesDir if (flaggedBinariesDir != newBinariesDir) { updateYAML = true } withBinaries = config.withBinaries binariesDirectory = config.binariesDirectory val newTestsDir = config.testsDir if (testsDir != newTestsDir) { testsDir = newTestsDir updateYAML = true } val newExtensionsDir = config.flaggedExtensionsDir if (flaggedExtensionsDir != newExtensionsDir) { updateYAML = true } val newExtensionMainClass = config.flaggedExtensionMainClass if (flaggedExtensionMainClass != newExtensionMainClass) { updateYAML = true } withExtensions = config.withExtensions extensionsDirectory = config.extensionsDirectory extensionMainClassData = config.extensionMainClassData val newVersion = config.versionString if (versionString != newVersion) { versionString = newVersion updateYAML = true } val newLangVersion = config.langVersionString if (langVersionString != newLangVersion) { langVersionString = newLangVersion updateYAML = true } if (updateYAML) yamlFile?.write { langVersion = newLangVersion version = newVersion sourcesDir = newSourcesDir binariesDir = newBinariesDir testsDir = newTestsDir extensionsDir = newExtensionsDir extensionMainClass = newExtensionMainClass dependencies = newDependencies } if (reload) { synchronized = false librariesRoot = newLibrariesRoot ModuleSynchronizer.synchronizeModule(this, true) } } fun updateSourceDirFromIDEA(newSourcesDir: String) { if (sourcesDir != newSourcesDir) { sourcesDir = newSourcesDir yamlFile?.write { sourcesDir = newSourcesDir } } } fun updateTestDirFromIDEA(newTestDir: String) { if (testsDir != newTestDir) { testsDir = newTestDir yamlFile?.write { testsDir = newTestDir } } } companion object { fun getInstance(module: Module?) = if (module != null && ArendModuleType.has(module)) ModuleServiceManager.getService(module, ArendModuleConfigService::class.java) else null } }
55
Kotlin
16
83
caa2c5f2eaeef44acf53cf962f363f90fedbbf17
9,184
intellij-arend
Apache License 2.0
app/src/main/java/com/crossbowffs/quotelock/data/api/OpenAIConfigs.kt
Yubyf
60,074,817
false
null
package com.crossbowffs.quotelock.data.api import com.crossbowffs.quotelock.app.configs.openai.OpenAIPrefKeys.PREF_OPENAI_LANGUAGE_DEFAULT import com.crossbowffs.quotelock.app.configs.openai.OpenAIPrefKeys.PREF_OPENAI_MODEL_DEFAULT import com.crossbowffs.quotelock.app.configs.openai.OpenAIPrefKeys.PREF_OPENAI_QUOTE_TYPE_DEFAULT data class OpenAIConfigs( val language: String = PREF_OPENAI_LANGUAGE_DEFAULT, val model: String = PREF_OPENAI_MODEL_DEFAULT, val quoteType: Int = PREF_OPENAI_QUOTE_TYPE_DEFAULT, val apiHost: String? = null, val apiKey: String? = null, )
2
Kotlin
3
53
7e82ba2c535ed6f68a81c762805038f2b8bf0e4f
589
QuoteLockX
MIT License
clientprotocol/src/commonMain/generated/org/inthewaves/kotlinsignald/clientprotocol/v0/structures/JsonGroupV2Info.kt
inthewaves
398,221,861
false
null
// File is generated by ./gradlew generateSignaldClasses --- do not edit unless reformatting package org.inthewaves.kotlinsignald.clientprotocol.v0.structures import kotlinx.serialization.Serializable @Serializable @Deprecated("Will be removed after Sat, 1 Jan 2022 09:01:01 GMT") public data class JsonGroupV2Info( /** * Example: "EdSqI90cS0UomDpgUXOlCoObWvQOXlH5G3Z2d3f4ayE=" */ public val id: String? = null, /** * Example: 5 */ public val revision: Int? = null, /** * Example: "Parkdale Run Club" */ public val title: String? = null, public val description: String? = null, /** * path to the group's avatar on local disk, if available * * Example: "/var/lib/signald/avatars/group-EdSqI90cS0UomDpgUXOlCoObWvQOXlH5G3Z2d3f4ayE=" */ public val avatar: String? = null, /** * Example: 604800 */ public val timer: Int? = null, public val members: List<JsonAddress> = emptyList(), public val pendingMembers: List<JsonAddress> = emptyList(), public val requestingMembers: List<JsonAddress> = emptyList(), /** * the signal.group link, if applicable */ public val inviteLink: String? = null, /** * current access control settings for this group */ public val accessControl: GroupAccessControl? = null, /** * detailed member list */ public val memberDetail: List<GroupMember> = emptyList(), /** * detailed pending member list */ public val pendingMemberDetail: List<GroupMember> = emptyList() )
11
Kotlin
1
2
6f48a612fc307c08e44af25f826bb627e3e4f499
1,577
kotlin-signald
MIT License
settings.gradle.kts
PlanX-Universe
639,462,414
false
null
rootProject.name = "managing-service"
0
Kotlin
0
0
a33bce4b999a01a186ebe75e04ec5216053a202d
38
managing-service
MIT License
src/test/kotlin/com/sqlsorcery/kotlin/ImplementationTest.kt
sqlsorcery
49,568,029
false
null
package com.sqlsorcery.kotlin import com.sqlsorcery.* import com.sqlsorcery.queries.query import com.sqlsorcery.types.INTEGER import com.sqlsorcery.types.STRING import org.junit.Assert import org.junit.Test import kotlin.collections.first import kotlin.collections.map class ImplementationTest { class User : Model() { companion object : ModelTable<User>(::User) { val id = Column(INTEGER()) val name = Column(STRING(length = 50)) init { meta.primaryKeys = arrayOf(id) } } var id by User.id var name by User.name } @Test fun test() { val db = SQLSorcery() db.transaction { session -> session.execute("create table user (id INT, name VARCHAR(50));") session.add(User().apply { id = 1; name = "john" }) session.add(User().apply { id = 2; name = "bill" }) session.commit() val users = session.query(User).all().map { it.component1() } Assert.assertEquals(1, users[0].id) Assert.assertEquals("john", users[0].name) Assert.assertEquals(2, users[1].id) Assert.assertEquals("bill", users[1].name) val (user) = session.query(User).filter(User.id eq 1).one() Assert.assertEquals(1, user.id) Assert.assertEquals("john", user.name) // check identity map Assert.assertEquals(users.first { it.id == user.id }, user) } } }
0
Kotlin
0
0
cc84bcff623307d814a48485068e822b54fb63e1
1,527
sqlsorcery
MIT License
sdk-mobile/src/test/kotlin/io/github/wulkanowy/sdk/mobile/repository/RoutingRulesRepositoryTest.kt
dominik-korsa
237,057,001
true
{"Kotlin": 509705, "HTML": 128700, "Shell": 505}
package io.github.wulkanowy.sdk.mobile.repository import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.exception.InvalidTokenException import io.reactivex.observers.TestObserver import org.junit.Assert.assertEquals import org.junit.Test import retrofit2.create class RoutingRulesRepositoryTest : BaseLocalTest() { @Test fun getRouteByToken() { server.enqueueAndStart("RoutingRules.txt") val repo = RoutingRulesRepository(getRetrofit().create()) val route = repo.getRouteByToken("<PASSWORD>").blockingGet() assertEquals("https://uonetplus-komunikacja-test.mcuw.katowice.eu", route) } @Test fun getRouteByToken_invalid() { server.enqueueAndStart("RoutingRules.txt") val repo = RoutingRulesRepository(getRetrofit().create()) val route = repo.getRouteByToken("ERR<PASSWORD>") val routeObserver = TestObserver<String>() route.subscribe(routeObserver) routeObserver.assertNotComplete() routeObserver.assertError(InvalidTokenException::class.java) } @Test fun getRouteByToken_tooShort() { server.enqueueAndStart("RoutingRules.txt") val repo = RoutingRulesRepository(getRetrofit().create()) val route = repo.getRouteByToken("ER") val routeObserver = TestObserver<String>() route.subscribe(routeObserver) routeObserver.assertNotComplete() routeObserver.assertError(InvalidTokenException::class.java) } }
0
Kotlin
0
0
2d2b5176e6b3d5e5eb6b812441c1af740f26eeb5
1,512
sdk
Apache License 2.0
app/src/main/java/com/github/julesssss/tubestop/viewmodel/ScanViewModel.kt
Julesssss
129,299,367
false
{"Java": 42308, "Kotlin": 9121}
package com.github.julesssss.tubestop.viewmodel import android.app.Application import android.net.wifi.ScanResult import com.github.julesssss.tubestop.wifiscanner.WifiScanReceiver class ScanViewModel( context: Application, callback: ((results: List<ScanResult>) -> Unit), private val wifiScanReceiver: WifiScanReceiver = WifiScanReceiver(context, callback) ) { fun getWifiScanResults() { wifiScanReceiver.startScan() } fun unRegisterReciever() { wifiScanReceiver.deregisterDevice() } }
0
Java
0
0
aa4f084bd678806c588e7efae44ce2a6be579a21
546
Tube-Stop
Apache License 2.0
src/main/kotlin/lib/yggdrasil/AuthenticationResponse.kt
mcz0ne
242,615,194
false
null
package lib.yggdrasil import kotlinx.serialization.Serializable @Serializable data class AuthenticationResponse( val accessToken: String, val clientToken: String, val selectedProfile: AuthenticationSelectedProfile?, val user: AuthenticationUser? = null )
0
Kotlin
0
2
e1c8d500711a347ebd527cb63eb81641ddabca8d
272
launcher
Apache License 2.0
src/main/kotlin/dk/cachet/carp/webservices/common/notification/service/impl/NotificationServiceImpl.kt
cph-cachet
674,650,033
false
{"Kotlin": 658732, "HTML": 11277, "Shell": 2895, "Dockerfile": 922}
package dk.cachet.carp.webservices.common.notification.service.impl import com.github.seratch.jslack.Slack import com.github.seratch.jslack.api.webhook.Payload import com.github.seratch.jslack.api.webhook.WebhookResponse import dk.cachet.carp.webservices.common.configuration.internationalisation.service.MessageBase import dk.cachet.carp.webservices.common.environment.EnvironmentProfile import dk.cachet.carp.webservices.common.environment.EnvironmentUtil import dk.cachet.carp.webservices.common.exception.advices.CarpErrorResponse import dk.cachet.carp.webservices.common.exception.responses.BadRequestException import dk.cachet.carp.webservices.common.notification.domain.SlackChannel import dk.cachet.carp.webservices.common.notification.service.INotificationService import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import java.io.IOException /** * The Class [NotificationServiceImpl]. * The [NotificationServiceImpl] enables exception notifications [CarpErrorResponse] in slack channel. */ @Service class NotificationServiceImpl ( private val environment: EnvironmentUtil, private val validationMessages: MessageBase, @Value("\${slack.channel.name}") private val slackChannel: String, @Value("\${slack.channel.server}") private val slackServerChannel: String, @Value("\${slack.channel.heartbeat}") private val slackHeartbeatChannel: String, @Value("\${slack.webhook}") private val slackWebHook: String ): INotificationService { companion object { private val LOGGER: Logger = LogManager.getLogger() private const val NEW_LINE = "\n" } /** * The [sendExceptionNotificationToSlack] function sends a notification message with the given message. * @param notification The [notification] containing the message to send. * @param channelToSendTo The value of the slack channel the message needs to be sent to. */ override fun sendRandomOrAlertNotificationToSlack(notification: String, channelToSendTo: SlackChannel) { val messageBuilder = StringBuilder() messageBuilder.append(notification) messageBuilder.append(NEW_LINE) messageBuilder.append(NEW_LINE) messageBuilder.append("Environment: ${environment.profile}") when (channelToSendTo) { SlackChannel.CLIENT_ERRORS -> processException(messageBuilder.toString(), slackChannel) SlackChannel.SERVER_ERRORS -> processException(messageBuilder.toString(), slackServerChannel) SlackChannel.HEARTBEAT -> processException(messageBuilder.toString(), slackHeartbeatChannel) } } /** * The [sendExceptionNotificationToSlack] function sends a notification message with the given message. * @param errorResponse The errorResponse includes the error code, error message, and the error response. */ override fun sendExceptionNotificationToSlack(errorResponse: CarpErrorResponse) { if(environment.profile == EnvironmentProfile.PRODUCTION) { val messageBuilder = StringBuilder() messageBuilder.append("Exception Code: ${errorResponse.statusCode}") messageBuilder.append(NEW_LINE) messageBuilder.append("Exception: ${errorResponse.exception}") messageBuilder.append(NEW_LINE) messageBuilder.append("Message: ${errorResponse.message}") messageBuilder.append(NEW_LINE) messageBuilder.append("Path: ${errorResponse.path}") messageBuilder.append(NEW_LINE) messageBuilder.append("Environment: ${environment.profile}") messageBuilder.append(NEW_LINE) if (errorResponse.statusCode in 400..499) { processException(messageBuilder.toString(), slackChannel) } else if (errorResponse.statusCode in 500..599) { processException(messageBuilder.toString(), slackServerChannel) } } } /** * The [processException] function processes the exception and sends the message to the slack channel. * @param message The message to send on slack channel. * @throws IOException when the webhook cannot be reached. */ private fun processException(message: String, slackChannelToSend: String?) { val payload: Payload = Payload.builder() .channel(slackChannelToSend) .username("CARP-Webservices") .iconEmoji(":rocket:") .text(message) .build() try { val webhookResponse: WebhookResponse = Slack.getInstance().send(slackWebHook, payload) LOGGER.info("Slack response code -> {}, body -> {}", webhookResponse.code, "body -> " + webhookResponse.body) } catch (ex: IOException) { LOGGER.error("Unexpected Error! WebHook: $ex") throw BadRequestException(validationMessages.get("notification.slack.exception", ex.message.toString())) } } }
6
Kotlin
1
3
c1c9bcee88a4ef8bcdb7319d4352a7403ebeed26
5,181
carp-webservices-spring
MIT License
app/src/main/java/com/m3o/mobile/api/Networking.kt
m3o
463,779,432
false
{"Kotlin": 118347, "Java": 14412, "HTML": 10938, "C++": 10531, "CMake": 765}
package com.m3o.mobile.api import android.content.Context import com.cyb3rko.m3okotlin.CustomError import com.m3o.mobile.utils.logE import com.m3o.mobile.utils.showErrorDialog import io.ktor.client.* import io.ktor.client.features.* import io.ktor.client.features.json.* import io.ktor.client.features.json.serializer.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.coroutines.isActive import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json object Networking { private const val BASE_URL = "https://api.m3o.com/" private lateinit var authorization: Pair<String, String> internal lateinit var ktorHttpClient: HttpClient internal lateinit var ktorHttpAuthClient: HttpClient internal fun initialize(context: Context) { ktorHttpClient = HttpClient { install(JsonFeature) { serializer = KotlinxSerializer(kotlinx.serialization.json.Json { prettyPrint = true ignoreUnknownKeys = true }) } install(DefaultRequest) { header(HttpHeaders.ContentType, ContentType.Application.Json) } installResponseValidator(context) } } internal fun initializeAuth(context: Context, accessToken: String) { authorization = "Authorization" to "Bearer $accessToken" ktorHttpAuthClient = HttpClient { install(JsonFeature) { serializer = KotlinxSerializer(kotlinx.serialization.json.Json { prettyPrint = true ignoreUnknownKeys = true }) } install(DefaultRequest) { header(HttpHeaders.ContentType, ContentType.Application.Json) header(HttpHeaders.Authorization, authorization.second) } installResponseValidator(context) } } private fun HttpClientConfig<*>.installResponseValidator(context: Context) { HttpResponseValidator { handleResponseException { it.printStackTrace() val clientException = it as? ClientRequestException val serverException: ServerResponseException? val response: String if (clientException != null) { response = clientException.response.readText() } else { serverException = it as? ServerResponseException response = serverException?.response?.readText() ?: "No error information" } logE("Ktor/Serialization error - $response") try { val errorInformation = Json.decodeFromString<CustomError>(response) val title = errorInformation.status val message = when (errorInformation.code) { HttpStatusCode.Unauthorized.value -> "Your API Key may be invalid" else -> errorInformation.detail } context.showErrorDialog(title, message) } catch (_: Exception) { context.showErrorDialog(message = response) } } } } fun isInitialized(): Boolean { return if (::ktorHttpClient.isInitialized) { ktorHttpClient.engine.isActive } else false } fun isAuthInitialized(): Boolean { return if (::ktorHttpAuthClient.isInitialized) { ktorHttpAuthClient.engine.isActive } else false } fun getUrl(tail: String) = "$BASE_URL$tail" }
14
Kotlin
1
4
ae65eba4e523a4f5667b77ddc87aba3361617b4d
3,704
m3o-android
Apache License 2.0
strings/src/main/java/com/revenuecat/purchases/strings/AttributionStrings.kt
mt-mitchell
446,501,600
true
{"Kotlin": 1004355, "Java": 17062, "Ruby": 6167}
package com.revenuecat.purchases.strings object AttributionStrings { const val ATTRIBUTES_SYNC_ERROR = "Error when syncing subscriber attributes. App User ID: %s, Error: %s" const val ATTRIBUTES_SYNC_SUCCESS = "Subscriber attributes synced successfully for App User ID: %s" const val DELETING_ATTRIBUTES = "Deleting subscriber attributes for %s from cache" const val DELETING_ATTRIBUTES_OTHER_USERS = "Deleting old synced subscriber attributes that don't belong to %s" const val GOOGLE_PLAY_SERVICES_NOT_INSTALLED_FETCHING_ADVERTISING_IDENTIFIER = "GooglePlayServices is not " + "installed. Couldn't get advertising identifier. Message: %s" const val GOOGLE_PLAY_SERVICES_REPAIRABLE_EXCEPTION_WHEN_FETCHING_ADVERTISING_IDENTIFIER = "GooglePlayServicesRepairableException when getting advertising identifier. Message: %s" const val IO_EXCEPTION_WHEN_FETCHING_ADVERTISING_IDENTIFIER = "IOException when getting advertising " + "identifier. Message: %s" const val MARKING_ATTRIBUTES_SYNCED = "Marking the following attributes as synced for App User ID: %s" const val METHOD_CALLED = "%s called" const val NO_SUBSCRIBER_ATTRIBUTES_TO_SYNCHRONIZE = "No subscriber attributes to synchronize." const val SKIP_SAME_ATTRIBUTES = "Attribution data is the same as latest. Skipping." const val SUBSCRIBER_ATTRIBUTES_ERROR = "There were some subscriber attributes errors: %s" const val TIMEOUT_EXCEPTION_WHEN_FETCHING_ADVERTISING_IDENTIFIER = "TimeoutException when getting advertising " + "identifier. Message: %s" const val UNSYNCED_ATTRIBUTES_COUNT = "Found %d unsynced attributes for App User ID: %s" const val AMAZON_COULD_NOT_GET_ADID = "Couldn't get Amazon advertising identifier. Message: %s" }
0
Kotlin
0
0
de3566102841b06a3a592a8162f4967a636c4be0
1,799
purchases-android
MIT License
api/src/main/java/com/pitaya/mobile/uinspector/util/ToString.kt
YvesCheung
325,005,910
false
null
package com.pitaya.mobile.uinspector.util import android.content.Context import android.content.res.ColorStateList import android.content.res.Resources import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.BackgroundColorSpan import android.view.Gravity import android.view.View import androidx.annotation.AnyRes import androidx.annotation.ColorInt import androidx.annotation.IdRes import com.github.yvescheung.whisper.IntDef import com.pitaya.mobile.uinspector.R import com.pitaya.mobile.uinspector.UInspector import kotlin.math.roundToInt /** * @author YvesCheung * 2021/1/11 */ val Int.dpToPx: Int get() = (this.toFloat() * Resources.getSystem().displayMetrics.density).toInt() val Number.dpToPx: Float get() = this.toFloat() * Resources.getSystem().displayMetrics.density val Int.pxToDp: Int get() = (this.toFloat() / Resources.getSystem().displayMetrics.density).toInt() val Number.pxToDp: Float get() = this.toFloat() / Resources.getSystem().displayMetrics.density val Int.dpStr: String get() = if (UInspector.application.resources.getBoolean(R.bool.uinspector_dimension_dp)) "${pxToDp}dp" else "${this}px" val Number.dpStr: String get() = if (UInspector.application.resources.getBoolean(R.bool.uinspector_dimension_dp)) "${pxToDp.roundToInt()}dp" else "${this.toInt()}px" val Int.pxToSp: Int get() = (this.toFloat() / Resources.getSystem().displayMetrics.scaledDensity).toInt() val Number.pxToSp: Float get() = this.toFloat() / Resources.getSystem().displayMetrics.scaledDensity val Int.spStr: String get() = if (UInspector.application.resources.getBoolean(R.bool.uinspector_dimension_sp)) "${pxToSp}sp" else "${this}px" val Number.spStr: String get() = if (UInspector.application.resources.getBoolean(R.bool.uinspector_dimension_sp)) "${pxToSp.roundToInt()}sp" else "${this.toInt()}px" /** * todo: parse the state */ fun colorToString(color: ColorStateList): CharSequence { return colorToString(color.defaultColor) } fun colorToString(@ColorInt color: Int): CharSequence { val str = SpannableStringBuilder(hexToString(color)).append(" ") val start = str.length str.append(" ") val end = str.length str.setSpan(BackgroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return str } fun hexToString(hex: Int): String { return "0x${Integer.toHexString(hex).toUpperCase()}" } fun drawableToString(drawable: Drawable): CharSequence { return when (drawable) { is ColorDrawable -> colorToString(drawable.color) else -> drawable::class.java.simpleName } } fun resToString(context: Context, @AnyRes id: Int): String { return try { "@${context.resources.getResourceTypeName(id)}/${context.resources.getResourceEntryName(id)}" } catch (e: Resources.NotFoundException) { hexToString(id) } } fun idToString(context: Context, @IdRes id: Int): String { return try { "@+id/${context.resources.getResourceEntryName(id)}" } catch (e: Resources.NotFoundException) { hexToString(id) } } fun visibilityToString(@IntDef(View.VISIBLE, View.INVISIBLE, View.GONE) visibility: Int): String { return when (visibility) { View.VISIBLE -> "VISIBLE" View.INVISIBLE -> "INVISIBLE" View.GONE -> "GONE" else -> throw IllegalArgumentException("What's $visibility?") } } fun gravityToString(gravity: Int): String { val result = StringBuilder() if (gravity and Gravity.FILL == Gravity.FILL) { result.append("FILL").append(' ') } else { if (gravity and Gravity.FILL_VERTICAL == Gravity.FILL_VERTICAL) { result.append("FILL_VERTICAL").append(' ') } else { if (gravity and Gravity.TOP == Gravity.TOP) { result.append("TOP").append(' ') } if (gravity and Gravity.BOTTOM == Gravity.BOTTOM) { result.append("BOTTOM").append(' ') } } if (gravity and Gravity.FILL_HORIZONTAL == Gravity.FILL_HORIZONTAL) { result.append("FILL_HORIZONTAL").append(' ') } else { if (gravity and Gravity.START == Gravity.START) { result.append("START").append(' ') } else if (gravity and Gravity.LEFT == Gravity.LEFT) { result.append("LEFT").append(' ') } if (gravity and Gravity.END == Gravity.END) { result.append("END").append(' ') } else if (gravity and Gravity.RIGHT == Gravity.RIGHT) { result.append("RIGHT").append(' ') } } } if (gravity and Gravity.CENTER == Gravity.CENTER) { result.append("CENTER").append(' ') } else { if (gravity and Gravity.CENTER_VERTICAL == Gravity.CENTER_VERTICAL) { result.append("CENTER_VERTICAL").append(' ') } if (gravity and Gravity.CENTER_HORIZONTAL == Gravity.CENTER_HORIZONTAL) { result.append("CENTER_HORIZONTAL").append(' ') } } if (result.isEmpty()) { result.append("NO GRAVITY").append(' ') } if (gravity and Gravity.DISPLAY_CLIP_VERTICAL == Gravity.DISPLAY_CLIP_VERTICAL) { result.append("DISPLAY_CLIP_VERTICAL").append(' ') } if (gravity and Gravity.DISPLAY_CLIP_HORIZONTAL == Gravity.DISPLAY_CLIP_HORIZONTAL) { result.append("DISPLAY_CLIP_HORIZONTAL").append(' ') } result.deleteCharAt(result.length - 1) return result.toString() } fun CharSequence?.quote(): CharSequence? { return if (this != null) "\"$this\"" else this } val Any?.canonicalName: String get() = if (this == null) "null" else { val cn = this::class.java.canonicalName if (cn.isNullOrBlank()) { this::class.java.name } else { cn } } val Any?.simpleName: String get() = if (this == null) "null" else { val cn = this::class.java.simpleName if (cn.isNullOrBlank()) { this::class.java.name } else { cn } }
1
Kotlin
24
201
b404894d395d19d62473dba1cbfd19636664d5a7
6,307
UInspector
Apache License 2.0
codebase/android/core/designsystem/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/designsystem/component/MyScaffoldContentWrapper.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1369345, "Dart": 102426}
package com.makeappssimple.abhimanyu.financemanager.android.core.designsystem.component import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import com.makeappssimple.abhimanyu.financemanager.android.core.designsystem.extensions.conditionalClickable @Composable fun MyScaffoldContentWrapper( modifier: Modifier = Modifier, innerPadding: PaddingValues, onClick: () -> Unit, content: @Composable () -> Unit, ) { Box( modifier = modifier .background( color = MaterialTheme.colorScheme.background, ) .fillMaxSize() .conditionalClickable( indication = null, interactionSource = remember { MutableInteractionSource() }, ) { onClick() } .padding( paddingValues = innerPadding, ), ) { content() } }
0
Kotlin
0
0
376e832fb334545227d476171adfb877cfc9fc0b
1,388
finance-manager
Apache License 2.0
fns-hl7-pipeline/fn-redactor/src/test/kotlin/FunctionTest.kt
CDCgov
510,836,864
false
{"Kotlin": 746627, "Scala": 208820, "Python": 44391, "Java": 18075, "Batchfile": 11894, "Go": 8661, "JavaScript": 7609, "Groovy": 4230, "HTML": 2177, "Shell": 1362, "CSS": 979}
import com.google.gson.GsonBuilder import com.google.gson.JsonObject import com.google.gson.JsonParser import gov.cdc.dex.azure.EventHubMetadata import gov.cdc.dex.hl7.Helper import gov.cdc.dex.hl7.model.RedactorProcessMetadata import gov.cdc.dex.hl7.model.RedactorReport import gov.cdc.dex.metadata.DexMetadata import gov.cdc.dex.metadata.Provenance import gov.cdc.dex.util.JsonHelper.addArrayElement import org.junit.jupiter.api.Test class FunctionTest { @Test fun testRedactor(){ val msg = this::class.java.getResource("/BDB_LAB_02_redact.txt")?.readText() val helper = Helper() val report = msg?.let { helper.getRedactedReport(it,"CASE") } if (report != null) { println("report msg :${report._1}") println("report List: ${report._2()?.toList()}") } } @Test fun testRedactorELR(){ val msg = this::class.java.getResource("/HL7_2.5_New HHS Fields1.txt")?.readText() val helper = Helper() val report = msg?.let { helper.getRedactedReport(it,"ELR") } if (report != null) { println("report msg :${report._1}") println("report List: ${report._2()?.toList()}") } } @Test fun testRedactorPHLIPVPD(){ val msg = this::class.java.getResource("/Mumps-VPD.txt")?.readText() val helper = Helper() val report = msg?.let { helper.getRedactedReport(it,"ELR", "phlip_vpd") } if (report != null) { println("report msg :${report._1}") println("report List: ${report._2()?.toList()}") } } @Test fun testRedactorCOVID19(){ val msg = this::class.java.getResource("/covid25.txt")?.readText() val helper = Helper() val report = msg?.let { helper.getRedactedReport(it,"ELR", "covid19_elr") } if (report != null) { println("report msg :${report._1}") println("report List: ${report._2()?.toList()}") } } @Test fun extractValue(){ val helper = Helper() val msg = this::class.java.getResource("/BDB_LAB_02_redact.txt").readText() val pidVal = helper.extractValue(msg,"PID-5[2]") println("pidVal: $pidVal") } @Test fun testMetaData(){ val gson = GsonBuilder().serializeNulls().create() val msg = this::class.java.getResource("/BDB_LAB_02_redact.txt").readText() val helper = Helper() val report = helper.getRedactedReport(msg, "CASE") val w = report?._2()?.toList() println("w: ${w}") if(w != null) { val rw = RedactorReport(w) // gson.toJson(w) // val redactJson = w?.toJsonElement() // // println("redactJson: $redactJson") val config = listOf(helper.getConfigFileName("CASE")) val processMD = RedactorProcessMetadata("OK", rw, EventHubMetadata(1, 1, null, "20230101"), config) println(processMD) val prov = Provenance("event1", "123", "123", "test", "123", 123, "single", "a", "b", "c', 1", 1, "123") val md = DexMetadata(prov, listOf()) val mdJsonStr = gson.toJson(md) val mdJson = JsonParser.parseString(mdJsonStr) as JsonObject mdJson.addArrayElement("processes", processMD) mdJson.addProperty("test", "test") println("MD: $mdJson") } } }
118
Kotlin
14
9
e859ed7c4d5feb3a97acd6e3faef1382487a689f
3,404
data-exchange-hl7
Apache License 2.0
combusis/src/main/java/cn/rong/combusis/common/ui/widget/ActionSnackBar.kt
rongcloud
379,792,178
false
null
/* * Copyright © 2021 RongCloud. All rights reserved. */ package com.rongcloud.common.ui.widget import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.core.view.ViewCompat import androidx.core.view.setPadding import com.google.android.material.snackbar.BaseTransientBottomBar /** * @author gusd * @Date 2021/07/05 */ class ActionSnackBar private constructor( parentViewGroup: ViewGroup, content: View, contentViewCallback: com.google.android.material.snackbar.ContentViewCallback ) : BaseTransientBottomBar<ActionSnackBar>(parentViewGroup, content, contentViewCallback) { companion object { @SuppressLint("ResourceAsColor") fun make(parentViewGroup: ViewGroup, view: View): ActionSnackBar { val actionSnackBar = ActionSnackBar(parentViewGroup, view, CallbackImpl(view)) with(view) { actionSnackBar.getView().setPadding(0) actionSnackBar.duration = LENGTH_INDEFINITE } return actionSnackBar } fun make(parentViewGroup: ViewGroup, @LayoutRes layoutId: Int): ActionSnackBar { return make( parentViewGroup, LayoutInflater.from(parentViewGroup.context) .inflate(layoutId, parentViewGroup, false) ) } } class CallbackImpl(val content: View) : com.google.android.material.snackbar.ContentViewCallback { override fun animateContentOut(delay: Int, duration: Int) { content.scaleY = 1f ViewCompat.animate(content) .scaleY(0f) .setDuration(duration.toLong()) .startDelay = delay.toLong() } override fun animateContentIn(delay: Int, duration: Int) { content.scaleY = 0f ViewCompat.animate(content) .scaleY(1f) .setDuration(duration.toLong()) .startDelay = delay.toLong() } } }
0
Java
6
6
46ba4e512f2a5b24c9000a6b37ccc12a52857468
2,112
rongcloud-scene-android-demo
Apache License 2.0
app/src/test/java/com/yoelglus/notes/domain/UpdateNoteTest.kt
yoelglus
100,812,739
false
null
package com.yoelglus.notes.domain import com.yoelglus.notes.domain.gateways.NotesRepository import org.junit.Test import org.mockito.Mockito class UpdateNoteTest { @Test fun callsRepository() { val notesRepository = Mockito.mock(NotesRepository::class.java) val updateNote = UpdateNote(notesRepository) val note = Note(1, "title", "text") updateNote.execute(note) Mockito.verify(notesRepository).updateNote(note) } }
0
Kotlin
1
6
be02d69f18ccae0db6e9fe646876608766c8c500
472
notes
Apache License 2.0
plugins/space/src/main/kotlin/com/intellij/space/vcs/review/details/SpaceReviewDetails.kt
code-general
320,182,339
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.space.vcs.review.details import circlet.code.api.CodeReviewListItem import circlet.workspaces.Workspace import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.space.messages.SpaceBundle import com.intellij.space.vcs.SpaceProjectInfo import com.intellij.space.vcs.SpaceRepoInfo import com.intellij.space.vcs.review.SpaceReviewDataKeys import com.intellij.ui.tabs.TabInfo import com.intellij.ui.tabs.impl.SingleHeightTabs import com.intellij.util.ui.UIUtil import com.intellij.util.ui.codereview.ReturnToListComponent import com.intellij.util.ui.components.BorderLayoutPanel import libraries.coroutines.extra.Lifetime import runtime.reactive.MutableProperty import runtime.reactive.SequentialLifetimes internal class SpaceReviewDetails(parentDisposable: Disposable, project: Project, lifetime: Lifetime, private val workspace: Workspace, private val spaceProjectInfo: SpaceProjectInfo, private val repoInfo: Set<SpaceRepoInfo>, private val currentReview: MutableProperty<CodeReviewListItem?>) { private val sequentialLifetimes: SequentialLifetimes = SequentialLifetimes(lifetime) val view: BorderLayoutPanel = BorderLayoutPanel().apply { background = UIUtil.getListBackground() } init { var uiDisposable: Disposable? = null currentReview.forEach(lifetime) { reviewListItem: CodeReviewListItem? -> view.removeAll() uiDisposable?.let { Disposer.dispose(it) } if (reviewListItem == null) return@forEach val detailsLifetime = sequentialLifetimes.next() val detailsVm = createReviewDetailsVm(detailsLifetime, project, workspace, spaceProjectInfo, repoInfo, reviewListItem) uiDisposable = Disposer.newDisposable() Disposer.register(parentDisposable, uiDisposable as Disposable) val detailsTabInfo = TabInfo(SpaceReviewInfoTabPanel(detailsVm)).apply { text = SpaceBundle.message("review.tab.name.details") sideComponent = ReturnToListComponent.createReturnToListSideComponent(SpaceBundle.message("action.reviews.back.to.list")) { currentReview.value = null } } val commitsTabInfo = TabInfo(SpaceReviewCommitListPanel(parentDisposable,detailsVm)).apply { text = SpaceBundle.message("review.tab.name.commits") sideComponent = ReturnToListComponent.createReturnToListSideComponent(SpaceBundle.message("action.reviews.back.to.list")) { currentReview.value = null } } detailsVm.commits.forEach(lifetime) { commitsTabInfo.text = if (it == null) SpaceBundle.message("review.tab.name.commits") else SpaceBundle.message("review.tab.name.commits.count", it.size) } val tabs = object : SingleHeightTabs(project, uiDisposable as Disposable) { override fun adjust(each: TabInfo?) {} }.apply { setDataProvider { dataId -> when { SpaceReviewDataKeys.REVIEW_DETAILS_VM.`is`(dataId) -> detailsVm else -> null } } addTab(detailsTabInfo) addTab(commitsTabInfo) } view.addToCenter(tabs) view.validate() view.repaint() } } }
0
null
0
1
a00c61d009b376bdf62a2859dd757c0766894a28
3,585
intellij-community
Apache License 2.0
common/src/jvmMain/kotlin/com/github/mustafaozhan/ccc/common/Actual.kt
isabella232
352,967,844
true
{"Kotlin": 252275, "Swift": 45819, "HTML": 797}
/* * Copyright (c) 2021 <NAME>. All rights reserved. */ package com.github.mustafaozhan.ccc.common import com.github.mustafaozhan.ccc.common.model.PlatformType import com.github.mustafaozhan.ccc.common.sql.CurrencyConverterCalculatorDatabase import com.russhwolf.settings.ExperimentalSettingsImplementation import com.russhwolf.settings.JvmPreferencesSettings import com.russhwolf.settings.Settings import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.koin.core.module.Module import kotlin.coroutines.CoroutineContext actual val platform = PlatformType.JVM actual val platformCoroutineContext: CoroutineContext = Dispatchers.IO @ExperimentalSettingsImplementation actual fun Module.getSettingsDefinition() = single<Settings> { JvmPreferencesSettings(get()) } actual fun Module.getDatabaseDefinition() = single { CurrencyConverterCalculatorDatabase( JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) .also { CurrencyConverterCalculatorDatabase.Schema.create(it) } ) } actual fun runTest(block: suspend () -> Unit) = runBlocking { block() } // todo need to find correct implementation for JS @Suppress("FunctionOnlyReturningConstant") actual fun isDebug() = false
0
null
0
0
4a13bfd2b91d7707e7ec85ae52479a55b83c71b7
1,298
CCC
Apache License 2.0
app/src/main/java/com/jobs/assignment/presentation/ui/item/ItemViewModel.kt
SanushRadalage
342,923,629
false
null
package com.jobs.assignment.presentation.ui.item import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.ViewModel import com.jobs.assignment.presentation.ui.list.StateHandler import com.jobs.assignment.repository.JobRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch class ItemViewModel @ViewModelInject constructor( private val jobRepository: JobRepository, ) : ViewModel() { var id: String? = null var stateHandler: StateHandler? = null fun getItem() { CoroutineScope(IO).launch { try { val result = jobRepository.getItem(id!!) stateHandler!!.onSuccess(result) } catch (e: Exception) { stateHandler!!.onFailure() } } } }
0
Kotlin
0
0
46a48e46b5c1dd96477319639db9d13a9275524a
840
ComposeSamples
MIT License
libnavui-dropin/src/test/java/com/mapbox/navigation/dropin/LeftFrameCoordinatorTest.kt
mapbox
87,455,763
false
{"Kotlin": 9663566, "Python": 65081, "Java": 36671, "HTML": 17811, "Makefile": 9545, "Shell": 7129}
package com.mapbox.navigation.dropin import android.view.ViewGroup import com.mapbox.navigation.core.MapboxNavigation import com.mapbox.navigation.dropin.navigationview.NavigationViewContext import com.mapbox.navigation.ui.base.lifecycle.Binder import com.mapbox.navigation.ui.base.lifecycle.UIBinder import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import kotlinx.coroutines.test.runBlockingTest import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class LeftFrameCoordinatorTest { private val mapboxNavigation = mockk<MapboxNavigation>() private val leftFrameContentBinderFlow = MutableStateFlow<UIBinder?>(null) private val context = mockk<NavigationViewContext> { every { uiBinders } returns mockk { every { leftFrameContentBinder } returns leftFrameContentBinderFlow } } private val coordinator = LeftFrameCoordinator(context, mockk()) @Test fun `should return empty binder`() = runBlockingTest { coordinator.apply { val binders = mapboxNavigation.flowViewBinders().take(1).toList() assertTrue(binders.first() is EmptyBinder) } } @Test fun `should return custom binder`() = runBlockingTest { val customBinder = mockk<UIBinder>() coordinator.apply { leftFrameContentBinderFlow.value = customBinder val binders = mapboxNavigation.flowViewBinders().take(1).toList() assertTrue(binders.first() === customBinder) } } @Test fun `should reload binder when leftFrameContentBinder changes`() = runBlockingTest { val customBinder1 = mockk<UIBinder>() val customBinder2 = mockk<UIBinder>() val collectedBinders = mutableListOf<Binder<ViewGroup>>() coordinator.apply { val job = launch { mapboxNavigation.flowViewBinders().take(4).toList(collectedBinders) } leftFrameContentBinderFlow.value = customBinder1 leftFrameContentBinderFlow.value = null leftFrameContentBinderFlow.value = customBinder2 job.join() assertEquals(4, collectedBinders.size) assertTrue(collectedBinders[0] is EmptyBinder) assertTrue(collectedBinders[1] === customBinder1) assertTrue(collectedBinders[2] is EmptyBinder) assertTrue(collectedBinders[3] === customBinder2) } } @Test fun `should use different EmptyBinder instances`() = runBlockingTest { val collectedBinders = mutableListOf<Binder<ViewGroup>>() coordinator.apply { val job = launch { mapboxNavigation.flowViewBinders().take(3).toList(collectedBinders) } leftFrameContentBinderFlow.value = mockk() leftFrameContentBinderFlow.value = null job.join() assertTrue(collectedBinders[0] is EmptyBinder) assertTrue(collectedBinders[2] is EmptyBinder) assertFalse(collectedBinders[0] === collectedBinders[2]) } } }
471
Kotlin
326
603
56332c60cc5c2b20d611068934e7fe86ea5e18fb
3,379
mapbox-navigation-android
Apache License 2.0
app/src/main/java/com/sergeyfitis/androidexperiments/raycasting/RaycastingDrawable.kt
desugar-64
219,619,754
false
{"Kotlin": 12564}
package com.sergeyfitis.androidexperiments.raycasting import android.graphics.* import android.graphics.drawable.Drawable import androidx.core.graphics.ColorUtils import com.sergeyfitis.androidexperiments.common.Float2 import com.sergeyfitis.androidexperiments.common.dp import com.sergeyfitis.androidexperiments.common.strokePaint import com.sergeyfitis.androidexperiments.raycasting.rays.Boundary import com.sergeyfitis.androidexperiments.raycasting.rays.Light import com.sergeyfitis.androidexperiments.raycasting.rays.Ray import kotlin.random.Random class RaycastingDrawable : Drawable() { private val rnd: Random get() = Random(System.nanoTime()) private var walls = listOf( Boundary( a = Float2( x = rnd.nextInt(360.dp.toInt()).toFloat(), y = rnd.nextInt(360.dp.toInt()).toFloat() ), b = Float2( x = rnd.nextInt(600.dp.toInt()).toFloat(), y = rnd.nextInt(600.dp.toInt()).toFloat() ) ), Boundary( a = Float2( x = rnd.nextInt(360.dp.toInt()).toFloat(), y = rnd.nextInt(360.dp.toInt()).toFloat() ), b = Float2( x = rnd.nextInt(600.dp.toInt()).toFloat(), y = rnd.nextInt(600.dp.toInt()).toFloat() ) ), Boundary( a = Float2( x = rnd.nextInt(360.dp.toInt()).toFloat(), y = rnd.nextInt(360.dp.toInt()).toFloat() ), b = Float2( x = rnd.nextInt(600.dp.toInt()).toFloat(), y = rnd.nextInt(600.dp.toInt()).toFloat() ) ), Boundary( a = Float2( x = rnd.nextInt(360.dp.toInt()).toFloat(), y = rnd.nextInt(360.dp.toInt()).toFloat() ), b = Float2( x = rnd.nextInt(600.dp.toInt()).toFloat(), y = rnd.nextInt(600.dp.toInt()).toFloat() ) ) ) private val wallPaint: Paint = strokePaint(color = Color.WHITE) private val rayPaint: Paint = strokePaint(color = ColorUtils.setAlphaComponent(Color.GREEN, 50), width = 3.dp) private val light = Light(position = Float2(100.dp, 100.dp)).apply { for (i in 0..360 step 1) { val rad: Double = Math.toRadians(i.toDouble()) rays.add( Ray(origin = position, direction = Float2.fromAngle(rad)) ) } } override fun setHotspot(x: Float, y: Float) { super.setHotspot(x, y) light.position.x = x light.position.y = y invalidateSelf() } override fun draw(canvas: Canvas) = with(canvas) { drawColor(Color.BLACK) walls.forEach { wall -> wall.draw(this, wallPaint) } light.look(walls, this, rayPaint) light.draw(this, rayPaint) Unit } override fun setAlpha(alpha: Int) { // TODO } override fun getOpacity() = PixelFormat.OPAQUE override fun setColorFilter(colorFilter: ColorFilter?) { // TODO } }
0
Kotlin
0
2
643598c3da399bdc6f1171a4285e321413faa072
3,160
Android-Experiments
Apache License 2.0
modules/kilua-bootstrap/src/commonTest/kotlin/dev/kilua/panel/AccordionSpec.kt
rjaros
706,876,956
false
{"Kotlin": 1970010, "CSS": 6186, "JavaScript": 4263}
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.kilua.panel import dev.kilua.compose.root import dev.kilua.html.p import dev.kilua.test.DomSpec import kotlinx.coroutines.delay import kotlin.test.Test class AccordionSpec : DomSpec { @Test fun render() = runWhenDomAvailableAsync { val root = root("test") { accordion(flush = true, openedIndex = 1) { item("Item 1") { p("First item") } item("Item 2") { p("Second item") } item("Item 3") { p("Third item") } } } delay(100) assertEqualsHtml( """<div class="accordion accordion-flush" id="kilua_accordion_0"> <!--sid=1--> <!--sid=2--> <!--sid=3--> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#kilua_accordion_0-item-0" aria-expanded="false" aria-controls="kilua_accordion_0-item-0"> Item 1 </button> </h2> <div class="accordion-collapse collapse" id="kilua_accordion_0-item-0" data-bs-parent="#kilua_accordion_0"> <div class="accordion-body"> <p class="First item"> </p> </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#kilua_accordion_0-item-1" aria-expanded="true" aria-controls="kilua_accordion_0-item-1"> Item 2 </button> </h2> <div class="accordion-collapse collapse show" id="kilua_accordion_0-item-1" data-bs-parent="#kilua_accordion_0"> <div class="accordion-body"> <p class="Second item"> </p> </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#kilua_accordion_0-item-2" aria-expanded="false" aria-controls="kilua_accordion_0-item-2"> Item 3 </button> </h2> <div class="accordion-collapse collapse" id="kilua_accordion_0-item-2" data-bs-parent="#kilua_accordion_0"> <div class="accordion-body"> <p class="Third item"> </p> </div> </div> </div> </div>""".replace(Regex("sid=\\d+"), "sid=0").replace(Regex("kilua_accordion_[0-9]*"), "kilua_accordion_0"), root.element.innerHTML.replace(Regex("sid=\\d+"), "sid=0") .replace(Regex("kilua_accordion_[0-9]*"), "kilua_accordion_0"), "Should render an Accordion component to DOM" ) } @Test fun renderToString() = runAsync { val root = root { accordion(flush = true, openedIndex = 1) { item("Item 1") { p("First item") } item("Item 2") { p("Second item") } item("Item 3") { p("Third item") } } } delay(100) assertEqualsHtml( """<div class="accordion accordion-flush" id="kilua_accordion_0"> <!--sid=1--> <!--sid=2--> <!--sid=3--> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#kilua_accordion_0-item-0" aria-expanded="false" aria-controls="kilua_accordion_0-item-0"> Item 1 </button> </h2> <div class="accordion-collapse collapse" id="kilua_accordion_0-item-0" data-bs-parent="#kilua_accordion_0"> <div class="accordion-body"> <p class="First item"> </p> </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#kilua_accordion_0-item-1" aria-expanded="true" aria-controls="kilua_accordion_0-item-1"> Item 2 </button> </h2> <div class="accordion-collapse collapse show" id="kilua_accordion_0-item-1" data-bs-parent="#kilua_accordion_0"> <div class="accordion-body"> <p class="Second item"> </p> </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#kilua_accordion_0-item-2" aria-expanded="false" aria-controls="kilua_accordion_0-item-2"> Item 3 </button> </h2> <div class="accordion-collapse collapse" id="kilua_accordion_0-item-2" data-bs-parent="#kilua_accordion_0"> <div class="accordion-body"> <p class="Third item"> </p> </div> </div> </div> </div>""".replace(Regex("sid=\\d+"), "sid=0").replace(Regex("kilua_accordion_[0-9]*"), "kilua_accordion_0"), root.innerHTML.replace(Regex("sid=\\d+"), "sid=0") .replace(Regex("kilua_accordion_[0-9]*"), "kilua_accordion_0"), "Should render an Accordion component to a String" ) } }
0
Kotlin
1
49
f3a72704cbfacc91b1100f8c54522ea9de992396
5,893
kilua
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/datazone/RedshiftServerlessStoragePropertyDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5004663}
package com.faendir.awscdkkt.generated.services.datazone import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.datazone.CfnDataSource @Generated public fun buildRedshiftServerlessStorageProperty(initializer: @AwsCdkDsl CfnDataSource.RedshiftServerlessStorageProperty.Builder.() -> Unit = {}): CfnDataSource.RedshiftServerlessStorageProperty = CfnDataSource.RedshiftServerlessStorageProperty.Builder().apply(initializer).build()
2
Kotlin
0
0
c750c5d976f0ed7eeecb9ec1416bf02c2d2ecfd0
520
aws-cdk-kt
Apache License 2.0
shapes/src/main/java/com/xavijimenezmulet/shapes/weather/TimeStarShape.kt
xavijimenezmulet
663,193,932
false
null
package com.xavijimenezmulet.shapes.weather import android.graphics.Matrix import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.asAndroidPath import androidx.compose.ui.graphics.asComposePath import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp /** * @author xavierjimenez * @since 12/8/23 * @email <EMAIL> */ val TimeStarShape: Shape = object: Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { val baseWidth = 394.7587f val baseHeight = 418.9137f val path = Path().apply { moveTo(340.1446f, 124.3916f) cubicTo(338.5156f, 118.4816f, 333.4396f, 114.1667f, 327.3446f, 113.5117f) lineTo(233.9046f, 99.2187f) cubicTo(230.7046f, 99.0737f, 227.8406f, 97.1916f, 226.4376f, 94.3116f) lineTo(183.7706f, 8.9786f) cubicTo(181.3596f, 3.2876f, 175.6506f, -0.2914f, 169.4776f, 0.0186f) cubicTo(163.5256f, -0.0904f, 158.0766f, 3.3466f, 155.6106f, 8.7656f) lineTo(112.9436f, 94.0986f) cubicTo(111.6156f, 96.8516f, 108.9466f, 98.7126f, 105.9036f, 99.0056f) lineTo(11.8236f, 113.2987f) cubicTo(6.3976f, 114.7277f, 2.1596f, 118.9656f, 0.7306f, 124.3916f) cubicTo(-1.0284f, 130.0926f, 0.4416f, 136.2986f, 4.5706f, 140.6046f) lineTo(72.6236f, 206.9516f) cubicTo(74.7346f, 209.2566f, 75.6776f, 212.3986f, 75.1836f, 215.4846f) lineTo(59.1836f, 308.7116f) cubicTo(58.0276f, 314.7426f, 60.3316f, 320.9136f, 65.1566f, 324.7116f) cubicTo(70.5086f, 327.4826f, 76.8716f, 327.4826f, 82.2236f, 324.7116f) lineTo(141.3166f, 295.0586f) cubicTo(144.3616f, 251.3686f, 168.0546f, 211.7486f, 205.1036f, 188.3916f) lineTo(207.0236f, 187.3246f) cubicTo(210.0106f, 186.0446f, 213.2106f, 184.1247f, 217.0506f, 182.2047f) lineTo(220.4636f, 180.2847f) cubicTo(223.1786f, 178.9527f, 226.0436f, 177.9507f, 228.9966f, 177.2977f) lineTo(234.3296f, 175.1646f) lineTo(241.5826f, 172.6046f) lineTo(248.1956f, 170.8976f) lineTo(255.0226f, 169.4046f) cubicTo(257.2946f, 169.2276f, 259.5776f, 169.2276f, 261.8496f, 169.4046f) lineTo(277.2096f, 169.4046f) cubicTo(286.8666f, 169.3966f, 296.5056f, 170.2526f, 306.0096f, 171.9646f) lineTo(336.3026f, 141.4576f) cubicTo(340.8566f, 137.0346f, 342.3626f, 130.3386f, 340.1446f, 124.3916f) close() moveTo(307.2906f, 189.2446f) lineTo(306.0106f, 190.5246f) cubicTo(301.5966f, 189.2536f, 297.1076f, 188.2556f, 292.5706f, 187.5376f) cubicTo(288.4496f, 187.3016f, 284.3186f, 187.3016f, 280.1976f, 187.5376f) lineTo(278.9176f, 187.5376f) cubicTo(275.0806f, 187.3186f, 271.2346f, 187.3186f, 267.3976f, 187.5376f) lineTo(260.7846f, 187.5376f) lineTo(253.7446f, 188.8176f) lineTo(247.3446f, 190.7377f) lineTo(242.0116f, 192.4447f) lineTo(235.8246f, 194.7917f) cubicTo(233.9366f, 194.9297f, 232.1086f, 195.5146f, 230.4916f, 196.4986f) lineTo(225.3716f, 199.2717f) lineTo(218.9716f, 203.1116f) cubicTo(217.6486f, 203.5796f, 216.3646f, 204.1496f, 215.1316f, 204.8186f) cubicTo(212.7846f, 206.5256f, 210.2246f, 208.4456f, 208.0916f, 210.3656f) lineTo(205.5316f, 212.2856f) cubicTo(185.3246f, 227.6286f, 170.7706f, 249.2336f, 164.1446f, 273.7256f) cubicTo(162.9716f, 277.9346f, 162.0456f, 282.2086f, 161.3716f, 286.5256f) cubicTo(161.3716f, 290.3656f, 161.3716f, 295.2726f, 161.3716f, 299.1126f) cubicTo(161.3716f, 299.1126f, 161.3716f, 301.2456f, 161.3716f, 302.3126f) cubicTo(161.4226f, 366.7606f, 213.7096f, 418.9646f, 278.1576f, 418.9136f) cubicTo(342.6056f, 418.8626f, 394.8096f, 366.5756f, 394.7586f, 302.1276f) cubicTo(394.7156f, 248.9696f, 358.7536f, 202.5586f, 307.2906f, 189.2446f) close() moveTo(277.4246f, 393.8316f) lineTo(276.9976f, 393.8316f) cubicTo(253.7836f, 393.8956f, 231.4516f, 384.9466f, 214.7046f, 368.8716f) lineTo(228.1446f, 354.5786f) cubicTo(241.1936f, 367.4796f, 258.8626f, 374.6246f, 277.2116f, 374.4186f) cubicTo(316.3276f, 374.4026f, 348.0246f, 342.6786f, 348.0086f, 303.5626f) cubicTo(347.9926f, 264.4696f, 316.3046f, 232.7817f, 277.2116f, 232.7657f) cubicTo(258.2796f, 232.6877f, 240.1486f, 240.4026f, 227.0786f, 254.0986f) cubicTo(218.1116f, 262.8216f, 211.8206f, 273.9236f, 208.9456f, 286.0986f) lineTo(218.3326f, 295.9116f) lineTo(187.1856f, 326.6316f) lineTo(187.1856f, 303.5916f) cubicTo(187.3036f, 253.8716f, 227.7056f, 213.6607f, 277.4256f, 213.7787f) cubicTo(327.1456f, 213.8967f, 367.3566f, 254.2986f, 367.2386f, 304.0186f) cubicTo(367.1196f, 353.5726f, 326.9776f, 393.7146f, 277.4246f, 393.8316f) close() moveTo(290.4376f, 303.5916f) lineTo(290.2246f, 303.5916f) cubicTo(290.1146f, 310.8856f, 284.2896f, 316.8046f, 276.9976f, 317.0316f) cubicTo(271.4616f, 317.1076f, 266.5266f, 313.5576f, 264.8376f, 308.2846f) cubicTo(263.2046f, 311.3806f, 260.0166f, 313.3416f, 256.5176f, 313.4046f) lineTo(240.3046f, 313.4046f) cubicTo(234.9436f, 314.2016f, 229.9516f, 310.5016f, 229.1546f, 305.1406f) cubicTo(228.3576f, 299.7796f, 232.0576f, 294.7876f, 237.4186f, 293.9906f) cubicTo(238.3756f, 293.8486f, 239.3476f, 293.8486f, 240.3046f, 293.9906f) lineTo(256.5176f, 293.9906f) cubicTo(260.0166f, 294.0536f, 263.2046f, 296.0146f, 264.8376f, 299.1106f) cubicTo(265.1636f, 297.6316f, 265.8196f, 296.2456f, 266.7576f, 295.0576f) lineTo(266.7576f, 250.2576f) cubicTo(267.5546f, 244.8966f, 272.5466f, 241.1967f, 277.9076f, 241.9937f) cubicTo(282.1806f, 242.6287f, 285.5356f, 245.9836f, 286.1716f, 250.2576f) lineTo(286.1716f, 295.0576f) cubicTo(288.5576f, 297.3086f, 290.0696f, 300.3316f, 290.4376f, 303.5916f) close() } return Outline.Generic( path .asAndroidPath() .apply { transform(Matrix().apply { setScale(size.width / baseWidth, size.height / baseHeight) }) } .asComposePath() ) } } @Preview @Composable fun TimeStarShapePreview() { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = Modifier .size(200.dp) .clip(TimeStarShape) .background(Color.Yellow) ) } }
0
Kotlin
5
16
5ae3fded6755c9915370c82bba30f07e327a57e9
7,986
shapes-for-jetpackcompose
Apache License 2.0
app/src/main/java/com/kai/base/widget/load/RefreshDataListener.kt
pressureKai
326,004,502
false
null
package com.kai.base.widget.load /** * * @ProjectName: app-bookpage * @Description: 向外传递数据刷新操作 * @Author: pressureKai * @UpdateDate: 2021/4/1 9:15 */ interface RefreshDataListener { /** * @des pageLoader向外传递加载更多事件 * @param pageIndex 页码 * @param pageSize 总页数 */ fun onLoadMore(pageIndex: Int,pageSize: Int) /** * @des pageLoader向外传递刷新第一页数据事件 */ fun onRefresh() }
0
Kotlin
2
1
73edc5e8b838f9ba89e5ac717051c15871120673
509
FreeRead
Apache License 2.0
karibu-dsl-v8/src/main/kotlin/com/github/mvysny/karibudsl/v8/Accordion.kt
vlipovetskii
346,130,757
true
{"Kotlin": 591255, "CSS": 7440, "SCSS": 3191, "JavaScript": 2748}
package com.github.mvysny.karibudsl.v8 import com.vaadin.ui.Accordion import com.vaadin.ui.Component import com.vaadin.ui.HasComponents public open class _Accordion : Accordion() { /** * Allows you to access the current tab from the DSL: * ```kotlin * accordion { * // adding a component to tabsheet will create a tab for the component as well. * label("Foo bar baz blah blah blah") { * tab.caption = "Tab 1" * tab.icon = VaadinIcons.TAB * } * } * ``` */ @get:JvmName("getTab2") public val (@VaadinDsl Component).tab: Tab get() = this@_Accordion.getTab(this) ?: throw IllegalStateException("$this is not child of ${this@_Accordion}") } @VaadinDsl public fun (@VaadinDsl HasComponents).accordion(block: _Accordion.()->Unit = {}): _Accordion = init(_Accordion(), block)
0
Kotlin
0
0
6cd570657b0f7a54a508003a6652500c732d25eb
873
karibu-dsl
MIT License
src/main/java/com/nativedevps/model/SheetModel.kt
merlinJeyakumar
660,900,490
false
null
package com.nativedevps.model class SheetModel constructor( var sheetId: String = "", var sheetName: String = "", )
0
Kotlin
0
0
44f0d53f5f8e5e38e85dad80f5351dbc6f72b132
124
JGoogleAuth
MIT License
app/src/main/java/com/a/vocabulary15/presentation/test/composables/TestScoreCard.kt
thedeveloperworldisyours
405,696,476
false
{"Kotlin": 188765}
package com.a.vocabulary15.presentation.test.composables import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Card import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.ConstraintLayout import coil.compose.rememberImagePainter import com.a.vocabulary15.R import com.a.vocabulary15.util.TestTags @Composable fun TestScoreCard( newImage: String, right: Int, wrong: Int ) { Card( backgroundColor = Color.Blue, elevation = 5.dp, modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp, vertical = 8.dp) .testTag(TestTags.SCORE) ) { ConstraintLayout( modifier = Modifier .height(50.dp) .fillMaxWidth() .background(Color.Blue) ) { val (imageTest, imageStart, imageEnd, iconRight, iconLeft, textRight, textWrong) = createRefs() Text( modifier = Modifier .background(Color.Blue) .fillMaxHeight() .constrainAs(textRight) { end.linkTo(iconRight.start) }, text = right.toString(), fontSize = 35.sp, color = Color.White ) Image( modifier = Modifier .fillMaxHeight() .background(Color.Blue) .constrainAs(iconRight) { end.linkTo(imageStart.start) }, painter = painterResource(id = R.drawable.ic_green_24), contentDescription = null ) Image( modifier = Modifier .size(50.dp) .background(Color.White) .constrainAs(imageStart) { end.linkTo(imageTest.start) }, painter = painterResource(id = R.drawable.ic_arrow), contentDescription = null ) Image( modifier = Modifier .size(50.dp) .background(Color.White) .constrainAs(imageTest) { top.linkTo(parent.top) bottom.linkTo(parent.bottom) start.linkTo(parent.start) end.linkTo(parent.end) }, painter = rememberImagePainter(newImage), contentDescription = null ) Image( modifier = Modifier .size(50.dp) .background(Color.White) .constrainAs(imageEnd) { start.linkTo(imageTest.end) }, painter = painterResource(id = R.drawable.ic_arrow_right), contentDescription = null ) Image( modifier = Modifier .fillMaxHeight() .background(Color.Blue) .constrainAs(iconLeft) { start.linkTo(imageEnd.end) }, painter = painterResource(id = R.drawable.ic_red_24), contentDescription = null ) Text( modifier = Modifier .background(Color.Blue) .fillMaxHeight() .constrainAs(textWrong) { start.linkTo(iconLeft.end) }, text = wrong.toString(), fontSize = 35.sp, color = Color.White ) } } }
0
Kotlin
6
33
ef97e70a9eb9a71d4d8e44269711f47de220d072
4,140
ComposeClean
MIT License
src/main/kotlin/com/experive/benchmark/BenchmarkRunner.kt
meekyphotos
393,905,293
false
null
package com.experive.benchmark import com.experive.benchmark.utils.MarkdownTableWriter import org.apache.commons.math3.stat.descriptive.SummaryStatistics import java.util.concurrent.TimeUnit import java.util.stream.Stream import kotlin.math.sqrt import kotlin.reflect.KFunction import kotlin.system.measureNanoTime class BenchmarkRunner( /** * Number of iterations performed before starting to record the execution. * The warmup allows to reduce the overhead caused by the framework and * allow the JVM to perform the necessary optimization to the code under test */ private val warmup: Int = 5, /** * Number of iterations measured, the result will always be the average * of the executions, to have a reliable output you should tune the number * of iterations accordingly */ private val iterations: Int = 10, /** * Unit of measure used in the output, all measurements are done in nanos regardless of this parameter */ private val timeUnit: TimeUnit = TimeUnit.MILLISECONDS, /** * If iteration is greater than throttle, then print an output line once every _throttle_ times */ private val throttle: Int = THROTTLE, /** * Display mode: Average time or Throughput */ private val mode: Mode = Mode.Avgt() ) { init { check(iterations >= 1) { "Iteration count should be greater than zero" } check(warmup >= 0) { "Warmup cannot be negative" } } private var beforeEach: Runnable = Runnable {} private var afterEach: Runnable = Runnable {} private var beforeAll: Runnable = Runnable {} private var afterAll: Runnable = Runnable {} private val tests = ArrayList<Benchmark>() /** * Register a runnable that is execute before each execution (incl. warmup) */ fun doBeforeEach(b: Runnable): BenchmarkRunner { this.beforeEach = b return this } /** * Register a runnable that is executed after each execution (incl. warmup) */ fun doAfterEach(b: Runnable): BenchmarkRunner { this.afterEach = b return this } /** * Register a runnable that is executed before each benchmark */ fun doBeforeAll(b: Runnable): BenchmarkRunner { this.beforeAll = b return this } /** * Register a runnable that is executed after each benchmark */ fun doAfterAll(b: Runnable): BenchmarkRunner { this.afterAll = b return this } /** * Add a new benchmark to the comparison */ fun add(underTest: KFunction<*>, vararg args: Any?): BenchmarkRunner { tests.add(Benchmark(underTest, args)) return this } /** * Execute all registered benchmark */ fun runAll() { println("# Warmup: $warmup iterations") println("# Measurement: $iterations iterations") val unit = mode.unit(symbol(timeUnit)) println("# Benchmark mode: $mode, $unit") val results = ArrayList<StatRow>() tests.forEach { bench -> beforeAll.run() try { doWarmUp(bench, unit) println("# Benchmarking") val (average, error) = doIteration(bench, unit) results.add( StatRow( bench, mode.name, iterations.toString(), average, error, unit ) ) } finally { afterAll.run() } } println() MarkdownTableWriter(results).print() } fun compareImplementations(parameters: Stream<Parameters>, vararg implementations: KFunction<*>) { println("# Warmup: $warmup iterations") println("# Measurement: $iterations iterations") val unit = mode.unit(symbol(timeUnit)) println("# Comparison mode: $mode, $unit") beforeAll.run() val winner = HashMap<KFunction<*>, Int>() var scenarios = 0 parameters.forEach { val results = ArrayList<StatRow>() var best: StatRow? = null for (implementation in implementations) { val benchmark = Benchmark(implementation, it()) doWarmUp(benchmark, unit) println("# Benchmarking ${benchmark.name}") val (average, error) = doIteration(benchmark, unit) val res = StatRow( benchmark, mode.name, iterations.toString(), average, error, unit ) best = mode.bestOf(best, res) results.add(res) } println() if (best != null) { winner.compute(best.benchmark.underTest) { _, old -> (old ?: 0).inc() } MarkdownTableWriter(results) .printRelative(best.score, mode) } scenarios++ } winner.entries.sortedBy { -it.value }.forEach { println("${Benchmark.nameOf(it.key)} - Won: ${it.value} out of $scenarios") } afterAll.run() } @SuppressWarnings("SpreadOperator") private fun doIteration(bench: Benchmark, unit: String): Pair<Double, Double> { val stats = SummaryStatistics() /* new_Avg = Avg + (x[n]-x[0])/n new_Var = Var + (x[n]-new_Avg + x[0]-Avg)(x[n] - x[0])/(n-1) new_StdDev = sqrt(new_Var) */ for (i in 1..iterations) { beforeEach.run() val nano = measureNanoTime { bench.underTest.call(*bench.args) } afterEach.run() val runValue = mode.interpret(convertDuration(timeUnit, nano.toDouble())) stats.addValue(runValue) if (i % throttle == 0 || iterations < throttle) { println("Iteration $i: ${mode.getFormatted(runValue, unit)}") } } return Pair(stats.mean, stats.standardDeviation / sqrt(iterations.toDouble())) } @SuppressWarnings("SpreadOperator") private fun doWarmUp(bench: Benchmark, unit: String) { if (warmup > 0) { println("# Warming up") for (i in 0..warmup) { beforeEach.run() val nano = measureNanoTime { bench.underTest.call(*bench.args) } afterEach.run() val runValue = mode.interpret(convertDuration(timeUnit, nano.toDouble())) if (i % throttle == 0 || warmup < throttle) { println("# Warmup Iteration ( $i / $warmup ) - ${mode.getFormatted(runValue, unit)}") } } } } private fun symbol(target: TimeUnit): String { return when (target) { TimeUnit.NANOSECONDS -> "ns" TimeUnit.MICROSECONDS -> "µs" TimeUnit.MILLISECONDS -> "ms" TimeUnit.SECONDS -> "s" TimeUnit.MINUTES -> "m" TimeUnit.HOURS -> "h" TimeUnit.DAYS -> "d" } } private fun convertDuration(target: TimeUnit, nano: Double): Double { return when (target) { TimeUnit.NANOSECONDS -> nano * NANOSECONDS_RATE TimeUnit.MICROSECONDS -> nano * MICROSECONDS_RATE TimeUnit.MILLISECONDS -> nano * MILLISECONDS_RATE TimeUnit.SECONDS -> nano * SECONDS_RATE TimeUnit.MINUTES -> nano * MINUTES_RATE TimeUnit.HOURS -> nano * HOURS_RATE TimeUnit.DAYS -> TimeUnit.NANOSECONDS.toDays(nano.toLong()).toDouble() } } companion object { private const val NANOSECONDS_RATE = 1 private const val MICROSECONDS_RATE = 0.001 private const val MILLISECONDS_RATE = 1e-6 private const val SECONDS_RATE = 1e-9 private const val MINUTES_RATE = 1.6667e-11 private const val HOURS_RATE = 2.7778e-13 private const val THROTTLE = 1000 } }
0
Kotlin
0
0
4c7ee79e752481de15a5fffd5e3bb8c964259468
8,205
mini-benchmark
Apache License 2.0
WoTerFlow/src/main/kotlin/wot/search/jsonpath/JsonPathService.kt
dvgniele
632,881,398
false
{"Kotlin": 105451}
package wot.search.jsonpath import com.fasterxml.jackson.databind.node.ObjectNode import com.jayway.jsonpath.Configuration import com.jayway.jsonpath.InvalidPathException import com.jayway.jsonpath.JsonPath /** * Service to execute [JsonPath] queries. */ class JsonPathService { companion object{ /** * Executes the [JsonPath] query. * * @param query The [JsonPath] query to execute. * @param map The Things map to operate on. * * @return [List] of [ObjectNode] obtained via the [JsonPath] query. */ fun executeQuery(query: JsonPath, map: Map<String, ObjectNode>): List<ObjectNode> { val jsonPathConfig = Configuration.defaultConfiguration() return map.values.filter { td -> val matchingNodes = JsonPath.using(jsonPathConfig) .parse(td.toString()) .read(query) as List<ObjectNode> matchingNodes.isNotEmpty() } } /** * Validates if a [JsonPath] query is valid or not. * * @param query The query to validate. * * @return The compiled [JsonPath] query. * @throws InvalidPathException If [JsonPath] [query] not valid */ fun validateQuery(query: String): JsonPath { if (!query.startsWith("$")){ throw InvalidPathException("JSONPath should start with `$`") } return JsonPath.compile(query) } } }
0
Kotlin
0
0
6e5a07123c9afa778b9fc9acabe98d0fc64b7e94
1,539
WoTerFlow
Apache License 2.0
app/src/main/java/com/kusamaru/standroid/nicovideo/adapter/NicoVideoAdapter.kt
kusamaru
442,642,043
false
{"Kotlin": 1954773}
package com.kusamaru.standroid.nicovideo.adapter import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.fragment.app.FragmentManager import androidx.lifecycle.lifecycleScope import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.button.MaterialButton import com.google.android.material.snackbar.Snackbar import com.kusamaru.standroid.bottomfragment.CommentLockonBottomFragment import com.kusamaru.standroid.CommentJSONParse import com.kusamaru.standroid.nicoapi.nicovideo.NicoruAPI import com.kusamaru.standroid.R import com.kusamaru.standroid.room.init.KotehanDBInit import com.kusamaru.standroid.tool.CustomFont import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import org.json.JSONArray import java.text.SimpleDateFormat import java.util.* /** * ニコ動のコメント表示Adapter * @param isOffline trueにするとニコるくん押せなくします * @param arrayListArrayAdapter コメント配列 * @param fragmentManager BottomFragmentを表示する際に使う * @param nicoruAPI ニコるくんAPIのために * */ class NicoVideoAdapter(private val arrayListArrayAdapter: ArrayList<CommentJSONParse>, private val fragmentManager: FragmentManager, private val isOffline: Boolean, private val nicoruAPI: NicoruAPI?) : RecyclerView.Adapter<NicoVideoAdapter.ViewHolder>() { lateinit var prefSetting: SharedPreferences lateinit var font: CustomFont var textColor = Color.parseColor("#000000") /** コテハン。DBに変更が入ると自動で更新されます([setKotehanDBChangeObserve]参照)。ってかこれAdapterで持っとけば良くない? */ val kotehanMap = mutableMapOf<String, String>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.adapter_nicovideo, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return arrayListArrayAdapter.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val context = holder.commentTextView.context // しょっきかー if (!::font.isInitialized) { font = CustomFont(context) prefSetting = PreferenceManager.getDefaultSharedPreferences(context) textColor = TextView(context).textColors.defaultColor // コテハンデータベース監視 setKotehanDBChangeObserve(context) } val item = arrayListArrayAdapter[position] val comment = item.comment val date = item.date val vpos = item.vpos val time = vpos.toFloat() / 100 //再生時間。100で割ればいいっぽい? // きれいな形へ val formattedTime = formatTime(time) val mail = item.mail holder.userNameTextView.maxLines = 1 // たちみどろいど以外のキャッシュはCommentNoがないので? if (item.commentNo == "-1" || item.commentNo.isEmpty()) { holder.commentTextView.text = "$comment" } else { holder.commentTextView.text = "${item.commentNo}:$comment" } // ニコるくん表示 val isShowNicoruButton = prefSetting.getBoolean("setting_nicovideo_nicoru_show", false) // mail(コマンド)がないときは表示しない val mailText = if (item.mail.isNotEmpty()) { "| $mail " } else { "" } // NGスコア表示するか val ngScore = if (prefSetting.getBoolean("setting_show_ng", false) && item.score.isNotEmpty()) { "| ${item.score} " } else { "" } // ユーザーの設定したフォントサイズ font.apply { holder.commentTextView.textSize = commentFontSize holder.userNameTextView.textSize = userIdFontSize } // フォント font.apply { setTextViewFont(holder.commentTextView) setTextViewFont(holder.userNameTextView) } // かんたんコメント(あらし機能)、通常コメ、投稿者コメ、ニコるカウントに合わせて色つける val color = when { item.fork == 1 -> Color.argb(255, 172, 209, 94)// 投稿者コメント item.fork == 2 -> Color.argb(255, 234, 90, 61) // かんたんコメント else -> Color.argb(255, 0, 153, 229) // それ以外(通常) } holder.nicoruColor.setBackgroundColor(getNicoruLevelColor(item.nicoru, color)) // 一般会員にはニコる提供されてないのでニコる数だけ表示 // あとDevNicoVideoFragmentはがめんスワイプしてたらなんか落ちたので val nicoruCount = if (!isShowNicoruButton && item.nicoru > 0) { "| ニコる ${item.nicoru} " } else { "" } // 動画でコテハン。DevNicoVideoFragment(第二引数)がnullなら動きません。 val kotehanOrUserId = kotehanMap.get(item.userId) ?: item.userId holder.userNameTextView.text = "${setTimeFormat(date.toLong())} | $formattedTime $mailText$nicoruCount$ngScore| ${kotehanOrUserId}" holder.nicoruButton.text = item.nicoru.toString() // ロックオン芸(詳細画面表示) holder.parentLinearLayout.setOnClickListener { val bundle = Bundle() bundle.putString("comment", item.comment) bundle.putString("user_id", item.userId) bundle.putString("liveId", item.videoOrLiveId) bundle.putString("label", holder.userNameTextView.text.toString()) bundle.putLong("current_pos", item.vpos.toLong()) val commentLockonBottomFragment = CommentLockonBottomFragment() commentLockonBottomFragment.arguments = bundle commentLockonBottomFragment.show(fragmentManager, "comment_menu") } // ニコる押したとき holder.nicoruButton.setOnClickListener { postNicoru(context, holder, item) } // プレ垢はニコるくんつける if (nicoruAPI?.isPremium == true && isShowNicoruButton) { holder.nicoruButton.isVisible = true // ただしキャッシュ再生時は押せなくする if (isOffline) { holder.nicoruButton.apply { isClickable = false isEnabled = false } } } } /** * コテハンデータベースを監視する * */ private fun setKotehanDBChangeObserve(context: Context?) { // ContextがActivityじゃないと if (context is AppCompatActivity) { context.lifecycleScope.launch { withContext(Dispatchers.Default) { val dao = KotehanDBInit.getInstance(context).kotehanDBDAO() dao.flowGetKotehanAll().collect { kotehanList -> // コテハンDBに変更があった kotehanMap.clear() kotehanList.forEach { kotehan -> // 令和最新版のコテハン配列を適用する kotehanMap[kotehan.userId] = kotehan.kotehan } } } } } } /** ニコるくんニコる関数 */ private fun postNicoru(context: Context, holder: ViewHolder, item: CommentJSONParse) { val errorHandler = CoroutineExceptionHandler { coroutineContext, throwable -> showToast(context, "${context.getString(R.string.error)}\n${throwable}") } GlobalScope.launch(errorHandler) { val userSession = prefSetting.getString("user_session", "")!! if (nicoruAPI?.isPremium == true) { val responseNicoru = nicoruAPI.postNicoru(item.commentNo, item.comment, "${item.date}.${item.dateUsec}") if (!responseNicoru.isSuccessful) { // 失敗時 showToast(context, "${context.getString(R.string.error)}\n${responseNicoru.code}") return@launch } val responseString = responseNicoru.body?.string() // 成功したか val jsonObject = JSONArray(responseString).getJSONObject(0) val status = nicoruAPI.nicoruResultStatus(jsonObject) when (status) { 0 -> { // ニコれた item.nicoru = nicoruAPI.nicoruResultNicoruCount(jsonObject) val nicoruId = nicoruAPI.nicoruResultId(jsonObject) showSnackbar(holder.commentTextView, "${context.getString(R.string.nicoru_ok)}:${item.nicoru}\n${item.comment}", context.getString(R.string.nicoru_delete)) { // 取り消しAPI叩く GlobalScope.launch(Dispatchers.Default) { val deleteResponse = nicoruAPI.deleteNicoru(userSession, nicoruId) if (deleteResponse.isSuccessful) { [email protected](context, context.getString(R.string.nicoru_delete_ok)) } else { [email protected](context, "${context.getString(R.string.error)}${deleteResponse.code}") } } } // ニコるボタンに再適用 holder.nicoruButton.post { holder.nicoruButton.text = item.nicoru.toString() } } 2 -> { // nicoruKey失効。 GlobalScope.launch(Dispatchers.Default) { // 再取得 nicoruAPI.init() postNicoru(context, holder, item) } } else -> { [email protected](context, context.getString(R.string.nicoru_error)) } } } } } /** Snackbarを表示する */ private fun showSnackbar(view: View, message: String, action: String, click: () -> Unit) { Snackbar.make(view, message, Snackbar.LENGTH_SHORT).apply { setAction(action) { click() } getView().elevation = 30f // なんかBottomSheetから見えない }.show() } /** * 時間表記をきれいにする関数 * */ private fun formatTime(time: Float): String { val minutes = time / 60 val hour = (minutes / 60).toInt() val simpleDateFormat = SimpleDateFormat("mm:ss") return "${hour}:${simpleDateFormat.format(time * 1000)}" } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var commentTextView: TextView = itemView.findViewById(R.id.adapter_nicovideo_comment_textview) var userNameTextView: TextView = itemView.findViewById(R.id.adapter_nicovideo_user_textview) var nicoruButton: MaterialButton = itemView.findViewById(R.id.adapter_nicovideo_comment_nicoru) val nicoruColor: View = itemView.findViewById(R.id.adapter_nicovideo_nicoru_color) val parentLinearLayout: LinearLayout = itemView.findViewById(R.id.adapter_nicovideo_nicoru_parent) } fun setTimeFormat(date: Long): String? { val simpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") return simpleDateFormat.format(date * 1000) } fun showToast(context: Context, message: String) { (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } } /** * ニコるの数に応じた色。 * @param nicoruCount ニコるの数 * @param elseColor 3未満の場合に返す色 * @return いろ * */ private fun getNicoruLevelColor(nicoruCount: Int, elseColor: Int) = when { nicoruCount >= 9 -> Color.rgb(252, 216, 66) nicoruCount >= 6 -> Color.rgb(253, 235, 160) nicoruCount >= 3 -> Color.rgb(254, 245, 207) else -> elseColor } }
0
Kotlin
0
10
cc0aacd393a6d95e36506a01246e4244663fe7c8
12,972
StanDroid
Apache License 2.0
v1_27/src/main/java/de/loosetie/k8s/dsl/manifests/Selfsubjectreviewstatus.kt
loosetie
283,145,621
false
{"Kotlin": 8925107}
package de.loosetie.k8s.dsl.manifests import de.loosetie.k8s.dsl.K8sTopLevel import de.loosetie.k8s.dsl.K8sDslMarker import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasMetadata @K8sDslMarker interface Selfsubjectreviewstatus_authentication_k8s_io_v1beta1: K8sManifest { /** User attributes of the user making this request. */ val userInfo: UserInfo_authentication_k8s_io_v1? }
0
Kotlin
0
1
7ead2b0d96e807a41246394dce2e6aaabb2ada71
401
k8s-dsl
Apache License 2.0
sample-compose/app/src/main/java/co/nimblehq/sample/compose/ui/screens/main/home/HomeScreen.kt
nimblehq
101,353,301
false
{"Kotlin": 385849, "Ruby": 5344, "XSLT": 1824}
package co.nimblehq.sample.compose.ui.screens.main.home import android.Manifest.permission.* import androidx.compose.foundation.layout.* import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Scaffold import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import co.nimblehq.sample.compose.R import co.nimblehq.sample.compose.extensions.collectAsEffect import co.nimblehq.sample.compose.extensions.showToast import co.nimblehq.sample.compose.lib.IsLoading import co.nimblehq.sample.compose.ui.base.BaseDestination import co.nimblehq.sample.compose.ui.common.AppBar import co.nimblehq.sample.compose.ui.models.UiModel import co.nimblehq.sample.compose.ui.showToast import co.nimblehq.sample.compose.ui.theme.ComposeTheme import com.google.accompanist.permissions.* import kotlinx.coroutines.flow.* @Composable fun HomeScreen( viewModel: HomeViewModel = hiltViewModel(), navigator: (destination: BaseDestination) -> Unit, isResultOk: Boolean = false, ) { val context = LocalContext.current viewModel.error.collectAsEffect { e -> e.showToast(context) } viewModel.navigator.collectAsEffect { destination -> navigator(destination) } val isLoading: IsLoading by viewModel.isLoading.collectAsStateWithLifecycle() val uiModels: List<UiModel> by viewModel.uiModels.collectAsStateWithLifecycle() val isFirstTimeLaunch: Boolean by viewModel.isFirstTimeLaunch.collectAsStateWithLifecycle() LaunchedEffect(isFirstTimeLaunch) { if (isFirstTimeLaunch) { context.showToast(context.getString(R.string.message_first_time_launch)) viewModel.onFirstTimeLaunch() } } LaunchedEffect(Unit) { if (isResultOk) { context.showToast(context.getString(R.string.message_updated)) } } CameraPermission() HomeScreenContent( uiModels = uiModels, isLoading = isLoading, onItemClick = viewModel::navigateToSecond, onItemLongClick = viewModel::navigateToThird ) } /** * [CameraPermission] needs to be separate from [HomeScreenContent] to avoid re-composition */ @OptIn(ExperimentalPermissionsApi::class) @Composable private fun CameraPermission() { val context = LocalContext.current val cameraPermissionState = rememberPermissionState(CAMERA) if (cameraPermissionState.status.isGranted) { context.showToast("${cameraPermissionState.permission} granted") } else { if (cameraPermissionState.status.shouldShowRationale) { context.showToast("${cameraPermissionState.permission} needs rationale") } else { context.showToast("Request cancelled, missing permissions in manifest or denied permanently") } LaunchedEffect(Unit) { cameraPermissionState.launchPermissionRequest() } } } @Composable private fun HomeScreenContent( uiModels: List<UiModel>, isLoading: IsLoading, onItemClick: (UiModel) -> Unit, onItemLongClick: (UiModel) -> Unit, ) { Scaffold(topBar = { AppBar(R.string.home_title_bar) }) { paddingValues -> Box( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { if (isLoading) { CircularProgressIndicator(modifier = Modifier.align(Alignment.Center)) } else { ItemList( uiModels = uiModels, onItemClick = onItemClick, onItemLongClick = onItemLongClick ) } } } } @Preview(showSystemUi = true) @Composable private fun HomeScreenPreview() { ComposeTheme { HomeScreenContent( uiModels = listOf(UiModel("1", "name1"), UiModel("2", "name2"), UiModel("3", "name3")), isLoading = false, onItemClick = {}, onItemLongClick = {} ) } }
29
Kotlin
22
87
91c7ac8a4ba2370ab49aaf761bb79bcf1d36deb4
4,210
android-templates
MIT License
library/src/main/java/app/suprsend/notification/SSNotificationHelper.kt
suprsend
440,860,884
false
{"Kotlin": 280346}
package app.suprsend.notification import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ContentResolver import android.content.Context import android.content.Intent import android.graphics.Color import android.media.AudioAttributes import android.net.Uri import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import app.suprsend.BuildConfig import app.suprsend.R import app.suprsend.SSApi import app.suprsend.SSApiInternal import app.suprsend.base.Logger import app.suprsend.base.SSConstants import app.suprsend.base.SdkAndroidCreator import app.suprsend.base.UrlUtils import app.suprsend.base.appExecutorService import app.suprsend.base.mapToEnum import app.suprsend.base.safeBoolean import app.suprsend.base.safeJsonArray import app.suprsend.base.safeLong import app.suprsend.base.safeString import app.suprsend.base.toKotlinJsonObject import app.suprsend.config.ConfigHelper import app.suprsend.fcm.SSFirebaseMessagingService import app.suprsend.xiaomi.SSXiaomiReceiver import com.google.firebase.messaging.RemoteMessage import com.xiaomi.mipush.sdk.ErrorCode import com.xiaomi.mipush.sdk.MiPushClient import com.xiaomi.mipush.sdk.MiPushCommandMessage import com.xiaomi.mipush.sdk.MiPushMessage import org.json.JSONObject object SSNotificationHelper { fun showSSNotification(context: Context, notificationPayloadJson: String?) { try { if (notificationPayloadJson.isNullOrBlank()) return appExecutorService.execute { showRawNotification(context = context.applicationContext, rawNotification = notificationPayloadJson.getRawNotification()) } } catch (e: Exception) { Logger.e(SSFirebaseMessagingService.TAG, "Message data payload exception ", e) } } fun showFCMNotification(context: Context, remoteMessage: RemoteMessage) { try { Logger.i("notification","showFCMNotification") appExecutorService.execute { Logger.i(SSFirebaseMessagingService.TAG, "Message Id : ${remoteMessage.messageId}") if (remoteMessage.isSuprSendRemoteMessage()) { showRawNotification(context = context.applicationContext, rawNotification = remoteMessage.getRawNotification(), pushVendor = SSConstants.PUSH_VENDOR_FCM) } } } catch (e: Exception) { Logger.e(SSFirebaseMessagingService.TAG, "Message data payload exception ", e) } } fun showXiaomiNotification(context: Context, miPushMessage: MiPushMessage) { try { appExecutorService.execute { Logger.i(SSXiaomiReceiver.TAG, "Message Id : ${miPushMessage.messageId}") if (miPushMessage.isSuprSendPush()) { showRawNotification(context = context.applicationContext, rawNotification = miPushMessage.getRawNotification(), pushVendor = SSConstants.PUSH_VENDOR_XIAOMI) } } } catch (e: Exception) { Logger.e(SSXiaomiReceiver.TAG, "Message data payload exception ", e) } } private fun showRawNotification(context: Context, rawNotification: RawNotification, pushVendor: String? = null) { try { Logger.i("notification","showRawNotification $rawNotification") val notificationManagerCompat = NotificationManagerCompat.from(context) if(!notificationManagerCompat.areNotificationsEnabled()){ Logger.e("notification","Notifications are disabled please request the Manifest.permission.POST_NOTIFICATIONS permission") return } // Notification Delivered val instance = SSApi.getInstanceFromCachedApiKey() SSApiInternal.saveTrackEventPayload( eventName = SSConstants.S_EVENT_NOTIFICATION_DELIVERED, propertiesJO = JSONObject().apply { put("id", rawNotification.id) if (pushVendor != null) put(SSConstants.PUSH_VENDOR, pushVendor) } ) instance?.flush() val showNotificationId = String.format(SSConstants.CONFIG_NOTIFICATION_GROUP_SHOWN, rawNotification.notificationGroupId) val isShown = ConfigHelper.getBoolean(showNotificationId) Logger.i("notification","Notification isShown : ${rawNotification.notificationGroupId} $isShown") if (isShown == true) return ConfigHelper.addOrUpdate(showNotificationId, true) Logger.i("notification","showNotificationInternal") showNotificationInternal(context, rawNotification.getNotificationVo()) } catch (e: Exception) { Logger.e("notification", "showRawNotification", e) } } private fun showNotificationInternal(context: Context, notificationVo: NotificationVo) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager Logger.i("notification","setChannel") setChannel(context = context, notificationManager = notificationManager, notificationChannelVo = notificationVo.notificationChannelVo) val notificationBuilder = NotificationCompat.Builder(context, notificationVo.notificationChannelVo.id) Logger.i("notification","setBasicVo") setBasicVo(context = context, notificationBuilder = notificationBuilder, notificationVo = notificationVo) Logger.i("notification","setStyle") setStyle(builder = notificationBuilder, notificationVo = notificationVo) Logger.i("notification","setNotificationAction") setNotificationAction(context = context, notificationBuilder = notificationBuilder, notificationVo = notificationVo) Logger.i("notification","notify") notificationVo.notificationBasicVo.group?.let { val notificationBasicVo = notificationVo.notificationBasicVo val smallIcon = context.getDrawableIdFromName(notificationBasicVo.smallIconDrawableName) ?: R.drawable.ic_notification val groupNotification = NotificationCompat .Builder(context, notificationVo.notificationChannelVo.id) .setGroup(notificationBasicVo.group) .setSmallIcon(smallIcon) .setAutoCancel(true) .setGroupSummary(true) notificationBasicVo.groupSubText?.let { subText -> groupNotification.setSubText(subText) } notificationBasicVo.groupShowWhenTimeStamp?.let { showWhenTimeStamp -> groupNotification.setShowWhen(showWhenTimeStamp) } notificationBasicVo.groupWhenTimeStamp?.let { whenTimeStamp -> groupNotification.setWhen(whenTimeStamp) } notificationManager .notify( notificationBasicVo.group.hashCode(), groupNotification .build() ) } notificationManager.notify(notificationVo.id.hashCode(), notificationBuilder.build()) } private fun setNotificationAction(context: Context, notificationBuilder: NotificationCompat.Builder, notificationVo: NotificationVo) { try { notificationVo.actions?.forEachIndexed { index, notificationActionVo -> val actionIcon = context.getDrawableIdFromName(notificationActionVo.iconDrawableName) ?: 0 val actionIntent = NotificationRedirectionActivity.getIntent(context, notificationActionVo) actionIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP notificationBuilder.addAction( actionIcon, notificationActionVo.title, PendingIntent.getActivity( context, (System.currentTimeMillis() + index).toInt(), actionIntent, getPendingIntentFlag() ) ) } } catch (e: Exception) { Logger.e("notification", "setNotificationAction", e) } } private fun setBasicVo(context: Context, notificationBuilder: NotificationCompat.Builder, notificationVo: NotificationVo) { val notificationBasicVo = notificationVo.notificationBasicVo notificationBuilder.setChannelId(notificationVo.notificationChannelVo.id) notificationVo.notificationBasicVo.priority.let { priority -> notificationBuilder.priority = when (priority) { NotificationPriority.HIGH -> NotificationCompat.PRIORITY_HIGH NotificationPriority.LOW -> NotificationCompat.PRIORITY_LOW NotificationPriority.MAX -> NotificationCompat.PRIORITY_MAX NotificationPriority.MIN -> NotificationCompat.PRIORITY_MIN NotificationPriority.DEFAULT -> NotificationCompat.PRIORITY_DEFAULT } } notificationBasicVo.contentTitle.let { contentTitle -> notificationBuilder.setContentTitle(contentTitle) } notificationBasicVo.contentText.let { contentText -> notificationBuilder.setContentText(contentText) } notificationBasicVo.tickerText.let { tickerText -> notificationBuilder.setTicker(tickerText) } if (notificationVo.bigPictureVo == null) { notificationBasicVo.largeIconUrl?.let { largeIconUrl -> if (largeIconUrl.isNotBlank()) notificationBuilder .setLargeIcon( BitmapHelper .getBitmapFromUrl( UrlUtils .createNotificationLogoImage( largeIconUrl, 200, UrlUtils.calculateQuality(SdkAndroidCreator.networkInfo.getNetworkType()) ) ) ) } } notificationBasicVo.sound?.let { sound -> sound.createRawSoundUri(context)?.let { soundUri -> notificationBuilder.setSound(soundUri) } } notificationBasicVo.color?.let { stringColorCode -> if (stringColorCode.isNotBlank()) notificationBuilder.color = Color.parseColor(stringColorCode) } val smallIcon = context.getDrawableIdFromName(notificationBasicVo.smallIconDrawableName) ?: R.drawable.ic_notification notificationBuilder.setSmallIcon(smallIcon) notificationBasicVo.subText?.let { subText -> notificationBuilder.setSubText(subText) } notificationBasicVo.showWhenTimeStamp?.let { showWhenTimeStamp -> notificationBuilder.setShowWhen(showWhenTimeStamp) } notificationBasicVo.whenTimeStamp?.let { whenTimeStamp -> notificationBuilder.setWhen(whenTimeStamp) } // The duration of time after which the notification is automatically dismissed. notificationBasicVo.timeoutAfter?.let { timeoutAfter -> notificationBuilder.setTimeoutAfter(timeoutAfter) } // Dismiss the notification on click? notificationBasicVo.autoCancel?.let { autoCancel -> notificationBuilder.setAutoCancel(autoCancel) } // Set whether this notification is sticky. notificationBasicVo.onGoing?.let { onGoing -> notificationBuilder.setOngoing(onGoing) } // Set the handler in the event that the notification is dismissed. val notificationDeleteIntent = SSNotificationDismissBroadcastReceiver.notificationDismissIntent(context, NotificationDismissVo(notificationId = notificationVo.id)) notificationDeleteIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val notificationDeletePI = PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt(), notificationDeleteIntent, getPendingIntentFlag()) notificationBuilder.setDeleteIntent(notificationDeletePI) // The category of the notification which allows android to prioritize the notification as required. notificationBasicVo.category?.let { category -> notificationBuilder.setCategory(category) } // Set the key by which this notification will be grouped. notificationBasicVo.group?.let { group -> notificationBuilder.setGroup(group) } notificationBasicVo.sortKey?.let { sortKey -> notificationBuilder.setSortKey(sortKey) } // Set whether or not this notification is only relevant to the current device. notificationBasicVo.localOnly?.let { localOnly -> notificationBuilder.setLocalOnly(localOnly) } // notificationBuilder.setProgress(0,0,true) // notificationBuilder.addPerson( // Person // .Builder() // .setImportant(true) // .setName("") // .setIcon() // .setUri() // .build() // ) try { // Todo : set big text / picture notification content intent val notificationActionVo = notificationVo.getNotificationBodyActionVo() val contentIntent = NotificationRedirectionActivity.getIntent(context, notificationActionVo) contentIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val contentPI = PendingIntent.getActivity(context, System.currentTimeMillis().toInt(), contentIntent, getPendingIntentFlag()) notificationBuilder.setContentIntent(contentPI) } catch (e: Exception) { Logger.e("notification", "setBasicVo", e) } } private fun getPendingIntentFlag(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT } private fun setChannel(context:Context,notificationManager: NotificationManager, notificationChannelVo: NotificationChannelVo) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } notificationManager.getNotificationChannel(notificationChannelVo.id)?.run { name = notificationChannelVo.name description = notificationChannelVo.description notificationManager.createNotificationChannel(this) return } val importance = when (notificationChannelVo.channelImportance) { NotificationChannelImportance.HIGH -> NotificationManager.IMPORTANCE_HIGH NotificationChannelImportance.LOW -> NotificationManager.IMPORTANCE_LOW NotificationChannelImportance.MAX -> NotificationManager.IMPORTANCE_MAX NotificationChannelImportance.MIN -> NotificationManager.IMPORTANCE_MIN NotificationChannelImportance.DEFAULT -> NotificationManager.IMPORTANCE_DEFAULT } val notificationChannel = NotificationChannel(notificationChannelVo.id, notificationChannelVo.name, importance).apply { description = notificationChannelVo.description lockscreenVisibility = when (notificationChannelVo.channelLockScreenVisibility) { NotificationChannelVisibility.PUBLIC -> { Notification.VISIBILITY_PUBLIC } NotificationChannelVisibility.PRIVATE -> { Notification.VISIBILITY_PRIVATE } NotificationChannelVisibility.SECRET -> { Notification.VISIBILITY_SECRET } } setShowBadge(notificationChannelVo.showBadge) notificationChannelVo.channelSound.createRawSoundUri(context = context)?.let { channelSoundUri -> setSound(channelSoundUri, AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()) } } notificationManager.createNotificationChannel(notificationChannel) } private fun setStyle(builder: NotificationCompat.Builder, notificationVo: NotificationVo) { handleInboxStyleVo(notificationVo, builder) handleBigTextVo(notificationVo, builder) handleBigPictureVo(notificationVo, builder) handleMessagingStyleVo(notificationVo, builder) } private fun handleMessagingStyleVo(notificationVo: NotificationVo, builder: NotificationCompat.Builder) { // NotificationCompat // .MessagingStyle( // Person // .Builder() // .setImportant(true) // .setName("") // //.setIcon() // //.setUri() // .build() // ) // // .setConversationTitle(content.conversationTitle) // .also { s -> // content.messages.forEach { s.addMessage(it.text, it.timestamp, it.sender) } // } } private fun handleBigPictureVo(notificationVo: NotificationVo, builder: NotificationCompat.Builder) { val bigPictureVo = notificationVo.bigPictureVo ?: return // Big Picture val bigPictureStyle = NotificationCompat.BigPictureStyle() bigPictureVo.bigContentTitle?.let { bigContentTitle -> bigPictureStyle.setBigContentTitle(bigContentTitle) } bigPictureVo.summaryText?.let { summaryText -> bigPictureStyle.setSummaryText(summaryText) } bigPictureVo.bigPictureUrl?.let { bigPictureUrl -> bigPictureStyle .bigPicture( BitmapHelper .getBitmapFromUrl( UrlUtils .createNotificationBannerImage( bigPictureUrl, SdkAndroidCreator.deviceInfo.getDeviceWidthPixel(), UrlUtils.calculateQuality(SdkAndroidCreator.networkInfo.getNetworkType()) ) ) ) } bigPictureVo.largeIconUrl?.let { largeIconUrl -> bigPictureStyle .bigLargeIcon( BitmapHelper .getBitmapFromUrl( UrlUtils .createNotificationLogoImage( largeIconUrl, 200, UrlUtils.calculateQuality(SdkAndroidCreator.networkInfo.getNetworkType()) ) ) ) } builder.setStyle(bigPictureStyle) } private fun handleBigTextVo(notificationVo: NotificationVo, builder: NotificationCompat.Builder) { val bigTextVo = notificationVo.bigTextVo ?: return val bigTextStyle = NotificationCompat.BigTextStyle() bigTextVo.bigContentTitle?.let { bigContentTitle -> bigTextStyle.setBigContentTitle(bigContentTitle) } bigTextVo.summaryText?.let { summaryText -> bigTextStyle.setSummaryText(summaryText) } bigTextVo.bigText?.let { bigText -> bigTextStyle.bigText(bigText) } builder.setStyle(bigTextStyle) } private fun handleInboxStyleVo(notificationVo: NotificationVo, builder: NotificationCompat.Builder) { val inboxStyleVo = notificationVo.inboxStyleVo ?: return val inboxStyle = NotificationCompat.InboxStyle() inboxStyleVo.bigContentTitle?.let { bigContentTitle -> inboxStyle.setBigContentTitle(bigContentTitle) } inboxStyleVo.summaryText?.let { summaryText -> inboxStyle.setSummaryText(summaryText) } inboxStyleVo.lines?.forEach { line -> inboxStyle.addLine(line) } builder.setStyle(inboxStyle) } } private fun Context.getDrawableIdFromName(drawableName: String?): Int? { return getIdentifierIdFromName(drawableName,"drawable") } private fun Context.getIdentifierIdFromName(resourceName: String?,defType:String): Int? { resourceName ?: return null return try { val id = resources.getIdentifier(resourceName, defType, packageName) return if (id == 0) null else id } catch (e: Exception) { Logger.e("utils","$defType $resourceName not found") null } } fun RemoteMessage.isSuprSendRemoteMessage(): Boolean { return data.containsKey(SSConstants.NOTIFICATION_PAYLOAD) } fun RemoteMessage.getRawNotification(): RawNotification { val notificationPayload = (data[SSConstants.NOTIFICATION_PAYLOAD] ?: "") return notificationPayload.getRawNotification() } private fun String?.getRawNotification(): RawNotification { this ?: return RawNotification("1", "1") val notificationPayloadJO = toKotlinJsonObject() if (BuildConfig.DEBUG) { Logger.i("push_", "Payload : $this") } val id = notificationPayloadJO.safeString("id") ?: "" return RawNotification( id = id, notificationGroupId = notificationPayloadJO.safeString("notificationGroupId") ?: id, channelId = notificationPayloadJO.safeString("channelId"), channelName = notificationPayloadJO.safeString("channelName"), channelDescription = notificationPayloadJO.safeString("channelDescription"), channelShowBadge = notificationPayloadJO.safeBoolean("channelShowBadge"), channelLockScreenVisibility = notificationPayloadJO.safeString("channelLockScreenVisibility").mapToEnum<NotificationChannelVisibility>(), channelImportance = notificationPayloadJO.safeString("channelImportance").mapToEnum<NotificationChannelImportance>(), channelSound = notificationPayloadJO.safeString("channelSound"), priority = notificationPayloadJO.safeString("priority").mapToEnum<NotificationPriority>(), smallIconDrawableName = notificationPayloadJO.safeString("smallIconIdentifierName"), color = notificationPayloadJO.safeString("color"), notificationTitle = notificationPayloadJO.safeString("notificationTitle"), subText = notificationPayloadJO.safeString("subText"), shortDescription = notificationPayloadJO.safeString("shortDescription"), longDescription = notificationPayloadJO.safeString("longDescription"), tickerText = notificationPayloadJO.safeString("tickerText"), iconUrl = notificationPayloadJO.safeString("iconUrl"), imageUrl = notificationPayloadJO.safeString("imageUrl"), deeplink = notificationPayloadJO.safeString("deeplink"), sound = notificationPayloadJO.safeString("sound"), category = notificationPayloadJO.safeString("category"), group = notificationPayloadJO.safeString("group"), groupSubText = notificationPayloadJO.safeString("groupSubText"), groupShowWhenTimeStamp = notificationPayloadJO.safeBoolean("groupShowWhenTimeStamp"), groupWhenTimeStamp = notificationPayloadJO.safeLong("groupWhenTimeStamp"), sortKey = notificationPayloadJO.safeString("sortKey"), onGoing = notificationPayloadJO.safeBoolean("onGoing"), autoCancel = notificationPayloadJO.safeBoolean("autoCancel"), timeoutAfter = notificationPayloadJO.safeLong("timeoutAfter"), showWhenTimeStamp = notificationPayloadJO.safeBoolean("showWhenTimeStamp"), whenTimeStamp = notificationPayloadJO.safeLong("whenTimeStamp"), localOnly = notificationPayloadJO.safeBoolean("localOnly"), actions = getActions(notificationPayloadJO) ) } private fun getActions(notificationPayloadJO: JSONObject): List<NotificationActionVo>? { val safeActions = notificationPayloadJO.safeJsonArray("actions") safeActions ?: return null val actionsList = arrayListOf<NotificationActionVo>() for (i in 0 until safeActions.length()) { val actionObj = safeActions.getJSONObject(i) actionsList.add( NotificationActionVo( id = actionObj.safeString("id"), title = actionObj.safeString("title"), link = actionObj.safeString("link"), iconDrawableName = actionObj.safeString("iconIdentifierName"), notificationId = actionObj.safeString("notificationId"), notificationActionType = actionObj.safeString("notificationActionType").mapToEnum<NotificationActionType>() ) ) } return actionsList } fun MiPushMessage.isSuprSendPush(): Boolean { return content.toKotlinJsonObject().has(SSConstants.NOTIFICATION_PAYLOAD) } fun MiPushMessage.getRawNotification(): RawNotification { return content.toKotlinJsonObject().getString(SSConstants.NOTIFICATION_PAYLOAD).getRawNotification() } fun MiPushCommandMessage?.getToken(): String? { Logger.i( SSXiaomiReceiver.TAG, "getToken\n" + "Command : ${this?.command} \n" + "resultCode : ${this?.resultCode} \n" + "token : ${this?.commandArguments?.firstOrNull()} \n" + "reason : ${this?.reason} \n" ) this ?: return null val token = commandArguments?.firstOrNull() if (MiPushClient.COMMAND_REGISTER == command && resultCode == ErrorCode.SUCCESS.toLong() && !token.isNullOrBlank()) { return token } return null } private fun String?.createRawSoundUri(context: Context): Uri? { var soundFile = this ?: return null if (soundFile.isBlank()) { return null } soundFile = soundFile.substringBeforeLast(".") //If resource not found in raw folder then return context.getIdentifierIdFromName(soundFile,"raw")?:return null return Uri.parse( ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context .packageName + "/raw/" + soundFile ) }
3
Kotlin
1
4
6d31470ec366fa1efe1595e32dfeb86159d2c717
26,654
suprsend-android-sdk
MIT License
libnavui-shield/src/main/java/com/mapbox/navigation/ui/shield/internal/api/MapboxRouteShieldApiEx.kt
mapbox
87,455,763
false
{"Kotlin": 9663566, "Python": 65081, "Java": 36671, "HTML": 17811, "Makefile": 9545, "Shell": 7129}
package com.mapbox.navigation.ui.shield.internal.api import com.mapbox.bindgen.Expected import com.mapbox.navigation.ui.shield.api.MapboxRouteShieldApi import com.mapbox.navigation.ui.shield.internal.model.RouteShieldToDownload import com.mapbox.navigation.ui.shield.model.RouteShieldError import com.mapbox.navigation.ui.shield.model.RouteShieldResult import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine suspend fun MapboxRouteShieldApi.getRouteShieldsFromModels( shieldsToDownload: List<RouteShieldToDownload> ): List<Expected<RouteShieldError, RouteShieldResult>> { return suspendCoroutine { continuation -> getRouteShieldsInternal(shieldsToDownload) { continuation.resume(it) } } }
471
Kotlin
326
603
56332c60cc5c2b20d611068934e7fe86ea5e18fb
750
mapbox-navigation-android
Apache License 2.0
src/main/kotlin/io/viascom/devutils/springbootstartermaintenance/core/event/MaintenanceEvent.kt
viascom
438,303,560
false
{"Kotlin": 11798}
package io.viascom.devutils.springbootstartermaintenance.core.event import io.viascom.devutils.springbootstartermaintenance.core.model.MaintenanceState import org.springframework.context.ApplicationEvent class MaintenanceEvent(source: Any?, val state: MaintenanceState) : ApplicationEvent(source!!)
6
Kotlin
0
3
6e83ce205e47c2f5e0c5db0827d24000a7cb38d1
307
spring-boot-starter-maintenance
The Unlicense
AgoraEduUIKit/src/main/java/com/agora/edu/component/view/FixPopupWindow.kt
AgoraIO-Community
330,886,965
false
null
package com.agora.edu.component.view import android.graphics.Rect import android.os.Build import android.view.View import android.widget.PopupWindow /** * author : felix * date : 2022/2/7 * description : 兼容高版本 PopupWindow bug */ class FixPopupWindow(contentView: View?, width: Int, height: Int, focusable: Boolean) : PopupWindow(contentView, width, height, focusable) { override fun showAsDropDown(anchor: View?) { if (Build.VERSION.SDK_INT == 24 && anchor != null) { val rect = Rect() anchor.getGlobalVisibleRect(rect) val h = anchor.resources.displayMetrics.heightPixels - rect.bottom height = h } super.showAsDropDown(anchor) } }
4
Kotlin
19
16
650f5c9892763a61ed4e468003bf1757abd90238
733
CloudClass-Android
MIT License
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/MessageError.kt
tuProlog
230,784,338
false
{"Kotlin": 3879230, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818}
package it.unibo.tuprolog.solve.exception.error import it.unibo.tuprolog.core.Atom import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.ExecutionContext import it.unibo.tuprolog.solve.exception.LogicError /** * The [MessageError] is used whenever no other [LogicError] instance is suitable for representing the error * * @param message the detail message string. * @param cause the cause of this exception. * @param contexts a stack of contexts localising the exception * @param extraData The possible extra data to be carried with the error * * @author Giovanni */ class MessageError internal constructor( message: String? = null, cause: Throwable? = null, contexts: Array<ExecutionContext>, extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, extraData: Term? = null, ) : this(message, cause, arrayOf(context), extraData) /** The content of this message error */ val content: Term by lazy { extraData ?: errorStruct } override fun updateContext( newContext: ExecutionContext, index: Int, ): MessageError = MessageError(message, cause, contexts.setItem(index, newContext), extraData) override fun updateLastContext(newContext: ExecutionContext): MessageError = updateContext( newContext, contexts.lastIndex, ) override fun pushContext(newContext: ExecutionContext): MessageError = MessageError(message, cause, contexts.addLast(newContext), extraData) companion object { /** The message error Struct functor */ @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "" /** Factory method to create a [MessageError] */ fun of( content: Term, context: ExecutionContext, cause: Throwable? = null, ) = MessageError(content.toString(), cause, context, content) } }
71
Kotlin
13
79
804e57913f072066a4e66455ccd91d13a5d9299a
2,101
2p-kt
Apache License 2.0
web/build.gradle.kts
isabella232
352,967,844
true
{"Kotlin": 252275, "Swift": 45819, "HTML": 797}
/* * Copyright (c) 2020 <NAME>. All rights reserved. */ plugins { with(Plugins) { kotlin(js) kotlin(serializationPlugin) } } dependencies { with(Dependencies.JS) { implementation(kotlinXHtml) implementation(kotlinReact) implementation(kotlinReactDom) } with(Dependencies.Common) { implementation(koinCore) } with(Modules) { implementation(project(client)) implementation(project(logmob)) } } kotlin { js { useCommonJs() browser { binaries.executable() } } }
0
null
0
0
4a13bfd2b91d7707e7ec85ae52479a55b83c71b7
612
CCC
Apache License 2.0
compose-imageviewer/shared/src/jsWasmMain/kotlin/example/imageviewer/view/LocationVisualizer.js.kt
Kotlin
598,690,962
false
{"Kotlin": 417925, "HTML": 12113, "JavaScript": 3485, "Swift": 1755, "Ruby": 101}
package example.imageviewer.view import androidx.compose.foundation.Image import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import example.imageviewer.painterResourceCached import org.jetbrains.compose.resources.* import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable internal actual fun LocationVisualizer(modifier: Modifier) { Image( painter = painterResourceCached("dummy_map.png"), contentDescription = "Map", contentScale = ContentScale.Crop, modifier = modifier ) }
18
Kotlin
53
399
068c94953eb47fef47e800f49d203b4a4286e8bc
642
kotlin-wasm-examples
Apache License 2.0
libnavigation-core/src/main/java/com/mapbox/navigation/core/trip/session/NavigationSession.kt
mapbox
87,455,763
false
{"Kotlin": 9663566, "Python": 65081, "Java": 36671, "HTML": 17811, "Makefile": 9545, "Shell": 7129}
package com.mapbox.navigation.core.trip.session import com.mapbox.navigation.core.MapboxNavigation import com.mapbox.navigation.core.directions.session.RoutesObserver import com.mapbox.navigation.core.directions.session.RoutesUpdatedResult import com.mapbox.navigation.core.history.MapboxHistoryRecorder import com.mapbox.navigation.core.trip.session.NavigationSessionState.ActiveGuidance import com.mapbox.navigation.core.trip.session.NavigationSessionState.FreeDrive import com.mapbox.navigation.core.trip.session.NavigationSessionState.Idle import java.util.concurrent.CopyOnWriteArraySet internal class NavigationSession : RoutesObserver, TripSessionStateObserver { private val stateObservers = CopyOnWriteArraySet<NavigationSessionStateObserver>() internal var state: NavigationSessionState = Idle set(value) { if (field == value) { return } field = value stateObservers.forEach { it.onNavigationSessionStateChanged(value) } } private var hasRoutes = false set(value) { if (field != value) { field = value updateState() } } private var isDriving = false set(value) { if (field != value) { field = value updateState() } } private fun updateState() { state = NavigationSessionUtils.getNewNavigationSessionState( isDriving = isDriving, hasRoutes = hasRoutes ) } internal fun registerNavigationSessionStateObserver( navigationSessionStateObserver: NavigationSessionStateObserver ) { stateObservers.add(navigationSessionStateObserver) navigationSessionStateObserver.onNavigationSessionStateChanged(state) } internal fun unregisterNavigationSessionStateObserver( navigationSessionStateObserver: NavigationSessionStateObserver ) { stateObservers.remove(navigationSessionStateObserver) } internal fun unregisterAllNavigationSessionStateObservers() { stateObservers.clear() } override fun onRoutesChanged(result: RoutesUpdatedResult) { hasRoutes = result.navigationRoutes.isNotEmpty() } override fun onSessionStateChanged(tripSessionState: TripSessionState) { isDriving = NavigationSessionUtils.isDriving(tripSessionState) } } /** * Contains the various states that can occur during a navigation. * * The [MapboxNavigation] implementation can enter into the following session states: * - [Idle] * - [FreeDrive] * - [ActiveGuidance] * * The SDK starts off in an [Idle] state. * Whenever the [MapboxNavigation.startTripSession] is called, the SDK will enter the [FreeDrive] state. * If the session is stopped, the SDK will enter the [Idle] state. * If the SDK is in an [Idle] state, it stays in this same state even when a primary route is available. * If the SDK is already in the [FreeDrive] mode or entering it whenever a primary route is available, * the SDK will enter the [ActiveGuidance] mode instead. * When the routes are manually cleared, the SDK automatically fall back to either [Idle] or [FreeDrive] state. * When transitioning across states of a trip session the [sessionId] will change (empty when [Idle]). */ sealed class NavigationSessionState { /** * Random session UUID. * This is generated internally based on the current state within a trip session. * I.e. will change when transitioning across states of a trip session. Empty when [Idle]. * * Useful to use it in combination with the [MapboxHistoryRecorder]. * * @see [TripSessionState] */ abstract val sessionId: String /** * Idle state */ object Idle : NavigationSessionState() { override val sessionId = "" } /** * Free Drive state */ data class FreeDrive internal constructor( override val sessionId: String ) : NavigationSessionState() /** * Active Guidance state */ data class ActiveGuidance internal constructor( override val sessionId: String ) : NavigationSessionState() }
471
Kotlin
326
603
56332c60cc5c2b20d611068934e7fe86ea5e18fb
4,220
mapbox-navigation-android
Apache License 2.0
src/main/kotlin/words/corpora/Corpus.kt
yttrian
453,615,192
false
{"Kotlin": 35268}
package org.yttr.lordle.words.corpora data class Corpus(val name: String, val url: String, val innerFiles: List<String>) { constructor(name: String, url: String, vararg innerFiles: String) : this(name, url, innerFiles.toList()) }
6
Kotlin
0
2
497ed50a5de1d856e30f2cdc6d1810baacd64a12
235
wormdle
MIT License
SampleArch/data/src/main/java/com/bins/data/api/RandomUserApi.kt
binsdreams
247,954,176
false
null
package com.bins.data.api import com.bins.data.entities.UserResponse import kotlinx.coroutines.Deferred import retrofit2.http.GET interface RandomUserApi{ @GET("api?/page=1&results=10") fun getRandomUsers(): Deferred<UserResponse> }
0
Kotlin
0
0
848ae32c8ebce7cf903636896bc5ea6b44e82e2b
244
coroutinesclean
Apache License 2.0
app/src/main/java/eu/kanade/presentation/browse/manga/MigrateMangaSearchScreen.kt
tonmoyislam12
725,240,487
false
{"Kotlin": 4266256}
package eu.kanade.presentation.browse.manga import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.State import eu.kanade.presentation.browse.GlobalSearchEmptyResultItem import eu.kanade.presentation.browse.GlobalSearchErrorResultItem import eu.kanade.presentation.browse.GlobalSearchLoadingResultItem import eu.kanade.presentation.browse.GlobalSearchResultItem import eu.kanade.presentation.browse.GlobalSearchToolbar import eu.kanade.presentation.browse.manga.components.GlobalMangaSearchCardRow import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.ui.browse.manga.migration.search.MigrateMangaSearchState import eu.kanade.tachiyomi.ui.browse.manga.source.globalsearch.MangaSearchItemResult import eu.kanade.tachiyomi.util.system.LocaleHelper import tachiyomi.domain.entries.manga.model.Manga import tachiyomi.presentation.core.components.LazyColumn import tachiyomi.presentation.core.components.material.Scaffold @Composable fun MigrateMangaSearchScreen( navigateUp: () -> Unit, state: MigrateMangaSearchState, getManga: @Composable (Manga) -> State<Manga>, onChangeSearchQuery: (String?) -> Unit, onSearch: (String) -> Unit, onClickSource: (CatalogueSource) -> Unit, onClickItem: (Manga) -> Unit, onLongClickItem: (Manga) -> Unit, ) { Scaffold( topBar = { scrollBehavior -> GlobalSearchToolbar( searchQuery = state.searchQuery, progress = state.progress, total = state.total, navigateUp = navigateUp, onChangeSearchQuery = onChangeSearchQuery, onSearch = onSearch, scrollBehavior = scrollBehavior, ) }, ) { paddingValues -> MigrateMangaSearchContent( sourceId = state.manga?.source ?: -1, items = state.items, contentPadding = paddingValues, getManga = getManga, onClickSource = onClickSource, onClickItem = onClickItem, onLongClickItem = onLongClickItem, ) } } @Composable fun MigrateMangaSearchContent( sourceId: Long, items: Map<CatalogueSource, MangaSearchItemResult>, contentPadding: PaddingValues, getManga: @Composable (Manga) -> State<Manga>, onClickSource: (CatalogueSource) -> Unit, onClickItem: (Manga) -> Unit, onLongClickItem: (Manga) -> Unit, ) { LazyColumn( contentPadding = contentPadding, ) { items.forEach { (source, result) -> item(key = source.id) { GlobalSearchResultItem( title = if (source.id == sourceId) "▶ ${source.name}" else source.name, subtitle = LocaleHelper.getDisplayName(source.lang), onClick = { onClickSource(source) }, ) { when (result) { MangaSearchItemResult.Loading -> { GlobalSearchLoadingResultItem() } is MangaSearchItemResult.Success -> { if (result.isEmpty) { GlobalSearchEmptyResultItem() return@GlobalSearchResultItem } GlobalMangaSearchCardRow( titles = result.result, getManga = getManga, onClick = onClickItem, onLongClick = onLongClickItem, ) } is MangaSearchItemResult.Error -> { GlobalSearchErrorResultItem(message = result.throwable.message) } } } } } } }
0
Kotlin
0
0
c852223a03d574ecba369fcfebb9958c8ca8a67f
3,956
aniyomi
Apache License 2.0
app-inspection/inspectors/database/testSrc/com/android/tools/idea/sqlite/databaseConnection/live/LiveDatabaseConnectionTest.kt
JetBrains
60,701,247
false
{"Kotlin": 47313864, "Java": 36708134, "HTML": 1217549, "Starlark": 856523, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28591, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.sqlite.databaseConnection.live import androidx.sqlite.inspection.SqliteInspectorProtocol import androidx.sqlite.inspection.SqliteInspectorProtocol.GetSchemaResponse import androidx.sqlite.inspection.SqliteInspectorProtocol.QueryResponse import androidx.sqlite.inspection.SqliteInspectorProtocol.Response import com.android.testutils.MockitoKt.any import com.android.testutils.MockitoKt.whenever import com.android.tools.idea.appinspection.inspector.api.AppInspectorMessenger import com.android.tools.idea.concurrency.FutureCallbackExecutor import com.android.tools.idea.concurrency.pumpEventsAndWaitForFuture import com.android.tools.idea.concurrency.pumpEventsAndWaitForFutureException import com.android.tools.idea.protobuf.ByteString import com.android.tools.idea.sqlite.DatabaseInspectorAnalyticsTracker import com.android.tools.idea.sqlite.DatabaseInspectorMessenger import com.android.tools.idea.sqlite.createErrorSideChannel import com.android.tools.idea.sqlite.model.RowIdName import com.android.tools.idea.sqlite.model.SqliteAffinity import com.android.tools.idea.sqlite.model.SqliteStatement import com.android.tools.idea.sqlite.model.SqliteStatementType import com.android.tools.idea.sqlite.model.SqliteValue import com.google.wireless.android.sdk.stats.AppInspectionEvent import com.intellij.openapi.util.Disposer import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.registerServiceInstance import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.cancel import kotlinx.coroutines.runBlocking import org.jetbrains.ide.PooledThreadExecutor import org.mockito.Mockito.mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions class LiveDatabaseConnectionTest : LightPlatformTestCase() { private val taskExecutor: FutureCallbackExecutor = FutureCallbackExecutor.wrap(PooledThreadExecutor.INSTANCE) private lateinit var liveDatabaseConnection: LiveDatabaseConnection private lateinit var scope: CoroutineScope override fun setUp() { super.setUp() scope = CoroutineScope(taskExecutor.asCoroutineDispatcher() + SupervisorJob()) } override fun tearDown() { try { Disposer.dispose(liveDatabaseConnection) scope.cancel() } catch (t: Throwable) { addSuppressedException(t) } finally { super.tearDown() } } fun testReadSchema() = runBlocking<Unit> { // Prepare val column1 = SqliteInspectorProtocol.Column.newBuilder().setName("column1").setType("TEXT").build() val column2 = SqliteInspectorProtocol.Column.newBuilder().setName("column2").setType("INTEGER").build() val column3 = SqliteInspectorProtocol.Column.newBuilder().setName("column3").setType("FLOAT").build() val column4 = SqliteInspectorProtocol.Column.newBuilder().setName("column4").setType("BLOB").build() val table = SqliteInspectorProtocol.Table.newBuilder() .addColumns(column1) .addColumns(column2) .addColumns(column3) .addColumns(column4) .build() val schema = GetSchemaResponse.newBuilder().addTables(table).build() val schemaResponse = Response.newBuilder().setGetSchema(schema).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(schemaResponse.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act val sqliteSchema = pumpEventsAndWaitForFuture(liveDatabaseConnection.readSchema()) // Assert assertSize(1, sqliteSchema.tables) assertSize(4, sqliteSchema.tables.first().columns) assertEquals(RowIdName._ROWID_, sqliteSchema.tables.first().rowIdName) assertEquals("column1", sqliteSchema.tables.first().columns[0].name) assertEquals("column2", sqliteSchema.tables.first().columns[1].name) assertEquals("column3", sqliteSchema.tables.first().columns[2].name) assertEquals("column4", sqliteSchema.tables.first().columns[3].name) assertEquals(SqliteAffinity.TEXT, sqliteSchema.tables.first().columns[0].affinity) assertEquals(SqliteAffinity.INTEGER, sqliteSchema.tables.first().columns[1].affinity) assertEquals(SqliteAffinity.REAL, sqliteSchema.tables.first().columns[2].affinity) assertEquals(SqliteAffinity.BLOB, sqliteSchema.tables.first().columns[3].affinity) } fun testExecuteQuery() = runBlocking<Unit> { val largeFloat = Float.MAX_VALUE * 2.0 val largeInteger = Long.MAX_VALUE // Prepare val cellValueString = SqliteInspectorProtocol.CellValue.newBuilder().setStringValue("a string").build() val cellValueFloat = SqliteInspectorProtocol.CellValue.newBuilder().setDoubleValue(largeFloat).build() val cellValueBlob = SqliteInspectorProtocol.CellValue.newBuilder() .setBlobValue(ByteString.copyFrom("a blob".toByteArray())) .build() val cellValueInt = SqliteInspectorProtocol.CellValue.newBuilder().setLongValue(largeInteger).build() val cellValueNull = SqliteInspectorProtocol.CellValue.newBuilder().build() val columnNames = listOf("column1", "column2", "column3", "column4", "column5") val rows = SqliteInspectorProtocol.Row.newBuilder() .addValues(cellValueString) .addValues(cellValueFloat) .addValues(cellValueBlob) .addValues(cellValueInt) .addValues(cellValueNull) .build() val cursor = Response.newBuilder() .setQuery(QueryResponse.newBuilder().addAllColumnNames(columnNames).addRows(rows)) .build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act val resultSet = pumpEventsAndWaitForFuture( liveDatabaseConnection.query(SqliteStatement(SqliteStatementType.SELECT, "fake query")) )!! // Assert val sqliteColumns = pumpEventsAndWaitForFuture(resultSet.columns) val sqliteRows = pumpEventsAndWaitForFuture(resultSet.getRowBatch(0, 1)) assertSize(1, sqliteRows) assertSize(5, sqliteColumns) assertEquals("column1", sqliteColumns[0].name) assertEquals("column2", sqliteColumns[1].name) assertEquals("column3", sqliteColumns[2].name) assertEquals("column4", sqliteColumns[3].name) assertEquals("column5", sqliteColumns[4].name) assertNull(sqliteColumns[0].affinity) assertNull(sqliteColumns[1].affinity) assertNull(sqliteColumns[2].affinity) assertNull(sqliteColumns[3].affinity) assertNull(sqliteColumns[4].affinity) assertEquals(sqliteRows[0].values[0].value, SqliteValue.StringValue("a string")) assertEquals(sqliteRows[0].values[1].value, SqliteValue.StringValue(largeFloat.toString())) // the value for the blob corresponds to the base16 encoding of the byte array of the blob. assertEquals(sqliteRows[0].values[2].value, SqliteValue.StringValue("6120626C6F62")) assertEquals(sqliteRows[0].values[3].value, SqliteValue.StringValue(largeInteger.toString())) assertEquals(sqliteRows[0].values[4].value, SqliteValue.NullValue) } fun testExecuteExplain() = runBlocking<Unit> { // Prepare val cellValueString = SqliteInspectorProtocol.CellValue.newBuilder().setStringValue("a string").build() val cellValueFloat = SqliteInspectorProtocol.CellValue.newBuilder().setDoubleValue(1.0).build() val cellValueBlob = SqliteInspectorProtocol.CellValue.newBuilder() .setBlobValue(ByteString.copyFrom("a blob".toByteArray())) .build() val cellValueInt = SqliteInspectorProtocol.CellValue.newBuilder().setLongValue(1).build() val cellValueNull = SqliteInspectorProtocol.CellValue.newBuilder().build() val columnNames = listOf("column1", "column2", "column3", "column4", "column5") val rows = SqliteInspectorProtocol.Row.newBuilder() .addValues(cellValueString) .addValues(cellValueFloat) .addValues(cellValueBlob) .addValues(cellValueInt) .addValues(cellValueNull) .build() val cursor = Response.newBuilder() .setQuery(QueryResponse.newBuilder().addAllColumnNames(columnNames).addRows(rows)) .build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act val resultSet = pumpEventsAndWaitForFuture( liveDatabaseConnection.query(SqliteStatement(SqliteStatementType.EXPLAIN, "fake query")) )!! // Assert val sqliteColumns = pumpEventsAndWaitForFuture(resultSet.columns) val sqliteRows = pumpEventsAndWaitForFuture(resultSet.getRowBatch(0, 1)) assertSize(1, sqliteRows) assertSize(5, sqliteColumns) assertEquals("column1", sqliteColumns[0].name) assertEquals("column2", sqliteColumns[1].name) assertEquals("column3", sqliteColumns[2].name) assertEquals("column4", sqliteColumns[3].name) assertEquals("column5", sqliteColumns[4].name) assertNull(sqliteColumns[0].affinity) assertNull(sqliteColumns[1].affinity) assertNull(sqliteColumns[2].affinity) assertNull(sqliteColumns[3].affinity) assertNull(sqliteColumns[4].affinity) assertEquals(sqliteRows[0].values[0].value, SqliteValue.StringValue("a string")) assertEquals(sqliteRows[0].values[1].value, SqliteValue.StringValue(1f.toString())) // the value for the blob corresponds to the base16 encoding of the byte array of the blob. assertEquals(sqliteRows[0].values[2].value, SqliteValue.StringValue("6120626C6F62")) assertEquals(sqliteRows[0].values[3].value, SqliteValue.StringValue(1.toString())) assertEquals(sqliteRows[0].values[4].value, SqliteValue.NullValue) } fun testExecutePragma() = runBlocking<Unit> { // Prepare val cellValueString = SqliteInspectorProtocol.CellValue.newBuilder().setStringValue("a string").build() val cellValueFloat = SqliteInspectorProtocol.CellValue.newBuilder().setDoubleValue(1.0).build() val cellValueBlob = SqliteInspectorProtocol.CellValue.newBuilder() .setBlobValue(ByteString.copyFrom("a blob".toByteArray())) .build() val cellValueInt = SqliteInspectorProtocol.CellValue.newBuilder().setLongValue(1).build() val cellValueNull = SqliteInspectorProtocol.CellValue.newBuilder().build() val columnNames = listOf("column1", "column2", "column3", "column4", "column5") val rows = SqliteInspectorProtocol.Row.newBuilder() .addValues(cellValueString) .addValues(cellValueFloat) .addValues(cellValueBlob) .addValues(cellValueInt) .addValues(cellValueNull) .build() val cursor = Response.newBuilder() .setQuery(QueryResponse.newBuilder().addAllColumnNames(columnNames).addRows(rows)) .build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act val resultSet = pumpEventsAndWaitForFuture( liveDatabaseConnection.query( SqliteStatement(SqliteStatementType.PRAGMA_QUERY, "fake query") ) ) // Assert val sqliteColumns = pumpEventsAndWaitForFuture(resultSet.columns) val sqliteRows = pumpEventsAndWaitForFuture(resultSet.getRowBatch(0, 1)) assertSize(1, sqliteRows) assertSize(5, sqliteColumns) assertEquals("column1", sqliteColumns[0].name) assertEquals("column2", sqliteColumns[1].name) assertEquals("column3", sqliteColumns[2].name) assertEquals("column4", sqliteColumns[3].name) assertEquals("column5", sqliteColumns[4].name) assertNull(sqliteColumns[0].affinity) assertNull(sqliteColumns[1].affinity) assertNull(sqliteColumns[2].affinity) assertNull(sqliteColumns[3].affinity) assertNull(sqliteColumns[4].affinity) assertEquals(sqliteRows[0].values[0].value, SqliteValue.StringValue("a string")) assertEquals(sqliteRows[0].values[1].value, SqliteValue.StringValue(1f.toString())) // the value for the blob corresponds to the base16 encoding of the byte array of the blob. assertEquals(sqliteRows[0].values[2].value, SqliteValue.StringValue("6120626C6F62")) assertEquals(sqliteRows[0].values[3].value, SqliteValue.StringValue(1.toString())) assertEquals(sqliteRows[0].values[4].value, SqliteValue.NullValue) } fun testExecuteStatementWithParameters() = runBlocking<Unit> { // Prepare val mockMessenger = mock(AppInspectorMessenger::class.java) val sqliteStatement = SqliteStatement( SqliteStatementType.UNKNOWN, "fake query", listOf(SqliteValue.StringValue("1"), SqliteValue.NullValue), "fakeQuery" ) val cursor = Response.newBuilder().setQuery(QueryResponse.newBuilder()).build() whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act pumpEventsAndWaitForFuture(liveDatabaseConnection.execute(sqliteStatement))!! // Assert val param1 = SqliteInspectorProtocol.QueryParameterValue.newBuilder().setStringValue("1").build() val paramNull = SqliteInspectorProtocol.QueryParameterValue.newBuilder().build() val queryBuilder = SqliteInspectorProtocol.QueryCommand.newBuilder() .setQuery(sqliteStatement.sqliteStatementText) .addAllQueryParameterValues(listOf(param1, paramNull)) .setDatabaseId(1) val queryCommand = SqliteInspectorProtocol.Command.newBuilder().setQuery(queryBuilder).build() verify(mockMessenger).sendRawCommand(queryCommand.toByteArray()) } fun testReturnsEmptyResultSetForEmptyResponse() = runBlocking<Unit> { // Prepare val cursor = Response.newBuilder().build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act val resultSet = pumpEventsAndWaitForFuture( liveDatabaseConnection.query(SqliteStatement(SqliteStatementType.SELECT, "fake query")) )!! // Assert val sqliteColumns = pumpEventsAndWaitForFuture(resultSet.columns) val sqliteRows = pumpEventsAndWaitForFuture(resultSet.getRowBatch(0, 1)) assertSize(0, sqliteRows) assertSize(0, sqliteColumns) } fun testThrowsRecoverableErrorOnErrorOccurredResponse() = runBlocking<Unit> { // Prepare val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability( SqliteInspectorProtocol.ErrorRecoverability.newBuilder() .setIsRecoverable(true) .build() ) .setStackTrace("stackTrace") .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert val error1 = pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) val error2 = pumpEventsAndWaitForFutureException( liveDatabaseConnection.execute(SqliteStatement(SqliteStatementType.UNKNOWN, "fake query")) ) assertEquals(error1.cause, error2.cause) assertInstanceOf(error1.cause, LiveInspectorException::class.java) assertEquals("errorMessage", error1.cause!!.message) assertEquals("stackTrace", (error1.cause as LiveInspectorException).onDeviceStackTrace) } fun testThrowsNonRecoverableErrorOnErrorOccurredResponse() = runBlocking<Unit> { // Prepare val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability( SqliteInspectorProtocol.ErrorRecoverability.newBuilder() .setIsRecoverable(false) .build() ) .setStackTrace("stackTrace") .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert val error1 = pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) val error2 = pumpEventsAndWaitForFutureException( liveDatabaseConnection.execute(SqliteStatement(SqliteStatementType.UNKNOWN, "fake query")) ) assertEquals(error1.cause, error2.cause) assertInstanceOf(error1.cause, LiveInspectorException::class.java) assertEquals( "An error has occurred which requires you to restart your app: errorMessage", error1.cause!!.message ) assertEquals("stackTrace", (error1.cause as LiveInspectorException).onDeviceStackTrace) } fun testThrowsUnknownRecoverableErrorOnErrorOccurredResponse() = runBlocking<Unit> { // Prepare val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability(SqliteInspectorProtocol.ErrorRecoverability.newBuilder().build()) .setStackTrace("stackTrace") .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert val error1 = pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) val error2 = pumpEventsAndWaitForFutureException( liveDatabaseConnection.execute(SqliteStatement(SqliteStatementType.UNKNOWN, "fake query")) ) assertEquals(error1.cause, error2.cause) assertInstanceOf(error1.cause, LiveInspectorException::class.java) assertEquals( "An error has occurred which might require you to restart your app: errorMessage", error1.cause!!.message ) assertEquals("stackTrace", (error1.cause as LiveInspectorException).onDeviceStackTrace) } fun testRecoverableErrorAnalytics() = runBlocking<Unit> { // Prepare val mockTrackerService = mock(DatabaseInspectorAnalyticsTracker::class.java) project.registerServiceInstance( DatabaseInspectorAnalyticsTracker::class.java, mockTrackerService ) val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability( SqliteInspectorProtocol.ErrorRecoverability.newBuilder() .setIsRecoverable(true) .build() ) .setStackTrace("stackTrace") .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) pumpEventsAndWaitForFutureException( liveDatabaseConnection.execute(SqliteStatement(SqliteStatementType.UNKNOWN, "fake query")) ) verify(mockTrackerService, times(2)) .trackErrorOccurred(AppInspectionEvent.DatabaseInspectorEvent.ErrorKind.IS_RECOVERABLE_TRUE) } fun testNonRecoverableErrorAnalytics() = runBlocking<Unit> { // Prepare val mockTrackerService = mock(DatabaseInspectorAnalyticsTracker::class.java) project.registerServiceInstance( DatabaseInspectorAnalyticsTracker::class.java, mockTrackerService ) val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability( SqliteInspectorProtocol.ErrorRecoverability.newBuilder() .setIsRecoverable(false) .build() ) .setStackTrace("stackTrace") .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) pumpEventsAndWaitForFutureException( liveDatabaseConnection.execute(SqliteStatement(SqliteStatementType.UNKNOWN, "fake query")) ) verify(mockTrackerService, times(2)) .trackErrorOccurred( AppInspectionEvent.DatabaseInspectorEvent.ErrorKind.IS_RECOVERABLE_FALSE ) } fun testUnknownRecoverableErrorAnalytics() = runBlocking<Unit> { // Prepare val mockTrackerService = mock(DatabaseInspectorAnalyticsTracker::class.java) project.registerServiceInstance( DatabaseInspectorAnalyticsTracker::class.java, mockTrackerService ) val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability(SqliteInspectorProtocol.ErrorRecoverability.newBuilder().build()) .setStackTrace("stackTrace") .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) pumpEventsAndWaitForFutureException( liveDatabaseConnection.execute(SqliteStatement(SqliteStatementType.UNKNOWN, "fake query")) ) verify(mockTrackerService, times(2)) .trackErrorOccurred( AppInspectionEvent.DatabaseInspectorEvent.ErrorKind.IS_RECOVERABLE_UNKNOWN ) } fun testErrorNoExistingDbIsNotReportedInAnalytics() = runBlocking<Unit> { // Prepare val mockTrackerService = mock(DatabaseInspectorAnalyticsTracker::class.java) project.registerServiceInstance( DatabaseInspectorAnalyticsTracker::class.java, mockTrackerService ) val errorOccurredEvent = SqliteInspectorProtocol.ErrorOccurredResponse.newBuilder() .setContent( SqliteInspectorProtocol.ErrorContent.newBuilder() .setMessage("errorMessage") .setRecoverability( SqliteInspectorProtocol.ErrorRecoverability.newBuilder() .setIsRecoverable(true) .build() ) .setStackTrace("stackTrace") .setErrorCode( SqliteInspectorProtocol.ErrorContent.ErrorCode .ERROR_NO_OPEN_DATABASE_WITH_REQUESTED_ID ) .build() ) .build() val cursor = Response.newBuilder().setErrorOccurred(errorOccurredEvent).build() val mockMessenger = mock(AppInspectorMessenger::class.java) whenever(mockMessenger.sendRawCommand(any(ByteArray::class.java))) .thenReturn(cursor.toByteArray()) liveDatabaseConnection = createLiveDatabaseConnection(mockMessenger) // Act / Assert pumpEventsAndWaitForFutureException(liveDatabaseConnection.readSchema()) verifyNoMoreInteractions(mockTrackerService) } private fun createLiveDatabaseConnection( messenger: AppInspectorMessenger ): LiveDatabaseConnection { return LiveDatabaseConnection( testRootDisposable, DatabaseInspectorMessenger(messenger, scope, taskExecutor, createErrorSideChannel(project)), 1, taskExecutor ) } }
2
Kotlin
231
892
ca717ad602b0c2141bd5e7db4a88067a55b71bfe
27,338
android
Apache License 2.0
spring/src/main/kotlin/com/example/demoio/DemoIoApplication.kt
Kotlin
180,830,311
false
null
package com.example.demoio import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.gcp.data.datastore.core.mapping.Entity import org.springframework.cloud.gcp.data.datastore.repository.DatastoreRepository import org.springframework.cloud.gcp.storage.GoogleStorageResource import org.springframework.context.ApplicationContext import org.springframework.core.io.Resource import org.springframework.data.annotation.Id import org.springframework.data.rest.core.annotation.RepositoryRestResource import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import org.springframework.web.multipart.MultipartFile import java.util.* @SpringBootApplication class DemoIoApplication fun main(args: Array<String>) { runApplication<DemoIoApplication>(*args) } @RestController class UploadController( private val applicationContext: ApplicationContext, private val photoRepository: PhotoRepository ) { private val prefix = "gs://cloud-kotlin-io19/demo" @PostMapping("/upload") fun upload(@RequestParam("file") file: MultipartFile): Photo { val id = UUID.randomUUID().toString() val fileUri = "$prefix/$id" val resource = applicationContext.getResource(fileUri) as GoogleStorageResource resource.outputStream.use { out -> file.inputStream.use { it.copyTo(out) } } return photoRepository.save(Photo( id = id, uri = "/image/$id" )) } @GetMapping("/image/{id}") fun image(@PathVariable id: String): ResponseEntity<Resource> { val resource = applicationContext.getResource("$prefix/$id") val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_OCTET_STREAM return ResponseEntity(resource, headers, HttpStatus.OK) } @DeleteMapping("/image/{id}") fun deleteImage(@PathVariable id: String): ResponseEntity<String> { val resource = applicationContext.getResource("$prefix/$id") as GoogleStorageResource return if (resource.exists()) { photoRepository.deleteById(id) resource.blob.delete() ResponseEntity(HttpStatus.OK) } else { ResponseEntity(HttpStatus.NOT_FOUND) } } } @RepositoryRestResource interface PhotoRepository : DatastoreRepository<Photo, String> @Entity data class Photo( @Id var id: String? = null, var uri: String? = null, var label: String? = null )
0
Kotlin
9
31
e583ea3da3788dae3447777efaedcbdaec79e555
3,075
io2019-serverside-demo
Apache License 2.0
app/src/main/java/pokercc/android/boxshadowlayout/demo/AttrActivity.kt
Xigong93
305,630,470
false
{"Kotlin": 33070}
package pokercc.android.boxshadowlayout.demo import android.annotation.SuppressLint import android.app.Activity import android.app.Dialog import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.EditText import android.widget.NumberPicker import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDialog import androidx.core.app.ActivityOptionsCompat import androidx.core.widget.doOnTextChanged import com.flask.colorpicker.ColorPickerView import com.flask.colorpicker.builder.ColorPickerDialogBuilder import pokercc.android.boxshadowlayout.demo.databinding.AttrActivitiyBinding class AttrActivity : AppCompatActivity() { companion object { fun start(activity: Activity, shareView: View, shareElementName: String) { val activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation( activity, shareView, shareElementName ) activity.startActivity( Intent(activity, AttrActivity::class.java), activityOptions.toBundle() ) } } private val binding by lazy { AttrActivitiyBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) setClickEvents() } private fun setClickEvents() { setUpColorPicker() val boxShadow = binding.boxShadowLayout binding.shadowBlur.setDpChange { boxShadow.setShadowBlur(it.toFloat()) } binding.shadowHorizontalOffset.setDpChange { boxShadow.setShadowHorizontalOffset(it.toFloat()) } binding.shadowVerticalOffset.setDpChange { boxShadow.setShadowVerticalOffset(it.toFloat()) } binding.shadowSpread.setDpChange { boxShadow.setShadowSpread(it.toFloat()) } binding.shadowInset.occupyParent() binding.shadowInset.setOnClickListener { binding.shadowInset.isSelected = !binding.shadowInset.isSelected binding.shadowInset.text = binding.shadowInset.isSelected.toString() boxShadow.setShadowInset(binding.shadowInset.isSelected) } binding.boxRadiusTopLeft.setDpChange { boxShadow.setBoxRadius( it.toFloat(), boxShadow.getTopRightRadius(), boxShadow.getBottomLeftRadius(), boxShadow.getBottomRightRadius() ) } binding.boxRadiusTopRight.setDpChange { boxShadow.setBoxRadius( boxShadow.getTopLeftRadius(), it.toFloat(), boxShadow.getBottomLeftRadius(), boxShadow.getBottomRightRadius() ) } binding.boxRadiusBottomLeft.setDpChange { boxShadow.setBoxRadius( boxShadow.getTopLeftRadius(), boxShadow.getTopRightRadius(), it.toFloat(), boxShadow.getBottomRightRadius() ) } binding.boxRadiusBottomRight.setDpChange { boxShadow.setBoxRadius( boxShadow.getTopLeftRadius(), boxShadow.getTopRightRadius(), boxShadow.getBottomLeftRadius(), it.toFloat() ) } } private fun setUpColorPicker() { val defaultColorStr = "#ff000000" binding.shadowColor.text = defaultColorStr binding.shadowColor.setBackgroundColor(Color.parseColor(defaultColorStr)) binding.shadowColor.occupyParent() binding.shadowColor.setOnClickListener { var colorPicker: Dialog? = null colorPicker = ColorPickerDialogBuilder .with(this) .setTitle("Choose Blur Color") .wheelType(ColorPickerView.WHEEL_TYPE.FLOWER) .density(12) .noSliders() .setOnColorSelectedListener { selectedColor -> @SuppressLint("SetTextI18n") binding.shadowColor.text = "#${Integer.toHexString(selectedColor)}" binding.shadowColor.setBackgroundColor(selectedColor) binding.boxShadowLayout.setShadowColor(selectedColor) colorPicker?.dismiss() } .build() colorPicker?.show() } } } private fun TextView.setDpChange(onDpChange: (Px) -> Unit) { occupyParent() setOnClickListener { view -> NumberPickerDialog(view.context) { onDpChange(Px(it)) this.text = it.toString() }.show() } } private fun View.occupyParent() { (parent as? View)?.setOnClickListener { this.performClick() } } private class NumberPickerDialog(context: Context, private val onSelectedNumber: (Number) -> Unit) : AppCompatDialog(context) { private val numberPicker = NumberPicker(context) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(numberPicker) numberPicker.minValue = 0 numberPicker.maxValue = 30 numberPicker.setOnValueChangedListener { picker, oldVal, newVal -> onSelectedNumber(newVal) } } override fun onStart() { super.onStart() setTitle(null) window?.attributes = window?.attributes?.apply { width = WindowManager.LayoutParams.MATCH_PARENT } window?.setGravity(Gravity.BOTTOM) window?.setBackgroundDrawable(ColorDrawable(Color.WHITE)) } }
1
Kotlin
0
13
f0c611b66439a51c01729d02312747de03fa41e9
5,946
BoxShadowLayout
MIT License
communication-core/src/main/java/com/joel/communication_core/request/ImmutableRequestBuilder.kt
jogcaetano13
524,525,946
false
{"Kotlin": 85255}
package com.joel.communication_core.request import com.joel.communication_core.alias.Header class ImmutableRequestBuilder internal constructor( @PublishedApi internal val builder: RequestBuilder, val preCall: (() -> Unit)?, val headers: List<Header>, val dateFormat: String ) { fun updateParameter(key: String, value: Any) = builder.updateParameter(key, value) }
0
Kotlin
0
0
33668cd374ecbdc5d4c7077417c94423c77bd75b
389
communication
MIT License
app/src/client/java/com/twoplaytech/drbetting/ui/settings/SettingsItem.kt
iamdamjanmiloshevski
346,013,436
false
null
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.twoplaytech.drbetting.ui.settings import androidx.annotation.DrawableRes import androidx.annotation.StringRes /* Author: <NAME> Created on 3/20/21 8:23 PM */ sealed class SettingsItem { data class AppInfo(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class Contact(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class Feedback(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class RateUs(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class PrivacyPolicy(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class TermsOfUse(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class ThirdPartySoftware(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class Language(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class Notifications(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() data class NightMode(@StringRes override val name: Int, @DrawableRes override val icon: Int) : ISettingsItem, SettingsItem() }
0
Kotlin
2
2
6f4998dde4c0ed20f2f6300b8a32fc88608abc1d
2,748
betting-doctor
MIT License
feature/repolist/src/main/java/com/danielefavaro/githubapiplayground/feature/repolist/ui/RepoListViewModel.kt
dfavaro
645,763,005
false
null
package com.danielefavaro.githubapiplayground.feature.repolist.ui import androidx.annotation.VisibleForTesting import androidx.lifecycle.viewModelScope import com.danielefavaro.githubapiplayground.core.data.domain.UserReposRepository import com.danielefavaro.githubapiplayground.core.model.exception.ConnectionError import com.danielefavaro.githubapiplayground.core.ui.model.BaseUiEvent import com.danielefavaro.githubapiplayground.core.ui.viewmodel.BaseViewModel import com.danielefavaro.githubapiplayground.feature.repolist.R import com.danielefavaro.githubapiplayground.feature.repolist.ui.model.RepoListUiState import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @HiltViewModel class RepoListViewModel @Inject constructor( private val userReposRepository: UserReposRepository ) : BaseViewModel() { val state: StateFlow<RepoListUiState> = MutableStateFlow(RepoListUiState()) init { fetchUserRepos() collectUserRepos() } fun fetchUserRepos() { onLoadingState(isLoading = true) viewModelScope.launch { try { userReposRepository.updateUserRepos() } catch (e: Exception) { onLoadingState(isLoading = false) when (e) { is ConnectionError -> onErrorEvent( BaseUiEvent.ErrorEvent.OnErrorResWithRetry(R.string.connection_error) ) else -> onErrorEvent( BaseUiEvent.ErrorEvent.OnErrorRes(R.string.generic_error) ) } } } } @VisibleForTesting fun collectUserRepos() { viewModelScope.launch { try { userReposRepository.getUserRepos().collect { it.map { userRepo -> RepoListUiState.UserRepo( id = userRepo.id, name = userRepo.name, isPrivate = userRepo.isPrivate, stars = userRepo.stargazersCount ) }.also { userRepos -> (state as MutableStateFlow).update { state -> state.copy( data = userRepos ) } }.also { onLoadingState(isLoading = false) } } } catch (e: Exception) { onLoadingState(isLoading = false) // TODO check for different errors onErrorEvent(BaseUiEvent.ErrorEvent.OnErrorRes(R.string.generic_error)) } } } }
0
Kotlin
0
0
f11180d90e161d22eb50d08cc2d0624fe7a0c8da
2,940
github-api-playground-android
MIT License
app/src/main/java/me/suttichai/develop/koinexample/CharacterRepository.kt
KingKoge
180,266,610
false
null
package me.suttichai.develop.koinexample import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.Completable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers class CharacterRepository(private val api: ApiService, private val db: DatabaseService) { private var composite: CompositeDisposable? = null private val data: MutableLiveData<MutableList<Character>?> = MutableLiveData() init { composite = CompositeDisposable() } fun observerData(): LiveData<MutableList<Character>?> { return data } fun cleared() { composite?.clear() } fun getData() { composite?.add( db.characterDao().getAll() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ Log.d("Repository", "get all character: $it") handlerLocalResource(it) }, { Log.d("Repository", "get all character: $it") handlerLocalResource(null) }) ) } private fun handlerLocalResource(characters: MutableList<Character>?) { if (characters.isNullOrEmpty()) { data.postValue(null) callServiceGetCharacters() } else { data.postValue(characters) //todo service check last update } } private fun callServiceGetCharacters() { val request = api.create().getCharacters() composite?.add( request.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ handlerApiResponse(it) }, { handlerApiError(it) }) ) } private fun handlerApiResponse(result: ApiResult<MutableList<Character>>) { if (result.meta.code == 200) { composite?.add( Completable.fromCallable { db.characterDao().insertAll(result.data) }.subscribeOn(Schedulers.io()) .subscribe { data.postValue(result.data) } ) } else { handlerApiError(Throwable("Error Code: ${result.meta.code}")) } } private fun handlerApiError(error: Throwable) { Log.e("Repository", error.message, error) data.postValue(mutableListOf()) } }
0
Kotlin
0
0
acb575c29d369f31ba155bc0296e6184de8a57fd
2,637
KoinExample
Apache License 2.0
base/src/main/java/org/kin/sdk/base/tools/Observers.kt
kinecosystem
267,638,129
false
null
package org.kin.sdk.base.tools import java.util.concurrent.CopyOnWriteArrayList interface Disposable<T> { fun dispose() fun disposedBy(disposeBag: DisposeBag): Observer<T> fun doOnDisposed(onDisposed: () -> Unit): Observer<T> } class DisposeBag { private val lock = Any() private val disposables = mutableListOf<Disposable<*>>() fun add(disposable: Disposable<*>) { synchronized(lock) { disposables.add(disposable) } } fun dispose() { synchronized(lock) { disposables.apply { forEach { it.dispose() } clear() } } } } interface Observer<T> : Disposable<T> { fun add(listener: (T) -> Unit): Observer<T> fun remove(listener: (T) -> Unit): Observer<T> fun listenerCount(): Int fun requestInvalidation(): Observer<T> fun <V> map(function: (T) -> V): Observer<V> fun <V> mapPromise(map: (T) -> V): Promise<V> fun <V> flatMapPromise(promise: (T) -> Promise<V>): Promise<V> fun filter(function: (T) -> Boolean): Observer<T> } /** * [onCompleted] to be called when callback is complete with * _either_ a non null value or an error but never both. */ interface Callback<T> : Function<T> { fun onCompleted(value: T? = null, error: Throwable? = null) } class ObservableCallback<T>( val onNext: (value: T) -> Unit, val onCompleted: () -> Unit, val onError: ((error: Throwable) -> Unit)? = { throw it } ) { operator fun invoke(value: T) = onNext(value) operator fun invoke() = onCompleted() operator fun invoke(error: Throwable) = onError?.invoke(error) } /** * May call [onNext] or [onError] in a sequence of value updates. * Should not emit onNext updates after an onError event. */ interface ValueListener<T> { fun onNext(value: T) fun onError(error: Throwable) } fun <T> Promise<T>.callback(callback: Callback<T>) { then({ callback.onCompleted(it, null) }, { callback.onCompleted(null, it) }) } fun <T> Observer<T>.listen(listener: ValueListener<T>): Observer<T> { return add { listener.onNext(it) } } fun <T> ListObserver<T>.listen(listener: ValueListener<List<T>>): ListObserver<T> { return add { listener.onNext(it) } } open class ValueSubject<T>( private val triggerInvalidation: (() -> Unit)? = null ) : Observer<T> { private val listeners by lazy { CopyOnWriteArrayList<(T) -> Unit>() } private var currentValue: T? = null private val onDisposed by lazy { mutableListOf<() -> Unit>() } private var isDisposed = false override fun add(listener: (T) -> Unit): Observer<T> = apply { listeners.add(listener) currentValue?.let { listener(it) } } fun onNext(newValue: T) { listeners.forEach { it(newValue) } currentValue = newValue } override fun remove(listener: (T) -> Unit): Observer<T> = apply { listeners.remove(listener) } override fun listenerCount(): Int = listeners.size override fun dispose() { if (isDisposed) { return } isDisposed= true listeners.clear() onDisposed.forEach { it.invoke() } onDisposed.clear() } override fun disposedBy(disposeBag: DisposeBag): Observer<T> = apply { disposeBag.add(this) } override fun requestInvalidation(): Observer<T> = apply { triggerInvalidation?.invoke() } override fun doOnDisposed(onDisposed: () -> Unit): Observer<T> = apply { this.onDisposed.add(onDisposed) } override fun <V> mapPromise(map: (T) -> V): Promise<V> { return Promise.create { resolve, reject -> add { try { resolve(map(it)) } catch (t: Throwable) { reject(t) } } } } override fun <V> flatMapPromise(promise: (T) -> Promise<V>): Promise<V> { return Promise.create { resolve, reject -> add { promise(it).then(resolve, reject) } } } override fun <V> map(function: (T) -> V): Observer<V> { val thiz = this return ValueSubject<V>().apply { val innerSubject = this thiz.add { innerSubject.onNext(function(it)) } innerSubject.doOnDisposed { thiz.dispose() } thiz.doOnDisposed { innerSubject.dispose() } } } override fun filter(function: (T) -> Boolean): Observer<T> { val thiz = this return ValueSubject<T>().also { downstream -> thiz.add { if (function(it)) { downstream.onNext(it) } } downstream.doOnDisposed { thiz.dispose() } thiz.doOnDisposed { downstream.dispose() } } } } interface ListOperations<T> { fun requestNextPage(): ListObserver<T> fun requestPreviousPage(): ListObserver<T> } interface ListObserver<T> : Observer<List<T>>, ListOperations<T> { override fun add(listener: (List<T>) -> Unit): ListObserver<T> } class ListSubject<T>( private val fetchNextPage: (() -> Unit)? = null, private val fetchPreviousPage: (() -> Unit)? = null, private val triggerInvalidation: (() -> Unit)? = null ) : ValueSubject<List<T>>(triggerInvalidation), ListObserver<T> { override fun add(listener: (List<T>) -> Unit): ListObserver<T> { super.add(listener) return this } override fun requestNextPage(): ListObserver<T> { fetchNextPage?.let { it() } return this } override fun requestPreviousPage(): ListObserver<T> { fetchPreviousPage?.let { it() } return this } }
6
Kotlin
24
38
2a873ee87e1524dca06f1ad7b17d09eb39e4b3a6
5,821
kin-android
MIT License
radialgraph/src/main/java/com/duartbreedt/radialgraph/drawable/RadialGraphDrawable.kt
abdul-sayed22
297,296,866
true
{"Kotlin": 34483}
package com.duartbreedt.radialgraph.drawable import android.animation.ObjectAnimator import android.content.res.Resources import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.PathMeasure import android.os.Build import android.util.FloatProperty import android.view.animation.AccelerateDecelerateInterpolator import androidx.annotation.RequiresApi import com.duartbreedt.radialgraph.model.GraphConfig import com.duartbreedt.radialgraph.model.GraphNode import com.duartbreedt.radialgraph.model.SectionState class RadialGraphDrawable( override val graphConfig: GraphConfig, override val sectionStates: List<SectionState> ) : GraphDrawable(graphConfig, sectionStates) { override fun draw(canvas: Canvas) { val boundaries = calculateBoundaries() for (sectionState in sectionStates) { if (sectionState.path == null) { sectionState.path = buildCircularPath(boundaries) } if (sectionState.length == null) { sectionState.length = PathMeasure(sectionState.path, false).length } sectionState.paint = buildPhasedPathPaint(sectionState) canvas.drawPath(sectionState.path!!, sectionState.paint!!) } if (graphConfig.graphNodeType == GraphNode.PERCENT) { val sectionState = sectionStates.first { it.isLastSection } val coordinates = FloatArray(2) // Get the position of the end of the last drawn segment PathMeasure(sectionState.path!!, false).getPosTan( sectionState.length!! - sectionState.currentProgress, coordinates, null ) // Add a circle with the same background as the last segment drawn canvas.drawCircle( coordinates[0], coordinates[1], graphConfig.strokeWidth / 2, buildFillPaint(sectionState.color) ) // Draw coloured node circle canvas.drawCircle( coordinates[0], coordinates[1], (graphConfig.strokeWidth / 2) - (graphConfig.strokeWidth / 10), buildFillPaint(graphConfig.graphNodeColor) ) val textCenterOffset: Float = graphConfig.graphNodeTextSize / Resources.getSystem().displayMetrics.scaledDensity canvas.drawText( "%", coordinates[0] - textCenterOffset, coordinates[1] + textCenterOffset, buildNodeTextPaint(sectionState.color, graphConfig.graphNodeTextSize) ) } } override fun setAlpha(alpha: Int) { // This method is required } override fun setColorFilter(colorFilter: ColorFilter?) { // This method is required } fun animateIn() { ObjectAnimator.ofFloat(this, FillProgress, 0f, 1f).apply { duration = graphConfig.animationDuration interpolator = AccelerateDecelerateInterpolator() }.start() } fun animateOut() { ObjectAnimator.ofFloat(this, FillProgress, 1f, 0f).apply { duration = graphConfig.animationDuration interpolator = AccelerateDecelerateInterpolator() }.start() } // Creates a progress property to be animated animated @RequiresApi(Build.VERSION_CODES.N) private object FillProgress : FloatProperty<RadialGraphDrawable>("progress") { override fun setValue(drawable: RadialGraphDrawable, progressPercent: Float) { drawable.invalidateSelf() for (sectionState in drawable.sectionStates) { sectionState.currentProgress = progressPercent * (sectionState.length ?: 0f) * (sectionState.sweepSize + sectionState.startPosition) } } override fun get(drawable: RadialGraphDrawable) = drawable.sectionStates[0].currentProgress } }
0
Kotlin
0
0
9c59bfa398d985dc68880f459c6c62039a75369b
3,996
RadialGraph
Apache License 2.0
codegen/src/main/kotlin/com/arianegraphql/codegen/CodegenPlugin.kt
arianegraphql
354,885,191
false
{"Kotlin": 70882, "HTML": 20}
package com.arianegraphql.codegen import org.gradle.api.Plugin import org.gradle.api.Project class CodegenPlugin : Plugin<Project> { override fun apply(project: Project) { val ext = project.extensions.create("ariane", CodegenExtension::class.java) project.tasks.register(CodegenTask.TaskName, CodegenTask::class.java) { it.schema.set(ext.schema) it.configuration.set(ext.configuration) } project.tasks.named("compileKotlin").configure { it.dependsOn(CodegenTask.TaskName) } } }
6
Kotlin
0
5
b75e5dce14a2daa885afb240a6b56a8708b37549
566
ariane-server
MIT License
samples/kofu-reactive-validation/src/main/kotlin/com/sample/Routes.kt
spring-projects-experimental
134,733,282
false
{"Java": 266521, "Kotlin": 215169, "Shell": 515, "HTML": 78, "Mustache": 30}
package com.sample import org.springframework.web.reactive.function.server.router fun routes(userHandler: UserHandler) = router { POST("/api/user", userHandler::createApi) }
39
Java
139
1,660
c41806b1429dc31f75e2cb0f69ddd51a0bd8e9da
180
spring-fu
Apache License 2.0
android/app/src/main/kotlin/com/example/learn_ar_flutter/MainActivity.kt
riyasm449
427,062,434
false
{"Dart": 73199, "Shell": 596, "Swift": 404, "Kotlin": 398, "HTML": 189, "Objective-C": 37}
package com.example.learn_ar_flutter //import io.flutter.embedding.android.FlutterActivity import android.os.Bundle import io.flutter.app.FlutterActivity import io.flutter.plugins.GeneratedPluginRegistrant class MainActivity: FlutterActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GeneratedPluginRegistrant.registerWith(this) } }
0
Dart
0
0
57d40f65a09860b19daff819e0c09bf10132186e
398
flutter_furniture_app
MIT License
app/src/main/java/com/a/vocabulary15/data/datamapper.kt
thedeveloperworldisyours
405,696,476
false
{"Kotlin": 188765}
package com.a.vocabulary15.data import com.a.vocabulary15.data.local.ElementData import com.a.vocabulary15.data.local.GroupData import com.a.vocabulary15.data.local.StatisticsData import com.a.vocabulary15.domain.model.Element import com.a.vocabulary15.domain.model.Group import com.a.vocabulary15.domain.model.Statistics fun Group.toData() = GroupData( 0, name ) fun GroupData.toModel() = Group( id, name ) fun Element.toData() = ElementData( 0, groupId, image, value, link ) fun ElementData.toModel() = Element( id, groupId, image, value, link ) fun Statistics.toData() = StatisticsData( 0, date, points, groupId ) fun StatisticsData.toModel() = Statistics( id, date, points, groupId )
0
Kotlin
6
33
ef97e70a9eb9a71d4d8e44269711f47de220d072
782
ComposeClean
MIT License
gradle-plugins/src/main/kotlin/com/lyeeedar/build/SourceRewriter/ClassRegister.kt
Lyeeedar
128,124,056
false
null
package com.lyeeedar.build.SourceRewriter import java.io.File class ClassRegister(val files: List<File>, val defFolder: File) { val classMap = HashMap<String, ClassDefinition>() val interfaceMap = HashMap<String, InterfaceDefinition>() val enumMap = HashMap<String, EnumDefinition>() fun registerClasses() { for (file in files) { parseFile(file) } for (classDef in classMap.values) { var didSuperClass = false for (inheritFrom in classDef.inheritDeclarations) { if (!didSuperClass) { didSuperClass = true if (inheritFrom.endsWith(")")) { val superClass = classMap[inheritFrom.replace("()", "")] if (superClass != null) { classDef.superClass = superClass } } else { val interfaceDef = interfaceMap[inheritFrom] if (interfaceDef != null) { classDef.interfaces.add(interfaceDef) } } } else { val interfaceDef = interfaceMap[inheritFrom] if (interfaceDef != null) { classDef.interfaces.add(interfaceDef) } } } } for (classDef in classMap.values) { classDef.updateParents() } for (classDef in classMap["XmlDataClass"]!!.inheritingClasses) { classDef.isXmlDataClass = true } } fun parseFile(file: File) { val lines = file.readLines() var packageStr: String = "" for (i in 0 until lines.size) { val line = lines[i] val trimmed = line.trim() if (trimmed.startsWith("package ")) { packageStr = trimmed.replace("package ", "") } else if (trimmed.startsWith("class ")) { val split = trimmed.split(':') val name = split[0].replace("class ", "").trim() val classDef = ClassDefinition(name) classDef.packageStr = packageStr if (split.size > 1) { val inheritsFrom = split[1].split(',') for (other in inheritsFrom) { classDef.inheritDeclarations.add(other.trim()) } } classMap.put(name, classDef) } else if (trimmed.startsWith("abstract class ")) { val split = trimmed.split(':') val name = split[0].replace("abstract class ", "").trim() val classDef = ClassDefinition(name) classDef.isAbstract = true classDef.packageStr = packageStr if (split.size > 1) { val inheritsFrom = split[1].split(',') for (other in inheritsFrom) { classDef.inheritDeclarations.add(other.trim()) } } classMap.put(name, classDef) } else if (trimmed.startsWith("interface ")) { val name = trimmed.replace("interface ", "").trim() val interfaceDef = InterfaceDefinition(name) interfaceDef.packageStr = packageStr interfaceMap.put(name, interfaceDef) } else if (trimmed.startsWith("enum class ")) { val name = trimmed.replace("enum class ", "").trim().split(" ")[0] val enumDef = EnumDefinition(name) var ii = i+2 while (true) { val line = lines[ii] val enumValue = line.split(',', '(', ';')[0].trim() enumDef.values.add(enumValue) if (!line.trim().endsWith(',')) { break } ii++ } enumMap.put(name, enumDef) } } } fun isXmlDataClass(name: String): Boolean { return classMap[name]!!.isXmlDataClass } fun writeXmlDefFiles() { val xmlDataClasses = classMap.values.filter { it.isXmlDataClass }.toList() val rootClasses = xmlDataClasses.filter { it.classDef!!.annotations.any { it.name == "DataFile" } }.toHashSet() rootClasses.addAll(xmlDataClasses.filter { it.classDef!!.forceGlobal }) val refCountMap = HashMap<ClassDefinition, Int>() for (dataClass in rootClasses) { fun writeRef(classDef: ClassDefinition) { val referenced = refCountMap.get(classDef) if (referenced == null) { refCountMap.put(classDef, 0) } else { refCountMap.put(classDef, referenced+1) } } for (referencedClass in dataClass.getAllReferencedClasses(HashSet())) { writeRef(referencedClass) } } if (!defFolder.exists()) defFolder.mkdirs() val defFolder = defFolder.absolutePath // clean folder val sharedFolder = File("$defFolder/Shared") for (file in sharedFolder.listFiles()?.filterNotNull() ?: ArrayList()) { file.delete() } for (file in this.defFolder.listFiles()?.filterNotNull() ?: ArrayList()) { file.delete() } // write root files val writtenSpecificFiles = HashSet<ClassDefinition>() for (root in rootClasses) { val otherClasses = HashSet<ClassDefinition>() for (referencedClass in root.getAllReferencedClasses(HashSet())) { if (rootClasses.contains(referencedClass)) continue val refCount = refCountMap[referencedClass] ?: 0 if (refCount == 0) { otherClasses.add(referencedClass) } } val dataClassAnnotation = root.classDef!!.annotations.firstOrNull { it.name == "DataFile" } ?: AnnotationDescription("@DataFile()") val name = root.classDef!!.dataClassName val colour = dataClassAnnotation.paramMap["colour"] val icon = dataClassAnnotation.paramMap["icon"] val builder = IndentedStringBuilder() val colourLine = if (colour != null) "Colour=\"$colour\"" else "" val iconLine = if (icon != null) "Icon=\"$icon\"" else "" builder.appendln(0, "<Definitions $colourLine $iconLine xmlns:meta=\"Editor\">") if (writtenSpecificFiles.contains(root)) throw RuntimeException("Class written twice!") root.classDef!!.createDefFile(builder, false) writtenSpecificFiles.add(root) for (classDef in otherClasses.sortedBy { it.name }) { if (classDef.classDef!!.forceGlobal) continue if (writtenSpecificFiles.contains(classDef)) throw RuntimeException("Class written twice!") classDef.classDef!!.createDefFile(builder, false) writtenSpecificFiles.add(classDef) if (classDef.isAbstract) { val defNames = HashMap<String, ArrayList<String>>() for (childDef in classDef.inheritingClasses) { if (!childDef.isAbstract) { var category = defNames[childDef.classDef!!.dataClassCategory] if (category == null) { category = ArrayList() defNames[childDef.classDef!!.dataClassCategory] = category } category.add(childDef.classDef!!.dataClassName) } } val keysStr: String if (defNames.size == 1) { keysStr = defNames.values.first().sorted().joinToString(",") } else { keysStr = defNames.entries.sortedBy { it.key }.joinToString(",") { "${it.key}(${it.value.sorted().joinToString(",")})" } } builder.appendln(1, """<Definition Name="${classDef.classDef!!.dataClassName}Defs" Keys="$keysStr" meta:RefKey="ReferenceDef" />""") } } if (root.isAbstract) { val defNames = HashMap<String, ArrayList<String>>() for (childDef in root.inheritingClasses) { if (!childDef.isAbstract) { var category = defNames[childDef.classDef!!.dataClassCategory] if (category == null) { category = ArrayList() defNames[childDef.classDef!!.dataClassCategory] = category } category.add(childDef.classDef!!.dataClassName) } } val keysStr: String if (defNames.size == 1) { keysStr = defNames.values.first().sorted().joinToString(",") } else { keysStr = defNames.entries.sortedBy { it.key }.joinToString(",") { "${it.key}(${it.value.sorted().joinToString(",")})" } } builder.appendln(1, """<Definition Name="${root.classDef!!.dataClassName}Defs" Keys="$keysStr" IsGlobal="True" meta:RefKey="ReferenceDef" />""") } builder.appendln(0, "</Definitions>") File("$defFolder/$name.xmldef").writeText(builder.toString()) println("Created def file $name") } // write shared files val sharedClasses = refCountMap.filter { it.value > 0 }.map { it.key }.toHashSet() if (sharedClasses.isNotEmpty()) { File("$defFolder/Shared").mkdirs() val sharedClassesToWrite = HashSet<ClassDefinition>() for (classDef in sharedClasses) { if (rootClasses.contains(classDef)) continue sharedClassesToWrite.add(classDef) if (classDef.isAbstract) { for (childDef in classDef.inheritingClasses) { if (rootClasses.contains(childDef)) continue sharedClassesToWrite.add(childDef) } } } for (abstractClass in sharedClassesToWrite.filter { it.isAbstract && it.superClass!!.superClass == null }.toList()) { val builder = IndentedStringBuilder() builder.appendln(0, "<Definitions xmlns:meta=\"Editor\">") val defNames = HashMap<String, ArrayList<String>>() abstractClass.classDef!!.createDefFile(builder, true) sharedClassesToWrite.remove(abstractClass) for (classDef in abstractClass.inheritingClasses) { if (writtenSpecificFiles.contains(classDef)) throw RuntimeException("Class written twice!") classDef.classDef!!.createDefFile(builder, true) sharedClassesToWrite.remove(classDef) if (!classDef.isAbstract) { var category = defNames[classDef.classDef!!.dataClassCategory] if (category == null) { category = ArrayList() defNames[classDef.classDef!!.dataClassCategory] = category } category.add(classDef.classDef!!.dataClassName) } } val keysStr: String if (defNames.size == 1) { keysStr = defNames.values.first().sorted().joinToString(",") } else { keysStr = defNames.entries.sortedBy { it.key }.joinToString(",") { "${it.key}(${it.value.sorted().joinToString(",")})" } } val abstractClassName = abstractClass.classDef!!.dataClassName builder.appendln(1, """<Definition Name="${abstractClassName}Defs" Keys="$keysStr" IsGlobal="True" meta:RefKey="ReferenceDef" />""") builder.appendln(0, "</Definitions>") File("$defFolder/Shared/${abstractClassName}.xmldef").writeText(builder.toString()) println("Created def file $abstractClassName") } for (classDef in sharedClassesToWrite) { if (writtenSpecificFiles.contains(classDef)) throw RuntimeException("Class written twice!") val builder = IndentedStringBuilder() builder.appendln(0, "<Definitions xmlns:meta=\"Editor\">") classDef.classDef!!.createDefFile(builder, true) builder.appendln(0, "</Definitions>") File("$defFolder/Shared/${classDef.classDef!!.dataClassName}.xmldef").writeText(builder.toString()) println("Created def file ${classDef.classDef!!.dataClassName}") } } } } class ClassDefinition(val name: String) { var packageStr: String = "" var superClass: ClassDefinition? = null val interfaces = ArrayList<InterfaceDefinition>() var isAbstract = false var inheritDeclarations = ArrayList<String>() val inheritingClasses = ArrayList<ClassDefinition>() var isXmlDataClass = false var classID: String? = null var classDef: XmlDataClassDescription? = null var referencedClasses = ArrayList<ClassDefinition>() fun updateParents(classDef: ClassDefinition? = null) { if (classDef != null) { inheritingClasses.add(classDef) superClass?.updateParents(classDef) } else { superClass?.updateParents(this) } } fun getAllReferencedClasses(processedClasses: HashSet<ClassDefinition>): HashSet<ClassDefinition> { val output = HashSet<ClassDefinition>() output.addAll(referencedClasses) output.addAll(inheritingClasses) for (classDef in referencedClasses) { if (!processedClasses.contains(classDef)) { processedClasses.add(classDef) output.addAll(classDef.getAllReferencedClasses(processedClasses)) } } for (classDef in inheritingClasses) { output.addAll(classDef.getAllReferencedClasses(processedClasses)) } return output } } class InterfaceDefinition(val name: String) { var packageStr: String = "" } class EnumDefinition(val name: String) { val values = ArrayList<String>() }
0
Kotlin
0
1
c35a65d458591b1508c6db499583391151c2db05
11,861
MatchDungeon
Apache License 2.0
src/day04/Day04.kt
tiginamaria
573,173,440
false
{"Kotlin": 7901}
package day04 import readInput fun main() { fun part1(input: List<String>) = input.count { val (a, b, c, d) = it.split(',') .flatMap { range -> range.split("-").map { border -> border.toInt() } } (a >= c && b <= d) || (a <= c && b >= d) } fun part2(input: List<String>) = input.count { val (a, b, c, d) = it.split(',') .flatMap { range -> range.split("-").map { border -> border.toInt() } } (c <= b && a <= d) } val input = readInput("Day04", 4) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bf81cc9fbe11dce4cefcb80284e3b19c4be9640e
584
advent-of-code-kotlin
Apache License 2.0
data-cache/src/main/java/prieto/fernando/model/RandomJokeLocalModel.kt
ferPrieto
216,438,304
false
null
package prieto.fernando.model data class RandomJokeLocalModel( val id: String, val joke: String, val categories: List<CategoryLocalModel> ) enum class CategoryLocalModel { EXPLICIT, NERDY, UNKNOWN }
0
Kotlin
1
13
aecbd0054faa15beb29aac1c694eff9db0179432
225
MVVM-Modularized
Apache License 2.0
app/src/main/java/uk/co/jatra/noted/network/Api.kt
Jatra
190,070,014
false
null
package uk.co.jatra.noted.network import io.reactivex.Single import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST /** * Definition of the Server API for Retrofit generation. */ interface Api { /** * Get all occurrences. * * @return an RxJava [Single] of a the list of [Occurrence] */ @GET("occurences") fun getOccurences(): Single<List<Occurrence>> /** * Get all users. * * @return an RxJava [Single] of a the list of [User] */ @GET("users") fun getUsers(): Single<List<User>> /** * Get all events. * * @return an RxJava [Single] of a the list of [Event] */ @GET("events") fun getEvents(): Single<List<Event>> /** * Add a single [Occurrence] * * @param[request] an [OccurrenceRequest] * @return the newly created [Occurrence] */ @POST("occurence") fun addOccurrence(@Body request: OccurrenceRequest) : Single<Occurrence> /** * Add a single [Event] * * @param[request] an [EventRequest] * @return the newly created [Event] */ @POST("event") fun addEvent(@Body request: EventRequest) : Single<Event> /** * Add a single [User] * * @param[request] an [UserRequest] * @return the newly created [User] */ @POST("user") fun addUser(@Body request: UserRequest) : Single<User> }
0
Kotlin
0
0
a1faa5317cf7a0724d0945d673de6bdbb148f18b
1,413
Noted
Apache License 2.0
app/src/main/java/top/jowanxu/wanandroidclient/presenter/ContentPresenterImpl.kt
wangzailfm
114,053,615
false
null
package top.jowanxu.wanandroidclient.presenter import top.jowanxu.wanandroidclient.bean.HomeListResponse import top.jowanxu.wanandroidclient.model.CollectArticleModel import top.jowanxu.wanandroidclient.model.CollectOutsideArticleModel import top.jowanxu.wanandroidclient.model.CollectOutsideArticleModelImpl import top.jowanxu.wanandroidclient.model.SearchModelImpl import top.jowanxu.wanandroidclient.view.CollectArticleView class ContentPresenterImpl(private val collectArticleView: CollectArticleView) : HomePresenter.OnCollectArticleListener, HomePresenter.OnCollectOutsideArticleListener { private val collectArticleModel: CollectArticleModel = SearchModelImpl() private val collectOutsideArticleModel: CollectOutsideArticleModel = CollectOutsideArticleModelImpl() /** * add or remove collect article * @param id article id * @param isAdd true add, false remove */ override fun collectArticle(id: Int, isAdd: Boolean) { collectArticleModel.collectArticle(this, id, isAdd) } /** * add collect article success * @param result HomeListResponse * @param isAdd true add, false remove */ override fun collectArticleSuccess(result: HomeListResponse, isAdd: Boolean) { if (result.errorCode != 0) { collectArticleView.collectArticleFailed(result.errorMsg, isAdd) } else { collectArticleView.collectArticleSuccess(result, isAdd) } } /** * add collect article failed * @param errorMessage error message * @param isAdd true add, false remove */ override fun collectArticleFailed(errorMessage: String?, isAdd: Boolean) { collectArticleView.collectArticleFailed(errorMessage, isAdd) } /** * add or remove outside collect article * @param title article title * @param author article author * @param link article link * @param isAdd true add, false remove */ override fun collectOutSideArticle( title: String, author: String, link: String, isAdd: Boolean ) { collectOutsideArticleModel.collectOutsideArticle(this, title, author, link, isAdd) } /** * add collect outside article success * @param result HomeListResponse * @param isAdd true add, false remove */ override fun collectOutsideArticleSuccess(result: HomeListResponse, isAdd: Boolean) { if (result.errorCode != 0) { collectArticleView.collectArticleFailed(result.errorMsg, isAdd) } else { collectArticleView.collectArticleSuccess(result, isAdd) } } /** * add collect outside article failed * @param errorMessage error message * @param isAdd true add, false remove */ override fun collectOutsideArticleFailed(errorMessage: String?, isAdd: Boolean) { collectArticleView.collectArticleFailed(errorMessage, isAdd) } fun cancelRequest() { collectArticleModel.cancelCollectRequest() collectOutsideArticleModel.cancelCollectOutsideRequest() } }
6
Kotlin
131
628
fef70711199ff6d06a9623f9732d684267cb3f78
3,114
WanAndroidClient
Apache License 2.0
android/testSrc/com/android/tools/idea/gradle/ui/GradleJdkPathEditComboBoxTest.kt
JetBrains
60,701,247
false
{"Kotlin": 47313864, "Java": 36708134, "HTML": 1217549, "Starlark": 856523, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28591, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * 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.idea.gradle.ui import com.android.testutils.MockitoKt.argumentCaptor import com.android.testutils.MockitoKt.eq import com.android.testutils.MockitoKt.mock import com.android.testutils.MockitoKt.mockStatic import com.android.testutils.TestUtils import com.intellij.icons.AllIcons import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.testFramework.LightPlatformTestCase import com.intellij.ui.JBColor import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.util.Consumer import org.jetbrains.android.util.AndroidBundle import org.mockito.ArgumentCaptor import kotlin.io.path.Path class GradleJdkPathEditComboBoxTest : LightPlatformTestCase() { fun `test Given no selection and empty suggested JDKs When create component Then no JDK path is selected and dropdown items are empty`() { val jdkComboBox = GradleJdkPathEditComboBox(emptyList(), null, "") assertEmpty(jdkComboBox.selectedJdkPath) assertEquals(0, jdkComboBox.itemCount) } fun `test Given no selection and suggested JDKs When create component Then no JDK path is selected and dropdown items are not empty`() { val itemValidJdk = LabelAndFileForLocation("valid", TestUtils.getEmbeddedJdk17Path()) val itemInvalidJdk = LabelAndFileForLocation("invalid", Path("/invalid/jdk/path")) val jdkComboBox = GradleJdkPathEditComboBox(listOf(itemValidJdk, itemInvalidJdk), null, "") assertEmpty(jdkComboBox.selectedJdkPath) assertEquals(2, jdkComboBox.itemCount) } fun `test Given initial selection When create component Then specified JDK path is selected`() { val currentJdkPath = "/jdk/path" val jdkComboBox = GradleJdkPathEditComboBox(emptyList(), currentJdkPath, "") assertEquals(currentJdkPath, jdkComboBox.selectedJdkPath) assertFalse(jdkComboBox.isModified) } fun `test Given comboBox When select JDK path and reset selection Then selected JDK path is consistent`() { val currentJdkPath = "/jdk/path" val jdkComboBox = GradleJdkPathEditComboBox(emptyList(), currentJdkPath, "") val differentSelectionJdkPath = "/another/jdk/path" jdkComboBox.selectedItem = differentSelectionJdkPath assertEquals(differentSelectionJdkPath, jdkComboBox.selectedJdkPath) assertTrue(jdkComboBox.isModified) jdkComboBox.resetSelection() assertEquals(currentJdkPath, jdkComboBox.selectedJdkPath) assertFalse(jdkComboBox.isModified) } fun `test Given comboBox When select valid or invalid JDK path Then foreground change accordingly`() { val itemValidJdk = LabelAndFileForLocation("valid", TestUtils.getEmbeddedJdk17Path()) val itemInvalidJdk = LabelAndFileForLocation("invalid", Path("/invalid/jdk/path")) val jdkComboBox = GradleJdkPathEditComboBox(listOf(itemValidJdk, itemInvalidJdk), null, "") val jdkEditor = jdkComboBox.editor.editorComponent jdkComboBox.selectedItem = null assertEquals(JBColor.red, jdkEditor.foreground) jdkComboBox.selectedItem = itemValidJdk assertEquals(JBColor.black, jdkEditor.foreground) jdkComboBox.selectedItem = itemInvalidJdk assertEquals(JBColor.red, jdkEditor.foreground) } fun `test Given list of suggested JDKs When create component Then dropdown contains all items`() { val items = listOf( LabelAndFileForLocation("label1", Path("path1")), LabelAndFileForLocation("label2", Path("path2")), LabelAndFileForLocation("label3", Path("path3")), LabelAndFileForLocation("label4", Path("path4")) ) val jdkComboBox = GradleJdkPathEditComboBox(items, null, "") assertEquals(items.size, jdkComboBox.itemCount) items.forEachIndexed { index, labelAndFileForLocation -> assertEquals(labelAndFileForLocation, jdkComboBox.getItemAt(index)) } } fun `test Given comboBox Then was configured with expected settings`() { val itemValidJdk = LabelAndFileForLocation("valid", TestUtils.getEmbeddedJdk17Path()) val jdkComboBox = GradleJdkPathEditComboBox(listOf(itemValidJdk), null, "") val jdkExtendableText = jdkComboBox.editor.editorComponent as ExtendableTextField assertEquals(1, jdkExtendableText.extensions.size) jdkExtendableText.extensions.first().run { assertEquals(AllIcons.General.OpenDisk, getIcon(false)) assertEquals(AllIcons.General.OpenDiskHover, getIcon(true)) assertEquals(AndroidBundle.message("gradle.settings.jdk.browse.button.tooltip.text"), tooltip) } } fun `test Given comboBox When select a browsed JDK Then browsed JDK path is selected`() { val jdkComboBox = GradleJdkPathEditComboBox(emptyList(), null, "") val jdkExtendableText = jdkComboBox.editor.editorComponent as ExtendableTextField jdkExtendableText.extensions.first().run { val captor: ArgumentCaptor<Consumer<String>> = argumentCaptor() mockStatic<SdkConfigurationUtil>().use { getActionOnClick(mock()).run() it.verify { SdkConfigurationUtil.selectSdkHome(eq(JavaSdk.getInstance()), captor.capture()) } captor.value.consume("/selected/jdk/path") assertEquals("/selected/jdk/path", jdkComboBox.selectedJdkPath) } } } }
2
Kotlin
231
892
ca717ad602b0c2141bd5e7db4a88067a55b71bfe
5,838
android
Apache License 2.0
projects/Kotlin/src/proto/fbe/FieldModelInt16.kt
dendisuhubdy
164,466,220
true
{"C++": 3424832, "Yacc": 13858, "Lex": 11840, "CMake": 7836, "C": 80}
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: fbe // Version: 1.2.0.0 @file:Suppress("UnusedImport", "unused") package fbe import java.io.* import java.lang.* import java.lang.reflect.* import java.math.* import java.nio.charset.* import java.time.* import java.util.* // Fast Binary Encoding Short field model class FieldModelInt16(buffer: Buffer, offset: Long) : FieldModel(buffer, offset) { // Field size override val fbeSize: Long = 2 // Get the value fun get(defaults: Short = 0.toShort()): Short { if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size) return defaults return readInt16(fbeOffset) } // Set the value fun set(value: Short) { assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" } if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size) return write(fbeOffset, value) } }
1
C++
0
1
1cde1633c43e5c44db591b782beb227e05772a02
1,038
FastBinaryEncoding
MIT License
app/src/main/java/com/example/homepage/features/plazaTab/plazaDashboard/PlazaDashBoardFragment.kt
Parvez-Uni-Projects
516,901,454
false
{"Kotlin": 271402, "HTML": 6242, "Ruby": 3020, "Python": 789}
package com.example.homepage.features.plazaTab.plazaDashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.homepage.databinding.FragmentPlazaDashBoardBinding import com.example.homepage.features.plazaTab.plazaDashboard.Adapter.PlazaDashBoardAdapter import com.example.homepage.features.plazaTab.plazaDashboard.Model.PlazaDashBoardViewModel import com.example.homepage.utils.helpers.ReplaceFragment import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase class PlazaDashBoardFragment : ReplaceFragment() { private lateinit var fragmentBinding: FragmentPlazaDashBoardBinding private val viewBinding get() = fragmentBinding private lateinit var database: DatabaseReference private lateinit var auth: FirebaseAuth private lateinit var recycler: RecyclerView private var adapter: PlazaDashBoardAdapter? = null private lateinit var viewModel: PlazaDashBoardViewModel private lateinit var _inflater: LayoutInflater override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { container?.removeAllViews() fragmentBinding = FragmentPlazaDashBoardBinding.inflate(inflater, container, false) _inflater = inflater auth = Firebase.auth database = Firebase.database.reference return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler = viewBinding.postedItemList recycler.layoutManager = LinearLayoutManager(context) recycler.setHasFixedSize(true) adapter = PlazaDashBoardAdapter(_inflater) recycler.adapter = adapter viewModel = ViewModelProvider(this)[PlazaDashBoardViewModel::class.java] viewModel.allUserAnnouncements.observe(viewLifecycleOwner) { adapter!!.updatePlazaDashboardList(it) } } }
10
Kotlin
4
9
a2bbc2ca9310241e623b123b4e9f62004c28e2e5
2,353
AUST_BUDDY
MIT License
app/src/main/java/me/sedlar/osrs_clue_hint/component/ExpandableMapAdapter.kt
TSedlar
274,257,117
false
null
package me.sedlar.osrs_clue_hint.component import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseExpandableListAdapter import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import me.sedlar.osrs_clue_hint.MainActivity import me.sedlar.osrs_clue_hint.R import me.sedlar.osrs_clue_hint.data.MapData import me.sedlar.osrs_clue_hint.helper.DownloadImageTask import me.sedlar.osrs_clue_hint.helper.LineBreakParser class ExpandableMapAdapter internal constructor( private val context: Context, private val data: List<MapData> ) : BaseExpandableListAdapter() { private val dataList = HashMap<String, List<String>>() private val titleList = data.map { it.notes } private val groupMap = HashMap<String, View>() private val viewMap = HashMap<String, ArrayList<View>>() init { data.forEach { map -> dataList[map.notes] = listOf(map.notes, map.image) viewMap[map.notes] = ArrayList() } } override fun getChild(listPosition: Int, expandedListPosition: Int): Any { return this.dataList[this.titleList[listPosition]]!![expandedListPosition] } override fun getChildId(listPosition: Int, expandedListPosition: Int): Long { return expandedListPosition.toLong() } @SuppressLint("InflateParams", "SetTextI18n") override fun getChildView( listPosition: Int, expandedListPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup ): View { val map = data[listPosition] val viewList = viewMap[map.notes]!! if (viewList.isEmpty()) { val layoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val noteView = layoutInflater.inflate(R.layout.list_item_map, null) noteView.findViewById<TextView>(R.id.expandedListItemTitle)?.text = "Notes:" noteView.findViewById<TextView>(R.id.expandedListItem)?.let { it.text = LineBreakParser.parse(map.notes) } val imageView = layoutInflater.inflate(R.layout.list_item_map_image, null) imageView?.findViewById<TextView>(R.id.expandedListItemTitle)?.text = "Location:" imageView?.findViewById<ImageView>(R.id.expandedListItem)?.let { locImageView -> locImageView.setOnClickListener { MainActivity.solutionDialog?.hide() val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(map.image)) context.startActivity(browserIntent) } DownloadImageTask(locImageView, onFinish = { imageView.findViewById<ProgressBar>(R.id.progressIndicator)?.visibility = View.GONE locImageView.visibility = View.VISIBLE }) .execute(map.image) } viewList.addAll(arrayOf(noteView, imageView)) } return viewList[expandedListPosition] } override fun getChildrenCount(listPosition: Int): Int { return this.dataList[this.titleList[listPosition]]!!.size } override fun getGroup(listPosition: Int): Any { return this.titleList[listPosition] } override fun getGroupCount(): Int { return this.titleList.size } override fun getGroupId(listPosition: Int): Long { return listPosition.toLong() } @SuppressLint("InflateParams") override fun getGroupView(listPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View { val map = data[listPosition] if (!groupMap.containsKey(map.notes)) { val layoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val view = layoutInflater.inflate(R.layout.list_group_image, null) val listTitleTextView = view!!.findViewById<ImageView>(R.id.listTitle) DownloadImageTask(listTitleTextView, onFinish = { view.findViewById<ProgressBar>(R.id.progressIndicator)?.visibility = View.GONE listTitleTextView.visibility = View.VISIBLE }) .execute(map.map) groupMap[map.notes] = view } return groupMap[map.notes]!! } override fun hasStableIds(): Boolean { return false } override fun isChildSelectable(listPosition: Int, expandedListPosition: Int): Boolean { return true } }
0
Kotlin
0
0
17736538a5724b6bd0d14f905278cf472e7174d1
4,741
OSRS-Clue-Hint
MIT License
render-resources/src/com/android/tools/res/AssetFileOpener.kt
JetBrains
60,701,247
false
{"Kotlin": 47313864, "Java": 36708134, "HTML": 1217549, "Starlark": 856523, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28591, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * 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.res import java.io.InputStream /** * Abstract out the specific logic of receiving the [InputStream] for the resource file located at path. In some case (e.g. inside Studio) * it might not be as simple as reading the file from disk since file on disk might be out-of-date and the updated file version is kept in * e.g. memory. */ interface AssetFileOpener { fun openAssetFile(path: String): InputStream? fun openNonAssetFile(path: String): InputStream? }
2
Kotlin
231
892
ca717ad602b0c2141bd5e7db4a88067a55b71bfe
1,110
android
Apache License 2.0
src/test/kotlin/com/github/kkkiio/intellij/protobuf/golang/PbGoGotoProtoTest.kt
KKKIIO
314,425,028
false
{"Java": 792472, "Kotlin": 55946, "Lex": 12570, "PureBasic": 367, "HTML": 247}
package com.github.kkkiio.intellij.protobuf.golang import com.github.kkkiio.intellij.protobuf.test.TestCaseBase import com.intellij.psi.util.QualifiedName import idea.plugin.protoeditor.lang.psi.PbFile class PbGoGotoProtoTest : TestCaseBase() { @ExperimentalStdlibApi fun testComputePbGoSymbolMap() { val testName: String = getTestName(true) val file = configureCaseFile("$testName.proto") val pbFile = assertInstanceOf(file, PbFile::class.java) val symbolMap = PbGoGotoProto.computePbGoSymbolMap(pbFile) assertSameElements( symbolMap.keys, setOf( "ExampleMessage", "ExampleMessage.Id", "ExampleMessage.Status", "ExampleMessage.Type", "ExampleMessage.Data", "ExampleMessage_Status", "ExampleMessage_INACTIVE", "ExampleMessage_ACTIVE", "ExampleMessagePtype", "ExampleMessage_P0", "ExampleMessage_P1" ).map { QualifiedName.fromDottedString(it) } ) } }
2
Java
0
2
06b4bd04801826a95099ea750273fb9908aa3788
1,124
intellij-protobuf-support
Apache License 2.0
lang/src/org/partiql/lang/ast/passes/StaticTypeRewriter.kt
sullis
282,318,013
true
{"Kotlin": 2044878, "HTML": 99272, "Shell": 8944, "Java": 1352}
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All rights reserved. */ package org.partiql.lang.ast.passes import com.amazon.ion.* import org.partiql.lang.ast.* import org.partiql.lang.errors.* import org.partiql.lang.eval.* import org.partiql.lang.types.* import org.partiql.lang.util.* /** * Extra constraints which may be imposed on the type checking. */ enum class StaticTypeRewriterConstraints { /** * With this constraint, any VariableReferences in SFW queries must be * defined within the FROM clause. * * This provides for variable resolution which is akin to what users of a * traditional RDBMS would expect. */ PREVENT_GLOBALS_EXCEPT_IN_FROM, /** * With this constraint, all variables from nested queries must resolve to * lexically scoped variables. * * Constraining a user's access to global binds is useful for simplified * query planning in a DB environment where global binds may be costly to * fetch or lead to large intermediate results. */ PREVENT_GLOBALS_IN_NESTED_QUERIES; } /** * An [AstRewriter] that annotates nodes with their static types and resolves implicit variables * explicitly based on the static types. * * The validations performed may be enhanced by the passing of additional [StaticTypeRewriterConstraints]. * * @param globalEnv The global bindings to the static environment. This is data catalog purely from a lookup * perspective. * @param constraints Additional constraints on what variable scoping, or other rules should be followed. */ class StaticTypeRewriter(private val ion: IonSystem, globalBindings: Bindings<StaticType>, constraints: Set<StaticTypeRewriterConstraints> = setOf()) : AstRewriter { /** Used to allow certain binding lookups to occur directly in the global scope. */ private val globalEnv = wrapBindings(globalBindings, 0) private val preventGlobalsExceptInFrom = StaticTypeRewriterConstraints.PREVENT_GLOBALS_EXCEPT_IN_FROM in constraints private val preventGlobalsInNestedQueries = StaticTypeRewriterConstraints.PREVENT_GLOBALS_IN_NESTED_QUERIES in constraints /** Captures a [StaticType] and the depth at which it is bound. */ private data class TypeAndDepth(val type: StaticType, val depth: Int) /** Indicates the scope at which a particular bind was found. */ private enum class BindingScope { /** Describes a binding to a variable defined within the same statement. */ LOCAL, /** * Describes a binding to a variable defined within the overall scope * of a statement. With nested statements, a variable binding from an * outer scope would be [LEXICAL], not [LOCAL]. */ LEXICAL, /** * A binding to a variable defined in the DB environment, not within * the user's statement. */ GLOBAL; } /** Captures a [StaticType] and what scope it is bound within. */ private data class TypeAndScope(val type: StaticType, val scope: BindingScope) /** Defines the current scope search order--i.e. globals first when in a FROM source, lexical everywhere else. */ private enum class ScopeSearchOrder { LEXICAL, GLOBALS_THEN_LEXICAL } /** * @param parentEnv the enclosing bindings * @param currentScopeDepth How deeply nested the current scope is. * - 0 means we are in the global scope * - 1 is the top-most statement with a `FROM` clause (i.e. select-from-where or DML operation), * - Values > 1 are for each subsequent level of nested sub-query. */ private inner class Rewriter(private val parentEnv: Bindings<TypeAndDepth>, private val currentScopeDepth: Int) : AstRewriterBase() { /** Specifies the current scope search order--default is LEXICAL. */ private var scopeOrder = ScopeSearchOrder.LEXICAL private val localsMap = mutableMapOf<String, StaticType>() // TODO this used to use a wrapper over localsMap, but that API no longer exists, we should figure something // more reasonable out later for this at some point, but this is good enough for now private var localsOnlyEnv = wrapBindings(Bindings.ofMap(localsMap), currentScopeDepth) // because of the mutability of the above reference, we need to encode the lookup as a thunk private val currentEnv = Bindings.over { localsOnlyEnv[it] }.delegate(parentEnv) private var containsJoin = false /** Set to true after any FROM source has been visited.*/ private var fromVisited = false /** * In short, after the FROM sources have been visited, this is set to the name if-and-only-if there is * a single from source. Otherwise, it is null. */ private var singleFromSourceName: String? = null private fun singleFromSourceRef(sourceName: String, metas: MetaContainer): VariableReference { val sourceType = currentEnv[BindingName(sourceName, BindingCase.SENSITIVE)] ?: throw IllegalArgumentException("Could not find type for single FROM source variable") return VariableReference( sourceName, CaseSensitivity.SENSITIVE, ScopeQualifier.LEXICAL, metas + metaContainerOf(StaticTypeMeta(sourceType.type)) ) } private fun VariableReference.toPathComponent(): PathComponentExpr = PathComponentExpr(Literal(ion.newString(id), metas.sourceLocationContainer), case) private fun errUnboundName(name: String, metas: MetaContainer): Nothing = throw SemanticException( "No such variable named '$name'", ErrorCode.SEMANTIC_UNBOUND_BINDING, propertyValueMapOf( Property.BINDING_NAME to name ).addSourceLocation(metas) ) private fun errIllegalGlobalVariableAccess(name: String, metas: MetaContainer): Nothing = throw SemanticException( "Global variable access is illegal in this context", ErrorCode.SEMANTIC_ILLEGAL_GLOBAL_VARIABLE_ACCESS, propertyValueMapOf( Property.BINDING_NAME to name ).addSourceLocation(metas) ) private fun errAmbiguousName(name: String, metas: MetaContainer): Nothing = throw SemanticException( "A variable named '$name' was already defined in this scope", ErrorCode.SEMANTIC_AMBIGUOUS_BINDING, propertyValueMapOf( Property.BINDING_NAME to name ).addSourceLocation(metas) ) private fun errUnimplementedFeature(name: String, metas: MetaContainer? = null): Nothing = throw SemanticException( "Feature not implemented yet", ErrorCode.UNIMPLEMENTED_FEATURE, propertyValueMapOf( Property.FEATURE_NAME to name ).also { if (metas != null) { it.addSourceLocation(metas) } } ) private fun addLocal(name: String, type: StaticType, metas: MetaContainer) { val existing = localsOnlyEnv[BindingName(name, BindingCase.INSENSITIVE)] if (existing != null) { errAmbiguousName(name, metas) } localsMap[name] = type // this requires a new instance because of how [Bindings.ofMap] works localsOnlyEnv = wrapBindings(Bindings.ofMap(localsMap), currentScopeDepth) } override fun rewriteCallAgg(node: CallAgg): ExprNode { return CallAgg( // do not rewrite the funcExpr--as this is a symbolic name in another namespace (AST is over generalized here) node.funcExpr, node.setQuantifier, rewriteExprNode(node.arg), rewriteMetas(node)) } override fun rewriteNAry(node: NAry): ExprNode = when (node.op) { // do not write the name of the call--this should be a symbolic name in another namespace (AST is over generalized here) NAryOp.CALL -> NAry( node.op, listOf(node.args[0]) + node.args.drop(1).map { rewriteExprNode(it) }, rewriteMetas(node)) else -> super.rewriteNAry(node) } private fun Bindings<TypeAndDepth>.lookupBinding(bindingName: BindingName): TypeAndScope? = when (val match = this[bindingName]) { null -> null else -> { val (type, depth) = match val scope = when { depth == 0 -> BindingScope.GLOBAL depth < currentScopeDepth -> BindingScope.LEXICAL depth == currentScopeDepth -> BindingScope.LOCAL else -> error("Unexpected: depth should never be > currentScopeDepth") } TypeAndScope(type, scope) } } /** * Encapsulates variable reference lookup, layering the scoping * rules from the exclusions given the current state. * * Returns an instance of [TypeAndScope] if the binding was found, otherwise returns null. */ private fun findBind(bindingName: BindingName, scopeQualifier: ScopeQualifier): TypeAndScope? { // Override the current scope search order if the var is lexically qualified. val overridenScopeSearchOrder = when(scopeQualifier) { ScopeQualifier.LEXICAL -> ScopeSearchOrder.LEXICAL ScopeQualifier.UNQUALIFIED -> this.scopeOrder } val scopes: List<Bindings<TypeAndDepth>> = when(overridenScopeSearchOrder) { ScopeSearchOrder.GLOBALS_THEN_LEXICAL -> listOf(globalEnv, currentEnv) ScopeSearchOrder.LEXICAL -> listOf(currentEnv, globalEnv) } return scopes .asSequence() .mapNotNull { it.lookupBinding(bindingName) } .firstOrNull() } /** * The actual variable resolution occurs in this method--all other parts of the * [StaticTypeRewriter] support what's happening here. */ override fun rewriteVariableReference(node: VariableReference): ExprNode { val bindingName = BindingName(node.id, node.case.toBindingCase()) val found = findBind(bindingName, node.scopeQualifier) val singleBinding = singleFromSourceName //Copy to immutable local variable to enable smart-casting // If we didn't find a variable with that name... if(found == null) { // ...and there is a single from-source in the current query, then rewrite it into // a path expression, i.e. `SELECT foo FROM bar AS b` becomes `SELECT b.foo FROM bar AS b` return when { // If there's a single from source... singleBinding != null -> { makePathIntoFromSource(singleBinding, node) } else -> { // otherwise there is more than one from source so an undefined variable was referenced. errUnboundName(node.id, node.metas) } } } if(found.scope == BindingScope.GLOBAL) { when { // If we found a variable in the global scope but a there is a single // from source, we should rewrite to this to path expression anyway and pretend // we didn't match the global variable. singleBinding != null -> { return makePathIntoFromSource(singleBinding, node) } preventGlobalsExceptInFrom && fromVisited -> { errIllegalGlobalVariableAccess(bindingName.name, node.metas) } preventGlobalsInNestedQueries && currentScopeDepth > 1 -> { errIllegalGlobalVariableAccess(bindingName.name, node.metas) } } } val newScopeQualifier = when(found.scope) { BindingScope.LOCAL, BindingScope.LEXICAL -> ScopeQualifier.LEXICAL BindingScope.GLOBAL -> ScopeQualifier.UNQUALIFIED } return node.copy( scopeQualifier = newScopeQualifier, metas = node.metas.add(StaticTypeMeta(found.type))) } /** * Changes the specified variable reference to a path expression with the name of the variable as * its first and only element. */ private fun makePathIntoFromSource(fromSourceAlias: String, node: VariableReference): Path { return Path( singleFromSourceRef(fromSourceAlias, node.metas.sourceLocationContainer), listOf(node.toPathComponent()), node.metas.sourceLocationContainer) } override fun rewritePath(node: Path): ExprNode = when (node.root) { is VariableReference -> super.rewritePath(node).let { it as Path when (it.root) { // we started with a variable, that got turned into a path, normalize it // SELECT x.y FROM tbl AS t --> SELECT ("t".x).y FROM tbl AS t --> SELECT "t".x.y FROM tbl AS t is Path -> { val childPath = it.root Path(childPath.root, childPath.components + it.components, it.metas) } // nothing to do--the rewrite didn't change anything else -> it } } else -> super.rewritePath(node) } // TODO support analyzing up the call chain (n-ary, etc.) override fun rewriteFromSourceLet(fromSourceLet: FromSourceLet): FromSourceLet { // we need to rewrite the source expression before binding the names to our scope val from = super.rewriteFromSourceLet(fromSourceLet) fromSourceLet.variables.atName?.let { addLocal(it.name, StaticType.ANY, it.metas) } fromSourceLet.variables.byName?.let { addLocal(it.name, StaticType.ANY, it.metas) } val asSymbolicName = fromSourceLet.variables.asName ?: error("fromSourceLet.variables.asName is null. This wouldn't be the case if FromSourceAliasRewriter was executed first.") addLocal(asSymbolicName.name, StaticType.ANY, asSymbolicName.metas) if (!containsJoin) { fromVisited = true if (currentScopeDepth == 1) { singleFromSourceName = asSymbolicName.name } } return from } override fun rewriteFromSourceJoin(fromSource: FromSourceJoin): FromSource { // this happens before FromSourceExpr or FromSourceUnpivot gets hit val outermostJoin = !containsJoin containsJoin = true return super.rewriteFromSourceJoin(fromSource) .also { if (outermostJoin) { fromVisited = true singleFromSourceName = null } } } override fun rewriteFromSourceValueExpr(expr: ExprNode): ExprNode { this.scopeOrder = ScopeSearchOrder.GLOBALS_THEN_LEXICAL return rewriteExprNode(expr).also { this.scopeOrder = ScopeSearchOrder.LEXICAL } } // TODO support PIVOT // TODO support GROUP BY override fun rewriteGroupBy(groupBy: GroupBy): Nothing { errUnimplementedFeature("GROUP BY") } override fun rewriteSelect(selectExpr: Select): ExprNode { // a SELECT introduces a new scope, we evaluate the each from source // which is correlated (and thus has visibility from the previous bindings) return createRewriterForNestedScope().innerRewriteSelect(selectExpr) } override fun rewriteDataManipulation(node: DataManipulation): DataManipulation { return createRewriterForNestedScope().innerRewriteDataManipulation(node) } private fun createRewriterForNestedScope(): Rewriter { return Rewriter(currentEnv, currentScopeDepth + 1) } /** * This function differs from the the overridden function only in that it does not attempt to resolve * [CreateIndex.keys], which would be a problem because they contain [VariableReference]s yet the keys are * scoped to the table and do not follow traditional lexical scoping rules. This indicates that * [CreateIndex.keys] is incorrectly modeled as a [List<ExprNode>]. */ override fun rewriteCreateIndex(node: CreateIndex): CreateIndex = CreateIndex( node.tableName, node.keys, rewriteMetas(node)) /** * This function differs from the the overridden function only in that it does not attempt to resolve * [DropIndex.identifier], which would be a problem because index names are scoped to the table and do not * follow traditional lexical scoping rules. This is not something the [StaticTypeRewriter] is currently * plumbed to deal with and also indicates that [DropIndex.identifier] is incorrectly modeled as a * [VariableReference]. */ override fun rewriteDropIndex(node: DropIndex): DropIndex = DropIndex( node.tableName, node.identifier, rewriteMetas(node)) } override fun rewriteExprNode(node: ExprNode): ExprNode = Rewriter(wrapBindings(Bindings.empty(), 1), 0) .rewriteExprNode(node) private fun wrapBindings(bindings: Bindings<StaticType>, depth: Int): Bindings<TypeAndDepth> { return Bindings.over { name -> bindings[name]?.let { bind -> TypeAndDepth(bind, depth) } } } }
0
Kotlin
0
0
7360a8daae12f7bb43d531036a21dcd7b81db9d1
18,709
partiql-lang-kotlin
Apache License 2.0
app/src/main/java/com/delminiusdevs/toppop/data/remote/dto/chart/User.kt
MilicTG
503,690,908
false
{"Kotlin": 28985}
package com.delminiusdevs.toppop.data.remote.dto.chart data class User( val id: Long, val name: String, val tracklist: String, val type: String )
0
Kotlin
0
0
86e84f4c0d9f6269efcd8a1a71447091a27a632b
162
TopPop
MIT License
app/src/main/java/com/serapercel/seraphine/ui/fragments/PlayFragment.kt
SerapErcel
653,820,213
false
null
package com.serapercel.seraphine.ui.fragments import android.content.Context import android.media.MediaPlayer import android.net.Uri import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SeekBar import androidx.activity.OnBackPressedCallback import com.serapercel.seraphine.databinding.FragmentPlayBinding import com.serapercel.seraphine.model.Music import com.serapercel.seraphine.util.toastLong import androidx.navigation.fragment.findNavController import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.serapercel.seraphine.R class PlayFragment : Fragment() { private var _binding: FragmentPlayBinding? = null private val binding get() = _binding!! private lateinit var music: Music lateinit var mediaPlayer: MediaPlayer override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentPlayBinding.inflate(inflater, container, false) music = arguments?.getSerializable("music") as Music getMusicFavorites().addOnSuccessListener { musicList -> if (musicList.contains(music)) { binding.btnAddFavorite.visibility = View.INVISIBLE binding.btnRemoveFavorite.visibility = View.VISIBLE } else { binding.btnAddFavorite.visibility = View.VISIBLE binding.btnRemoveFavorite.visibility = View.INVISIBLE } }.addOnFailureListener { e -> requireContext().toastLong(e.message.toString()) } try { val uri = Uri.parse(music.url) mediaPlayer = MediaPlayer.create(requireContext(), uri) } catch (e: Exception) { requireContext().toastLong(e.message.toString()) } val volume = getVolume() mediaPlayer.setVolume(volume, volume) binding.sbSound.progress = (volume * 100).toInt() mediaPlayer.start() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.tvMusicTitle.text = music.title binding.btnPause.setOnClickListener { mediaPlayer.pause() binding.btnPause.visibility = View.INVISIBLE binding.btnPlay.visibility = View.VISIBLE binding.lottieAnimation.visibility = View.GONE } binding.btnPlay.setOnClickListener { mediaPlayer.start() binding.btnPause.visibility = View.VISIBLE binding.btnPlay.visibility = View.INVISIBLE binding.lottieAnimation.visibility = View.VISIBLE } binding.btnAddFavorite.setOnClickListener { addFirebase() binding.btnAddFavorite.visibility = View.INVISIBLE binding.btnRemoveFavorite.visibility = View.VISIBLE } binding.sbSound.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { val volume = progress.toFloat() / 100 mediaPlayer.setVolume(volume, volume) saveVolume(volume) } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { findNavController().navigate(R.id.action_playFragment_to_homeFragment) mediaPlayer.stop() } }) } private fun saveVolume(volume: Float) { val sharedPref = requireActivity().getSharedPreferences("seraphine", Context.MODE_PRIVATE) val editor = sharedPref.edit() editor.putFloat("Volume", volume) editor.apply() } private fun getVolume(): Float { val sharedPref = requireActivity().getSharedPreferences("seraphine", Context.MODE_PRIVATE) return sharedPref.getFloat("Volume", 0.5f) } override fun onResume() { super.onResume() mediaPlayer.start() } override fun onStop() { super.onStop() mediaPlayer.pause() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun addFirebase() { val auth = FirebaseAuth.getInstance() val db = FirebaseFirestore.getInstance() val collectionRef = db.collection("users").document(auth.currentUser!!.uid).collection("favorites") collectionRef.add(music) .addOnSuccessListener { documentReferences -> // Başarılı bir şekilde eklenmişse burası çalışır. Log.d("music", " favorite Success.") } .addOnFailureListener { e -> // Bir hata oluşursa burası çalışır. Log.d("music", "favorite Error: $e") } } private fun getMusicFavorites(): Task<MutableList<Music>> { val auth = FirebaseAuth.getInstance() val db = FirebaseFirestore.getInstance() val collectionRef = db.collection("users").document(auth.currentUser!!.uid).collection("favorites") val newList = mutableListOf<Music>() return collectionRef.get() .continueWith { task -> val querySnapshot = task.result for (document in querySnapshot.documents) { val data = document.toObject(Music::class.java) data?.let { newList.add(it) } } newList } } }
0
Kotlin
0
2
00fe42d28135fffa88a19be86e62fda10336d987
6,090
Seraphine
MIT License
feature/history/ui/build.gradle.kts
miguelaboliveira
590,654,618
false
{"Kotlin": 66447}
plugins { id("svpolitician-android-library-feature") } android { namespace = "com.miguelaboliveira.svpolitician.feature.history.ui" resourcePrefix = "history" } dependencies { implementation(projects.feature.history.domain) implementation(projects.core.ui.design) implementation(projects.core.ui.fragmentext) kapt(libs.androidx.lifecycleCompiler) implementation(libs.androidx.lifecycleRuntimeCompose) implementation(libs.kotlinx.collectionsImmutable) testImplementation(libs.androidx.lifecycleRuntimeTesting) }
3
Kotlin
0
0
0845fe511e9ec2503759a37aacb229846bf319fb
553
svpolitician
Apache License 2.0
src/main/kotlin/bk70/Problem1.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package bk70 fun main() { val res = Problem1().minimumCost(intArrayOf(5,5)) println(res) } class Problem1 { fun minimumCost(cost: IntArray): Int { cost.sortDescending() var res = 0 var count = 0 for (i in cost) { if (count < 2) { count++ res += i } if (count == 2) { count++ continue } if (count > 2) { count = 0 } } return res } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
550
leetcode-kotlin
MIT License
app/src/main/java/com/muhammetkdr/mvvm_attemp_to_learn/roomdb/Converters.kt
mskdr
562,519,277
false
{"Kotlin": 42111}
package com.muhammetkdr.mvvm_attemp_to_learn.roomdb import androidx.room.TypeConverter import com.muhammetkdr.mvvm_attemp_to_learn.models.Source class Converters { @TypeConverter fun fromSource(source: Source?): String? { return source?.name } @TypeConverter fun toSource(name: String?): Source { return Source(name,name) } }
0
Kotlin
0
0
81f816ca922accf9dacbfe556ebdb675ccd9fe1b
368
NewsApp
MIT License
src/main/kotlin/behavioralPatterns/strategy/GameResultType.kt
takaakit
138,280,665
false
{"Kotlin": 89952}
package behavioralPatterns.strategy // ˅ // ˄ enum class GameResultType { Win, Loss, Draw; // ˅ // ˄ } // ˅ // ˄
0
Kotlin
0
11
ce3f7ca0ac87a9e09c1bcce5092922187c71d3bf
151
design-pattern-examples-in-kotlin
Creative Commons Zero v1.0 Universal
src/com/theah64/ugh/utils/InputUtils.kt
theapache64
169,757,452
false
{"Kotlin": 11954}
package com.theah64.ugh.utils import java.lang.NumberFormatException import java.util.* class InputUtils private constructor( private val scanner: Scanner ) { /** * Get a String with given prompt as prompt */ fun getString(prompt: String, isRequired: Boolean): String { print("$prompt: ") val value = scanner.nextLine() while (value.trim().isEmpty() && isRequired) { println("Invalid ${prompt.toLowerCase()} `$value`") return getString(prompt, isRequired) } return value } fun getInt(prompt: String, lowerBound: Int, upperBound: Int): Int { print("$prompt :") val sVal = scanner.nextLine() try { val value = sVal.toInt() if (value < lowerBound || value > upperBound) { println("Input must between $lowerBound and $upperBound") return getInt(prompt, lowerBound, upperBound) } return value } catch (e: NumberFormatException) { println("Invalid input `$sVal`") return getInt(prompt, lowerBound, upperBound) } } companion object { private var instance: InputUtils? = null fun getInstance(scanner: Scanner): InputUtils { if (instance == null) { instance = InputUtils(scanner) } return instance!! } } }
4
Kotlin
3
13
b7b4d42f3ee9fe5beb568dd69041fb685545871f
1,429
ugh
Apache License 2.0
HW5/src/test/kotlin/ru/otus/spring/kushchenko/hw5/service/ReaderServiceImplTest.kt
ElenaKushchenko
139,555,821
false
{"Kotlin": 821703, "HTML": 46397, "TypeScript": 32941, "CSS": 751, "Dockerfile": 203}
package ru.otus.spring.kushchenko.hw5.service import com.nhaarman.mockito_kotlin.doNothing import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.whenever import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import ru.otus.spring.kushchenko.hw5.model.Reader import ru.otus.spring.kushchenko.hw5.repository.ReaderRepository /** * Created by Елена on Авг., 2018 */ internal class ReaderServiceImplTest { private val repository: ReaderRepository = mock() private val service = ReaderServiceImpl(repository) @Test fun getAll() { val expected = listOf( Reader(1, "Reader1"), Reader(2, "Reader2") ) whenever(repository.getAll()).thenReturn(expected) assertEquals(expected, service.getAll()) verify(repository).getAll() verifyNoMoreInteractions(repository) } @Test fun get() { val expectedId = 1 val expected = Reader(expectedId, "Reader1") whenever(repository.get(expectedId)).thenReturn(expected) assertEquals(expected, service.get(expectedId)) verify(repository).get(expectedId) verifyNoMoreInteractions(repository) } @Test fun create() { val expected = Reader(1, "Reader1") whenever(repository.create(expected)).thenReturn(expected) assertEquals(expected, service.create(expected)) verify(repository).create(expected) verifyNoMoreInteractions(repository) } @Test fun update() { val expectedId = 1 val expected = Reader(expectedId, "Reader1") whenever(repository.update(expectedId, expected)).thenReturn(expected) assertEquals(expected, service.update(expectedId, expected)) verify(repository).update(expectedId, expected) verifyNoMoreInteractions(repository) } @Test fun delete() { val expectedId = 1 doNothing().whenever(repository).delete(expectedId) service.delete(expectedId) verify(repository).delete(expectedId) verifyNoMoreInteractions(repository) } }
0
Kotlin
0
0
0286627b4e66873c28d18174d125b63e5723e4f7
2,259
otus-spring-2018-06-hw
MIT License