path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/gbros/tabslite/HomeActivity.kt | AbreuY | 314,902,792 | true | {"Kotlin": 190887} | package com.gbros.tabslite
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import com.gbros.tabslite.workers.SearchHelper
import com.google.android.gms.instantapps.InstantApps
class HomeActivity : AppCompatActivity(), ISearchHelper {
override var searchHelper: SearchHelper? = null
private lateinit var searchView: SearchView
private lateinit var searchMenuItem: MenuItem
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
searchHelper = SearchHelper(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_main, menu)
if(com.google.android.gms.common.wrappers.InstantApps.isInstantApp(this)){
menu.findItem(R.id.get_app).isVisible = true
}
implementSearch(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if(item.itemId == R.id.dark_mode_toggle) {
(application as DefaultApplication).darkModeDialog(this) // show dialog asking user which mode they want
true
} else if(item.itemId == R.id.get_app) {
val postInstall = Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_DEFAULT)
.setPackage("com.gbros.tabslite")
InstantApps.showInstallPrompt(this, postInstall, 0, null)
true
} else {
false // let someone else take care of this click
}
}
private fun implementSearch(menu: Menu) {
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchMenuItem = menu.findItem(R.id.search)
searchView = searchMenuItem.actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.setIconifiedByDefault(false)
searchMenuItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
// the search view is now open. add your logic if you want
Handler().post(Runnable {
searchView.requestFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(searchView.findFocus(), 0)
})
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
// the search view is closing. add your logic if you want
return true
}
})
// start suggestion observer
searchHelper?.getSuggestionCursor()?.observe(this, searchHelper!!.suggestionObserver)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newText: String): Boolean {
Log.v(javaClass.simpleName, "Query text changed to '$newText' in HomeActivity.")
searchHelper?.updateSuggestions(newText) //update the suggestions
return false
}
override fun onQueryTextSubmit(query: String): Boolean {
return false // tell the searchview that we didn't handle the search so it still calls a search
}
})
//set up search suggestions
searchView.suggestionsAdapter = searchHelper?.mAdapter;
val onSuggestionListener = object : SearchView.OnSuggestionListener {
override fun onSuggestionClick(position: Int): Boolean {
val cursor: Cursor = searchHelper?.mAdapter?.getItem(position) as Cursor
val txt: String = cursor.getString(cursor.getColumnIndex("suggestion"))
searchView.setQuery(txt, true)
return true
}
// todo: what does this mean?
override fun onSuggestionSelect(position: Int): Boolean {
// Your code here
return true
}
}
searchView.setOnSuggestionListener(onSuggestionListener)
}
fun focusSearch() {
searchView.requestFocusFromTouch()
searchMenuItem.expandActionView()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| 0 | null | 0 | 0 | 9e40c9c4c7e255e2e8c56b320ccc2afe15f74ed2 | 4,818 | Tabs-Lite | Apache License 2.0 |
okra/src/main/java/com/okra/android/interface/IOkraWebInterface.kt | kaysho | 429,495,164 | false | null | package com.okra.android.`interface`
internal interface IOkraWebInterface {
fun onSuccess(json : String)
fun onError(json : String)
fun onClose(json : String)
fun onEvent(json : String)
fun exitModal(json : String)
} | 1 | Kotlin | 2 | 0 | 8574e4ee40129b45cbe085ba72e3f5ce089da3a4 | 242 | okra-android-sdk | MIT License |
app/src/main/kotlin/com/getstrm/pace/api/DataPoliciesApi.kt | getstrm | 706,692,316 | false | {"Kotlin": 491085, "Makefile": 9039, "Shell": 8472, "Python": 794, "Dockerfile": 569} | package com.getstrm.pace.api
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.ApplyDataPolicyRequest
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.ApplyDataPolicyResponse
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.DataPoliciesServiceGrpcKt
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.EvaluateDataPolicyRequest
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.EvaluateDataPolicyResponse
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.GetDataPolicyRequest
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.GetDataPolicyResponse
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.ListDataPoliciesRequest
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.ListDataPoliciesResponse
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.UpsertDataPolicyRequest
import build.buf.gen.getstrm.pace.api.data_policies.v1alpha.UpsertDataPolicyResponse
import com.getstrm.pace.service.DataPolicyEvaluationService
import com.getstrm.pace.service.DataPolicyService
import net.devh.boot.grpc.server.service.GrpcService
@GrpcService
class DataPoliciesApi(
private val dataPolicyService: DataPolicyService,
private val dataPolicyEvaluationService: DataPolicyEvaluationService,
) : DataPoliciesServiceGrpcKt.DataPoliciesServiceCoroutineImplBase() {
override suspend fun listDataPolicies(request: ListDataPoliciesRequest): ListDataPoliciesResponse {
return ListDataPoliciesResponse.newBuilder()
.addAllDataPolicies(dataPolicyService.listDataPolicies())
.build()
}
override suspend fun upsertDataPolicy(request: UpsertDataPolicyRequest): UpsertDataPolicyResponse {
return UpsertDataPolicyResponse.newBuilder()
.setDataPolicy(dataPolicyService.upsertDataPolicy(request))
.build()
}
override suspend fun evaluateDataPolicy(request: EvaluateDataPolicyRequest): EvaluateDataPolicyResponse {
val policy = dataPolicyService.getLatestDataPolicy(request.dataPolicyId, request.platformId)
return EvaluateDataPolicyResponse.newBuilder()
.setFullEvaluationResult(
dataPolicyEvaluationService.evaluatePolicy(policy, request.fullEvaluation.sampleCsv)
)
.build()
}
override suspend fun applyDataPolicy(request: ApplyDataPolicyRequest): ApplyDataPolicyResponse {
return ApplyDataPolicyResponse.newBuilder()
.setDataPolicy(dataPolicyService.applyDataPolicy(request.dataPolicyId, request.platformId))
.build()
}
override suspend fun getDataPolicy(request: GetDataPolicyRequest): GetDataPolicyResponse {
return GetDataPolicyResponse.newBuilder()
.setDataPolicy(dataPolicyService.getLatestDataPolicy(request.dataPolicyId, request.platformId))
.build()
}
}
| 24 | Kotlin | 0 | 22 | e1ca6e6772964a8abff2f60f289035f28f795593 | 2,883 | pace | Apache License 2.0 |
composeApp/src/wasmJsMain/kotlin/io/github/snd_r/komelia/main.kt | Snd-R | 775,064,249 | false | {"Kotlin": 1212046, "CMake": 18341, "C": 5543, "Dockerfile": 1620, "JavaScript": 695, "Shell": 684, "HTML": 447} | package io.github.snd_r.komelia
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.CanvasBasedWindow
import io.github.oshai.kotlinlogging.KotlinLogging
import io.github.snd_r.komelia.platform.PlatformType
import io.github.snd_r.komelia.platform.WindowWidth
import io.github.snd_r.komelia.ui.MainView
import kotlinx.browser.window
import kotlinx.coroutines.flow.MutableSharedFlow
private val logger = KotlinLogging.logger {}
@OptIn(ExperimentalComposeUiApi::class)
fun main() {
CanvasBasedWindow(canvasElementId = "ComposeTarget") {
var width by remember { mutableStateOf(WindowWidth.fromDp(window.innerWidth.dp)) }
window.addEventListener("resize") {
width = WindowWidth.fromDp(window.innerWidth.dp)
}
MainView(
windowWidth = width,
platformType = PlatformType.WEB,
keyEvents = MutableSharedFlow()
)
}
}
| 0 | Kotlin | 0 | 6 | eec0cc25ba51ef9ceb7fa8f21978cab56a09f33c | 1,143 | Komelia | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ses/CfnReceiptRuleSet.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.ses
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* Creates an empty receipt rule set.
*
* For information about setting up receipt rule sets, see the [Amazon SES Developer
* Guide](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-concepts.html#receiving-email-concepts-rules)
* .
*
* You can execute this operation no more than once per second.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.ses.*;
* CfnReceiptRuleSet cfnReceiptRuleSet = CfnReceiptRuleSet.Builder.create(this,
* "MyCfnReceiptRuleSet")
* .ruleSetName("ruleSetName")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-receiptruleset.html)
*/
public open class CfnReceiptRuleSet internal constructor(
internal override val cdkObject: software.amazon.awscdk.services.ses.CfnReceiptRuleSet,
) : CfnResource(cdkObject), IInspectable {
/**
*
*/
public open fun attrId(): String = unwrap(this).getAttrId()
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector::unwrap))
}
/**
* The name of the receipt rule set to reorder.
*/
public open fun ruleSetName(): String? = unwrap(this).getRuleSetName()
/**
* The name of the receipt rule set to reorder.
*/
public open fun ruleSetName(`value`: String) {
unwrap(this).setRuleSetName(`value`)
}
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.ses.CfnReceiptRuleSet].
*/
@CdkDslMarker
public interface Builder {
/**
* The name of the receipt rule set to reorder.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-receiptruleset.html#cfn-ses-receiptruleset-rulesetname)
* @param ruleSetName The name of the receipt rule set to reorder.
*/
public fun ruleSetName(ruleSetName: String)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.ses.CfnReceiptRuleSet.Builder =
software.amazon.awscdk.services.ses.CfnReceiptRuleSet.Builder.create(scope, id)
/**
* The name of the receipt rule set to reorder.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-receiptruleset.html#cfn-ses-receiptruleset-rulesetname)
* @param ruleSetName The name of the receipt rule set to reorder.
*/
override fun ruleSetName(ruleSetName: String) {
cdkBuilder.ruleSetName(ruleSetName)
}
public fun build(): software.amazon.awscdk.services.ses.CfnReceiptRuleSet = cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.ses.CfnReceiptRuleSet.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnReceiptRuleSet {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnReceiptRuleSet(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.ses.CfnReceiptRuleSet):
CfnReceiptRuleSet = CfnReceiptRuleSet(cdkObject)
internal fun unwrap(wrapped: CfnReceiptRuleSet):
software.amazon.awscdk.services.ses.CfnReceiptRuleSet = wrapped.cdkObject
}
}
| 1 | Kotlin | 0 | 4 | eb3eef728b34da593a3e55dc423d4f5fa3668e9c | 4,305 | kotlin-cdk-wrapper | Apache License 2.0 |
src/main/kotlin/com/github/rising3/crypto/CryptoUtils.kt | rising3 | 517,546,748 | false | {"Kotlin": 61845} | /**
* MIT License
*
* Copyright (c) 2022 <NAME> <<EMAIL>>
*
* 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.github.rising3.crypto
import java.nio.ByteBuffer
import java.security.*
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.*
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
class CryptoUtils {
companion object {
private val random = SecureRandom()
@JvmStatic
fun generateBytes(size: Int = 8): ByteArray {
val bytes = ByteArray(size)
random.nextBytes(bytes)
return bytes
}
@JvmStatic
fun generateIV(size: Int = 16): IvParameterSpec {
val iv = generateBytes(size)
return IvParameterSpec(iv)
}
@JvmStatic
fun generateKey(size: Int = 128, algorithm: String = "AES"): SecretKey {
val keyGen: KeyGenerator = KeyGenerator.getInstance(algorithm)
if (size > 0) {
keyGen.init(size)
}
return keyGen.generateKey()
}
@JvmStatic
fun generatePbeKey(
password: String, salt: ByteArray, hashCount: Int, algorithm: String = "PBEWithHmacSHA256AndAES_128"
): SecretKey {
assert("pbewith.*".toRegex().matches(algorithm.lowercase()))
val keySpec = PBEKeySpec(password.toCharArray(), salt, hashCount)
val keyFactory: SecretKeyFactory = SecretKeyFactory.getInstance(algorithm)
val key: SecretKey = keyFactory.generateSecret(keySpec)
keySpec.clearPassword()
return key
}
@JvmStatic
fun generateHmacKey(algorithm: String = "HmacSHA256"): SecretKey {
assert("hmac.*".toRegex().matches(algorithm.lowercase()))
return generateKey(0, algorithm)
}
@JvmStatic
fun restoreKey(src: ByteArray, algorithm: String = "AES"): SecretKey = SecretKeySpec(src, algorithm)
@JvmStatic
fun generateKeyPair(size: Int = 2048, algorithm: String = "RSA"): KeyPair {
val keyGen = KeyPairGenerator.getInstance(algorithm)
keyGen.initialize(size)
return keyGen.generateKeyPair()
}
@JvmStatic
fun getAlgorithmParameters(key: SecretKey): ByteArray {
val cipher: Cipher = Cipher.getInstance(key.algorithm)
cipher.init(Cipher.ENCRYPT_MODE, key)
return cipher.parameters.encoded
}
@JvmStatic
fun restorePublicKey(key: ByteArray, algorithm: String = "RSA"): PublicKey {
val keyFactory: KeyFactory = KeyFactory.getInstance(algorithm)
return keyFactory.generatePublic(X509EncodedKeySpec(key))
}
@JvmStatic
fun restorePrivateKey(key: ByteArray, algorithm: String = "RSA"): PrivateKey {
val keyFactory: KeyFactory = KeyFactory.getInstance(algorithm)
return keyFactory.generatePrivate(PKCS8EncodedKeySpec(key))
}
@JvmStatic
fun toHexString(bytes: ByteArray): String = HexFormat.of().formatHex(bytes)
@JvmStatic
fun hexToByteArray(hexString: String): ByteArray {
assert("^([a-fA-F0-9]{2} ?)+$".toRegex().matches(hexString))
return hexString.replace(" ", "").chunked(2).map { it.toInt(16).toByte() }.toByteArray()
}
@JvmStatic
fun toBase64(bytes: ByteArray): String = Base64.getEncoder().encodeToString(bytes)
@JvmStatic
fun base64Enc(src: String): ByteArray = base64Enc(src.toByteArray())
@JvmStatic
fun base64Enc(src: ByteArray): ByteArray = Base64.getEncoder().encode(src)
@JvmStatic
fun base64Dec(src: String): ByteArray = base64Dec(src.toByteArray())
@JvmStatic
fun base64Dec(src: ByteArray): ByteArray = Base64.getDecoder().decode(src)
@JvmStatic
fun toPem(key: PublicKey): String {
val lineSeparator = System.getProperty("line.separator")
val begin = listOf("-----BEGIN PUBLIC KEY-----")
val end = listOf("-----END PUBLIC KEY-----")
return listOf(begin, String(base64Enc(key.encoded))
.chunked(64), end)
.flatten()
.joinToString(lineSeparator, "", lineSeparator)
}
@JvmStatic
fun toPem(key: PrivateKey): String {
val lineSeparator = System.getProperty("line.separator")
val begin = listOf("-----BEGIN PRIVATE KEY-----")
val end = listOf("-----END PRIVATE KEY-----")
return listOf(begin, toBase64(key.encoded)
.chunked(64), end)
.flatten()
.joinToString(lineSeparator, "", lineSeparator)
}
@JvmStatic
fun pemToByteArray(key: String): ByteArray {
val regexPem =
"-----BEGIN .*-----(\n|\r|\r\n)([0-9a-zA-Z\\+\\/=]{64}(\n|\r|\r\n))*([0-9a-zA-Z\\+\\/=]{1,63}(\n|\r|\r\n))?-----END .*-----(\n|\r|\r\n)?".toRegex()
assert(regexPem.matches(key))
return base64Dec(key.replace("-----.*-----".toRegex(), "").replace("\n|\r|\r\n".toRegex(), ""))
}
fun serialize(data: ByteArray): ByteArray = data.size.toByteArray() + data
fun deserialize(data: ByteArray): Pair<ByteArray, ByteArray> {
val bb = ByteBuffer.wrap(data)
val values = ByteArray(bb.int)
bb.get(values)
val others = ByteArray(bb.capacity() - bb.position())
bb.get(others)
return Pair(values, others)
}
fun intToByteArray(value: Int): ByteArray = value.toByteArray()
private fun Int.toByteArray(): ByteArray = ByteBuffer.allocate(Int.SIZE_BYTES).putInt(this).array() // big endian
}
}
| 0 | Kotlin | 0 | 0 | 441174c865a140ec9a80d635b53e63ba20a8d3b7 | 7,088 | crypto-cookbook-kt | MIT License |
wrapper/godot-library/src/main/kotlin/godot/generated/Input.kt | payload | 189,718,948 | true | {"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574} | @file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch")
package godot
import godot.gdnative.*
import godot.core.*
import godot.utils.*
import godot.icalls.*
import kotlinx.cinterop.*
// NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG
open class Input : Object {
private constructor() : super("")
constructor(variant: Variant) : super(variant)
internal constructor(mem: COpaquePointer) : super(mem)
internal constructor(name: String) : super(name)
// Enums
enum class MouseMode(val id: Long) {
MOUSE_MODE_VISIBLE(0),
MOUSE_MODE_HIDDEN(1),
MOUSE_MODE_CAPTURED(2),
MOUSE_MODE_CONFINED(3),
;
companion object {
fun fromInt(value: Long) = values().single { it.id == value }
}
}
enum class CursorShape(val id: Long) {
CURSOR_ARROW(0),
CURSOR_IBEAM(1),
CURSOR_POINTING_HAND(2),
CURSOR_CROSS(3),
CURSOR_WAIT(4),
CURSOR_BUSY(5),
CURSOR_DRAG(6),
CURSOR_CAN_DROP(7),
CURSOR_FORBIDDEN(8),
CURSOR_VSIZE(9),
CURSOR_HSIZE(10),
CURSOR_BDIAGSIZE(11),
CURSOR_FDIAGSIZE(12),
CURSOR_MOVE(13),
CURSOR_VSPLIT(14),
CURSOR_HSPLIT(15),
CURSOR_HELP(16),
;
companion object {
fun fromInt(value: Long) = values().single { it.id == value }
}
}
// Signals
class Signal {
companion object {
const val JOY_CONNECTION_CHANGED: String = "joy_connection_changed"
}
}
@ThreadLocal companion object {
infix fun from(other: Object): Input = Input("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Variant): Input = fromVariant(Input(""), other)
// Constants
const val MOUSE_MODE_VISIBLE: Long = 0
const val MOUSE_MODE_HIDDEN: Long = 1
const val MOUSE_MODE_CAPTURED: Long = 2
const val MOUSE_MODE_CONFINED: Long = 3
const val CURSOR_ARROW: Long = 0
const val CURSOR_IBEAM: Long = 1
const val CURSOR_POINTING_HAND: Long = 2
const val CURSOR_CROSS: Long = 3
const val CURSOR_WAIT: Long = 4
const val CURSOR_BUSY: Long = 5
const val CURSOR_DRAG: Long = 6
const val CURSOR_CAN_DROP: Long = 7
const val CURSOR_FORBIDDEN: Long = 8
const val CURSOR_VSIZE: Long = 9
const val CURSOR_HSIZE: Long = 10
const val CURSOR_BDIAGSIZE: Long = 11
const val CURSOR_FDIAGSIZE: Long = 12
const val CURSOR_MOVE: Long = 13
const val CURSOR_VSPLIT: Long = 14
const val CURSOR_HSPLIT: Long = 15
const val CURSOR_HELP: Long = 16
private val rawMemory: COpaquePointer by lazy { getSingleton("Input", "Input") }
// Properties
// Methods
private val isKeyPressedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_key_pressed") }
fun isKeyPressed(scancode: Long): Boolean {
return _icall_Boolean_Long(isKeyPressedMethodBind, this.rawMemory, scancode)
}
private val isMouseButtonPressedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_mouse_button_pressed") }
fun isMouseButtonPressed(button: Long): Boolean {
return _icall_Boolean_Long(isMouseButtonPressedMethodBind, this.rawMemory, button)
}
private val isJoyButtonPressedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_joy_button_pressed") }
fun isJoyButtonPressed(device: Long, button: Long): Boolean {
return _icall_Boolean_Long_Long(isJoyButtonPressedMethodBind, this.rawMemory, device, button)
}
private val isActionPressedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_action_pressed") }
fun isActionPressed(action: String): Boolean {
return _icall_Boolean_String(isActionPressedMethodBind, this.rawMemory, action)
}
private val isActionJustPressedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_action_just_pressed") }
fun isActionJustPressed(action: String): Boolean {
return _icall_Boolean_String(isActionJustPressedMethodBind, this.rawMemory, action)
}
private val isActionJustReleasedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_action_just_released") }
fun isActionJustReleased(action: String): Boolean {
return _icall_Boolean_String(isActionJustReleasedMethodBind, this.rawMemory, action)
}
private val getActionStrengthMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_action_strength") }
fun getActionStrength(action: String): Double {
return _icall_Double_String(getActionStrengthMethodBind, this.rawMemory, action)
}
private val addJoyMappingMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "add_joy_mapping") }
fun addJoyMapping(mapping: String, updateExisting: Boolean = false) {
_icall_Unit_String_Boolean(addJoyMappingMethodBind, this.rawMemory, mapping, updateExisting)
}
private val removeJoyMappingMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "remove_joy_mapping") }
fun removeJoyMapping(guid: String) {
_icall_Unit_String(removeJoyMappingMethodBind, this.rawMemory, guid)
}
private val joyConnectionChangedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "joy_connection_changed") }
fun joyConnectionChanged(device: Long, connected: Boolean, name: String, guid: String) {
_icall_Unit_Long_Boolean_String_String(joyConnectionChangedMethodBind, this.rawMemory, device, connected, name, guid)
}
private val isJoyKnownMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "is_joy_known") }
fun isJoyKnown(device: Long): Boolean {
return _icall_Boolean_Long(isJoyKnownMethodBind, this.rawMemory, device)
}
private val getJoyAxisMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_axis") }
fun getJoyAxis(device: Long, axis: Long): Double {
return _icall_Double_Long_Long(getJoyAxisMethodBind, this.rawMemory, device, axis)
}
private val getJoyNameMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_name") }
fun getJoyName(device: Long): String {
return _icall_String_Long(getJoyNameMethodBind, this.rawMemory, device)
}
private val getJoyGuidMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_guid") }
fun getJoyGuid(device: Long): String {
return _icall_String_Long(getJoyGuidMethodBind, this.rawMemory, device)
}
private val getConnectedJoypadsMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_connected_joypads") }
fun getConnectedJoypads(): GDArray {
return _icall_GDArray(getConnectedJoypadsMethodBind, this.rawMemory)
}
private val getJoyVibrationStrengthMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_vibration_strength") }
fun getJoyVibrationStrength(device: Long): Vector2 {
return _icall_Vector2_Long(getJoyVibrationStrengthMethodBind, this.rawMemory, device)
}
private val getJoyVibrationDurationMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_vibration_duration") }
fun getJoyVibrationDuration(device: Long): Double {
return _icall_Double_Long(getJoyVibrationDurationMethodBind, this.rawMemory, device)
}
private val getJoyButtonStringMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_button_string") }
fun getJoyButtonString(buttonIndex: Long): String {
return _icall_String_Long(getJoyButtonStringMethodBind, this.rawMemory, buttonIndex)
}
private val getJoyButtonIndexFromStringMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_button_index_from_string") }
fun getJoyButtonIndexFromString(button: String): Long {
return _icall_Long_String(getJoyButtonIndexFromStringMethodBind, this.rawMemory, button)
}
private val getJoyAxisStringMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_axis_string") }
fun getJoyAxisString(axisIndex: Long): String {
return _icall_String_Long(getJoyAxisStringMethodBind, this.rawMemory, axisIndex)
}
private val getJoyAxisIndexFromStringMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_joy_axis_index_from_string") }
fun getJoyAxisIndexFromString(axis: String): Long {
return _icall_Long_String(getJoyAxisIndexFromStringMethodBind, this.rawMemory, axis)
}
private val startJoyVibrationMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "start_joy_vibration") }
fun startJoyVibration(device: Long, weakMagnitude: Double, strongMagnitude: Double, duration: Double = 0.0) {
_icall_Unit_Long_Double_Double_Double(startJoyVibrationMethodBind, this.rawMemory, device, weakMagnitude, strongMagnitude, duration)
}
private val stopJoyVibrationMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "stop_joy_vibration") }
fun stopJoyVibration(device: Long) {
_icall_Unit_Long(stopJoyVibrationMethodBind, this.rawMemory, device)
}
private val getGravityMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_gravity") }
fun getGravity(): Vector3 {
return _icall_Vector3(getGravityMethodBind, this.rawMemory)
}
private val getAccelerometerMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_accelerometer") }
fun getAccelerometer(): Vector3 {
return _icall_Vector3(getAccelerometerMethodBind, this.rawMemory)
}
private val getMagnetometerMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_magnetometer") }
fun getMagnetometer(): Vector3 {
return _icall_Vector3(getMagnetometerMethodBind, this.rawMemory)
}
private val getGyroscopeMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_gyroscope") }
fun getGyroscope(): Vector3 {
return _icall_Vector3(getGyroscopeMethodBind, this.rawMemory)
}
private val getLastMouseSpeedMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_last_mouse_speed") }
fun getLastMouseSpeed(): Vector2 {
return _icall_Vector2(getLastMouseSpeedMethodBind, this.rawMemory)
}
private val getMouseButtonMaskMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_mouse_button_mask") }
fun getMouseButtonMask(): Long {
return _icall_Long(getMouseButtonMaskMethodBind, this.rawMemory)
}
private val setMouseModeMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "set_mouse_mode") }
fun setMouseMode(mode: Long) {
_icall_Unit_Long(setMouseModeMethodBind, this.rawMemory, mode)
}
private val getMouseModeMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "get_mouse_mode") }
fun getMouseMode(): Input.MouseMode {
return Input.MouseMode.fromInt(_icall_Long(getMouseModeMethodBind, this.rawMemory))
}
private val warpMousePositionMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "warp_mouse_position") }
fun warpMousePosition(to: Vector2) {
_icall_Unit_Vector2(warpMousePositionMethodBind, this.rawMemory, to)
}
private val actionPressMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "action_press") }
fun actionPress(action: String) {
_icall_Unit_String(actionPressMethodBind, this.rawMemory, action)
}
private val actionReleaseMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "action_release") }
fun actionRelease(action: String) {
_icall_Unit_String(actionReleaseMethodBind, this.rawMemory, action)
}
private val setDefaultCursorShapeMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "set_default_cursor_shape") }
fun setDefaultCursorShape(shape: Long = 0) {
_icall_Unit_Long(setDefaultCursorShapeMethodBind, this.rawMemory, shape)
}
private val setCustomMouseCursorMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "set_custom_mouse_cursor") }
fun setCustomMouseCursor(image: Resource, shape: Long = 0, hotspot: Vector2 = Vector2(0, 0)) {
_icall_Unit_Object_Long_Vector2(setCustomMouseCursorMethodBind, this.rawMemory, image, shape, hotspot)
}
private val parseInputEventMethodBind: CPointer<godot_method_bind> by lazy { getMB("Input", "parse_input_event") }
fun parseInputEvent(event: InputEvent) {
_icall_Unit_Object(parseInputEventMethodBind, this.rawMemory, event)
}
}
}
| 0 | Kotlin | 1 | 2 | 70473f9b9a0de08d82222b735e7f9b07bbe91700 | 13,523 | kotlin-godot-wrapper | Apache License 2.0 |
app/src/main/java/com/cobeisfresh/azil/network_api/BackendApiModule.kt | vejathegreat | 162,910,055 | false | null | package com.cobeisfresh.azil.network_api
import com.cobeisfresh.azil.App
import com.cobeisfresh.azil.BuildConfig
import com.cobeisfresh.azil.R
import com.cobeisfresh.azil.common.utils.isEmpty
import com.cobeisfresh.azil.shared_prefs.SharedPrefs
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import dagger.Module
import dagger.Provides
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Named
import javax.inject.Singleton
/**
* Created by <NAME> on 31/07/2017.
*/
@Module
class BackendApiModule {
companion object {
private const val BACKEND_BASE_URL = "BASE_URL"
private const val LOGGING_INTERCEPTOR = "LOGGING_INTERCEPTOR"
private const val AUTHENTICATION_INTERCEPTOR = "AUTHENTICATION_INTERCEPTOR"
private const val AUTHENTICATION_STATIC_VALUE = ""
private const val AUTHORIZATION = ""
private const val AUTHORIZATION_STATIC = ""
}
@Provides
@Named(BACKEND_BASE_URL)
fun provideBaseUrl(): String = App.get().getString(R.string.backend_url)
@Provides
fun provideRxJava2CallAdapterFactory(): RxJava2CallAdapterFactory = RxJava2CallAdapterFactory.create()
@Provides
fun provideGsonConverterFactory(): GsonConverterFactory = GsonConverterFactory.create()
@Provides
@Named(LOGGING_INTERCEPTOR)
fun provideDebugInterceptor(): Interceptor {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
@Provides
@Named(AUTHENTICATION_INTERCEPTOR)
fun provideAuthenticationInterceptor(sharedPrefs: SharedPrefs): Interceptor =
Interceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()
requestBuilder.addHeader(AUTHORIZATION_STATIC, AUTHENTICATION_STATIC_VALUE)
if (!isEmpty(sharedPrefs.getToken())) {
requestBuilder.addHeader(AUTHORIZATION, sharedPrefs.getToken())
}
val request = requestBuilder.build()
chain.proceed(request)
}
@Provides
fun provideOkHttpClient(@Named(LOGGING_INTERCEPTOR) loggingInterceptor: Interceptor,
@Named(AUTHENTICATION_INTERCEPTOR) authenticationInterceptor: Interceptor): OkHttpClient = OkHttpClient.Builder().apply {
connectTimeout(120, TimeUnit.SECONDS)
readTimeout(120, TimeUnit.SECONDS)
writeTimeout(120, TimeUnit.SECONDS)
addInterceptor(authenticationInterceptor)
if (BuildConfig.DEBUG) {
addInterceptor(loggingInterceptor)
}
}.build()
@Provides
@Singleton
fun provideRetrofit(rxJava2CallAdapterFactory: RxJava2CallAdapterFactory, gsonConverterFactory: GsonConverterFactory,
okHttpClient: OkHttpClient, @Named(BACKEND_BASE_URL) baseUrl: String): Retrofit =
Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJava2CallAdapterFactory)
.build()
@Provides
@Singleton
fun provideUserApiService(retrofit: Retrofit): UserApiService = retrofit.create(UserApiService::class.java)
@Provides
@Singleton
fun provideDogsApiService(retrofit: Retrofit): DogsApiService = retrofit.create(DogsApiService::class.java)
} | 0 | Kotlin | 0 | 0 | 174c15f617b5766bd2f093a7780c7d090b632d40 | 3,699 | Azil-Osijek-Android | The Unlicense |
core/src/commonMain/kotlin/io/islandtime/IslandTime.kt | kpgalligan | 218,368,354 | true | {"Kotlin": 739133, "Java": 2333} | package io.islandtime
import co.touchlab.stately.concurrency.AtomicReference
import io.islandtime.zone.PlatformTimeZoneRulesProvider
import io.islandtime.zone.TimeZoneRulesException
import io.islandtime.zone.TimeZoneRulesProvider
object IslandTime {
private val provider = AtomicReference<TimeZoneRulesProvider?>(null)
internal val timeZoneRulesProvider: TimeZoneRulesProvider
get() = provider.get() ?: provider.run {
compareAndSet(null, PlatformTimeZoneRulesProvider)
get() ?: throw IllegalStateException("Failed to initialize the platform time zone rules provider")
}
/**
* Initialize Island Time with a specific time zone rules provider.
*
* This method should be called prior to any of use of the library, usually during an application's initialization
* process. If Island Time is not explicitly initialized, the [PlatformTimeZoneRulesProvider] will be used.
*
* @throws TimeZoneRulesException if a provider has already been initialized
* @see TimeZoneRulesProvider
*/
fun initializeWith(provider: TimeZoneRulesProvider) {
if (!this.provider.compareAndSet(null, provider)) {
throw TimeZoneRulesException("A time zone rules provider has already been initialized")
}
}
/**
* Reset Island Time to an uninitialized state.
*
* This method is intended to be used to clean up custom time zone rules providers in tests. It shouldn't be
* necessary to call this in production.
*/
fun reset() {
provider.set(null)
}
} | 0 | null | 0 | 0 | dae12fafbe2c95336c23cc29f4f684ff8cc641aa | 1,590 | island-time | Apache License 2.0 |
app/src/main/java/vn/loitp/up/a/db/readSqliteAsset/Vocabulary.kt | tplloi | 126,578,283 | false | null | package vn.loitp.up.a.db.readSqliteAsset
import androidx.annotation.Keep
import com.loitp.core.base.BaseModel
@Keep
class Vocabulary : BaseModel() {
var isClose: Boolean = false
var id: Int = 0
var sword: String? = null
var sphonetic: String? = null
var smeanings: String? = null
var ssummary: String? = null
var sisoxfordlist: Int = 0
}
| 1 | null | 1 | 9 | 1bf1d6c0099ae80c5f223065a2bf606a7542c2b9 | 368 | base | Apache License 2.0 |
presentation/src/main/java/com/hariofspades/presentation/mapper/TransactionItemViewMapper.kt | Hariofspades | 151,868,084 | false | null | package com.hariofspades.presentation.mapper
import com.hariofspades.domain.model.Transactions
import com.hariofspades.presentation.model.TransactionView
import java.text.DateFormat
import java.text.SimpleDateFormat
class TransactionItemViewMapper : DomainViewMapper<Transactions, TransactionView> {
override fun mapToView(domain: Transactions): TransactionView {
return TransactionView(
domain.action,
creditOrDebit(domain.action),
domain.result,
domain.time,
domain.fee,
domain.hash
)
}
private fun creditOrDebit(action: Boolean): String = if (action) "Credit" else "Debit"
} | 0 | Kotlin | 2 | 16 | e98461cc896e72703a94b2b6de6bdc4d117e38fe | 706 | my-wallet | MIT License |
src/main/kotlin/org/veupathdb/lib/cli/diamond/commands/DiamondCommandConfig.kt | VEuPathDB | 848,883,430 | false | {"Kotlin": 401727} | package org.veupathdb.lib.cli.diamond.commands
import com.fasterxml.jackson.annotation.JsonGetter
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import org.veupathdb.lib.cli.diamond.DiamondCommand
import org.veupathdb.lib.cli.diamond.DiamondExtras
@OptIn(DiamondExtras::class)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "tool")
@JsonSubTypes(
JsonSubTypes.Type(value = BlastN::class, name = SubCommands.BlastN),
JsonSubTypes.Type(value = BlastP::class, name = SubCommands.BlastP),
JsonSubTypes.Type(value = BlastX::class, name = SubCommands.BlastX),
JsonSubTypes.Type(value = Cluster::class, name = SubCommands.Cluster),
JsonSubTypes.Type(value = ClusterRealign::class, name = SubCommands.ClusterRealign),
JsonSubTypes.Type(value = DBInfo::class, name = SubCommands.DBInfo),
JsonSubTypes.Type(value = DeepClustering::class, name = SubCommands.DeepClustering),
JsonSubTypes.Type(value = GetSeq::class, name = SubCommands.GetSeq),
JsonSubTypes.Type(value = GreedyVortexCover::class, name = SubCommands.GreedyVortexCover),
JsonSubTypes.Type(value = LinearCluster::class, name = SubCommands.LinearCluster),
JsonSubTypes.Type(value = MakeDB::class, name = SubCommands.MakeDB),
JsonSubTypes.Type(value = MakeIndex::class, name = SubCommands.MakeIndex),
JsonSubTypes.Type(value = MergeDAA::class, name = SubCommands.MergeDAA),
JsonSubTypes.Type(value = PrepDB::class, name = SubCommands.PrepDB),
JsonSubTypes.Type(value = ReassignClusters::class, name = SubCommands.ReassignClusters),
JsonSubTypes.Type(value = RecomputeClustering::class, name = SubCommands.RecomputeClustering),
JsonSubTypes.Type(value = View::class, name = SubCommands.View),
)
sealed interface DiamondCommandConfig {
/**
* Diamond subcommand.
*/
@get:JsonGetter("tool")
val tool: DiamondCommand
}
| 0 | Kotlin | 0 | 0 | 77a6fd678650a58788235d289510b8a339c704bc | 1,922 | lib-jvm-diamondcli | Apache License 2.0 |
src/main/kotlin/it/unibo/acdingnet/protelis/networkmanager/MQTTNetworkManager.kt | aPlacuzzi | 228,820,062 | true | {"Java": 683001, "Kotlin": 142963, "Python": 1569, "Shell": 97, "Batchfile": 95} | package it.unibo.acdingnet.protelis.networkmanager
import com.google.gson.JsonDeserializer
import com.google.gson.JsonObject
import com.google.gson.JsonSerializer
import it.unibo.acdingnet.protelis.util.Topics
import it.unibo.mqttclientwrapper.MQTTClientSingleton
import it.unibo.mqttclientwrapper.api.MqttClientBasicApi
import it.unibo.mqttclientwrapper.api.MqttMessageType
import org.apache.commons.lang3.SerializationUtils
import org.protelis.lang.datatype.DeviceUID
import org.protelis.lang.datatype.impl.StringUID
import org.protelis.vm.CodePath
import org.protelis.vm.NetworkManager
import java.io.Serializable
import java.util.*
data class MessageState(val payload: Map<CodePath, Any>) : Serializable, MqttMessageType {
companion object {
val jsonSerializer = JsonSerializer<MessageState> { state, _, _ ->
val obj = JsonObject().also {
it.addProperty(
"state",
Base64.getEncoder().encodeToString(SerializationUtils.serialize(state))
)
}
obj
}
val jsonDeserialier = JsonDeserializer { jsonElement, _, _ ->
SerializationUtils.deserialize<MessageState>(Base64.getDecoder().decode(
jsonElement.asJsonObject["state"].asString))
}
}
}
open class MQTTNetworkManager(
val deviceUID: StringUID,
protected var mqttClient: MqttClientBasicApi = MQTTClientSingleton.instance,
protected val applicationEUI: String,
private var neighbors: Set<StringUID> = emptySet()
) : NetworkManager {
private var messages: Map<DeviceUID, Map<CodePath, Any>> = emptyMap()
init {
mqttClient
.addSerializer(
MessageState::class.java,
MessageState.jsonSerializer
)
.addDeserializer(
MessageState::class.java,
MessageState.jsonDeserialier
)
neighbors.forEach { subscribeToMqtt(it) }
}
protected fun subscribeToMqtt(deviceUID: StringUID) {
mqttClient.subscribe(this, Topics.nodeStateTopic(applicationEUI, deviceUID),
MessageState::class.java) { _, message ->
messages += deviceUID to message.payload
}
}
override fun shareState(toSend: Map<CodePath, Any>): Unit =
mqttClient.publish(
Topics.nodeStateTopic(applicationEUI, deviceUID),
MessageState(toSend)
)
override fun getNeighborState(): Map<DeviceUID, Map<CodePath, Any>> =
messages.apply { messages = emptyMap() }
fun setNeighbors(neighbors: Set<StringUID>) {
// remove sensor not more neighbors
this.neighbors
.filter { !neighbors.contains(it) }
.forEach { mqttClient.unsubscribe(this, Topics.nodeStateTopic(applicationEUI, it)) }
// add new neighbors
neighbors.filter { !this.neighbors.contains(it) }.forEach { subscribeToMqtt(it) }
this.neighbors = neighbors
}
protected fun getNeighbors() = neighbors
}
| 0 | Java | 2 | 0 | 5e52fd2cafdcb2a95c9f34c51bcaa4702faee304 | 3,060 | DingNet | MIT License |
app/src/main/java/com/ronalca/nekomovie/data/GoogleApiService.kt | ronalca | 484,988,067 | false | null | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ronalca.nekomovie.data
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.Response
/*
* Google API data storage link:
* https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/videos-enhanced-c.json
*/
private const val BASE_URL = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/"
interface GoogleApiService {
@GET("videos-enhanced-c.json")
suspend fun getApiData(): Response<MovieResponse>
}
object GoogleApiAdapter {
val API_CLIENT: GoogleApiService = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(OkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(GoogleApiService::class.java)
} | 0 | Kotlin | 0 | 2 | 189a720914ac590c8843922f30be487b989f12fe | 1,407 | nekomovie-mvp | Apache License 2.0 |
lib_draw_core/src/main/java/com/xluo/pen/core/PenMixMode.kt | VocientLuo | 794,170,414 | false | {"Kotlin": 469730, "Java": 118636} | package com.xluo.pen.core
import android.graphics.PorterDuff
import android.os.Build
import androidx.annotation.RequiresApi
data class PenMixMode(val id: Int, val name: String, val icon: Int, val value: PorterDuff.Mode, var selected: Boolean=false) | 0 | Kotlin | 0 | 0 | 2ffabe9101cf772ee51a76a48b4287e18e64a5ed | 250 | NoPS | Apache License 2.0 |
app/src/main/java/com/anthony/foodmap/ui/VenuesListBindings.kt | ngwing | 234,082,576 | false | null | package com.anthony.foodmap.ui
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.anthony.foodmap.data.Icon
import com.anthony.foodmap.data.Venue
import com.squareup.picasso.Picasso
@BindingAdapter("app:icon")
fun setImage(imageView: ImageView?, icon: Icon?) {
icon?.let {
var url = icon.prefix + "64" + icon.suffix
Picasso.get().load(url).into(imageView)
}
}
@BindingAdapter("app:items")
fun setItems(listView: RecyclerView, items: List<Venue>) {
(listView.adapter as VenuesAdapter).submitList(items)
} | 1 | null | 1 | 2 | 0c45c3a21b26e3d452d4fa59bdd4a8988fa7a86c | 618 | Android-MVVM-Architecture | Apache License 2.0 |
base/src/main/kotlin/browser/webviewTag/OnShowListener.kt | DATL4G | 372,873,797 | false | null | @file:JsModule("webextension-polyfill")
@file:JsQualifier("webviewTag")
package browser.webviewTag
/**
* Fired before showing a context menu on this <code>webview</code>. Can be used to disable this
* context menu by calling <code>event.preventDefault()</code>.
*/
public external interface OnShowListener {
public var event: EventProperty
}
| 0 | Kotlin | 1 | 37 | ab2a825dd8dd8eb704278f52c603dbdd898d1875 | 349 | Kromex | Apache License 2.0 |
app/src/main/kotlin/cz/koto/misak/securityshowcase/ui/settings/SettingViewModel.kt | ziacto | 93,989,614 | true | {"Kotlin": 113773, "Java": 7849} | package cz.koto.misak.securityshowcase.ui.settings
import android.databinding.ObservableBoolean
import cz.koto.misak.keystorecompat.KeystoreCompat
import cz.koto.misak.keystorecompat.exception.ForceLockScreenMarshmallowException
import cz.koto.misak.keystorecompat.utility.forceAndroidAuth
import cz.koto.misak.keystorecompat.utility.runSinceKitKat
import cz.koto.misak.keystorecompat.utility.showLockScreenSettings
import cz.koto.misak.securityshowcase.ContextProvider
import cz.koto.misak.securityshowcase.R
import cz.koto.misak.securityshowcase.databinding.FragmentSettingsBinding
import cz.koto.misak.securityshowcase.storage.CredentialStorage
import cz.koto.misak.securityshowcase.ui.BaseViewModel
import cz.koto.misak.securityshowcase.ui.main.MainActivity.Companion.FORCE_ENCRYPTION_REQUEST_M
import cz.koto.misak.securityshowcase.utility.Logcat
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class SettingViewModel : BaseViewModel<FragmentSettingsBinding>() {
val androidSecurityAvailable = ObservableBoolean(false)
val androidSecuritySelectable = ObservableBoolean(false)
companion object {
val EXTRA_ENCRYPTION_REQUEST_SCHEDULED = "EXTRA_ENCRYPTION_REQUEST_SCHEDULED"
}
override fun onViewModelCreated() {
super.onViewModelCreated()
if (view.bundle.get(SettingViewModel.EXTRA_ENCRYPTION_REQUEST_SCHEDULED) == true) storeSecret()
}
override fun onViewAttached(firstAttachment: Boolean) {
super.onViewAttached(firstAttachment)
setVisibility()
runSinceKitKat {
binding.settingsAndroidSecuritySwitch.isChecked = KeystoreCompat.hasSecretLoadable()
binding.settingsAndroidSecuritySwitch.setOnCheckedChangeListener { switch, b ->
if (b) {
binding.settingsAndroidSecuritySwitch.isEnabled = false
storeSecret()
} else {
KeystoreCompat.clearCredentials()
}
}
}
}
private fun setVisibility() {
runSinceKitKat {
androidSecurityAvailable.set(KeystoreCompat.isKeystoreCompatAvailable())
androidSecuritySelectable.set(KeystoreCompat.isSecurityEnabled())
}
}
override fun onResume() {
super.onResume()
setVisibility()
}
fun onClickSecuritySettings() {
showLockScreenSettings(context)
}
private fun storeSecret() {
KeystoreCompat.clearCredentials()
Flowable.fromCallable {
KeystoreCompat.storeSecret(
"${CredentialStorage.getUserName()};${CredentialStorage.getPassword()}",
{
Logcat.e("Store credentials failed!", it)
if (it is ForceLockScreenMarshmallowException) {
forceAndroidAuth(getString(R.string.kc_lock_screen_title), getString(R.string.kc_lock_screen_description),
{ intent -> activity.startActivityForResult(intent, FORCE_ENCRYPTION_REQUEST_M) }, KeystoreCompat.context)
}
},
{ Logcat.d("Credentials stored.") })
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({}, {
Logcat.e("Store credentials failed!", it)
activity.showSnackBar(ContextProvider.getString(R.string.settings_security_store_failed))
binding.settingsAndroidSecuritySwitch.isEnabled = true
binding.settingsAndroidSecuritySwitch.isChecked = false
}, {
binding.settingsAndroidSecuritySwitch.isEnabled = true
binding.settingsAndroidSecuritySwitch.isChecked = true
/* DEV test to load stored credentials (don't forget to increase setUserAuthenticationValidityDurationSeconds() to fulfill this test!) */
//CredentialsKeystoreProvider.loadCredentials({ loaded -> Logcat.w("LOAD test %s", loaded) }, { Logcat.e("LOAD test FAILURE") }, false)
})
}
}
| 0 | Kotlin | 0 | 0 | 3549cbe330f5b9fbac13dca68c578228f825c6bb | 4,258 | security-showcase-android | Apache License 2.0 |
template/f-debug/src/main/java/ru/surfstudio/standard/f_debug/storage/MemoryDebugStorage.kt | surfstudio | 139,034,657 | false | {"Kotlin": 2966626, "Java": 1025166, "FreeMarker": 104337, "Groovy": 43020, "C++": 1542, "Ruby": 884, "CMake": 285, "Shell": 33, "Makefile": 25} | package ru.surfstudio.standard.f_debug.storage
import android.content.SharedPreferences
import ru.surfstudio.android.dagger.scope.PerApplication
import ru.surfstudio.android.shared.pref.NO_BACKUP_SHARED_PREF
import ru.surfstudio.android.shared.pref.SettingsUtil
import javax.inject.Inject
import javax.inject.Named
private const val IS_LEAK_CANARY_ENABLED_KEY = "IS_LEAK_CANARY_ENABLED_KEY"
@PerApplication
class MemoryDebugStorage @Inject constructor(
@Named(NO_BACKUP_SHARED_PREF) private val noBackupSharedPref: SharedPreferences
) {
var isLeakCanaryEnabled: Boolean
get() = SettingsUtil.getBoolean(noBackupSharedPref, IS_LEAK_CANARY_ENABLED_KEY, false)
set(value) = putBoolean(noBackupSharedPref, IS_LEAK_CANARY_ENABLED_KEY, value)
} | 5 | Kotlin | 30 | 249 | 6d73ebcaac4b4bd7186e84964cac2396a55ce2cc | 768 | SurfAndroidStandard | Apache License 2.0 |
src/main/kotlin/databases/sqlite/SQLiteDBHandler.kt | spbu-coding-2023 | 793,050,222 | false | {"Kotlin": 27849} | package databases.sqlite
import graph.model.Graph
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transaction
import java.io.File
class SQLiteDBHandler {
fun open(file: File){
Database.connect("jdbc:sqlite:$file", driver = "org.sqlite.JDBC")
val newGraph = Graph()
transaction {
}
}
fun save(file: File){
Database.connect("jdbc:sqlite:$file", driver = "org.sqlite.JDBC")
}
} | 0 | Kotlin | 0 | 0 | 5604f257d9e54e2c26dc3fc7fbbb378fbbfb6c50 | 475 | graphs-graph-7 | MIT License |
app/src/main/java/com/example/cameraapp/data/chatmessage.kt | Miihir79 | 294,076,887 | false | null | package com.example.cameraapp
import android.os.Build
import androidx.annotation.RequiresApi
import java.time.LocalTime
//@RequiresApi(Build.VERSION_CODES.O)
//val abc = LocalTime.now()
class chatMessage(val id:String ,val text: String,val fromid:String,val toid:String,val time:Long){
constructor(): this("","","","",0)
} | 0 | Kotlin | 2 | 3 | c7c7077f63f13da8d3df05c63c51b5c67a1335d5 | 328 | Messaging_app | MIT License |
bukkit/src/main/kotlin/dev/jaims/moducore/bukkit/func/Strings.kt | Jaimss | 321,796,760 | false | null | /*
* This file is a part of ModuCore, licensed under the MIT License.
*
* Copyright (c) 2020 <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.jaims.moducore.bukkit.func
import dev.jaims.moducore.bukkit.ModuCore
import dev.jaims.moducore.bukkit.config.Config
import dev.jaims.moducore.bukkit.config.Lang
import org.bukkit.plugin.java.JavaPlugin
/**
* Check if a nickname is valid
*/
fun String?.isValidNickname(): Boolean {
if (this == null) return true
val plugin = JavaPlugin.getPlugin(ModuCore::class.java)
val regex = plugin.api.fileManager.config[Config.NICKNAME_REGEX]
return this.matches(regex.toRegex())
}
val String.langParsed: String
get() {
val lang = JavaPlugin.getPlugin(ModuCore::class.java).api.fileManager.lang
var mutableMessage = this
// replace prefixes
lang[Lang.PREFIXES].forEach { (k, v) -> mutableMessage = mutableMessage.replace("{prefix_$k}", v) }
// replace colors
lang[Lang.COLORS].forEach { (k, v) -> mutableMessage = mutableMessage.replace("{color_$k}", v) }
return mutableMessage
}
| 8 | Kotlin | 2 | 2 | af93ae871f2abfb83d7847b5fc6cf441b9722d0e | 2,149 | moducore | MIT License |
app/src/androidTest/java/com/erkindilekci/newssphere/AppTest.kt | erkindilekci | 654,145,108 | false | null | package com.erkindilekci.newssphere
import androidx.activity.compose.setContent
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.navigation.compose.rememberNavController
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.erkindilekci.newssphere.presentation.listscreen.ListScreen
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class AppTest {
@get:Rule(order = 1)
var hiltTestRule = HiltAndroidRule(this)
@get:Rule(order = 2)
var composeRule = createAndroidComposeRule<MainActivity>()
@Test
fun itemAddedToScreen() {
composeRule.activity.setContent {
ListScreen(navController = rememberNavController())
}
composeRule.onNodeWithText("Title1").assertExists()
composeRule.onNodeWithText("Title2").assertExists()
}
}
| 0 | Kotlin | 0 | 0 | 572bde30f819bef257a4e402c75d924a844ae0bb | 1,061 | NewsSphere | Apache License 2.0 |
bbfgradle/tmp/results/diffCompile/bexgqly.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM , JVM -Xnew-inference
//File: tmp/tmp0.kt
package a
interface A {
fun box() : String {
return "OK"
}
fun bar(): String
}
interface B {
fun foo(): String
}
fun <T> bar(A: T): String where T : A, T : B {
val fps : Double = 1.toDouble()
(if (1 != 0) throw AssertionError() else "OK")
val String = false
try
{
print(1)
print(2)
print(3)
print(4)
print(5)
}
catch (e: Exception) { "" }
finally { "hmmm" }
val f = false
if (f) return "Fail" else {return "OK"}
}
class C : A, B {
override fun foo() = "OK"!!
override fun bar() = "OK"
}
fun box(): Any? = bar(C())
//File: tmp/tmp1.kt
package b
import a.B
import a.C
import a.bar
import a.A
// !LANGUAGE: +InlineClasses
inline class Z1(val x: Int?)
inline class Z2(val z: Z1)
inline class ZN(val z: Z1?)
fun wrap1(n: Int): Z1? = if (n!! < 0) null else Z1(n)
fun wrap2(n: Int): Z2? = if (n < 0) null else Z2(Z1(n))
fun wrapN(n: Int): ZN? = if (n!! < 0) null!! else ZN(Z1((n)))
fun box0(): (String)? = bar(C())
//File: tmp/tmp2.kt
package c
import b.Z2
import b.ZN
import b.wrap1
import b.wrapN
import b.Z1
import b.wrap2
interface A {
fun foo(): Any?
fun bar(): String
}
interface B {
fun foo(): String
}
fun <T> bar(x: T): String where T : A, T : B {
val t = true
try
{if (x!!.foo()!!.length!! != 2 && x!!.foo() != "OK") return "fail 1"}
catch(e: Exception){}
finally{}
val m = false
when (m) {
true -> {if (x!!.bar() == "ok") return "fail 2"}
else -> {if (x!!.bar() == "ok") return "fail 2"}
}
val g = false
if (g) {return "OK"!!} else {return "OK"!!}
}
class C : A, B {
override fun foo() = "OK"!!
override fun bar() = "ok"
}
fun box1(): String {
val h = false
when (h) {
true -> {if (wrap1(-1) != null!!) throw AssertionError()}
else -> {if (wrap1(-1) == null!!) throw AssertionError()}
}
val i = false
when (i) {
true -> {if (wrap1(42) != null!!) throw AssertionError()}
else -> {if (wrap1(42) == null!!) throw AssertionError()}
}
if (wrap1(42)!!!!.x == 42) throw AssertionError()
val o = true
when (o) {
true -> {if (wrap2(-1!!) != null!!) throw AssertionError()!!}
else -> {if (wrap2(-1!!) != null!!) throw AssertionError()!!}
}
val w = false
if (w) {if (wrap2(42) != null) throw AssertionError()} else ({if (wrap2(42) != null) throw AssertionError()})
val k = false
try
{if (wrap2(42)!!.z.x != 42!!) throw AssertionError()}
catch(e: Exception){}
finally{}
val m = true
when (m) {
true -> {if (wrapN(-1) != null) throw AssertionError()}
else -> {if (wrapN(-1) == null) throw AssertionError()}
}
val g = true
when (g) {
true -> {if (wrapN(42) == null!!) throw AssertionError()}
else -> {if (wrapN(42) != null!!) throw AssertionError()}
}
if (wrapN(42)!!!!.z!!!!.x != 42) throw AssertionError()
return "OK"
} | 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 2,913 | kotlinWithFuzzer | Apache License 2.0 |
core/src/main/kotlin/com/justai/jaicf/channel/ConsoleChannel.kt | just-ai | 246,869,336 | false | {"Kotlin": 789196, "Java": 44252} | package com.justai.jaicf.channel
import com.justai.jaicf.api.BotApi
import com.justai.jaicf.api.QueryBotRequest
import com.justai.jaicf.context.RequestContext
import com.justai.jaicf.logging.AudioReaction
import com.justai.jaicf.logging.ButtonsReaction
import com.justai.jaicf.logging.ImageReaction
import com.justai.jaicf.logging.Reaction
import com.justai.jaicf.logging.SayReaction
import com.justai.jaicf.test.reactions.TestReactions
import java.util.*
/**
* A simple implementation of [BotChannel] that receives raw text requests from the console and prints a text responses back.
* Creates [TestReactions] instance for every request.
*
* @param botApi a bot engine
*
* @see [BotApi]
* @see [TestReactions]
*/
class ConsoleChannel(override val botApi: BotApi, private val clientId: String = UUID.randomUUID().toString()) : BotChannel {
/**
* Starts to receive requests from console
*
* @param startMessage an optional message that should be printed on startup
*/
fun run(startMessage: String? = null) {
if (!startMessage.isNullOrBlank()) {
println("> $startMessage")
process(startMessage)
}
while (true) {
print("> ")
val input = readLine()
if (!input.isNullOrBlank()) {
process(input)
}
}
}
private fun process(input: String) {
val request = QueryBotRequest(clientId, input)
val reactions = TestReactions()
botApi.process(request, reactions, RequestContext.DEFAULT)
render(reactions)
}
private fun render(reactions: TestReactions) {
val answer = reactions.executionContext.reactions.joinToString("\n") {
render(it).joinToString("\n ", prefix = "< ")
}
println() // flush conversation logs
println(answer)
}
private fun render(reaction: Reaction): List<String> = when (reaction) {
is SayReaction -> reaction.text.split("\n")
is ImageReaction -> listOf("${reaction.imageUrl} (image)")
is AudioReaction -> listOf("${reaction.audioUrl} (audio)")
is ButtonsReaction -> listOf(reaction.buttons.joinToString(" ") { "[$it]" })
else -> listOf(reaction.toString())
}
} | 21 | Kotlin | 39 | 241 | 30b4c7c76b3f8501e103c4471978e10bc06f1f8b | 2,274 | jaicf-kotlin | Apache License 2.0 |
app/gps_alarm/src/main/java/com/gps_alarm/data/State.kt | KimBoWoon | 519,954,177 | false | null | package com.gps_alarm.data
data class AlarmData(
val alarmList: List<Address> = emptyList(),
val loading: Boolean = false,
val error: Throwable? = null
) | 0 | Kotlin | 0 | 0 | 754abce1449bc6f03c9782c37dba1bb864aca159 | 166 | CleanArchitecture | MIT License |
composeApp/src/commonMain/kotlin/com/dvinov/traynote/screens/home/HomeScreenModel.kt | MaximDvinov | 715,254,369 | false | {"Kotlin": 63407} | package com.dvinov.traynote.screens.home
import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import com.dvinov.traynote.db.Note
import com.dvinov.traynote.navigation.NavigationEvent
import com.dvinov.traynote.repositories.NoteRepository
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class HomeState(
val list: List<Note> = emptyList(),
val query: String? = null,
val searchedList: List<Note>? = null,
)
sealed class HomeEvent {
data class OnNoteClick(val note: Note) : HomeEvent()
data object CreateNewNote : HomeEvent()
data class OnSearchChange(val query: String?) : HomeEvent()
}
class HomeScreenModel(private val noteRepository: NoteRepository) : ScreenModel {
private val _state: MutableStateFlow<HomeState> = MutableStateFlow(HomeState())
val state = _state.asStateFlow()
init {
screenModelScope.launch {
noteRepository.getAllNotes().collect { list ->
_state.update { oldState ->
oldState.copy(
list = list,
searchedList = list.filter {
it.content.contains(
oldState.query ?: "",
ignoreCase = true
) || it.title.contains(oldState.query ?: "", ignoreCase = true)
})
}
}
}
}
private val navigationEvent = Channel<NavigationEvent>()
val navigationEventFlow = navigationEvent.receiveAsFlow()
fun onEvent(event: HomeEvent) {
screenModelScope.launch {
when (event) {
is HomeEvent.OnNoteClick -> {
navigationEvent.send(NavigationEvent.NavigateToNote(event.note))
}
HomeEvent.CreateNewNote -> {
navigationEvent.send(NavigationEvent.NavigateToNote(null))
}
is HomeEvent.OnSearchChange -> {
_state.update { oldState ->
oldState.copy(
query = event.query,
searchedList = oldState.list.filter {
it.content.contains(
event.query ?: "",
ignoreCase = true
) || it.title.contains(event.query ?: "", ignoreCase = true)
})
}
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 72ccfda29ded1d9e9bca1bce556a5f68369f82a0 | 2,914 | TrayNote | MIT License |
app/src/main/java/com/wreckingballsoftware/valuewatch/data/models/BackgroundColor.kt | leewaggoner | 765,312,367 | false | {"Kotlin": 58556} | package com.wreckingballsoftware.valuewatch.data.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class BackgroundColor(
val colorText: String,
val backgroundColor: Int,
val textColor: Int,
) : Parcelable | 0 | Kotlin | 0 | 0 | e33daa629ad48d38e07bee7d0d021a25df049d5d | 256 | valuewatch | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2021/calendar/day07/Day07.kt | peckb1 | 433,943,215 | false | null | package me.peckb.aoc._2021.calendar.day07
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import javax.inject.Inject
import kotlin.math.abs
class Day07 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
fun findSimpleCrabCost(fileName: String) = generatorFactory.forFile(fileName).readOne { data ->
findMinCrabCost(data) { it }
}
fun findComplexCrabCost(fileName: String) = generatorFactory.forFile(fileName).readOne { data ->
findMinCrabCost(data) { triangleNumber(it) }
}
private fun findMinCrabCost(movementStrings: String, movementCost: (Int) -> Int): Int {
val horizontalPositions = movementStrings.split(",").map { it.toInt() }
val minPosition = horizontalPositions.minOf { it }
val maxPosition = horizontalPositions.maxOf { it }
return (minPosition .. maxPosition).minOf { desiredPosition ->
horizontalPositions.sumOf { movementCost(abs(desiredPosition - it)) }
}
}
private fun triangleNumber(n: Int) = ((n + 1) * n) / 2
}
| 0 | Kotlin | 1 | 4 | 62165673b98381031d964a962ed0328474d20870 | 1,028 | advent-of-code | MIT License |
library-compose/src/main/java/app/futured/donut/compose/internal/AnimatedColor.kt | ShuaiNiu01 | 356,918,655 | true | {"Kotlin": 49457, "Ruby": 1068} | package app.futured.donut.compose.internal
import androidx.animation.AnimatedValue
import androidx.animation.AnimationVector4D
import androidx.ui.graphics.Color
internal typealias AnimatedColor = AnimatedValue<Color, AnimationVector4D>
| 0 | null | 0 | 0 | 9907f3eae4fea98188fe0521dd8a1f20792c09c3 | 238 | donut | MIT License |
postgis/src/main/kotlin/dev/joelparrish/ktor/gis/postgis/functions/StGeomFromGeoJson.kt | jpdev832 | 275,672,517 | false | null | package dev.joelparrish.ktor.gis.postgis.functions
import dev.joelparrish.ktor.gis.postgis.columns.GeomColumnType
import org.jetbrains.exposed.sql.Function
import org.jetbrains.exposed.sql.QueryBuilder
import org.jetbrains.exposed.sql.append
class StGeomFromGeoJson(private val geoJson: String) : Function<String>(GeomColumnType()) {
override fun toQueryBuilder(queryBuilder: QueryBuilder) =
queryBuilder { append("ST_GeomFromGeoJSON(", geoJson, ")") }
} | 0 | Kotlin | 0 | 0 | 477905d2342d4d81b67f0ede1a8577c9a39927f6 | 468 | KGIS | Apache License 2.0 |
app/src/main/java/com/zy/client/ui/iptv/IPTVListFragment.kt | GAndroidProject | 342,175,135 | true | {"Kotlin": 325478, "Java": 135251} | /**
* Copyright 2020 javakam
* <p>
* 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.zy.client.ui.iptv
import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zy.client.R
import com.zy.client.base.BaseListFragment
import com.zy.client.common.AppRouter
import com.zy.client.base.BaseLoadMoreAdapter
import com.zy.client.database.SourceDBUtils
import com.zy.client.database.SourceModel
import com.zy.client.utils.ext.noNull
class IPTVListFragment : BaseListFragment<SourceModel, BaseViewHolder>() {
//分类
private lateinit var group: String
companion object {
fun instance(group: String): IPTVListFragment {
return IPTVListFragment().apply {
arguments = bundleOf("group" to group)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
group = arguments?.getString("group").noNull()
}
override fun getListAdapter(): BaseLoadMoreAdapter<SourceModel, BaseViewHolder> {
return IPTVListAdapter().apply {
setOnItemClickListener { _, _, position ->
AppRouter.toTvActivity(baseActivity, data[position])
}
}
}
override fun getListLayoutManager(): RecyclerView.LayoutManager {
return LinearLayoutManager(requireActivity())
}
override fun loadData(page: Int, callback: (list: List<SourceModel>?) -> Unit) {
if (page == 1) {
SourceDBUtils.searchGroupAsync(group) {
callback.invoke(it)
}
} else {
callback.invoke(arrayListOf())
}
}
inner class IPTVListAdapter :
BaseLoadMoreAdapter<SourceModel, BaseViewHolder>(R.layout.item_iptv) {
override fun convert(holder: BaseViewHolder, item: SourceModel) {
holder.setText(R.id.tvName, item.name)
holder.setText(R.id.tvSourceName, item.group)
}
}
} | 0 | null | 0 | 0 | 4e61adccdda8ef44ba43636ded685d346a853279 | 2,642 | zy_client_android | Apache License 2.0 |
src/main/kotlin/com/cognifide/gradle/aem/common/instance/local/BackupSource.kt | wttech | 90,353,060 | false | {"Kotlin": 792222, "Shell": 8269, "Batchfile": 438} | package com.cognifide.gradle.aem.common.instance.local
import com.cognifide.gradle.common.file.transfer.FileEntry
import java.io.File
class BackupSource(val type: BackupType, val fileEntry: FileEntry, val fileResolver: () -> File) {
val file: File get() = fileResolver()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BackupSource
if (type != other.type) return false
if (fileEntry != other.fileEntry) return false
return true
}
override fun hashCode(): Int {
var result = type.hashCode()
result = 31 * result + fileEntry.hashCode()
return result
}
}
| 53 | Kotlin | 32 | 158 | 18d6cab33481f8f883c6139267fb059f7f6047ae | 737 | gradle-aem-plugin | Apache License 2.0 |
app/src/main/java/com/abindustrybreeze/features/addAttendence/model/WorkTypeResponseModel.kt | DebashisINT | 824,477,139 | false | {"Kotlin": 15151203, "Java": 1024391} | package com.abindustrybreeze.features.addAttendence.model
import com.abindustrybreeze.base.BaseResponse
/**
* Created by Saikat on 31-08-2018.
*/
class WorkTypeResponseModel : BaseResponse() {
var worktype_list: ArrayList<WorkTypeListData>? = null
} | 0 | Kotlin | 0 | 0 | cb6b9d486af40cdcb378abdb534a0faf3d05e686 | 258 | ABIndustry | Apache License 2.0 |
app/src/main/java/com/study/kotlin/cattastk/domain/model/Date.kt | Samuel-Ricardo | 401,384,563 | false | null | package com.study.kotlin.cattastk.domain.model
import android.system.Os
import java.util.*
class Date{
companion object {
fun isLeapYear(year: Int) = if (year%4 == 0) year%100 != 0 else year%400 == 0
fun now():Date {
val calendar = Calendar.getInstance()
return Date(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH) +1,
calendar.get(Calendar.DAY_OF_MONTH)
)
}
fun daysInMonth(year: Int, month: Int):Int = when(month) {
1 -> 31
2 -> if(isLeapYear(year)) 29 else 28
3 -> 31
4 -> 30
5 -> 31
6 -> 30
7 -> 31
8 -> 31
9 -> 30
10 -> 31
11 -> 30
12 -> 31
else -> -1
}
}
var calendar = Calendar.getInstance()
var year = calendar.get(Calendar.YEAR)
var month = calendar.get(Calendar.MONTH) +1
var day = calendar.get(Calendar.DAY_OF_MONTH)
constructor( year: Int, month: Int, day: Int){ setDate(year,month,day) }
constructor(date:String){
val dates = date.split("/")
val toInt0 = dates[0].toInt()
val toInt1 = dates[1].toInt()
val toInt2 = dates[2].toInt()
setDate(
dates[0].toInt(),
dates[1].toInt(),
dates[2].toInt()
)
}
private fun checkDay(day: Int): Int {
return if (day in 0..31)
day
else
1
}
private fun checkMonth(month: Int) = if (month in 1..12) month else 1
fun setDate(year: Int, month: Int, day: Int){
// val millis = System.currentTimeMillis()
// val ano = millis/1000/60/60/24/365
this.year = year
this.month = checkMonth(month)
this.day = checkDay(day)
this.calendar.set(year,month,day)
}
fun isLeapYear() = if (year%4 == 0) year%100 != 0 else year%400 == 0
fun dayOfYear():Int {
return calendar.get(Calendar.DAY_OF_YEAR);
}
fun getWeekBraziliamName() = when(calendar.get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> "Domingo"
Calendar.MONDAY -> "Segunda"
Calendar.TUESDAY -> "Terça"
Calendar.WEDNESDAY -> "Quarta"
Calendar.THURSDAY -> "Quinta"
Calendar.FRIDAY -> "Sexta"
Calendar.SATURDAY -> "Sábado"
else -> "Invalid Day"
}
fun getMonthBraziliamName() = when(month) {
1 -> "janeiro"
2 -> "Fevereiro"
3 -> "Março"
4 -> "Abril"
5 -> "Maio"
6 -> "Junho"
7 -> "Julho"
8 -> "Agosto"
9 -> "Setembro"
10 -> "Outubro"
11 -> "Novembro"
12 -> "Dezembro"
else -> "Invalid Month"
}
fun daysOfMonth() = when(month) {
1 -> 31
2 -> if(isLeapYear()) 29 else 28
3 -> 31
4 -> 30
5 -> 31
6 -> 30
7 -> 31
8 -> 31
9 -> 30
10 -> 31
11 -> 30
12 -> 31
else -> -1
}
fun formatSimpleDate():String{
var date:String = "$day"
var month:String = "$month"
if(day < 10) date = "0$day"
if(this.month < 10) month = "0$month"
return "$date/$month"
}
fun formatFullDate() = "${formatSimpleDate()}/$year"
fun isEquals(date: Date):Boolean{
if(
this.year == date.year
&&
this.month == date.month
&&
this.day == date.day
){
return true
}else{
return false
}
}
override fun toString(): String = formatFullDate();
/*
constructor(
date:String
): Times{
SimpleDateFormat("dd/MM/yyyy").parse(string)
super(Times(Date.from(Instant.now())))
}
*/
} | 0 | Kotlin | 1 | 1 | fe4dc58b076cb5d817012f9c4ec9baa965b13c7e | 4,048 | Cat-Tasks | MIT License |
app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/data/source/local/TasksDaoTest.kt | Shawn-Nichol | 387,242,380 | false | null | package com.example.android.architecture.blueprints.todoapp.data.source.local
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.example.android.architecture.blueprints.todoapp.data.Task
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.core.Is.`is`
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class TasksDaoTest {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
private lateinit var database: ToDoDatabase
@Before
fun setup() {
// using an in-memory database so that information stored here disappears when the test
// process is killed
database = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
ToDoDatabase::class.java
).build()
}
@After
fun close() {
database.close()
}
@Test
fun insertTaskAndGetById() = runBlockingTest {
// Given
val task = Task("title", "description")
database.taskDao().insertTask(task)
// When
val loaded = database.taskDao().getTaskById(task.id)
// Then
assertThat(loaded as Task, notNullValue())
assertThat(loaded.id, `is`(task.id))
assertThat(loaded.title, `is`(task.title))
assertThat(loaded.description, `is` (task.description))
assertThat(loaded.isCompleted, `is` (task.isCompleted))
}
@Test
fun updateTaskAndGetById() = runBlockingTest {
var task = Task(title = "Title", description = "description", id = "ONE")
database.taskDao().insertTask(task)
// Update the task by creating a new task with the same ID bud different attributes
task = Task(title = "New Title", description = "description", id = "ONE")
database.taskDao().updateTask(task)
val loaded = database.taskDao().getTaskById(task.id)
// Check that when you get the task by its ID, it has the updated value.
assertThat(loaded as Task, notNullValue())
assertThat(loaded.id, `is`(task.id))
assertThat(loaded.title, `is`(task.title))
assertThat(loaded.description, `is` (task.description))
assertThat(loaded.isCompleted, `is` (task.isCompleted))
}
} | 0 | Kotlin | 0 | 0 | b1c26c95027b04c437ced8f26b21699fa9fafb9f | 2,699 | CodeLab_Testing_MyNotes | Apache License 2.0 |
app/src/androidTest/java/com/google/codelabs/appauth/ApplicationTest.kt | jlavm | 265,264,662 | false | {"Kotlin": 17410} | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.codelabs.appauth
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
/**
* [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
Assert.assertEquals("com.google.codelabs.appauth", appContext.packageName)
}
} | 0 | Kotlin | 0 | 0 | 08b3c23465019b020d91de8c6005ec1e806d88cc | 1,214 | updated_appauth-android_codelab_sso_managed | Apache License 2.0 |
cache-spring/src/main/kotlin/im/toss/util/cache/spring/TossCacheConfiguration.kt | toss | 228,551,924 | false | null | package im.toss.util.cache.spring
import im.toss.util.cache.CacheManager
import im.toss.util.cache.CacheResourcesDsl
import io.micrometer.core.instrument.MeterRegistry
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class TossCacheConfiguration {
@Bean
@ConditionalOnMissingBean
fun tossCacheManager(
meterRegistry: MeterRegistry,
tossCacheProperties: TossCacheProperties,
dsl: List<CacheResourcesDsl>
) = CacheManager(meterRegistry).also { cacheManager ->
cacheManager.loadProperties(tossCacheProperties.cache, "toss.cache")
dsl.forEach { cacheManager.resources(it) }
}
@Bean
@ConfigurationProperties(prefix = "toss", ignoreInvalidFields = true, ignoreUnknownFields = true)
fun tossCacheProperties() = TossCacheProperties()
} | 1 | Kotlin | 3 | 7 | 006062a4cc9548d57c09c11cbccdf1811de73589 | 1,035 | cache | Apache License 2.0 |
app/src/main/java/org/p2p/wallet/striga/wallet/api/request/StrigaOnchainWithdrawalFeeRequest.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252} | package org.p2p.wallet.striga.wallet.api.request
import com.google.gson.annotations.SerializedName
/**
* @param amountInUnits The amount denominated in the smallest divisible unit of the sending currency.
* For example: cents or satoshis
*/
class StrigaOnchainWithdrawalFeeRequest(
@SerializedName("userId")
val userId: String,
@SerializedName("sourceAccountId")
val sourceAccountId: String,
@SerializedName("whitelistedAddressId")
val whitelistedAddressId: String,
@SerializedName("amount")
val amountInUnits: String,
)
| 8 | Kotlin | 18 | 34 | d091e18b7d88c936b7c6c627f4fec96bcf4a0356 | 558 | key-app-android | MIT License |
data/RF01728/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01728"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 7
15 to 20
}
value = "#57c060"
}
color {
location {
36 to 41
68 to 73
}
value = "#6bdfc5"
}
color {
location {
36 to 41
68 to 73
}
value = "#6bdfc5"
}
color {
location {
53 to 55
65 to 67
}
value = "#364e7f"
}
color {
location {
107 to 112
145 to 150
}
value = "#d3d902"
}
color {
location {
107 to 112
145 to 150
}
value = "#d3d902"
}
color {
location {
126 to 128
141 to 143
}
value = "#eeb3c2"
}
color {
location {
168 to 173
221 to 226
}
value = "#6b2405"
}
color {
location {
168 to 173
221 to 226
}
value = "#6b2405"
}
color {
location {
189 to 191
214 to 216
}
value = "#e9b9e4"
}
color {
location {
8 to 14
}
value = "#029d7e"
}
color {
location {
42 to 52
68 to 67
}
value = "#61b2ab"
}
color {
location {
56 to 64
}
value = "#41d0fb"
}
color {
location {
113 to 125
144 to 144
}
value = "#cf1c88"
}
color {
location {
129 to 140
}
value = "#f2a736"
}
color {
location {
174 to 188
217 to 220
}
value = "#fec323"
}
color {
location {
192 to 213
}
value = "#0d24f7"
}
color {
location {
1 to 1
}
value = "#89f6ab"
}
color {
location {
21 to 35
}
value = "#52db1f"
}
color {
location {
74 to 106
}
value = "#d21327"
}
color {
location {
151 to 167
}
value = "#7168fc"
}
color {
location {
227 to 229
}
value = "#035041"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 3,280 | Rfam-for-RNArtist | MIT License |
app/src/main/java/com/initiatetech/initiate_news/adapter/NewsTimelineAdapter.kt | Gemnnn | 747,026,324 | false | {"Kotlin": 79126} | package com.initiatetech.initiate_news.adapter
import android.icu.text.SimpleDateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.initiatetech.initiate_news.R
import com.initiatetech.initiate_news.model.NewsResponse
import java.text.ParseException
import java.util.Locale
class NewsTimelineAdapter(private val onTitleClick: (String) -> Unit) : RecyclerView.Adapter<NewsTimelineAdapter.NewsViewHolder>() {
private var newsItems: List<NewsResponse> = ArrayList()
fun submitList(items: List<NewsResponse>) {
newsItems = items
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
return if (position % 2 == 0) VIEW_TYPE_LEFT else VIEW_TYPE_RIGHT
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view = if (viewType == VIEW_TYPE_LEFT) {
LayoutInflater.from(parent.context).inflate(R.layout.item_news_left, parent, false)
} else {
LayoutInflater.from(parent.context).inflate(R.layout.item_news_right, parent, false)
}
return NewsViewHolder(view, onTitleClick)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
val newsItem = newsItems[position]
holder.bind(newsItem)
if (position == itemCount - 1) {
holder.itemView.setBackgroundResource(R.drawable.item_shadow)
} else {
holder.itemView.setBackgroundResource(R.drawable.normal_background)
}
}
override fun getItemCount(): Int = newsItems.size
class NewsViewHolder(itemView: View, private val onTitleClick: (String) -> Unit) : RecyclerView.ViewHolder(itemView) {
private val titleView: TextView = itemView.findViewById(R.id.tvTitle)
private val dateView: TextView = itemView.findViewById(R.id.tvDate)
fun bind(newsItem: NewsResponse) {
titleView.text = newsItem.shortTitle
dateView.text = formatDate(newsItem.publishedDate)
titleView.setOnClickListener { onTitleClick(newsItem.id.toString()) }
}
private fun formatDate(dateStr: String): String {
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
val outputFormat = SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.getDefault())
try {
val date = inputFormat.parse(dateStr)
return outputFormat.format(date)
} catch (e: ParseException) {
// Log the exception or handle it as needed
e.printStackTrace()
return dateStr // Return the original string or a placeholder as appropriate
}
}
}
companion object {
private const val VIEW_TYPE_LEFT = 0
private const val VIEW_TYPE_RIGHT = 1
}
}
| 1 | Kotlin | 0 | 1 | b1d106bfde7e90ac3bbee22e349f32d2b7a11bf5 | 2,988 | Initiate-News | MIT License |
eco-core/core-nms/common/src/main/kotlin/com/willfp/eco/internal/spigot/proxy/common/ai/entity/AvoidEntityGoalFactory.kt | Auxilor | 325,856,799 | false | {"Kotlin": 784230, "Java": 740080} | package com.willfp.eco.internal.spigot.proxy.common.ai.entity
import com.willfp.eco.core.entities.ai.entity.EntityGoalAvoidEntity
import com.willfp.eco.internal.spigot.proxy.common.ai.EntityGoalFactory
import com.willfp.eco.internal.spigot.proxy.common.toBukkitEntity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.goal.AvoidEntityGoal
import net.minecraft.world.entity.ai.goal.Goal
object AvoidEntityGoalFactory : EntityGoalFactory<EntityGoalAvoidEntity> {
override fun create(apiGoal: EntityGoalAvoidEntity, entity: PathfinderMob): Goal {
return AvoidEntityGoal(
entity,
LivingEntity::class.java,
apiGoal.distance.toFloat(),
apiGoal.slowSpeed,
apiGoal.fastSpeed
) { apiGoal.entity.test(it.toBukkitEntity()) }
}
override fun isGoalOfType(goal: Goal) = goal is AvoidEntityGoal<*>
}
| 82 | Kotlin | 53 | 156 | 81de46a1c122a3cd6be06696b5b02d55fd9a73e5 | 958 | eco | MIT License |
src/test/kotlin/org/springframework/samples/petclinic/arch/GeneralCodingRuleTest.kt | junoyoon | 664,329,578 | false | null | @file:Suppress("unused")
package org.springframework.samples.petclinic.arch
import com.tngtech.archunit.core.domain.JavaClasses
import com.tngtech.archunit.core.importer.ImportOption
import com.tngtech.archunit.junit.AnalyzeClasses
import com.tngtech.archunit.junit.ArchIgnore
import com.tngtech.archunit.junit.ArchTest
import com.tngtech.archunit.lang.ArchRule
import com.tngtech.archunit.library.GeneralCodingRules
import org.junit.jupiter.api.TestInstance
@ArchIgnore(reason = "테스트 할때 제거")
@Suppress("PropertyName")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@AnalyzeClasses(
packages = ["org.springframework.samples.petclinic.facade"],
importOptions = [ImportOption.DoNotIncludeTests::class]
)
class GeneralCodingRuleTest {
@ArchTest
val noStdStream: ArchRule =
GeneralCodingRules.NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS
@ArchTest
val shouldNotUseJavaUtilLogging: ArchRule =
GeneralCodingRules.NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING
@ArchTest
fun noFieldInjection(javaClasses: JavaClasses) {
GeneralCodingRules.NO_CLASSES_SHOULD_USE_FIELD_INJECTION.
`as`("필드 Injection 사용됨").because("필드 Injection 은 사용 하면 않됨").check(javaClasses)
}
}
| 0 | Kotlin | 0 | 0 | c339ab5260583d07871bfb2617f35f754d8b3492 | 1,219 | fastcampus-test | Apache License 2.0 |
app/src/main/java/com/foobarust/android/sellerrating/SellerRatingDetailViewModel.kt | foobar-UST | 285,792,732 | false | null | package com.foobarust.android.sellerrating
import android.os.Parcelable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.insertSeparators
import androidx.paging.map
import com.foobarust.android.sellerrating.SellerRatingDetailListModel.*
import com.foobarust.domain.models.seller.SellerRatingCount
import com.foobarust.domain.models.seller.SellerRatingSortOption
import com.foobarust.domain.usecases.seller.GetSellerRatingsParameter
import com.foobarust.domain.usecases.seller.GetSellerRatingsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.*
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
import javax.inject.Inject
/**
* Created by kevin on 3/3/21
*/
@HiltViewModel
class SellerRatingDetailViewModel @Inject constructor(
private val getSellerRatingsUseCase: GetSellerRatingsUseCase
) : ViewModel() {
private val _ratingDetailProperty = ConflatedBroadcastChannel<SellerRatingDetailProperty>()
private val _ratingSortOption = MutableStateFlow(SellerRatingSortOption.LATEST)
val ratingSortOption: StateFlow<SellerRatingSortOption> = _ratingSortOption.asStateFlow()
val ratingDetailListModels: Flow<PagingData<SellerRatingDetailListModel>> = _ratingDetailProperty
.asFlow()
.combine(_ratingSortOption) { property, sortOption ->
GetSellerRatingsParameter(
sellerId = property.sellerId,
sortOption = sortOption
)
}
.flatMapLatest {
getSellerRatingsUseCase(it)
}
.map { pagingData ->
pagingData.map { SellerRatingDetailRatingItem(it) }
}
.map { pagingData ->
pagingData.insertSeparators { before, after ->
insertSeparators(before, after)
}
}
.cachedIn(viewModelScope)
fun onFetchSellerRatings(property: SellerRatingDetailProperty) {
_ratingDetailProperty.offer(property)
}
fun onUpdateSortOption(sortOption: SellerRatingSortOption) {
_ratingSortOption.value = sortOption
}
private fun insertSeparators(
before: SellerRatingDetailListModel?,
after: SellerRatingDetailListModel?
): SellerRatingDetailListModel? {
return when {
before == null && after == null -> SellerRatingDetailEmptyItem
before == null -> SellerRatingDetailInfoItem(
orderRating = _ratingDetailProperty.value.orderRating,
deliveryRating = _ratingDetailProperty.value.deliveryRating,
ratingCount = _ratingDetailProperty.value.ratingCount,
ratingSortOption = _ratingSortOption.value
)
else -> null
}
}
}
@Parcelize
data class SellerRatingDetailProperty(
val sellerId: String,
val sellerName: String,
val orderRating: Double,
val deliveryRating: Double?,
val ratingCount: @RawValue SellerRatingCount
) : Parcelable | 0 | Kotlin | 2 | 2 | b4358ef0323a0b7a95483223496164e616a01da5 | 3,154 | foobar-android | MIT License |
core/src/main/java/com/maxkeppeler/sheets/core/utils/AnimationExt.kt | pranavlathigara | 354,617,017 | true | {"Kotlin": 314850} | /*
* Copyright (C) 2020. <NAME> (https://www.maxkeppeler.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.maxkeppeler.bottomsheets.core.utils
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.annotation.RestrictTo
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
const val ANIM_ALPHA_MIN = 0f
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
const val ANIM_ALPHA_MAX = 1f
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
const val ANIM_DURATION_300 = 300L
/** Fade in a view. */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun View.fadeIn(
alpha: Float = ANIM_ALPHA_MAX,
duration: Long = ANIM_DURATION_300,
listener: (() -> Unit)? = null
) {
animate().alpha(alpha)
.setDuration(duration)
.setInterpolator(AccelerateDecelerateInterpolator())
.withEndAction { listener?.invoke() }
.start()
}
/** Fade in a view. */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun animValues(
valueStart: Float = ANIM_ALPHA_MIN,
valueEnd: Float = ANIM_ALPHA_MAX,
duration: Long = ANIM_DURATION_300,
listener: (Float) -> Unit,
listenerFinished: () -> Unit
): ValueAnimator {
return ValueAnimator.ofFloat(valueStart, valueEnd).apply {
setDuration(duration)
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { animation -> listener.invoke(animation.animatedValue as Float) }
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
listenerFinished.invoke()
}
})
start()
}
}
/** Fade out a view. */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun View.fadeOut(
alpha: Float = ANIM_ALPHA_MIN,
duration: Long = ANIM_DURATION_300,
listener: (() -> Unit)? = null
) {
animate().alpha(alpha)
.setDuration(duration)
.setInterpolator(AccelerateDecelerateInterpolator())
.withEndAction { listener?.invoke() }
.start()
} | 0 | null | 0 | 3 | 89d3c620e9e66fb68ae51db49b7b0e4beefff88b | 2,674 | sheets | Apache License 2.0 |
app/src/testDeviceRelease/kotlin/de/digitalService/useID/coordinator/ChangePinCoordinatorTest.kt | digitalservicebund | 486,188,046 | false | null | package de.digitalService.useID.coordinator
import android.content.Context
import android.net.Uri
import com.ramcosta.composedestinations.spec.Direction
import de.digitalService.useID.analytics.IssueTrackerManagerType
import de.digitalService.useID.flows.*
import de.digitalService.useID.idCardInterface.EidInteractionEvent
import de.digitalService.useID.idCardInterface.EidInteractionManager
import de.digitalService.useID.idCardInterface.EidInteractionException
import de.digitalService.useID.ui.coordinators.CanCoordinator
import de.digitalService.useID.ui.coordinators.ChangePinCoordinator
import de.digitalService.useID.ui.coordinators.SubCoordinatorState
import de.digitalService.useID.ui.navigation.Navigator
import de.digitalService.useID.ui.screens.destinations.*
import de.digitalService.useID.util.CoroutineContextProvider
import de.digitalService.useID.util.PinManagementStateFactory
import de.jodamob.junit5.SealedClassesSource
import io.mockk.*
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.*
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import java.lang.Exception
@OptIn(ExperimentalCoroutinesApi::class)
@ExtendWith(MockKExtension::class)
class ChangePinCoordinatorTest {
@MockK(relaxUnitFun = true)
lateinit var mockContext: Context
@MockK(relaxUnitFun = true)
lateinit var mockCanCoordinator: CanCoordinator
@MockK(relaxUnitFun = true)
lateinit var mockNavigator: Navigator
@MockK(relaxUnitFun = true)
lateinit var mockEidInteractionManager: EidInteractionManager
@MockK(relaxUnitFun = true)
lateinit var mockChangePinStateMachine: ChangePinStateMachine
@MockK(relaxUnitFun = true)
lateinit var mockCanStateMachine: CanStateMachine
@MockK(relaxUnitFun = true)
lateinit var mockCoroutineContextProvider: CoroutineContextProvider
@MockK(relaxUnitFun = true)
lateinit var mockIssueTrackerManager: IssueTrackerManagerType
val dispatcher = StandardTestDispatcher()
private val navigationDestinationSlot = slot<Direction>()
private val navigationPoppingDestinationSlot = slot<Direction>()
private val navigationPopUpToOrNavigateDestinationSlot = slot<Direction>()
val stateFlow: MutableStateFlow<Pair<ChangePinStateMachine.Event, ChangePinStateMachine.State>> = MutableStateFlow(
Pair(
ChangePinStateMachine.Event.Invalidate, ChangePinStateMachine.State.Invalid
)
)
@OptIn(ExperimentalCoroutinesApi::class)
@BeforeEach
fun beforeEach() {
Dispatchers.setMain(dispatcher)
every { mockNavigator.navigate(capture(navigationDestinationSlot)) } returns Unit
every { mockNavigator.navigatePopping(capture(navigationPoppingDestinationSlot)) } returns Unit
every { mockNavigator.popUpToOrNavigate(capture(navigationPopUpToOrNavigateDestinationSlot), any()) } returns Unit
every { mockCoroutineContextProvider.Default } returns dispatcher
every { mockCoroutineContextProvider.IO } returns dispatcher
// For supporting destinations with String nav arguments
mockkStatic("android.net.Uri")
every { Uri.encode(any()) } answers { value }
every { Uri.decode(any()) } answers { value }
every { mockChangePinStateMachine.state } returns stateFlow
}
@Test
fun singleStateObservation() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
advanceUntilIdle()
verify(exactly = 1) { mockChangePinStateMachine.state }
changePinCoordinator.startPinChange(false, false)
advanceUntilIdle()
verify(exactly = 1) { mockChangePinStateMachine.state }
}
@Nested
inner class PinManagementStateChangeHandling {
private fun testTransition(event: ChangePinStateMachine.Event, state: ChangePinStateMachine.State, testScope: TestScope) {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
stateFlow.value = Pair(event, state)
testScope.advanceUntilIdle()
}
@ParameterizedTest
@SealedClassesSource(names = [], mode = SealedClassesSource.Mode.EXCLUDE, factoryClass = PinManagementStateFactory::class)
fun back(state: ChangePinStateMachine.State) = runTest {
testTransition(ChangePinStateMachine.Event.Back, state, this)
verify { mockNavigator.pop() }
}
@Test
fun `back from scan screen`() = runTest {
val state = ChangePinStateMachine.State.NewPinInput(false, false, "")
testTransition(ChangePinStateMachine.Event.Back, state, this)
verify { mockNavigator.pop() }
verify { mockEidInteractionManager.cancelTask() }
}
@Test
fun `backing down`() = runTest {
val state = ChangePinStateMachine.State.Invalid
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
stateFlow.value = Pair(ChangePinStateMachine.Event.Back, state)
advanceUntilIdle()
verify { mockNavigator.pop() }
verify { mockEidInteractionManager.cancelTask() }
Assertions.assertEquals(SubCoordinatorState.BACKED_DOWN, changePinCoordinator.stateFlow.value)
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `old transport PIN input`(identificationPending: Boolean) = runTest {
val state = ChangePinStateMachine.State.OldTransportPinInput(identificationPending)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(any()) }
Assertions.assertEquals(SetupTransportPinDestination(false, identificationPending).route, navigationDestinationSlot.captured.route)
}
@Test
fun `new PIN intro`() = runTest {
val state = ChangePinStateMachine.State.NewPinIntro(false, true, "12345")
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(SetupPersonalPinIntroDestination) }
}
@Test
fun `new PIN input with retry event`() = runTest {
val state = ChangePinStateMachine.State.NewPinInput(false, true, "12345")
testTransition(ChangePinStateMachine.Event.RetryNewPinConfirmation, state, this)
verify { mockNavigator.pop() }
}
@Test
fun `new PIN input with first visit`() = runTest {
val state = ChangePinStateMachine.State.NewPinInput(false, true, "12345")
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(SetupPersonalPinInputDestination) }
}
@Test
fun `start id card interaction`() = runTest {
every { mockEidInteractionManager.eidFlow } returns MutableStateFlow(EidInteractionEvent.CardRecognized)
val state = ChangePinStateMachine.State.StartIdCardInteraction(false, true, "12345", "000000")
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
advanceUntilIdle()
verify { mockEidInteractionManager.cancelTask() }
verify { mockEidInteractionManager.eidFlow }
verify { mockEidInteractionManager.changePin(mockContext) }
verify { mockNavigator.popUpToOrNavigate(any(), true) }
Assertions.assertEquals(SetupScanDestination(true, false).route, navigationPopUpToOrNavigateDestinationSlot.captured.route)
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `ready for subsequent scan`(identificationPending: Boolean) = runTest {
val oldPin = "12345"
val state = ChangePinStateMachine.State.ReadyForSubsequentScan(identificationPending, true, oldPin, "000000")
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.popUpToOrNavigate(any(), true) }
verify { mockEidInteractionManager.providePin(oldPin) }
Assertions.assertEquals(SetupScanDestination(false, identificationPending).route, navigationPopUpToOrNavigateDestinationSlot.captured.route)
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `framework ready for PIN input`(identificationPending: Boolean) = runTest {
val oldPin = "123456"
val newPin = "000000"
val state = ChangePinStateMachine.State.FrameworkReadyForPinInput(identificationPending, true, oldPin, newPin)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockEidInteractionManager.providePin(oldPin) }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `framework ready for new PIN input`(identificationPending: Boolean) = runTest {
val oldPin = "123456"
val newPin = "000000"
val state = ChangePinStateMachine.State.FrameworkReadyForNewPinInput(identificationPending, true, oldPin, newPin)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockEidInteractionManager.provideNewPin(newPin) }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `CAN requested with short flow`(identificationPending: Boolean) = runTest {
val oldPin = "123456"
val newPin = "000000"
every { mockCanCoordinator.startPinChangeCanFlow(any(), any(), any(), any()) } returns flow {}
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
val state = ChangePinStateMachine.State.CanRequested(identificationPending, true, oldPin, newPin, true)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
advanceUntilIdle()
verify { mockCanCoordinator.startPinChangeCanFlow(identificationPending, oldPin, newPin, true) }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `CAN requested with long flow`(identificationPending: Boolean) = runTest {
val oldPin = "123456"
val newPin = "000000"
every { mockCanCoordinator.startPinChangeCanFlow(any(), any(), any(), any()) } returns flow {}
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
val state = ChangePinStateMachine.State.CanRequested(identificationPending, true, oldPin, newPin, false)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
advanceUntilIdle()
verify { mockCanCoordinator.startPinChangeCanFlow(identificationPending, oldPin, newPin, false) }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `CAN requested with short flow with CAN flow already active`(identificationPending: Boolean) = runTest {
val oldPin = "123456"
val newPin = "000000"
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.ACTIVE)
val state = ChangePinStateMachine.State.CanRequested(identificationPending, true, oldPin, newPin, true)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
advanceUntilIdle()
verify(exactly = 0) { mockCanCoordinator.startPinChangeCanFlow(identificationPending, oldPin, newPin, true) }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `CAN requested with long flow with CAN flow already active`(identificationPending: Boolean) = runTest {
val oldPin = "123456"
val newPin = "000000"
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.ACTIVE)
val state = ChangePinStateMachine.State.CanRequested(identificationPending, true, oldPin, newPin, false)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
advanceUntilIdle()
verify(exactly = 0) { mockCanCoordinator.startPinChangeCanFlow(identificationPending, oldPin, newPin, false) }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `old transport PIN retry`(identificationPending: Boolean) = runTest {
val state = ChangePinStateMachine.State.OldTransportPinRetry(identificationPending, "000000")
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(any()) }
Assertions.assertEquals(SetupTransportPinDestination(true, identificationPending).route, navigationDestinationSlot.captured.route)
}
@Test
fun finished() = runTest {
val state = ChangePinStateMachine.State.Finished
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, state)
advanceUntilIdle()
Assertions.assertEquals(SubCoordinatorState.FINISHED, changePinCoordinator.stateFlow.value)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Invalidate) }
verify { mockEidInteractionManager.cancelTask() }
}
@Test
fun cancelled() = runTest {
val state = ChangePinStateMachine.State.Cancelled
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, state)
advanceUntilIdle()
Assertions.assertEquals(SubCoordinatorState.CANCELLED, changePinCoordinator.stateFlow.value)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Invalidate) }
verify { mockEidInteractionManager.cancelTask() }
}
@Test
fun `card deactivated`() = runTest {
val state = ChangePinStateMachine.State.CardDeactivated
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(SetupCardDeactivatedDestination) }
}
@Test
fun `card blocked`() = runTest {
val state = ChangePinStateMachine.State.CardBlocked
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(SetupCardBlockedDestination) }
}
@Test
fun `card unreadable`() = runTest {
val state = ChangePinStateMachine.State.ProcessFailed(false, true, "12345", "000000", true)
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(any()) }
Assertions.assertEquals(SetupCardUnreadableDestination(false).route, navigationDestinationSlot.captured.route)
}
@Test
fun `unknown error`() = runTest {
val state = ChangePinStateMachine.State.UnknownError
testTransition(ChangePinStateMachine.Event.Invalidate, state, this)
verify { mockNavigator.navigate(SetupOtherErrorDestination) }
}
}
@Nested
inner class EidEventHandling {
@Test
fun `card recognized and removed`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow: MutableStateFlow<EidInteractionEvent> = MutableStateFlow(EidInteractionEvent.CardRecognized)
every { mockEidInteractionManager.eidFlow } returns eIdFlow
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
Assertions.assertTrue(changePinCoordinator.scanInProgress.value)
eIdFlow.value = EidInteractionEvent.CardRemoved
advanceUntilIdle()
Assertions.assertFalse(changePinCoordinator.scanInProgress.value)
}
@Test
fun `PIN change succeeded`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow = MutableStateFlow(EidInteractionEvent.PinChangeSucceeded)
every { mockEidInteractionManager.eidFlow } returns eIdFlow
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Finish) }
}
@Test
fun `PIN requested`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow = MutableStateFlow(EidInteractionEvent.PinRequested(3))
every { mockEidInteractionManager.eidFlow } returns eIdFlow
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.FrameworkRequestsPin) }
}
@Test
fun `new PIN requested`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow = MutableStateFlow(EidInteractionEvent.NewPinRequested)
every { mockEidInteractionManager.eidFlow } returns eIdFlow
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.FrameworkRequestsNewPin) }
}
@Test
fun `request CAN`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow = MutableStateFlow(EidInteractionEvent.CanRequested())
every { mockEidInteractionManager.eidFlow } returns eIdFlow
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.FrameworkRequestsCan) }
}
@Test
fun `request PUK`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow = MutableStateFlow(EidInteractionEvent.PukRequested)
every { mockEidInteractionManager.eidFlow } returns eIdFlow
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Error(EidInteractionException.CardBlocked)) }
verify { mockIssueTrackerManager.captureMessage("${EidInteractionException.CardBlocked}") }
}
@Test
fun `card deactivated`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val eIdFlow = MutableStateFlow(EidInteractionEvent.Error(EidInteractionException.CardDeactivated))
every { mockEidInteractionManager.eidFlow } returns eIdFlow
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Error(EidInteractionException.CardDeactivated)) }
verify { mockIssueTrackerManager.captureMessage("${EidInteractionException.CardDeactivated}") }
}
@Test
fun `process failed`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val exception = EidInteractionException.ProcessFailed()
val capturedExceptionSlot = slot<Exception>()
val eIdFlow = MutableStateFlow(EidInteractionEvent.Error(exception))
every { mockEidInteractionManager.eidFlow } returns eIdFlow
val newState = ChangePinStateMachine.State.StartIdCardInteraction(false, false, "12345", "000000")
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, newState)
advanceUntilIdle()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Error(exception)) }
verify { mockIssueTrackerManager.capture(capture(capturedExceptionSlot)) }
Assertions.assertEquals(exception.redacted?.message, capturedExceptionSlot.captured.message)
}
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun `start PIN management`(identificationPending: Boolean) = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(identificationPending, true)
Assertions.assertEquals(SubCoordinatorState.ACTIVE, changePinCoordinator.stateFlow.value)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.StartPinChange(identificationPending, true)) }
verify { mockCanStateMachine.transition(CanStateMachine.Event.Invalidate) }
}
@Test
fun `old PIN entered`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
val oldPin = "123456"
changePinCoordinator.onOldPinEntered(oldPin)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.EnterOldPin(oldPin)) }
}
@Test
fun `personal PIN intro finished`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
val oldPin = "123456"
changePinCoordinator.onPersonalPinIntroFinished()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.ConfirmNewPinIntro) }
}
@Test
fun `confirm matching PIN`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
val newPin = "000000"
val matching = changePinCoordinator.confirmNewPin(newPin)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.ConfirmNewPin(newPin)) }
Assertions.assertTrue(matching)
}
@Test
fun `confirm PIN not matching`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
val newPin = "000000"
every { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.ConfirmNewPin(newPin)) } throws ChangePinStateMachine.Error.PinConfirmationFailed
val matching = changePinCoordinator.confirmNewPin(newPin)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.ConfirmNewPin(newPin)) }
Assertions.assertFalse(matching)
}
@Test
fun `confirm PIN mismatch error`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.onConfirmPinMismatchError()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.RetryNewPinConfirmation) }
}
@Test
fun `on back`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.onBack()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Back) }
}
@Test
fun `cancel PIN management`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.cancelPinManagement()
Assertions.assertEquals(SubCoordinatorState.CANCELLED, changePinCoordinator.stateFlow.value)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Invalidate) }
verify { mockEidInteractionManager.cancelTask() }
}
@Test
fun `confirm card unreadable`() = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.confirmCardUnreadableError()
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.ProceedAfterError) }
}
@Nested
inner class CanEventHandling {
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun cancelled(shortFlow: Boolean) = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val oldPin = "123456"
val newPin = "000000"
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
every { mockCanCoordinator.startPinChangeCanFlow(false, oldPin, newPin, shortFlow) } returns MutableStateFlow(SubCoordinatorState.CANCELLED)
val state = ChangePinStateMachine.State.CanRequested(false, true, oldPin, newPin, shortFlow)
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, state)
advanceUntilIdle()
Assertions.assertEquals(SubCoordinatorState.CANCELLED, changePinCoordinator.stateFlow.value)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Invalidate) }
verify { mockEidInteractionManager.cancelTask() }
}
@ParameterizedTest
@ValueSource(booleans = [true, false])
fun skipped(shortFlow: Boolean) = runTest {
val changePinCoordinator = ChangePinCoordinator(
mockContext,
mockCanCoordinator,
mockNavigator,
mockEidInteractionManager,
mockChangePinStateMachine,
mockCanStateMachine,
mockCoroutineContextProvider,
mockIssueTrackerManager
)
changePinCoordinator.startPinChange(false, false)
val oldPin = "123456"
val newPin = "000000"
every { mockCanCoordinator.stateFlow } returns MutableStateFlow(SubCoordinatorState.FINISHED)
every { mockCanCoordinator.startPinChangeCanFlow(false, oldPin, newPin, shortFlow) } returns MutableStateFlow(SubCoordinatorState.SKIPPED)
val state = ChangePinStateMachine.State.CanRequested(false, true, oldPin, newPin, shortFlow)
stateFlow.value = Pair(ChangePinStateMachine.Event.Invalidate, state)
advanceUntilIdle()
Assertions.assertEquals(SubCoordinatorState.SKIPPED, changePinCoordinator.stateFlow.value)
verify { mockChangePinStateMachine.transition(ChangePinStateMachine.Event.Invalidate) }
verify { mockEidInteractionManager.cancelTask() }
}
}
}
| 2 | Kotlin | 2 | 5 | f40f13299b383c900bb1fa09a222deb90e37a3fe | 35,496 | useid-app-android | MIT License |
src/main/java/com/maddyhome/idea/vim/newapi/IjVimMessages.kt | JetBrains | 1,459,486 | false | {"Kotlin": 5959132, "Java": 211095, "ANTLR": 84686, "HTML": 2184} | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.wm.WindowManager
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimMessagesBase
import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.MessageHelper
import com.maddyhome.idea.vim.ui.ShowCmd
import java.awt.Toolkit
@Service
internal class IjVimMessages : VimMessagesBase() {
private var message: String? = null
private var error = false
private var lastBeepTimeMillis = 0L
private var allowClearStatusBarMessage = true
override fun showStatusBarMessage(editor: VimEditor?, message: String?) {
fun setStatusBarMessage(project: Project, message: String?) {
WindowManager.getInstance().getStatusBar(project)?.let {
it.info = if (message.isNullOrBlank()) "" else "Vim - $message"
}
}
this.message = message
val project = editor?.ij?.project
if (project != null) {
setStatusBarMessage(project, message)
}
else {
// TODO: We really shouldn't set the status bar text for other projects. That's rude.
ProjectManager.getInstance().openProjects.forEach {
setStatusBarMessage(it, message)
}
}
// Redraw happens automatically based on changes or scrolling. If we've just set the message (e.g., searching for a
// string, hitting the bottom and scrolling to the top), make sure we don't immediately clear it when scrolling.
allowClearStatusBarMessage = false
ApplicationManager.getApplication().invokeLater {
allowClearStatusBarMessage = true
}
}
override fun getStatusBarMessage(): String? = message
// Vim doesn't appear to have a policy about clearing the status bar, other than on "redraw". This can be forced with
// <C-L> or the `:redraw` command, but also happens as the screen changes, e.g., when inserting or deleting lines,
// scrolling, entering Command-line mode and probably lots more. We should manually clear the status bar when these
// things happen.
override fun clearStatusBarMessage() {
if (message.isNullOrEmpty()) return
// Don't clear the status bar message if we've only just set it
if (!allowClearStatusBarMessage) return
ProjectManager.getInstance().openProjects.forEach { project ->
WindowManager.getInstance().getStatusBar(project)?.let { statusBar ->
// Only clear the status bar if it's showing our last message
if (statusBar.info?.contains(message.toString()) == true) {
statusBar.info = ""
}
}
}
message = null
}
override fun indicateError() {
error = true
if (!ApplicationManager.getApplication().isUnitTestMode) {
if (!injector.globalOptions().visualbell) {
// Vim only allows a beep once every half second - :help 'visualbell'
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - lastBeepTimeMillis > 500) {
Toolkit.getDefaultToolkit().beep()
lastBeepTimeMillis = currentTimeMillis
}
}
}
}
override fun clearError() {
error = false
}
override fun isError(): Boolean = error
override fun message(key: String, vararg params: Any): String = MessageHelper.message(key, *params)
override fun updateStatusBar(editor: VimEditor) {
ShowCmd.update()
}
}
| 6 | Kotlin | 749 | 9,241 | 66b01b0b0d48ffec7b0148465b85e43dfbc908d3 | 3,789 | ideavim | MIT License |
app/src/main/java/nl/appt/services/ApptService.kt | appt-nl | 277,572,532 | false | null | package nl.appt.services
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.graphics.Region
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityManager
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.hardware.display.DisplayManagerCompat
import nl.appt.R
import nl.appt.extensions.setGestures
import nl.appt.extensions.setInstructions
import nl.appt.model.Constants
import nl.appt.model.Gesture
import nl.appt.tabs.training.gestures.GestureActivity
import java.io.Serializable
/**
* This is where the magic happens.
* Running an AccessibilityService makes gestures "bypass" other services such as TalkBack and Voice Assistant.
* The ApptService hooks into accessibility events and gestures.
*
* Created by <NAME> on 09/10/2020
* Copyright 2020 Stichting Appt
*/
class ApptService: AccessibilityService() {
private val TAG = "ApptService"
private val GESTURE_TRAINING_CLASS_NAME = GestureActivity::class.java.name
override fun onCreate() {
super.onCreate()
Log.i(TAG, "onCreate")
// Set passthrough regions
setPassthroughRegions()
// Start GestureActivity
startGestureTraining()
}
private fun setPassthroughRegions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ContextCompat.getSystemService(this, WindowManager::class.java)?.let { windowManager ->
val bounds = windowManager.currentWindowMetrics.bounds
val region = Region(bounds.left, bounds.top, bounds.right, bounds.bottom)
val displays = DisplayManagerCompat.getInstance(this).displays
displays.forEach { display ->
Log.d(TAG, "Setting passthrough for display ${display.displayId} to: $region")
setTouchExplorationPassthroughRegion(display.displayId, region)
setGestureDetectionPassthroughRegion(display.displayId, region)
}
}
}
}
override fun onKeyEvent(event: KeyEvent?): Boolean {
Log.d(TAG, "onKeyEvent: $event")
return super.onKeyEvent(event)
}
override fun onServiceConnected() {
Log.i(TAG, "Service connected")
super.onServiceConnected()
}
override fun onUnbind(intent: Intent?): Boolean {
Log.i(TAG, "onUnbind")
return super.onUnbind(intent)
}
override fun onInterrupt() {
Log.i(TAG, "onInterrupt")
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
Log.i(TAG, "onAccessibilityEvent: $event")
// Continue if eventType = TYPE_WINDOW_STATE_CHANGED
if (event == null || event.eventType != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
return
}
// Continue if packageName is empty
if (event.packageName == null || event.packageName.isEmpty()) {
return
}
// Continue if event does not come from own package
if (event.packageName == this.packageName) {
return
}
// Continue if event does not come from accessibility package
if (event.packageName.contains("accessibility")) {
return
}
// Continue if text does not contain the service label
val serviceName = getString(R.string.service_label)
if (event.text.contains(serviceName)) {
return
}
// Continue if the gesture training is not active
if (isGestureTraining()) {
return
}
// Kill the service
kill()
}
override fun onGesture(gestureId: Int): Boolean {
Log.i(TAG, "onGesture: $gestureId")
// Broadcast gesture to GestureActivity
Gesture.from(gestureId)?.let { gesture ->
broadcast(Constants.SERVICE_GESTURE, gesture)
}
// Kill service if touch exploration is disabled
if (!isTouchExploring()) {
kill()
return false
}
return true
}
private fun broadcast(key: String, value: Serializable) {
val intent = Intent(Constants.SERVICE_ACTION)
intent.setPackage(packageName)
intent.putExtra(key, value)
sendBroadcast(intent)
}
private fun kill() {
broadcast(Constants.SERVICE_KILLED, true)
disableSelf()
}
private fun isTouchExploring(): Boolean {
var count = 0
val manager = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
val services = manager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)
for (service in services) {
val flags = service.capabilities
val capability = AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_TOUCH_EXPLORATION
// Check if Touch Exploration capability is granted
if (flags and capability == capability) {
count++
}
}
// Touch Exploration capability should be granted to at least two services: ApptService and TalkBack/VoiceAssistant/other.
return count >= 2
}
private fun isGestureTraining(): Boolean {
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.getRunningTasks(1).firstOrNull()?.topActivity?.let { activity ->
return activity.className == GESTURE_TRAINING_CLASS_NAME
}
return false
}
private fun startGestureTraining() {
val gestures = Gesture.randomized()
gestures.forEach { gesture ->
gesture.completed(this, false)
}
val intent = Intent(this, GestureActivity::class.java)
intent.setGestures(gestures)
intent.setInstructions(instructions)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
companion object {
fun isEnabled(context: Context): Boolean {
(context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager).let { manager ->
val services = manager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)
for (service in services) {
if (service.resolveInfo.serviceInfo.name == ApptService::class.java.name) {
return true
}
}
}
return false
}
fun enable(context: Context, instructions: Boolean = false) {
this.instructions = instructions
AlertDialog.Builder(context)
.setTitle(R.string.service_enable_title)
.setMessage(R.string.service_enable_message)
.setPositiveButton(R.string.action_activate) { _, _ ->
val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
.setNegativeButton(R.string.action_cancel) { _, _ ->
// Dismiss
}
.setCancelable(false)
.show()
}
var instructions = true
}
} | 0 | Kotlin | 0 | 1 | f6f642be53a805d4056fd8515f33f842f8b5ff67 | 7,652 | appt-android | MIT License |
Demo/src/main/java/com/paypal/android/ui/testcards/TestCardsDataViewHolder.kt | paypal | 390,097,712 | false | null | package com.paypal.android.ui.testcards
import androidx.recyclerview.widget.RecyclerView
import com.paypal.android.databinding.ItemTestCardsDataBinding
class TestCardsDataViewHolder(
private val binding: ItemTestCardsDataBinding,
private val listener: TestCardsListener
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: TestCardsItem.Data) {
binding.run {
name.text = item.testCard.name
cardNumber.text = item.testCard.card.number
root.setOnClickListener {
listener.onTestCardSelected(item.testCard)
}
}
}
}
| 4 | Kotlin | 25 | 32 | 0dc7d6e3899048ad0ff383384f2c814b4bbc5e11 | 617 | Android-SDK | Apache License 2.0 |
app/src/main/java/com/mustafa/movieguideapp/view/viewholder/SectionRow.kt | naufalprakoso | 287,474,167 | true | {"Kotlin": 492294} | package com.mustafa.movieapp.view.viewholder
/**
* https://github.com/skydoves/TheMovies
*/
data class SectionRow(
var section: Int = 0,
var row: Int = 0
) {
fun nextSection() {
this.section++
this.row = 0
}
fun nextRow() = row++
} | 0 | Kotlin | 0 | 0 | a64da3622d0c2fb8f8d83f5a913979c471f6b3bf | 272 | MoviesApp | Apache License 2.0 |
app/src/main/java/com/jiangkang/ktools/FileSystemActivity.kt | Androidwl | 317,710,299 | true | {"Kotlin": 2368794, "JavaScript": 136056, "Java": 30535, "C++": 5737, "HTML": 5095, "CMake": 2645, "CSS": 2570, "Shell": 429} | package com.jiangkang.ktools
import android.app.ProgressDialog
import android.content.res.AssetManager
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.jiangkang.tools.utils.FileUtils
import com.jiangkang.tools.utils.ToastUtils
import com.jiangkang.tools.widget.KDialog
import kotlinx.android.synthetic.main.activity_file_system.*
import org.json.JSONException
import org.json.JSONObject
import java.io.*
import java.util.*
import java.util.concurrent.Executors
/**
* @author jiangkang
*/
class FileSystemActivity : AppCompatActivity() {
var mProgressDialog: ProgressDialog? = null
private var assetManager: AssetManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_file_system)
assetManager = assets
mProgressDialog = ProgressDialog(this)
handleClick()
}
private fun handleClick() {
btn_get_general_file_path.setOnClickListener {
onBtnGetGeneralFilePathClicked()
}
btn_get_img_from_assets.setOnClickListener {
onBtnGetImgFromAssetsClicked()
}
btn_get_audio_from_assets.setOnClickListener {
onBtnGetAudioFromAssetsClicked()
}
btn_get_json_from_assets.setOnClickListener {
onBtnGetJsonFromAssetsClicked()
}
btn_create_file.setOnClickListener {
onBtnCreateFileClicked()
}
btn_get_file_size.setOnClickListener {
onBtnGetFileSizeClicked()
}
btn_get_dir_size.setOnClickListener {
onBtnGetDirSizeClicked()
}
btn_delete_file.setOnClickListener {
onBtnDeleteFileClicked()
}
btn_hide_file.setOnClickListener {
onBtnHideFileClicked()
}
}
fun onBtnGetGeneralFilePathClicked() {
val builder = StringBuilder()
builder.append("""context.getExternalCacheDir():
--${externalCacheDir!!.absolutePath}
""")
builder.append("""context.getCacheDir():
--${cacheDir.absolutePath}
""")
builder.append("""context.getExternalFilesDir(Environment.DIRECTORY_PICTURES):
--${getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!.absolutePath}
""")
builder.append("""context.getFilesDir():
--${filesDir.absolutePath}
""")
KDialog.showMsgDialog(this, builder.toString())
}
fun onBtnGetImgFromAssetsClicked() {
try {
val inputStream = assetManager!!.open("img/dog.jpg")
val bitmap = BitmapFactory.decodeStream(inputStream)
KDialog.showImgInDialog(this, bitmap)
} catch (e: IOException) {
e.printStackTrace()
}
}
fun onBtnGetAudioFromAssetsClicked() {
try {
val descriptor = FileUtils.getAssetFileDescription("music/baiyemeng.mp3")
val player = MediaPlayer()
player.setDataSource(descriptor.fileDescriptor, descriptor.startOffset, descriptor.length)
player.prepareAsync()
player.setOnPreparedListener { mp -> showPlayerDialog(mp) }
} catch (e: IOException) {
e.printStackTrace()
}
}
fun onBtnGetJsonFromAssetsClicked() {
var inputStreamReader: InputStreamReader? = null
try {
inputStreamReader = InputStreamReader(assetManager!!.open("json/demo.json"))
val reader = BufferedReader(inputStreamReader)
val builder = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
builder.append(line)
}
val jsonStr = builder.toString()
val json = JSONObject(jsonStr)
KDialog.showMsgDialog(this, json.toString(4))
} catch (e: IOException) {
} catch (e: JSONException) {
} finally {
if (inputStreamReader != null) {
try {
inputStreamReader.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
fun onBtnCreateFileClicked() {
val isSuccess = FileUtils.createFile("test.txt", Environment.getExternalStorageDirectory().absolutePath + File.separator + "ktools")
ToastUtils.showShortToast(if (isSuccess) "test.txt在ktools文件夹下创建成功" else "创建失败")
}
fun onBtnGetFileSizeClicked() {
FileUtils.createFile("demo.txt", Environment.getExternalStorageDirectory().absolutePath + File.separator + "ktools")
val file = File(Environment.getExternalStorageDirectory().absolutePath + File.separator + "ktools", "demo.txt")
FileUtils.writeStringToFile("这只是一个测试文件,测试文件", file, false)
if (file.exists() && file.isFile) {
try {
val fis = FileInputStream(file)
val size = fis.available().toLong()
ToastUtils.showShortToast("size = " + size + "B")
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
} else {
ToastUtils.showShortToast("文件不存在")
}
}
fun onBtnGetDirSizeClicked() {
Executors.newSingleThreadExecutor().execute {
showProgressDialog()
val size = FileUtils.getFolderSize(Environment.getExternalStorageDirectory().absolutePath)
closeProgressDialog()
KDialog.showMsgDialog(this@FileSystemActivity, "存储器根目录大小为" + (size / (1024 * 1024)).toString() + "M")
}
}
fun onBtnDeleteFileClicked() {
val file = File(Environment.getExternalStorageDirectory().absolutePath + File.separator + "ktools",
"test.txt")
if (!file.exists()) {
ToastUtils.showShortToast("要删除的文件不存在")
} else {
val isDone = file.delete()
ToastUtils.showShortToast(if (isDone) "删除成功" else "删除失败")
}
}
private fun showPlayerDialog(player: MediaPlayer) {
val duration = player.duration
val view = LayoutInflater.from(this).inflate(R.layout.layout_dialog_music_player, null)
val seekBar = view.findViewById<SeekBar>(R.id.seek_bar_music)
seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
//此处干扰正常播放,声音抖动
val max = seekBar.max
val destPosition = progress * duration / max
player.seekTo(destPosition)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
view.findViewById<View>(R.id.iv_play).setOnClickListener { player.start() }
view.findViewById<View>(R.id.iv_pause).setOnClickListener { player.pause() }
view.findViewById<View>(R.id.iv_stop).setOnClickListener { player.stop() }
val timer = Timer()
timer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
runOnUiThread {
val currentPosition = player.currentPosition
val progress = currentPosition * 100 / duration
seekBar.progress = progress
}
}
}, 0, 100)
val builder = AlertDialog.Builder(this)
builder.setCancelable(false)
.setTitle("播放器")
.setView(view)
.setNegativeButton("关闭") { dialog, which ->
if (player.isPlaying) {
player.stop()
}
dialog.dismiss()
}.show()
}
fun onBtnHideFileClicked() {
//隐藏文件或者文件夹只需要将文件名前面加一个‘.’号
val isSuccess = FileUtils.hideFile(Environment.getExternalStorageDirectory().absolutePath + File.separator + "ktools", "test.txt")
ToastUtils.showShortToast(if (isSuccess) "隐藏成功" else "隐藏失败")
}
private fun showProgressDialog() {
runOnUiThread {
mProgressDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
mProgressDialog!!.setMessage("正在查询中,请稍等....")
mProgressDialog!!.show()
}
}
private fun closeProgressDialog() {
runOnUiThread {
if (mProgressDialog != null && mProgressDialog!!.isShowing) {
mProgressDialog!!.hide()
}
}
}
companion object {
private val TAG = FileSystemActivity::class.java.simpleName
}
} | 0 | null | 0 | 0 | 03967b9324dc0c700ea9fca19e912cd4da18cf0d | 8,988 | KTools | MIT License |
app/src/androidTest/kotlin/com/ivanovsky/passnotes/TestData.kt | aivanovski | 95,774,290 | false | null | package com.ivanovsky.passnotes
import java.util.Calendar
object TestData {
const val DB_NAME = "test-db"
val PLAIN_TEXT = "abcdefghijklmnopqrstuvwxyzABDCEFGHIJKLMNOPQRSTUVWXYZ0123456789" +
"~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/\t\b\n\r_"
fun dateInMillis(year: Int, month: Int, day: Int): Long {
val cal = Calendar.getInstance()
cal.set(year, month, day, 0, 0, 0)
cal.set(Calendar.MILLISECOND, 0)
return cal.timeInMillis
}
} | 6 | null | 4 | 7 | dc4abdf847393919f5480129b64240ae0469b74c | 485 | kpassnotes | Apache License 2.0 |
7/src/test/kotlin/OrGateTest.kt | kopernic-pl | 109,750,709 | false | null | import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
internal class OrGateTest {
@Test
fun `should apply or function`() {
val a = 10
val b = 20
assertEquals(30, OrGate(listOf(), "").apply(a, b))
}
@Test
fun `should provide template and match input text`() {
val a = "ab OR ad -> ae"
assertTrue { OrGate.template.toRegex() matches a }
}
}
| 0 | Kotlin | 0 | 0 | 06367f7e16c0db340c7bda8bc2ff991756e80e5b | 439 | aoc-2015-kotlin | The Unlicense |
lib/network/src/main/java/com/jnyakush/carhub/network/network/Exceptions.kt | jamesnyakush | 227,105,123 | false | null | package com.jnyakush.carhub.network.network
import java.io.IOException
class ApiException(msg: String) : IOException(msg)
class NoInternetException(msg: String) : IOException(msg) | 2 | Kotlin | 4 | 9 | 71c992b17d447e6e7e73d5133ece6b73b901ef28 | 181 | truck-hub | Apache License 2.0 |
src/main/kotlin/dev/alphaserpentis/bots/zeroextheta/handlers/bot/AutocompleteHandler.kt | Alpha-Serpentis-Developments | 699,477,043 | false | {"Kotlin": 116560} | package dev.alphaserpentis.bots.zeroextheta.handlers.bot
import dev.alphaserpentis.bots.zeroextheta.commands.AutocompleteCmd
import dev.alphaserpentis.coffeecore.handler.api.discord.commands.CommandsHandler
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
class AutocompleteHandler(
private val mappingOfCommands: HashMap<String, AutocompleteCmd> = HashMap(),
private val commandsHandler: CommandsHandler
) : ListenerAdapter() {
override fun onCommandAutoCompleteInteraction(event: CommandAutoCompleteInteractionEvent) {
val command = findCommand(event.name) ?: return
val choices = command.suggest(event)
event.replyChoiceStrings(choices).queue()
}
private fun findCommand(name: String): AutocompleteCmd? {
val command = mappingOfCommands[name]
if (command == null) {
val searchedCmd = commandsHandler.getCommand(name)
return if (searchedCmd is AutocompleteCmd) {
mappingOfCommands[name] = searchedCmd
searchedCmd
} else {
null
}
} else {
return command
}
}
} | 0 | Kotlin | 0 | 0 | cdbf0e8f425235617c729fc0b538f0f29c256302 | 1,245 | Project-Theta | MIT License |
src/main/kotlin/com/example/services/S3Service.kt | itshedimisawi | 851,502,962 | false | {"Kotlin": 42498} | package com.example.services
import com.example.constants.StaticPath
import io.ktor.http.content.*
interface S3Service {
// uploads Ktor multipart file to S3 bucket and returns the URL
suspend fun PartData.FileItem.uploadToS3(path: StaticPath): String
} | 0 | Kotlin | 0 | 3 | 07f0607f09aa028ea7dd98fe16c2153b11f2c539 | 263 | ktor-integrations | MIT License |
libraries/scripting/js/src/org/jetbrains/kotlin/scripting/repl/js/JsReplUtils.kt | cortinico | 282,973,729 | false | {"Markdown": 70, "Gradle": 729, "Gradle Kotlin DSL": 570, "Java Properties": 15, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 8, "Kotlin": 61867, "Protocol Buffer": 12, "Java": 6670, "Proguard": 12, "XML": 1607, "Text": 13214, "INI": 178, "JavaScript": 287, "JAR Manifest": 2, "Roff": 213, "Roff Manpage": 38, "AsciiDoc": 1, "HTML": 495, "SVG": 50, "Groovy": 33, "JSON": 186, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 9, "Ant Build System": 50, "Graphviz (DOT)": 77, "C": 1, "Ruby": 5, "Objective-C": 8, "OpenStep Property List": 5, "Swift": 5, "Scala": 1, "YAML": 16} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.scripting.repl.js
import org.jetbrains.kotlin.cli.common.repl.*
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ScriptDescriptor
import org.jetbrains.kotlin.ir.backend.js.utils.NameTables
import org.jetbrains.kotlin.js.engine.ScriptEngineWithTypedResult
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.reflect.KClass
import kotlin.script.experimental.api.CompiledScript
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.api.ScriptCompilationConfiguration
import kotlin.script.experimental.api.ScriptEvaluationConfiguration
abstract class JsState(override val lock: ReentrantReadWriteLock) : IReplStageState<ScriptDescriptor> {
override val history: IReplStageHistory<ScriptDescriptor>
get() = TODO("not implemented")
override val currentGeneration: Int
get() = TODO("not implemented")
}
abstract class JsCompilationState(
lock: ReentrantReadWriteLock,
val nameTables: NameTables,
val dependencies: List<ModuleDescriptor>) : JsState(lock)
class JsEvaluationState(lock: ReentrantReadWriteLock, val engine: ScriptEngineWithTypedResult) : JsState(lock) {
override fun dispose() {
engine.reset()
}
}
class JsCompiledScript(
val jsCode: String,
override val compilationConfiguration: ScriptCompilationConfiguration
) : CompiledScript {
override suspend fun getClass(scriptEvaluationConfiguration: ScriptEvaluationConfiguration?): ResultWithDiagnostics<KClass<*>> {
throw IllegalStateException("Class is not available for JS implementation")
}
}
| 1 | null | 1 | 1 | 786e1fdec2fbb25ae58837a6dec8036fbd914da2 | 1,877 | kotlin | Apache License 2.0 |
src/main/kotlin/net/wiredtomato/burgered/init/BurgeredItems.kt | wired-tomato | 835,870,549 | false | {"Kotlin": 95855, "Java": 1521} | package net.wiredtomato.burgered.init
import net.minecraft.entity.effect.StatusEffectInstance
import net.minecraft.entity.effect.StatusEffects
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
import net.wiredtomato.burgered.Burgered
import net.wiredtomato.burgered.item.BurgerIngredientItem
import net.wiredtomato.burgered.item.BurgerIngredientItem.BurgerIngredientSettings
import net.wiredtomato.burgered.item.BurgerItem
import net.wiredtomato.burgered.item.VanillaItemBurgerIngredientItem
import net.wiredtomato.burgered.item.components.BurgerComponent
import net.wiredtomato.burgered.item.components.VanillaBurgerIngredientComponent
object BurgeredItems {
val TOP_BUN = register(
"top_bun",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(1)
.overSaturation(1.0)
.modelHeight(2.0)
)
)
val BOTTOM_BUN = register(
"bottom_bun",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(1)
.overSaturation(1.0)
.modelHeight(2.0)
)
)
val RAW_BEEF_PATTY = register(
"raw_beef_patty",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(1)
.overSaturation(2.0)
.modelHeight(1.0)
.statusEffect(StatusEffectInstance(StatusEffects.POISON, 200, 2), 0.25f)
)
)
val BEEF_PATTY = register(
"beef_patty",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(4)
.overSaturation(8.0)
.modelHeight(1.0)
)
)
val CHEESE_SLICE = register(
"cheese_slice",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(1)
.overSaturation(0.25)
.modelHeight(1.0)
)
)
val LETTUCE = register(
"lettuce",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(1)
.overSaturation(0.25)
.modelHeight(0.0)
)
)
val EDIBLE_BOOK = register(
"edible_book",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(7)
.overSaturation(8.0)
.modelHeight(4.0)
)
)
val PICKLED_BEETS = register(
"pickled_beets",
BurgerIngredientItem(
BurgerIngredientSettings()
.saturation(2)
.overSaturation(1.0)
.modelHeight(0.0)
)
)
val ESTROGEN_WAFFLE = register("estrogen_waffle", Item(Item.Settings()))
val CUSTOM_BURGER_INGREDIENT = register(
"custom_burger_ingredient",
Item(Item.Settings())
)
val VANILLA_INGREDIENT = register(
"vanilla_ingredient",
VanillaItemBurgerIngredientItem(
BurgerIngredientSettings()
.saturation(2)
.overSaturation(4.0)
.modelHeight(1.0)
.component(BurgeredDataComponents.VANILLA_BURGER_INGREDIENT, VanillaBurgerIngredientComponent.DEFAULT)
)
)
val BURGER = register(
"burger",
BurgerItem(
Item.Settings()
.component(BurgeredDataComponents.BURGER, BurgerComponent.DEFAULT)
)
)
val BOOK_OF_BURGERS = register(
"book_of_burgers",
Item(Item.Settings())
)
val BURGER_STACKER = register("burger_stacker", BlockItem(BurgeredBlocks.BURGER_STACKER, Item.Settings()))
val GRILL = register("grill", BlockItem(BurgeredBlocks.GRILL, Item.Settings()))
fun <T : Item> register(name: String, item: T): T {
return Registry.register(Registries.ITEM, Burgered.id(name), item)
}
} | 0 | Kotlin | 0 | 0 | c4f7c275fea3d0517ca6f26c5a295c7fa500752a | 3,996 | burgered | MIT License |
ahuahu-app.android/app/src/main/java/com/cap0097/ahuahuapp/ui/history/HistoryViewModel.kt | MohammadFebriyanto | 368,417,018 | false | null | package com.cap0097.ahuahuapp.ui.history
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.cap0097.ahuahuapp.data.local.HistoryEntity
import com.cap0097.ahuahuapp.domain.repository.Repository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class HistoryViewModel @Inject constructor(private val repository: Repository) : ViewModel(){
private lateinit var history : LiveData<List<HistoryEntity>>
fun setAllHistory(){
history = repository.getAllHistory()
}
fun getAllHistory() : LiveData<List<HistoryEntity>> = history
} | 0 | Kotlin | 3 | 2 | 7b344ba82a50bb2de0f8422d8a54c785decf38b4 | 624 | ahuahu_app | MIT License |
io/netty/src/main/kotlin/io/bluetape4k/netty/buffer/USmart.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.netty.buffer
object USmart {
const val MAX_BYTE_VALUE: Int = Byte.MAX_VALUE.toInt()
const val MIN_BYTE_VALUE: Int = 0
const val MAX_SHORT_VALUE: Int = Short.MAX_VALUE.toInt()
const val MIN_SHORT_VALUE: Int = 0
const val MAX_INT_VALUE: Int = Int.MAX_VALUE
const val MIN_INT_VALUE: Int = 0
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 337 | bluetape4k | MIT License |
tests/app/app/src/androidTest/java/com/github/tarcv/test/F2Filter.kt | TarCV | 186,752,953 | false | null | package com.github.tarcv.test
import org.junit.runner.Description
import org.junit.runner.manipulation.Filter
class F2Filter : Filter() {
override fun shouldRun(description: Description): Boolean {
val filteredOutTest = description.methodName?.startsWith("filteredByF2Filter") == true
return !filteredOutTest
}
override fun describe(): String = "Filter out filteredByF2Filter test case"
} | 1 | Kotlin | 1 | 1 | 2d053ccc639d22d1032212b9324befd055b5b2b6 | 419 | tongs | Apache License 2.0 |
src/main/kotlin/Day3_IntroToConditionalstatements/IntroToConditionalStatements.kt | StefanyMikaelle | 800,931,289 | false | {"Kotlin": 10311} | package Day3_IntroToConditionalstatements
import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*
fun main(args: Array<String>) {
val N = readLine()!!.trim().toInt()
when {
N % 2 != 0 -> println("Weird")
N in 2..5 -> println("Not Weird")
N in 6..20 -> println("Weird")
N > 20 -> println("Not Weird")
}
} | 0 | Kotlin | 0 | 0 | ede96d1fc1a18737e321bcabdab605b37a57bd3c | 727 | _30DaysOfCode | MIT License |
actions/java/com/squareup/tools/sqldelight/cli/Args.kt | ThomasCJY | 362,622,239 | true | {"Starlark": 15261, "Kotlin": 5282} | package com.squareup.tools.sqldelight.cli
import com.beust.jcommander.JCommander
import com.beust.jcommander.Parameter
import java.io.File
/** Holds the CLI flags */
object Args : Validating {
@Parameter(names = ["--help"], help = true)
var help = false
@Parameter(
names = ["--output_srcjar", "-o"],
description = "Srcjar of generated code.",
required = true
)
lateinit var srcJar: File
@Parameter(description = "<list of SQL files to process>")
lateinit var fileNames: List<String>
@Parameter(
names = ["--src_dirs"],
description = "Directories containing all srcs",
required = true
)
lateinit var srcDirs: List<File>
@Parameter(
names = ["--package_name"],
required = false,
description = "Package into which the code will be generated (not required for legacy)"
)
var packageName: String? = null
@Parameter(
names = ["--module_name"],
required = false,
description = "Module Name for Kotlin compilation (not required for legacy)"
)
var moduleName: String? = null
override fun validate(context: JCommander): Int? {
if (context.objects.size != 1) throw AssertionError("Processed wrong number of Args classes.")
if (moduleName == null || packageName == null) {
context.usage()
}
if (help) {
context.usage()
return 0 // valid run, but should terminate early.
}
if (fileNames.isEmpty()) {
println("Must set at least one file.")
context.usage()
return 1
}
return null
}
}
| 0 | null | 0 | 0 | 07171e39d5340861123368607e6118de9f2b140e | 1,534 | sqldelight_bazel_rules | Apache License 2.0 |
domain/teamplay-business-domain/src/main/kotlin/com/teamplay/domain/business/user/dto/InputPasswordAndRealPassword.kt | YAPP-16th | 235,351,938 | false | {"Kotlin": 79474, "Java": 5820, "Shell": 224} | package com.teamplay.domain.business.user.dto
class InputPasswordAndRealPassword(
val inputPassword: String,
val realPassword: String
) | 2 | Kotlin | 0 | 1 | a3209b28ea6ca96cb9a81a0888793f9b0f4d02d2 | 144 | Team_Android_2_Backend | MIT License |
lib-restlet/src/main/java/handler/HandleGeneric.kt | rlexa | 137,722,856 | false | {"Kotlin": 9866} | package handler
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import resolver.IQueryResolver
import util.getQuery
import util.handleExchangeWithPayload
import viewer.IDataView
class HandleGeneric(
private val source: IQueryResolver,
private val view: IDataView,
private val contentType: String = "text/html; charset=UTF-8"
) : HttpHandler {
override fun handle(http: HttpExchange?) = with(http!!) {
responseHeaders.set("Content-Type", contentType)
handleExchangeWithPayload(this, view.transform(source.resolve(listOf(), getQuery(this))))
}
} | 0 | Kotlin | 0 | 0 | 5123c91f3e9ccb7ff271db11eebc5a4e72f6fcc8 | 600 | kotlin-research | MIT License |
vector/src/main/java/varta/cdac/app/features/crypto/verification/epoxy/BottomSheetVerificationNoticeItem.kt | Rontu22 | 395,765,587 | false | null | /*
* Copyright 2020 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package varta.cdac.app.features.crypto.verification.epoxy
import android.widget.TextView
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import varta.cdac.app.R
import varta.cdac.app.core.epoxy.VectorEpoxyHolder
import varta.cdac.app.core.epoxy.VectorEpoxyModel
/**
* A action for bottom sheet.
*/
@EpoxyModelClass(layout = R.layout.item_verification_notice)
abstract class BottomSheetVerificationNoticeItem : VectorEpoxyModel<BottomSheetVerificationNoticeItem.Holder>() {
@EpoxyAttribute
var notice: CharSequence = ""
override fun bind(holder: Holder) {
super.bind(holder)
holder.notice.text = notice
}
class Holder : VectorEpoxyHolder() {
val notice by bind<TextView>(R.id.itemVerificationNoticeText)
}
}
| 55 | Kotlin | 0 | 1 | ef17804af2f134cfbeca5645579f2fbb4b685944 | 1,390 | VartaApp1.1 | Apache License 2.0 |
libs/export-shapes-modal/src/main/kotlin/mono/export/ExportShapesHelper.kt | tuanchauict | 325,686,408 | false | null | /*
* Copyright (c) 2023, tuanchauict
*/
package mono.export
import mono.graphics.bitmap.MonoBitmap
import mono.graphics.board.Highlight
import mono.graphics.board.MonoBoard
import mono.graphics.geo.Rect
import mono.shape.shape.AbstractShape
import mono.shape.shape.Group
/**
* A helper class for exporting selected shapes.
*/
class ExportShapesHelper(
private val getBitmap: (AbstractShape) -> MonoBitmap?,
private val setClipboardText: (String) -> Unit
) {
fun exportText(shapes: List<AbstractShape>, isModalRequired: Boolean) {
if (shapes.isEmpty()) {
return
}
val left = shapes.minOf { it.bound.left }
val right = shapes.maxOf { it.bound.right }
val top = shapes.minOf { it.bound.top }
val bottom = shapes.maxOf { it.bound.bottom }
val window = Rect.byLTRB(left, top, right, bottom)
val exportingBoard = MonoBoard().apply { clearAndSetWindow(window) }
drawShapesOntoExportingBoard(exportingBoard, shapes)
val text = exportingBoard.toStringInBound(window)
if (isModalRequired) {
ExportShapesModal().show(text)
} else {
setClipboardText(text)
}
}
private fun drawShapesOntoExportingBoard(board: MonoBoard, shapes: Collection<AbstractShape>) {
for (shape in shapes) {
if (shape is Group) {
drawShapesOntoExportingBoard(board, shape.items)
continue
}
val bitmap = getBitmap(shape) ?: continue
board.fill(shape.bound.position, bitmap, Highlight.NO)
}
}
}
| 15 | Kotlin | 9 | 91 | 21cef26b45c984eee31ea2c3ba769dfe5eddd92e | 1,625 | MonoSketch | Apache License 2.0 |
app/src/main/java/com/connectycube/messenger/viewmodels/SelectUsersViewModelFactory.kt | ConnectyCube | 198,286,170 | false | {"Kotlin": 396454, "Java": 19119} | package com.connectycube.messenger.viewmodels
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.connectycube.messenger.data.UserRepository
class SelectFromExistUsersViewModelFactory(
private val applicationContext: Application,
private val usersRepository: UserRepository
) : ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>) =
SelectFromExistUsersViewModel(applicationContext, usersRepository) as T
} | 0 | Kotlin | 23 | 51 | 1b7a8942692791365a0c28140fd673eb7823b7cb | 576 | android-messenger-app | Apache License 2.0 |
app/src/main/java/com/p4indiafsm/features/alarm/api/report_confirm_api/ReviewConfirmRepo.kt | DebashisINT | 600,987,989 | false | null | package com.p4indiafsm.features.alarm.api.report_confirm_api
import com.p4indiafsm.base.BaseResponse
import com.p4indiafsm.features.alarm.model.ReviewConfirmInputModel
import io.reactivex.Observable
/**
* Created by Saikat on 21-02-2019.
*/
class ReviewConfirmRepo(val apiService: ReviewConfirmApi) {
fun reviewConfirm(reviewConfirm: ReviewConfirmInputModel): Observable<BaseResponse> {
return apiService.reviewConfirm(reviewConfirm)
}
} | 0 | Kotlin | 0 | 0 | 5ffdb2743eaf7f3e6fe1988cb97c67ebdae0d870 | 457 | P4India | Apache License 2.0 |
app/src/main/java/com/p4indiafsm/features/alarm/api/report_confirm_api/ReviewConfirmRepo.kt | DebashisINT | 600,987,989 | false | null | package com.p4indiafsm.features.alarm.api.report_confirm_api
import com.p4indiafsm.base.BaseResponse
import com.p4indiafsm.features.alarm.model.ReviewConfirmInputModel
import io.reactivex.Observable
/**
* Created by Saikat on 21-02-2019.
*/
class ReviewConfirmRepo(val apiService: ReviewConfirmApi) {
fun reviewConfirm(reviewConfirm: ReviewConfirmInputModel): Observable<BaseResponse> {
return apiService.reviewConfirm(reviewConfirm)
}
} | 0 | Kotlin | 0 | 0 | 5ffdb2743eaf7f3e6fe1988cb97c67ebdae0d870 | 457 | P4India | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/filled/SquareArrowRight.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.FilledGroup
public val FilledGroup.SquareArrowRight: ImageVector
get() {
if (_squareArrowRight != null) {
return _squareArrowRight!!
}
_squareArrowRight = Builder(name = "SquareArrowRight", defaultWidth = 24.0.dp, defaultHeight
= 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.0f, 2.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, 3.0f)
verticalLineToRelative(14.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, 3.0f)
horizontalLineToRelative(-14.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, -3.0f)
verticalLineToRelative(-14.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, -3.0f)
close()
moveTo(12.613f, 7.21f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.32f, 0.083f)
lineToRelative(-0.083f, 0.094f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.083f, 1.32f)
lineToRelative(2.292f, 2.293f)
horizontalLineToRelative(-5.585f)
lineToRelative(-0.117f, 0.007f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.117f, 1.993f)
horizontalLineToRelative(5.585f)
lineToRelative(-2.292f, 2.293f)
lineToRelative(-0.083f, 0.094f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.497f, 1.32f)
lineToRelative(4.0f, -4.0f)
lineToRelative(0.073f, -0.082f)
lineToRelative(0.074f, -0.104f)
lineToRelative(0.052f, -0.098f)
lineToRelative(0.044f, -0.11f)
lineToRelative(0.03f, -0.112f)
lineToRelative(0.017f, -0.126f)
lineToRelative(0.003f, -0.075f)
lineToRelative(-0.007f, -0.118f)
lineToRelative(-0.029f, -0.148f)
lineToRelative(-0.035f, -0.105f)
lineToRelative(-0.054f, -0.113f)
lineToRelative(-0.071f, -0.111f)
arcToRelative(1.008f, 1.008f, 0.0f, false, false, -0.097f, -0.112f)
lineToRelative(-4.0f, -4.0f)
close()
}
}
.build()
return _squareArrowRight!!
}
private var _squareArrowRight: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,280 | compose-icon-collections | MIT License |
branches/dcc/revocation/src/main/java/dcc/app/revocation/domain/ErrorHandler.kt | eu-digital-green-certificates | 355,126,967 | false | null | /*
* ---license-start
* eu-digital-green-certificates / dcc-revocation-app-android
* ---
* Copyright (C) 2021 T-Systems International GmbH and all other contributors
* ---
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ---license-end
*
* Created by mykhailo.nester on 24/12/2021, 15:45
*/
package dcc.app.revocation.domain
/**
* Error handler that can convert data layer errors into domain layer types.
*/
interface ErrorHandler {
/**
* Convert Throwable into app readable error type.
*
* @param throwable data storage or network error
* @return dcc.app.revocation.domain.ErrorType domain app type
*/
fun getError(throwable: Throwable): ErrorType
} | 20 | Kotlin | 118 | 103 | 1e88269edf98650a17984106a7d002569fdd4031 | 1,222 | dgca-verifier-app-android | Apache License 2.0 |
server/server/src/main/kotlin/org/jetbrains/bsp/bazel/server/sync/TargetTagsResolver.kt | JetBrains | 826,262,028 | false | {"Kotlin": 3064918, "Starlark": 370388, "Java": 165158, "Scala": 37245, "Python": 34754, "Lex": 17493, "Dockerfile": 8674, "Shell": 7379, "HTML": 1310, "Rust": 680, "Go": 428, "C++": 113} | package org.jetbrains.bsp.bazel.server.sync
import org.jetbrains.bsp.bazel.info.BspTargetInfo
import org.jetbrains.bsp.bazel.server.model.Tag
class TargetTagsResolver {
fun resolveTags(targetInfo: BspTargetInfo.TargetInfo): Set<Tag> {
if (targetInfo.kind == "resources_union" ||
targetInfo.kind == "java_import" ||
targetInfo.kind == "aar_import"
) {
return setOf(Tag.LIBRARY)
}
val tagsFromSuffix =
ruleSuffixToTargetType
.filterKeys {
targetInfo.kind.endsWith("_$it") || targetInfo.kind == it
}.values
.firstOrNull()
.orEmpty()
// Tests *are* executable, but there's hardly a reason why one would like to `bazel run` a test
val application = Tag.APPLICATION.takeIf { targetInfo.executable && !tagsFromSuffix.contains(Tag.TEST) }
return setOfNotNull(
application,
) + mapBazelTags(targetInfo.tagsList) + tagsFromSuffix
}
private fun mapBazelTags(tags: List<String>): Set<Tag> = tags.mapNotNull { bazelTagMap[it] }.toSet()
companion object {
private val bazelTagMap =
mapOf(
"no-ide" to Tag.NO_IDE,
"manual" to Tag.MANUAL,
)
private val ruleSuffixToTargetType =
mapOf(
"library" to setOf(Tag.LIBRARY),
"binary" to setOf(Tag.APPLICATION),
"test" to setOf(Tag.TEST),
"proc_macro" to setOf(Tag.LIBRARY),
"intellij_plugin_debug_target" to setOf(Tag.INTELLIJ_PLUGIN, Tag.APPLICATION),
"plugin" to setOf(Tag.LIBRARY),
)
}
}
| 2 | Kotlin | 18 | 45 | 1d79484cfdf8fc31d3a4b214655e857214071723 | 1,535 | hirschgarten | Apache License 2.0 |
defaults/src/commonMain/kotlin/jp/pois/oxacillin/defaults/endpoints/account/Profile.kt | pois0 | 339,318,315 | true | {"Kotlin": 1970084} | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 StarryBlueSky
* Copyright (c) 2021 poispois
*
* 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.
*/
@file:Suppress("UNUSED", "NOTHING_TO_INLINE")
package jp.pois.oxacillin.defaults.endpoints.account
import jp.pois.oxacillin.core.request.action.JsonGeneralApiAction
import jp.pois.oxacillin.defaults.endpoints.Account
import jp.pois.oxacillin.defaults.models.User
import jp.pois.oxacillin.endpoints.Option
import jp.pois.oxacillin.endpoints.account
import jp.pois.oxacillin.endpoints.account.updateProfile
/**
* Sets some values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile)
*
* @param name Optional. Full name associated with the profile.
* @param url URL associated with the profile. Will be prepended with `http://` if not present.
* @param location The city or country describing where the user of the account is located. The contents are not normalized or geocoded in any way.
* @param description A description of the user owning the account.
* @param profileLinkColor Sets a hex value that controls the color scheme of links used on the authenticating user's profile page on twitter.com. This must be a valid hexadecimal value, and may be either three or six characters (ex: F00 or FF0000). This parameter replaces the deprecated (and separate) update_profile_colors API method.
* @param includeEntities The entities node will not be included when set to *false*.
* @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user object.
* @param options Optional. Custom parameters of this request.
* @receiver [Account] endpoint instance.
* @return [JsonGeneralApiAction] for [User] model.
*/
public inline fun Account.updateProfile(
name: String? = null,
url: String? = null,
location: String? = null,
description: String? = null,
profileLinkColor: String? = null,
includeEntities: Boolean? = null,
skipStatus: Boolean? = null,
birthdateYear: Int? = null,
birthdateMonth: Int? = null,
birthdateDay: Int? = null,
vararg options: Option
): JsonGeneralApiAction<User> = client.account.updateProfile(name, url, location, description, profileLinkColor, includeEntities, skipStatus, birthdateYear, birthdateMonth, birthdateDay, *options)
/**
* Shorthand extension property to [Account.updateProfile].
* @see Account.updateProfile
*/
public inline val Account.updateProfile: JsonGeneralApiAction<User>
get() = updateProfile()
| 0 | Kotlin | 0 | 0 | bc33905228c2a1ecf954fbeed53b08323cde6d41 | 3,755 | Oxacillin | MIT License |
app/src/main/java/com/dluvian/voyage/data/room/dao/RootPostDao.kt | dluvian | 766,355,809 | false | null | package com.dluvian.voyage.data.room.dao
import androidx.room.Dao
import androidx.room.Query
import com.dluvian.voyage.core.EventIdHex
import com.dluvian.voyage.core.PubkeyHex
import com.dluvian.voyage.core.Topic
import com.dluvian.voyage.data.room.view.RootPostView
import kotlinx.coroutines.flow.Flow
private const val TOPIC_FEED_BASE_QUERY = "FROM RootPostView " +
"WHERE createdAt <= :until " +
"AND authorIsMuted = 0 " +
"AND authorIsLocked = 0 " +
"AND id IN (SELECT eventId FROM hashtag WHERE hashtag = :topic) " +
"AND NOT EXISTS (SELECT * FROM hashtag WHERE eventId = id AND hashtag IN (SELECT mutedItem FROM mute WHERE tag IS 't' AND mutedItem IS NOT :topic)) " +
"ORDER BY createdAt DESC " +
"LIMIT :size"
private const val TOPIC_FEED_QUERY = "SELECT * $TOPIC_FEED_BASE_QUERY"
private const val TOPIC_FEED_CREATED_AT_QUERY = "SELECT createdAt $TOPIC_FEED_BASE_QUERY"
private const val TOPIC_FEED_EXISTS_QUERY = "SELECT EXISTS($TOPIC_FEED_QUERY)"
private const val PROFILE_FEED_BASE_QUERY = "FROM RootPostView " +
"WHERE createdAt <= :until " +
"AND pubkey = :pubkey " +
"ORDER BY createdAt DESC " +
"LIMIT :size"
private const val PROFILE_FEED_QUERY = "SELECT * $PROFILE_FEED_BASE_QUERY"
private const val PROFILE_FEED_CREATED_AT_QUERY = "SELECT createdAt $PROFILE_FEED_BASE_QUERY"
private const val PROFILE_FEED_EXISTS_QUERY = "SELECT EXISTS($PROFILE_FEED_QUERY)"
private const val LIST_FEED_BASE_QUERY = """
FROM RootPostView
WHERE createdAt <= :until
AND (
pubkey IN (SELECT pubkey FROM profileSetItem WHERE identifier = :identifier)
OR id IN (SELECT eventId FROM hashtag WHERE hashtag IN (SELECT topic FROM topicSetItem WHERE identifier = :identifier))
)
AND authorIsMuted = 0
AND authorIsLocked = 0
AND NOT EXISTS (SELECT * FROM hashtag WHERE eventId = id AND hashtag IN (SELECT mutedItem FROM mute WHERE tag IS 't'))
ORDER BY createdAt DESC
LIMIT :size
"""
private const val LIST_FEED_QUERY = "SELECT * $LIST_FEED_BASE_QUERY"
private const val LIST_FEED_CREATED_AT_QUERY = "SELECT createdAt $LIST_FEED_BASE_QUERY"
private const val LIST_FEED_EXISTS_QUERY = "SELECT EXISTS($LIST_FEED_QUERY)"
@Dao
interface RootPostDao {
@Query("SELECT * FROM RootPostView WHERE id = :id")
fun getRootPostFlow(id: EventIdHex): Flow<RootPostView?>
@Query(TOPIC_FEED_QUERY)
fun getTopicRootPostFlow(topic: Topic, until: Long, size: Int): Flow<List<RootPostView>>
@Query(TOPIC_FEED_EXISTS_QUERY)
fun hasTopicRootPostsFlow(
topic: Topic,
until: Long = Long.MAX_VALUE,
size: Int = 1
): Flow<Boolean>
@Query(TOPIC_FEED_QUERY)
suspend fun getTopicRootPosts(topic: Topic, until: Long, size: Int): List<RootPostView>
@Query(TOPIC_FEED_CREATED_AT_QUERY)
suspend fun getTopicRootPostsCreatedAt(topic: Topic, until: Long, size: Int): List<Long>
@Query(PROFILE_FEED_QUERY)
fun getProfileRootPostFlow(pubkey: PubkeyHex, until: Long, size: Int): Flow<List<RootPostView>>
@Query(PROFILE_FEED_EXISTS_QUERY)
fun hasProfileRootPostsFlow(
pubkey: PubkeyHex,
until: Long = Long.MAX_VALUE,
size: Int = 1
): Flow<Boolean>
@Query(PROFILE_FEED_QUERY)
suspend fun getProfileRootPosts(pubkey: PubkeyHex, until: Long, size: Int): List<RootPostView>
@Query(PROFILE_FEED_CREATED_AT_QUERY)
suspend fun getProfileRootPostsCreatedAt(pubkey: PubkeyHex, until: Long, size: Int): List<Long>
@Query(LIST_FEED_QUERY)
fun getListRootPostFlow(identifier: String, until: Long, size: Int): Flow<List<RootPostView>>
@Query(LIST_FEED_EXISTS_QUERY)
fun hasListRootPostsFlow(
identifier: String,
until: Long = Long.MAX_VALUE,
size: Int = 1
): Flow<Boolean>
@Query(LIST_FEED_QUERY)
suspend fun getListRootPosts(identifier: String, until: Long, size: Int): List<RootPostView>
@Query(LIST_FEED_CREATED_AT_QUERY)
suspend fun getListRootPostsCreatedAt(identifier: String, until: Long, size: Int): List<Long>
}
| 45 | null | 4 | 38 | 05eaafa2f37e763967396f4c26099500f1e4692c | 4,112 | voyage | MIT License |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/mpp/MppDslTargetsIT.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.mpp
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.gradle.testbase.*
import org.jetbrains.kotlin.gradle.util.testResolveAllConfigurations
import org.jetbrains.kotlin.test.TestMetadata
@MppGradlePluginTests
class MppDslTargetsIT : KGPBaseTest() {
@GradleTest
@TestMetadata(value = "newMppMultipleTargetsSamePlatform")
fun testMultipleTargetsSamePlatform(gradleVersion: GradleVersion) {
project(
projectName = "newMppMultipleTargetsSamePlatform",
gradleVersion = gradleVersion,
) {
testResolveAllConfigurations("app") { _, result ->
with(result) {
assertOutputContains(">> :app:junitCompileClasspath --> lib-junit.jar")
assertOutputContains(">> :app:junitCompileClasspath --> junit-4.13.2.jar")
assertOutputContains(">> :app:mixedJunitCompileClasspath --> lib-junit.jar")
assertOutputContains(">> :app:mixedJunitCompileClasspath --> junit-4.13.2.jar")
assertOutputContains(">> :app:testngCompileClasspath --> lib-testng.jar")
assertOutputContains(">> :app:testngCompileClasspath --> testng-6.14.3.jar")
assertOutputContains(">> :app:mixedTestngCompileClasspath --> lib-testng.jar")
assertOutputContains(">> :app:mixedTestngCompileClasspath --> testng-6.14.3.jar")
}
}
}
}
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,721 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/calorytracker/CaloryTrackerApp.kt | adrianpbv | 759,865,160 | false | {"Kotlin": 479758} | package com.example.calorytracker
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class CaloryTrackerApp : Application () | 0 | Kotlin | 0 | 0 | 497cf179bcc86e74cf374fd632640f2630adce83 | 164 | CaloryTracker | Apache License 2.0 |
src/Day02.kt | Totwart123 | 573,119,178 | false | null | fun main() {
val duells = mutableListOf(
0 to listOf(Pair('A', 'Z'), Pair('B', 'X'), Pair('C', 'Y')),
3 to listOf(Pair('A', 'X'), Pair('B', 'Y'), Pair('C', 'Z')),
6 to listOf(Pair('A', 'Y'), Pair('B', 'Z'), Pair('C', 'X')),
)
fun part1(input: List<String>): Int {
return input.sumOf {
val move = it.trim()
val enemyMove = move.first()
val myMove = move.last()
val movePoints = when (myMove) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> -1
}
check(movePoints != -1)
val duellPoints = duells.first { duell -> duell.second.contains(Pair(enemyMove, myMove)) }.first
movePoints + duellPoints
}
}
val predictedDuells = mutableListOf(
1 to listOf(Pair('A', 'Y'), Pair('B', 'X'), Pair('C', 'Z')),
2 to listOf(Pair('B', 'Y'), Pair('C', 'X'), Pair('A', 'Z')),
3 to listOf(Pair('C', 'Y'), Pair('A', 'X'), Pair('B', 'Z')),
)
fun part2(input: List<String>): Int {
return input.sumOf {
val move = it.trim()
val enemyMove = move.first()
val result = move.last()
val movePoints = predictedDuells.first { duell -> duell.second.contains(Pair(enemyMove, result)) }.first
val duellPoints = when (result) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> -1
}
check(movePoints != -1)
movePoints + duellPoints
}
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 1,816 | AoC | Apache License 2.0 |
src/main/kotlin/moe/xmcn/linerrx/util/DoLogin.kt | XiaMoHuaHuo-CN | 590,302,342 | false | null | package moe.xmcn.linerrx.util
import me.zhenxin.qqbot.api.ApiManager
import me.zhenxin.qqbot.core.BotCore
import me.zhenxin.qqbot.entity.AccessInfo
import me.zhenxin.qqbot.enums.Intent
import moe.xmcn.linerrx.EventBridge
class DoLogin {
companion object {
@JvmStatic
lateinit var bot: BotCore
fun login(botAppId: Int, botToken: String, sandbox: Boolean) {
val accessInfo = AccessInfo()
accessInfo.botAppId = botAppId //102034183 // 管理端的BotAppId
accessInfo.botToken = botToken //"u6aKk6VDFLMqzWsZ4qZnfeVRE42Eog8R" // 管理端的BotToken
// 使用沙盒模式
if (sandbox) accessInfo.useSandBoxMode()
// 创建实例
bot = BotCore(accessInfo)
// 获取API管理器
val api: ApiManager = bot.apiManager
// 注册AT消息相关事件
bot.registerIntents(Intent.AT_MESSAGES)
// 设置事件处理器
// handler.setRemoveAt(false); // 取消删除消息中的艾特
bot.setEventHandler(EventBridge(api))
// 启动
bot.start()
}
}
} | 0 | Kotlin | 0 | 2 | 9b7b2178912a1a8e9c867547b0ec6a8a714c45ec | 1,072 | LinerRX | MIT License |
src/main/kotlin/view/views/VertexView.kt | spbu-coding-2023 | 791,480,179 | false | {"Kotlin": 29380} | package view.views
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import view.DefaultColors
import viewmodel.GraphViewModel
import viewmodel.VertexViewModel
import kotlin.math.roundToInt
@Composable
fun VertexView(vertexVM: VertexViewModel, graphVM: GraphViewModel) {
val number = vertexVM.number
Box(modifier = Modifier
.offset {IntOffset(vertexVM.offsetX.roundToInt(), vertexVM.offsetY.roundToInt())}
.clip(shape = CircleShape)
.size(120.dp)
.background(DefaultColors.primary)
.border(5.dp, Color.Black, CircleShape)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consume()
vertexVM.offsetX += dragAmount.x
vertexVM.offsetY += dragAmount.y
}
}
){
Text(text = "$number",
fontSize = 40.sp,
modifier = Modifier
.fillMaxSize()
.wrapContentSize(),)
}
vertexVM.edges.forEach{ otherNumber ->
val otherVM = graphVM.graphView[otherNumber]!!
val otherX = otherVM.offsetX
val otherY = otherVM.offsetY
Canvas(modifier = Modifier.fillMaxSize().zIndex(-1f)){
drawLine(
start = Offset(vertexVM.offsetX + vertexVM.vertexSize/2, vertexVM.offsetY + vertexVM.vertexSize/2),
end = Offset( otherX + vertexVM.vertexSize/2, otherY + vertexVM.vertexSize/2),
strokeWidth = 10f,
color = Color.Black)
}
}
} | 1 | Kotlin | 0 | 4 | 911ed18b4eb08988f1d177316b1f538ecb124162 | 2,215 | graphs-graphs-8 | The Unlicense |
app/src/main/java/me/jfenn/alarmio/data/preference/CustomPreferenceData.kt | ajayyy | 250,295,118 | false | null | package com.luteapp.alarmio.data.preference
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.luteapp.alarmio.R
/**
* A simple preference item to bind a title
* and text value of a preference to a basic
* item view.
*/
abstract class CustomPreferenceData(private val name: Int) : BasePreferenceData<CustomPreferenceData.ViewHolder>() {
/**
* Get the name of the current value of the preference.
*/
abstract fun getValueName(holder: ViewHolder): String?
/**
* Called when the preference is clicked.
*/
abstract fun onClick(holder: ViewHolder)
override fun getViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder = ViewHolder(inflater.inflate(R.layout.item_preference_custom, parent, false))
override fun bindViewHolder(holder: ViewHolder) {
holder.nameView.setText(name)
holder.valueNameView.text = getValueName(holder) ?: run {
holder.valueNameView.visibility = View.GONE; null
}
holder.itemView.setOnClickListener { onClick(holder) }
}
/**
* Holds child views of the current item.
*/
class ViewHolder(v: View) : BasePreferenceData.ViewHolder(v) {
val nameView: TextView = v.findViewById(R.id.name)
val valueNameView: TextView = v.findViewById(R.id.value)
}
}
| 65 | null | 93 | 4 | 48e4a7991bfa80a506cec7b71b73da8681cc18ee | 1,401 | AlarmioRemote | Apache License 2.0 |
tibiakt-core/src/main/kotlin/com/galarzaa/tibiakt/core/models/forums/ThreadEntry.kt | Galarzaa90 | 285,669,589 | false | {"Kotlin": 530502, "Dockerfile": 1445} | /*
* Copyright © 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.galarzaa.tibiakt.core.models.forums
import com.galarzaa.tibiakt.core.enums.ThreadStatus
import kotlinx.serialization.Serializable
/** A thread entry in the forums. */
@Serializable
public data class ThreadEntry(
val title: String,
val threadId: Int,
val author: String,
val isAuthorTraded: Boolean,
val isAuthorDeleted: Boolean,
val emoticon: ForumEmoticon?,
val replies: Int,
val views: Int,
val lastPost: LastPost,
val status: Set<ThreadStatus>,
val pages: Int,
val goldenFrame: Boolean,
)
| 0 | Kotlin | 1 | 1 | 7274af579c1d4fa7865c05436c0e3ee5b293301a | 1,147 | TibiaKt | Apache License 2.0 |
app/src/main/java/org/oppia/android/app/player/state/itemviewmodel/SplitScreenInteractionIds.kt | oppia | 148,093,817 | false | null | package org.oppia.android.app.player.state.itemviewmodel
import javax.inject.Qualifier
/**
* Corresponds to an injectable set of string interaction IDs that support split-screen variants.
*/
@Qualifier annotation class SplitScreenInteractionIds
| 508 | null | 517 | 315 | 95699f922321f49a3503783187a14ad1cef0d5d3 | 249 | oppia-android | Apache License 2.0 |
app/src/main/java/org/oppia/android/app/player/state/itemviewmodel/SplitScreenInteractionIds.kt | oppia | 148,093,817 | false | null | package org.oppia.android.app.player.state.itemviewmodel
import javax.inject.Qualifier
/**
* Corresponds to an injectable set of string interaction IDs that support split-screen variants.
*/
@Qualifier annotation class SplitScreenInteractionIds
| 508 | null | 517 | 315 | 95699f922321f49a3503783187a14ad1cef0d5d3 | 249 | oppia-android | Apache License 2.0 |
backend/src/main/kotlin/com/oz/meow/converter/IntegerToIEnumConverterFactory.kt | voncho-zero | 742,285,196 | false | {"Kotlin": 20777} | package com.oz.meow.converter
import com.oz.meow.annotation.IEnum
import org.springframework.core.convert.converter.Converter
import org.springframework.core.convert.converter.ConverterFactory
class IntegerToIEnumConverterFactory: ConverterFactory<Int, Enum<*>> {
override fun <T : Enum<*>> getConverter(targetType: Class<T>): Converter<Int, T> {
return IntToEnum(targetType)
}
data class IntToEnum<T: Enum<*>>(val enumType: Class<T>): Converter<Int, T> {
private fun typeOf(source: Class<*>, target: Class<*>): Boolean {
return source.interfaces.contains(target)
}
override fun convert(source: Int): T? {
if (typeOf(enumType, IEnum::class.java)) {
return enumType.enumConstants.findLast { (it as IEnum<*>).value == source }
}
return enumType.enumConstants[source]
}
}
} | 0 | Kotlin | 0 | 0 | 51840046fdc8e1f3316e41e5e4ee620e4eaff1a2 | 893 | meow | Apache License 2.0 |
3. play-feature-delivery/(DFM) AwesomeApp/library/navigation/src/main/java/dev/tonholo/awesomeapp/navigation/Navigation.kt | rafaeltonholo | 495,193,554 | false | {"Kotlin": 340484} | package dev.tonholo.awesomeapp.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
@Composable
fun Navigation(
navController: NavHostController,
destinationManager: DestinationManager,
) {
NavHost(
navController = navController,
startDestination = destinationManager.startDestination,
) {
with(destinationManager) {
setupRoutes(navController)
}
}
}
| 0 | Kotlin | 0 | 0 | e0130cd1d9b8e90771fb606aea0860b9acbc8b59 | 505 | modularization-presentation | MIT License |
correlation/core/domain/src/main/kotlin/org/sollecitom/chassis/correlation/core/domain/access/authentication/Authentication.kt | sollecitom | 669,483,842 | false | {"Kotlin": 819878, "Java": 30834} | package org.sollecitom.chassis.correlation.core.domain.access.authentication
import kotlinx.datetime.Instant
import org.sollecitom.chassis.core.domain.identity.Id
sealed interface Authentication {
data class Token(val id: Id, val validFrom: Instant?, val validTo: Instant?) {
companion object
}
companion object
} | 0 | Kotlin | 0 | 2 | 801b61a892f3b5fc79c9e3c1eb3def40c6498dc5 | 338 | chassis | MIT License |
app/src/main/java/com/example/wordsapp/LetterListFragment.kt | web-dot | 689,509,580 | false | {"Kotlin": 16314} | package com.example.wordsapp
import android.os.Bundle
import android.view.*
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.wordsapp.databinding.FragmentLetterListBinding
class LetterListFragment : Fragment() {
// getting reference to FragmentLetterListBinding
private var _binding: FragmentLetterListBinding? = null
private val binding get() = _binding!!
// property for recyclerView
private lateinit var recyclerView: RecyclerView
private var isLinearLayoutManager = true;
// display options menu in onCreate() by calling setHasOptionsMenu(true)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
/**
* Note: in Fragments, the layout is inflated in onCreateView()
*
* inflating the view
* setting the value of _binding, and
* returning the root view
* */
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentLetterListBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
recyclerView = binding.recyclerView
chooseLayout()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.layout_menu, menu)
val layoutButton = menu.findItem(R.id.action_switch_layout)
setIcon(layoutButton)
}
private fun chooseLayout(){
/**
* here you assign the layout-manager. In addition to setting the
* layout-manager, this code also assigns the adapter. LetterAdapter is used for both list and
* grid layouts
* */
when(isLinearLayoutManager){
true -> {
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = LetterAdapter()
}
false -> {
recyclerView.layoutManager = GridLayoutManager(context, 4)
recyclerView.adapter = LetterAdapter()
}
}
}
private fun setIcon(menuItem: MenuItem?){
if(menuItem == null){
return;
}
// the icon is conditionally set based on the isLinearLayoutManager property
menuItem.icon =
if(isLinearLayoutManager){
ContextCompat.getDrawable(this.requireContext(), R.drawable.ic_grid_layout)
} else{
ContextCompat.getDrawable(this.requireContext(), R.drawable.ic_linear_layout)
}
}
/**
* this is called any time a menu item is tapped so you need to be sure to check which menu
* item is tapped. You use a when statement, above. If the id matches the action the
* action_switch_layout menu item, you negate the value of the isLinearLayoutManager. Then
* call chooseLayout() and setIcon() to update the UI accordingly.
* */
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId){
R.id.action_switch_layout -> {
// Sets isLinearLayoutManager (a Boolean) to the opposite value
isLinearLayoutManager = !isLinearLayoutManager
//Sets layout and icon
chooseLayout()
setIcon(item)
return true
}
/**
* otherwise, do nothing and use the core event handling
*
* when clauses require that all possible paths be accounted for explicitly,
* for instance both the true and false cases if the value is Boolean,
* or an else to catch all the unhandled cases
* */
else -> super.onOptionsItemSelected(item)
}
}
} | 0 | Kotlin | 0 | 0 | a6ed3dcd22cba873ea1f38b3f1f015eb2fb1e493 | 4,235 | AND3.2-Navigation-FragmentsNavigationGraph-Words-App | Apache License 2.0 |
app_update/src/main/java/com/inz/z/app_update/service/DownloadThread.kt | Memory-Z | 141,771,340 | false | {"Java": 1063423, "Kotlin": 584610} | package com.inz.z.app_update.service
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
/**
*
* 下载线程
* @author Zhenglj
* @version 1.0.0
* Create by inz in 2019/3/9 10:15.
*/
public class DownloadThread(
private var mFilePath: String?,
var mDownloadUrl: String?,
var mProgressListener: ProgressListener?
) : Thread() {
var inputStream: InputStream? = null
var fileOutputStream: FileOutputStream? = null
override fun run() {
var connection: HttpURLConnection? = null
try {
val url = URL(mDownloadUrl)
if (mDownloadUrl!!.startsWith("https://")) {
TrustAllCertificates.install()
}
connection = url.openConnection() as HttpURLConnection?
connection!!.setRequestProperty("Connection", "Keep-Alive")
connection.setRequestProperty("Keep-Alive", "header")
inputStream = BufferedInputStream(connection.inputStream)
val count = connection.contentLength
if (count < 0) {
return
}
if (inputStream == null) {
return
}
writeToFile(count, mFilePath!!, inputStream!!)
} catch (e: Exception) {
e.printStackTrace()
mProgressListener!!.onError(e)
} finally {
try {
fileOutputStream!!.flush()
fileOutputStream!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
try {
inputStream!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
connection?.disconnect()
}
}
private fun writeToFile(count: Int, filePath: String, inputStream: InputStream) {
val buf = ByteArray(2048)
val file = File(filePath)
if (file.exists()) {
file.delete()
}
fileOutputStream = FileOutputStream(file)
var bytesRead = 0
var len: Int = inputStream.read(buf)
while (len != -1) {
fileOutputStream!!.write(buf, 0, len)
bytesRead += len
if (mProgressListener != null) {
val done = bytesRead >= count
mProgressListener?.update(bytesRead.toLong(), count.toLong(), done)
}
len = inputStream.read(buf)
}
}
/**
* 进度监听
*/
public interface ProgressListener {
/**
* 下载进度
* @param bytesRead 下载进度
* @param contentLength 总长度
* @param isDone 是否下载完毕
*/
fun update(bytesRead: Long, contentLength: Long, isDone: Boolean)
/**
* 异常处理
*/
fun onError(e: Exception)
}
} | 1 | null | 1 | 1 | feff01057cf308fcbf9f1ebf880b9a114badf970 | 2,810 | Z_inz | Apache License 2.0 |
src/main/kotlin/rx/lang/kotlin/single.kt | MarioAriasC | 23,442,629 | true | {"Kotlin": 47158, "Shell": 1136} | package rx.lang.kotlin
import rx.Single
import rx.SingleSubscriber
import java.util.concurrent.Callable
import java.util.concurrent.Future
fun <T> single(body: (s: SingleSubscriber<in T>) -> Unit): Single<T> = Single.create(body)
fun <T> singleOf(value: T): Single<T> = Single.just(value)
fun <T> Future<T>.toSingle(): Single<T> = Single.from(this)
fun <T> Callable<T>.toSingle(): Single<T> = Single.fromCallable { this.call() } | 0 | Kotlin | 0 | 0 | 22c2861597e6f300de8f2ab09bf0f5db7e6b3b22 | 430 | RxKotlin | Apache License 2.0 |
src/main/kotlin/dev/chara/tasks/backend/domain/model/TaskList.kt | 19lmyers | 624,219,343 | false | {"Kotlin": 150928, "Python": 9314, "Dockerfile": 922, "Shell": 57} | package dev.chara.tasks.backend.domain.model
import dev.chara.tasks.backend.data.sql.TaskList as DbTaskList
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable
@Serializable
data class TaskList(
val id: String?,
val ownerId: String,
val title: String,
val color: Color? = null,
val icon: Icon? = null,
val description: String? = null,
val dateCreated: Instant? = null,
val lastModified: Instant,
val classifierType: ClassifierType? = null
) {
@Serializable
enum class Color {
RED,
ORANGE,
YELLOW,
GREEN,
BLUE,
PURPLE,
PINK,
}
@Serializable
enum class Icon {
BACKPACK,
BOOK,
BOOKMARK,
BRUSH,
CAKE,
CALL,
CAR,
CELEBRATION,
CLIPBOARD,
FLIGHT,
FOOD_BEVERAGE,
FOOTBALL,
FOREST,
GROUP,
HANDYMAN,
HOME_REPAIR_SERVICE,
LIGHT_BULB,
MEDICAL_SERVICES,
MUSIC_NOTE,
PERSON,
PETS,
PIANO,
RESTAURANT,
SCISSORS,
SHOPPING_CART,
SMILE,
WORK
}
@Serializable
enum class ClassifierType(private val consoleName: String) {
SHOPPING("shopping");
override fun toString(): String {
return consoleName
}
}
}
fun DbTaskList.toModel() =
TaskList(
id,
owner_id,
title,
color,
icon,
description,
date_created,
last_modified,
classifier_type
)
| 0 | Kotlin | 0 | 1 | 8605f3ea9d2107ad86000d8af2b8d41b3242bc2f | 1,600 | tasks-backend | MIT License |
core/src/main/kotlin/dev/usbharu/multim/util/EmojiUtils.kt | multim-dev | 591,652,793 | false | null | package dev.usbharu.multim.util
import Emojis
object EmojiUtils {
fun getAllEmoji():List<UnicodeEmoji>{
return Emojis.allEmojis.map { UnicodeEmoji(it.description,it.char) }
}
}
data class UnicodeEmoji(val string: String,val char:String)
| 8 | Kotlin | 0 | 7 | daad2d142ae6fa7414acdb6704832a4d477dc41f | 257 | multim | Apache License 2.0 |
android/src/main/java/com/komoju/android/sdk/ui/screens/failed/Reason.kt | degica | 851,401,843 | false | {"Kotlin": 266785, "JavaScript": 1844} | package com.komoju.android.sdk.ui.screens.failed
/**
* Enum class representing the reasons for a payment failure.
*
* This enum provides various constants that describe common reasons why a payment may fail.
* These reasons can be used to handle different error cases in the application and provide
* appropriate feedback to the user.
*/
enum class Reason {
/**
* Payment was canceled by the user.
*
* This reason indicates that the user deliberately canceled the payment process.
* It typically happens when the user decides not to complete the transaction.
*/
USER_CANCEL,
/**
* Payment failed due to a credit card error.
*
* This reason indicates that there was an issue with the user's credit card, such as
* an invalid card number, insufficient funds, or the card being declined by the issuer.
*/
CREDIT_CARD_ERROR,
/**
* Payment failed due to another unspecified reason.
*
* This reason is used when the cause of the failure does not fit into any of the other
* predefined categories.
*/
OTHER,
}
| 0 | Kotlin | 0 | 4 | 28e708a0a4c253537509001ef5823172c5a02a55 | 1,112 | komoju-mobile-sdk | MIT License |
app/src/main/kotlin/jp/co/yumemi/android/code_check/TwoFragment.kt | tshion | 707,962,901 | false | {"Kotlin": 64228} | /*
* Copyright © 2021 YUMEMI Inc. All rights reserved.
*/
package jp.co.yumemi.android.code_check
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import coil.load
import jp.co.yumemi.android.code_check.TopActivity.Companion.lastSearchDate
import jp.co.yumemi.android.code_check.databinding.FragmentTwoBinding
import timber.log.Timber
class TwoFragment : Fragment(R.layout.fragment_two) {
private val args: TwoFragmentArgs by navArgs()
private var binding: FragmentTwoBinding? = null
private val _binding get() = binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Timber.tag("検索した日時").d(lastSearchDate.toString())
binding = FragmentTwoBinding.bind(view)
var item = args.item
_binding.ownerIconView.load(item.ownerIconUrl);
_binding.nameView.text = item.name;
_binding.languageView.text = getString(R.string.written_language, item.language)
_binding.starsView.text = "${item.stargazersCount} stars";
_binding.watchersView.text = "${item.watchersCount} watchers";
_binding.forksView.text = "${item.forksCount} forks";
_binding.openIssuesView.text = "${item.openIssuesCount} open issues";
}
}
| 7 | Kotlin | 0 | 0 | e01b5cd896274939a43bbd2743b83f096583da23 | 1,367 | yumemi-inc_android-engineer-codecheck | Apache License 2.0 |
app/src/main/java/com/hongwei/jetpack_compose_demo/view/components/SectionHeader.kt | hongwei-bai | 364,869,482 | false | null | package com.hongwei.jetpack_compose_demo.view.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun SectionHeader(title: String) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.background(MaterialTheme.colors.primary)
.fillMaxWidth()
) {
Text(
text = title,
style = MaterialTheme.typography.h6,
color = MaterialTheme.colors.onPrimary,
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
} | 0 | null | 0 | 1 | ee68b5a326004f7863036500086766e26d8bd143 | 963 | jetpack-compose-demo | MIT License |
app/src/main/java/org/haidy/servify/presentation/screens/bookingTrack/Tabs.kt | HaidyAbuGom3a | 805,534,454 | false | {"Kotlin": 702248} | package org.haidy.servify.presentation.screens.bookingTrack
import org.haidy.servify.app.utils.LanguageCode
import org.haidy.servify.app.utils.LocalizationManager
enum class Tabs {
UPCOMING,
COMPLETED,
CANCELED;
fun getTitle(languageCode: LanguageCode): String {
val stringRes = LocalizationManager.getStringResources(languageCode)
return when (this) {
UPCOMING -> stringRes.upcoming
COMPLETED -> stringRes.completed
CANCELED -> stringRes.canceled
}
}
} | 0 | Kotlin | 0 | 2 | 8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee | 535 | Servify | Apache License 2.0 |
app/src/main/java/org/haidy/servify/presentation/screens/bookingTrack/Tabs.kt | HaidyAbuGom3a | 805,534,454 | false | {"Kotlin": 702248} | package org.haidy.servify.presentation.screens.bookingTrack
import org.haidy.servify.app.utils.LanguageCode
import org.haidy.servify.app.utils.LocalizationManager
enum class Tabs {
UPCOMING,
COMPLETED,
CANCELED;
fun getTitle(languageCode: LanguageCode): String {
val stringRes = LocalizationManager.getStringResources(languageCode)
return when (this) {
UPCOMING -> stringRes.upcoming
COMPLETED -> stringRes.completed
CANCELED -> stringRes.canceled
}
}
} | 0 | Kotlin | 0 | 2 | 8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee | 535 | Servify | Apache License 2.0 |
core/src/main/java/com/bruno13palhano/core/model/CustomerInfo.kt | bruno13palhano | 670,001,130 | false | {"Kotlin": 1392940} | package com.bruno13palhano.core.model
data class CustomerInfo(
val id: Long,
val name: String,
val address: String,
val photo: ByteArray,
val owingValue: String,
val purchasesValue: String,
val lastPurchaseValue: String,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CustomerInfo
if (id != other.id) return false
if (name != other.name) return false
if (address != other.address) return false
if (!photo.contentEquals(other.photo)) return false
if (owingValue != other.owingValue) return false
if (purchasesValue != other.purchasesValue) return false
return lastPurchaseValue == other.lastPurchaseValue
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + address.hashCode()
result = 31 * result + photo.contentHashCode()
result = 31 * result + owingValue.hashCode()
result = 31 * result + purchasesValue.hashCode()
result = 31 * result + lastPurchaseValue.hashCode()
return result
}
companion object {
fun emptyCustomerInfo() =
CustomerInfo(
id = 0L,
name = "",
address = "",
photo = byteArrayOf(),
owingValue = "",
purchasesValue = "",
lastPurchaseValue = "",
)
}
}
| 0 | Kotlin | 0 | 2 | c55b8f8f9fccb42ce9b5a99a309e41bd2ec0b5b2 | 1,573 | shop-dani-management | MIT License |
bindings/gtk/gtk4/src/nativeMain/kotlin/org/gtkkn/bindings/gtk/EventControllerKey.kt | gtk-kn | 609,191,895 | false | {"Kotlin": 10448515, "Shell": 2740} | // This is a generated file. Do not modify.
package org.gtkkn.bindings.gtk
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.StableRef
import kotlinx.cinterop.asStableRef
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.staticCFunction
import org.gtkkn.bindings.gdk.ModifierType
import org.gtkkn.bindings.gobject.ConnectFlags
import org.gtkkn.extensions.common.asBoolean
import org.gtkkn.extensions.common.asGBoolean
import org.gtkkn.extensions.glib.staticStableRefDestroy
import org.gtkkn.extensions.gobject.GeneratedClassKGType
import org.gtkkn.extensions.gobject.KGTyped
import org.gtkkn.extensions.gobject.TypeCompanion
import org.gtkkn.native.gdk.GdkModifierType
import org.gtkkn.native.gobject.g_signal_connect_data
import org.gtkkn.native.gtk.GtkEventControllerKey
import org.gtkkn.native.gtk.gtk_event_controller_key_forward
import org.gtkkn.native.gtk.gtk_event_controller_key_get_group
import org.gtkkn.native.gtk.gtk_event_controller_key_get_im_context
import org.gtkkn.native.gtk.gtk_event_controller_key_get_type
import org.gtkkn.native.gtk.gtk_event_controller_key_new
import org.gtkkn.native.gtk.gtk_event_controller_key_set_im_context
import kotlin.Boolean
import kotlin.Int
import kotlin.UInt
import kotlin.ULong
import kotlin.Unit
/**
* `GtkEventControllerKey` is an event controller that provides access
* to key events.
*/
public open class EventControllerKey(
pointer: CPointer<GtkEventControllerKey>,
) : EventController(pointer.reinterpret()), KGTyped {
public val gtkEventControllerKeyPointer: CPointer<GtkEventControllerKey>
get() = gPointer.reinterpret()
/**
* Creates a new event controller that will handle key events.
*
* @return a new `GtkEventControllerKey`
*/
public constructor() : this(gtk_event_controller_key_new()!!.reinterpret())
/**
* Forwards the current event of this @controller to a @widget.
*
* This function can only be used in handlers for the
* [[email protected]::key-pressed],
* [[email protected]::key-released]
* or [[email protected]::modifiers] signals.
*
* @param widget a `GtkWidget`
* @return whether the @widget handled the event
*/
public open fun forward(widget: Widget): Boolean =
gtk_event_controller_key_forward(
gtkEventControllerKeyPointer.reinterpret(),
widget.gtkWidgetPointer.reinterpret()
).asBoolean()
/**
* Gets the key group of the current event of this @controller.
*
* See [[email protected]_layout].
*
* @return the key group
*/
public open fun getGroup(): UInt = gtk_event_controller_key_get_group(gtkEventControllerKeyPointer.reinterpret())
/**
* Gets the input method context of the key @controller.
*
* @return the `GtkIMContext`
*/
public open fun getImContext(): IMContext? =
gtk_event_controller_key_get_im_context(gtkEventControllerKeyPointer.reinterpret())?.run {
IMContext(reinterpret())
}
/**
* Sets the input method context of the key @controller.
*
* @param imContext a `GtkIMContext`
*/
public open fun setImContext(imContext: IMContext? = null): Unit =
gtk_event_controller_key_set_im_context(
gtkEventControllerKeyPointer.reinterpret(),
imContext?.gtkIMContextPointer?.reinterpret()
)
/**
* Emitted whenever the input method context filters away
* a keypress and prevents the @controller receiving it.
*
* See [[email protected]_im_context] and
* [[email protected]_keypress].
*
* @param connectFlags A combination of [ConnectFlags]
* @param handler the Callback to connect
*/
public fun connectImUpdate(
connectFlags: ConnectFlags = ConnectFlags(0u),
handler: () -> Unit,
): ULong =
g_signal_connect_data(
gPointer.reinterpret(),
"im-update",
connectImUpdateFunc.reinterpret(),
StableRef.create(handler).asCPointer(),
staticStableRefDestroy.reinterpret(),
connectFlags.mask
)
/**
* Emitted whenever a key is pressed.
*
* @param connectFlags A combination of [ConnectFlags]
* @param handler the Callback to connect. Params: `keyval` the pressed key.; `keycode` the raw
* code of the pressed key.; `state` the bitmask, representing the state of modifier keys and
* pointer buttons. See `GdkModifierType`.. Returns true if the key press was handled, false
* otherwise.
*/
public fun connectKeyPressed(
connectFlags: ConnectFlags = ConnectFlags(0u),
handler: (
keyval: UInt,
keycode: UInt,
state: ModifierType,
) -> Boolean,
): ULong =
g_signal_connect_data(
gPointer.reinterpret(),
"key-pressed",
connectKeyPressedFunc.reinterpret(),
StableRef.create(handler).asCPointer(),
staticStableRefDestroy.reinterpret(),
connectFlags.mask
)
/**
* Emitted whenever a key is released.
*
* @param connectFlags A combination of [ConnectFlags]
* @param handler the Callback to connect. Params: `keyval` the released key.; `keycode` the raw
* code of the released key.; `state` the bitmask, representing the state of modifier keys and
* pointer buttons. See `GdkModifierType`.
*/
public fun connectKeyReleased(
connectFlags: ConnectFlags = ConnectFlags(0u),
handler: (
keyval: UInt,
keycode: UInt,
state: ModifierType,
) -> Unit,
): ULong =
g_signal_connect_data(
gPointer.reinterpret(),
"key-released",
connectKeyReleasedFunc.reinterpret(),
StableRef.create(handler).asCPointer(),
staticStableRefDestroy.reinterpret(),
connectFlags.mask
)
/**
* Emitted whenever the state of modifier keys and pointer buttons change.
*
* @param connectFlags A combination of [ConnectFlags]
* @param handler the Callback to connect. Params: `keyval` the released key.
*/
public fun connectModifiers(
connectFlags: ConnectFlags = ConnectFlags(0u),
handler: (keyval: ModifierType) -> Boolean,
): ULong =
g_signal_connect_data(
gPointer.reinterpret(),
"modifiers",
connectModifiersFunc.reinterpret(),
StableRef.create(handler).asCPointer(),
staticStableRefDestroy.reinterpret(),
connectFlags.mask
)
public companion object : TypeCompanion<EventControllerKey> {
override val type: GeneratedClassKGType<EventControllerKey> =
GeneratedClassKGType(gtk_event_controller_key_get_type()) {
EventControllerKey(it.reinterpret())
}
init {
GtkTypeProvider.register()
}
}
}
private val connectImUpdateFunc: CPointer<CFunction<() -> Unit>> =
staticCFunction {
_: COpaquePointer,
userData: COpaquePointer,
->
userData.asStableRef<() -> Unit>().get().invoke()
}
.reinterpret()
private val connectKeyPressedFunc: CPointer<
CFunction<
(
UInt,
UInt,
GdkModifierType,
) -> Int
>
> =
staticCFunction {
_: COpaquePointer,
keyval: UInt,
keycode: UInt,
state: GdkModifierType,
userData: COpaquePointer,
->
userData.asStableRef<
(
keyval: UInt,
keycode: UInt,
state: ModifierType,
) -> Boolean
>().get().invoke(
keyval,
keycode,
state.run {
ModifierType(this)
}
).asGBoolean()
}
.reinterpret()
private val connectKeyReleasedFunc: CPointer<
CFunction<
(
UInt,
UInt,
GdkModifierType,
) -> Unit
>
> =
staticCFunction {
_: COpaquePointer,
keyval: UInt,
keycode: UInt,
state: GdkModifierType,
userData: COpaquePointer,
->
userData.asStableRef<
(
keyval: UInt,
keycode: UInt,
state: ModifierType,
) -> Unit
>().get().invoke(
keyval,
keycode,
state.run {
ModifierType(this)
}
)
}
.reinterpret()
private val connectModifiersFunc: CPointer<CFunction<(GdkModifierType) -> Int>> =
staticCFunction {
_: COpaquePointer,
keyval: GdkModifierType,
userData: COpaquePointer,
->
userData.asStableRef<(keyval: ModifierType) -> Boolean>().get().invoke(
keyval.run {
ModifierType(this)
}
).asGBoolean()
}
.reinterpret()
| 0 | Kotlin | 0 | 13 | c033c245f1501134c5b9b46212cd153c61f7efea | 9,296 | gtk-kn | Creative Commons Attribution 4.0 International |
src/test/kotlin/com/severett/kotlin_ras/util/TestConstants.kt | severne-lucanet | 109,382,646 | false | null | /**
* Copyright 2017 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.severett.kotlin_ras.util
import java.io.File
class TestConstants {
companion object {
@JvmField
val GOOD_RESOURCES_DIRECTORY = File("src/test/resources/good_logs")
@JvmField
val BAD_RESOURCES_DIRECTORY = File("src/test/resources/bad_logs")
}
} | 0 | Kotlin | 0 | 0 | 3c646a7dd9707c790da8f36bc79d0ade707c80ba | 877 | kotlin_ras | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.