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
src/main/kotlin/abc/186-e.kt
kirimin
197,707,422
false
null
package abc import utilities.debugLog import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val t = sc.nextInt() val nsk = (0 until t).map { Triple(sc.nextLong(), sc.nextLong(), sc.nextLong()) } println(problem186e(t, nsk)) } fun problem186e(t: Int, nsk: List<Triple<Long, Long, Long>>): String { val ans = mutableListOf<Long>() for (i in 0 until t) { val (n, s, k) = nsk[i] val div = (n - s) % k if (div == 0L) { ans.add((n - s) / k) continue } val zure = (n % k) if (zure == 0L) { ans.add(-1) continue } val roundCost = n / k + 1 debugLog(zure, roundCost) val diff = Math.abs(roundCost * k - n) debugLog(diff) } return ans.joinToString("\n") }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
843
AtCoderLog
The Unlicense
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmodes/misc/DoNotBreakThisTeleOpWithArm.kt
ManchesterMachineMakers
417,294,104
false
{"Kotlin": 79452, "Java": 46534, "Shell": 5590, "Makefile": 1243}
package org.firstinspires.ftc.teamcode.opmodes.misc import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotorSimple import org.firstinspires.ftc.teamcode.subassemblies.misc.DoNotBreakThisArm import kotlin.math.* @TeleOp(name = "Do Not Break This TeleOp with Arm", group = "do not break") class DoNotBreakThisTeleOpWithArm : LinearOpMode() { override fun runOpMode() { val arm = DoNotBreakThisArm(this) val leftFront = hardwareMap.dcMotor.get("left_front") val rightFront = hardwareMap.dcMotor.get("right_front") val leftRear = hardwareMap.dcMotor.get("left_rear") val rightRear = hardwareMap.dcMotor.get("right_rear") leftFront.configure(DcMotorSimple.Direction.FORWARD) rightFront.configure(DcMotorSimple.Direction.REVERSE) leftRear.configure(DcMotorSimple.Direction.REVERSE) rightRear.configure(DcMotorSimple.Direction.FORWARD) waitForStart() if (opModeIsActive()) { while (opModeIsActive()) { // from https://gm0.org/en/latest/docs/software/tutorials/mecanum-drive.html val leftX = gamepad1.left_stick_x.toDouble() val leftY = gamepad1.left_stick_y.toDouble() val rightX = -gamepad1.right_stick_x.toDouble() // Denominator is the largest motor power (absolute value) or 1 // This ensures all the powers maintain the same ratio, // but only if at least one is out of the range [-1, 1] // Denominator is the largest motor power (absolute value) or 1 // This ensures all the powers maintain the same ratio, // but only if at least one is out of the range [-1, 1] val denominator = max(abs(leftY) + abs(leftX) + abs(rightX), 1.0) val leftFrontPower = (leftY + leftX + rightX) / denominator val rightFrontPower = (leftY - leftX - rightX) / denominator val leftRearPower = (leftY - leftX + rightX) / denominator val rightRearPower = (leftY + leftX - rightX) / denominator leftFront.power = leftFrontPower rightFront.power = rightFrontPower leftRear.power = leftRearPower rightRear.power = rightRearPower arm.loop() arm.telemetry() telemetry.update() } } } private fun DcMotor.configure(direction: DcMotorSimple.Direction) { this.mode = DcMotor.RunMode.RUN_WITHOUT_ENCODER this.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE this.direction = direction } }
10
Kotlin
1
1
b54f1ef2cb933e3f98fc4e718b3c83bf29f4ae5a
2,831
RobotController
BSD 3-Clause Clear License
app/src/test/java/me/xhsun/gw2leo/registry/FakeAppModule.kt
xhsun
497,594,768
false
null
package me.xhsun.gw2leo.registry import androidx.paging.ExperimentalPagingApi import androidx.paging.RemoteMediator import dagger.Module import dagger.Provides import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn import io.mockk.mockk import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import me.xhsun.gw2leo.account.datastore.IAccountIDRepository import me.xhsun.gw2leo.account.service.IAccountService import me.xhsun.gw2leo.account.service.ICharacterService import me.xhsun.gw2leo.core.datastore.IDatastoreRepository import me.xhsun.gw2leo.core.http.IGW2RepositoryFactory import me.xhsun.gw2leo.core.refresh.service.IAccountRefreshService import me.xhsun.gw2leo.core.refresh.service.IStorageRefreshService import me.xhsun.gw2leo.storage.datastore.entity.MaterialStorage import me.xhsun.gw2leo.storage.service.IStorageRepository import me.xhsun.gw2leo.storage.service.IStorageRetrievalService import me.xhsun.gw2leo.storage.service.mediator.IStorageRemoteMediatorBuilder import javax.inject.Singleton @Module @TestInstallIn( components = [SingletonComponent::class], replaces = [AppModule::class] ) class FakeAppModule { @IoDispatcher @Provides fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO @Provides @Singleton fun provideGW2RepositoryFactory(): IGW2RepositoryFactory { return mockk() } @Provides @Singleton fun provideDatastoreRepository(): IDatastoreRepository { return mockk() } @Provides fun provideAccountIDRepository(): IAccountIDRepository { return mockk() } @Provides @Singleton fun provideAccountService( ): IAccountService { return mockk() } @Provides @Singleton fun provideCharacterService( ): ICharacterService { return mockk() } @Provides fun provideAccountRefreshService( ): IAccountRefreshService { return mockk() } @Provides fun provideStorageRetrievalService( ): IStorageRetrievalService { return mockk() } @Provides fun provideStorageRefreshService( ): IStorageRefreshService { return mockk() } @Provides fun provideStorageService( ): IStorageRepository { return mockk() } @Provides fun provideStorageRemoteMediatorBuilder( ): IStorageRemoteMediatorBuilder { return mockk() } @Provides @OptIn(ExperimentalPagingApi::class) fun provideMaterialStorageRemoteMediator( ): RemoteMediator<Int, MaterialStorage> { return mockk() } }
0
Kotlin
0
0
96a8b6dc6f29572006626a3bd3e4186d41a5839c
2,643
gw2-leo
Apache License 2.0
app/src/main/java/com/dilip/qrventory/presentation/auth/login/LoginViewModel.kt
dilip2882
870,066,912
false
{"Kotlin": 167330}
package com.dilip.qrventory.presentation.auth.login import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel class LoginScreenViewModel : ViewModel() { var uiState by mutableStateOf(LoginUiState()) private set fun updateEmail(input: String) { uiState.email = uiState.copy(email = input).toString() } fun updatePassword(input: String) { uiState.password = uiState.copy(password = input).toString() } } data class LoginUiState( var email: String = "", var password: String = "", )
0
Kotlin
1
1
c5b9375589a3ac213c6545e0c5b48088019a5b5a
644
QRVentory
Apache License 2.0
app/src/main/java/com/walker/war/adapter/MainAdatper.kt
walker0406
383,407,541
false
{"Gradle": 5, "Java Properties": 1, "Text": 1, "Ignore List": 4, "Markdown": 1, "Proguard": 3, "XML": 45, "Kotlin": 65, "INI": 1, "JSON": 1, "Java": 1}
package com.walker.war.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.RecyclerView import com.airbnb.epoxy.EpoxyDataBindingLayouts import com.bumptech.glide.Glide import com.walker.war.R import com.walker.war.data.model.User import com.walker.war.databinding.ItemLayoutBinding /** * Created by admin on 2021/7/10. */ class MainAdapter: RecyclerView.Adapter<MainAdapter.DataViewHolder>() { private val users: ArrayList<User> = ArrayList() fun updateData(data: ArrayList<User>?) { data?.let { users.clear() users.addAll(it) notifyDataSetChanged() } } class DataViewHolder(val binding: ItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(user: User) { binding.name = user.name; binding.email = user.email // binding.textViewUserName.text = user.name // binding.textViewUserEmail.text = user.email Glide.with(binding.imageViewAvatar.context) .load(user.avatar) .into(binding.imageViewAvatar) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = DataViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_layout, parent, false ) ) override fun getItemCount(): Int = users.size override fun onBindViewHolder(holder: DataViewHolder, position: Int) = holder.bind(users[position]) fun addData(list: List<User>) { users.addAll(list) } }
0
Kotlin
0
0
495fa94d9a53a64f11ae6adee4c094ae58482555
1,766
war
Apache License 2.0
src/main/kotlin/com/wrike/sprinter/settings/HotSwapAgentPluginModulesSettingsState.kt
wrike
632,906,511
false
null
package com.wrike.sprinter.settings import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project import com.intellij.util.xmlb.XmlSerializerUtil @State( name = "com.wrike.sprinter.settings.HotSwapAgentPluginModulesSettingsState", storages = [Storage("HotSwapAgentPluginModulesSettingsState.xml")] ) class ModulesWithHotSwapAgentPluginsSettingsState: PersistentStateComponent<ModulesWithHotSwapAgentPluginsSettingsState> { var moduleNames = mutableSetOf<String>() override fun getState(): ModulesWithHotSwapAgentPluginsSettingsState { return this } override fun loadState(state: ModulesWithHotSwapAgentPluginsSettingsState) { XmlSerializerUtil.copyBean(state, this) } } fun getModulesWithHotSwapAgentPluginsSettings(project: Project): ModulesWithHotSwapAgentPluginsSettingsState { return project.getService(ModulesWithHotSwapAgentPluginsSettingsState::class.java) }
0
Kotlin
0
0
e84952ed56fac0175e5347dee24c638963ae61bb
1,057
sprinter-idea-plugin
Apache License 2.0
mewwalletbl/src/main/java/com/myetherwallet/mewwalletbl/connection/MessageCrypt.kt
MyEtherWallet
225,456,139
false
null
package com.myetherwallet.mewwalletbl.connection import com.myetherwallet.mewwalletbl.MewEnvironment import com.myetherwallet.mewwalletbl.data.BaseMessage import com.myetherwallet.mewwalletbl.data.EncryptedMessage import com.myetherwallet.mewwalletkit.bip.bip44.PrivateKey import com.myetherwallet.mewwalletkit.core.extension.* import com.myetherwallet.mewwalletkit.core.util.HMAC import org.spongycastle.crypto.engines.AESEngine import org.spongycastle.crypto.modes.CBCBlockCipher import org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher import org.spongycastle.crypto.params.KeyParameter import org.spongycastle.crypto.params.ParametersWithIV import org.spongycastle.jce.ECNamedCurveTable import org.spongycastle.jce.provider.BouncyCastleProvider import org.spongycastle.jce.spec.ECPrivateKeySpec import org.spongycastle.jce.spec.ECPublicKeySpec import java.math.BigInteger import java.security.KeyFactory import java.security.SecureRandom import java.security.Security import java.util.* import javax.crypto.KeyAgreement /** * Created by BArtWell on 24.07.2019. */ class MessageCrypt(private val privateKey: String) { init { Security.addProvider(BouncyCastleProvider()) } fun signMessage(data: String): String { val hash = data.hashPersonalMessage() val signature = hash?.secp256k1RecoverableSign(this.privateKey.hexToByteArray()) val serialized = signature?.secp256k1SerializeSignature() val cropped = serialized!!.copyOfRange(0, 64) return (byteArrayOf((serialized[64].toInt() + 27).toByte()) + cropped).toHexString() } fun encrypt(data: BaseMessage) = encrypt(data.toByteArray()) fun encrypt(data: ByteArray): EncryptedMessage { val connectPublicKey = publicKeyFromPrivateWithControl(privateKey) val initVector = SecureRandom().generateSeed(16) val ephemPrivateKey = SecureRandom().generateSeed(32).toHexString().toLowerCase() val ephemPublicKey = publicKeyFromPrivateWithControl(ephemPrivateKey) val multipliedKeys = multiplyKeys(ephemPrivateKey, connectPublicKey) val hashed = multipliedKeys.sha512() val encKey = Arrays.copyOfRange(hashed, 0, 32) val macKey = Arrays.copyOfRange(hashed, 32, hashed.size) val cipher = encryptAes256Cbc(initVector, encKey, data) val dataToHMac = initVector + ephemPublicKey + cipher val macData = HMAC.authenticate(macKey, HMAC.Algorithm.HmacSHA256, dataToHMac) return EncryptedMessage(cipher, ephemPublicKey, initVector, macData) } fun decrypt(message: EncryptedMessage): ByteArray? { val multipliedKeys = multiplyKeys(privateKey, message.ephemPublicKey.data) val hashed = multipliedKeys.sha512() val encKey = Arrays.copyOfRange(hashed, 0, 32) val macKey = Arrays.copyOfRange(hashed, 32, hashed.size) val dataToHMac = message.iv.data + message.ephemPublicKey.data + message.ciphertext.data val macData = HMAC.authenticate(macKey, HMAC.Algorithm.HmacSHA256, dataToHMac) if (!Arrays.equals(macData, message.mac.data)) { return null } return decryptAes256Cbc(encKey, message.ciphertext.data, message.iv.data) } private fun publicKeyFromPrivateWithControl(privateKeySource: String): ByteArray { val privateKey = PrivateKey.createWithPrivateKey(privateKeySource.hexToByteArray(), MewEnvironment.current.network) val publicKey = privateKey.publicKey() return publicKey!!.data() } private fun multiplyKeys(privateKey: String, publicKey: ByteArray): ByteArray { val keyAgreement = KeyAgreement.getInstance("ECDH", "SC") val keyFactory = KeyFactory.getInstance("ECDH", "SC") val params = ECNamedCurveTable.getParameterSpec("secp256k1") val privateKeyItem = keyFactory.generatePrivate(ECPrivateKeySpec(BigInteger(privateKey, 16), params)) keyAgreement.init(privateKeyItem) val publicKeyItem = keyFactory.generatePublic(ECPublicKeySpec(params.curve.decodePoint(publicKey), params)) keyAgreement.doPhase(publicKeyItem, true) return keyAgreement.generateSecret() } private fun encryptAes256Cbc(initVector: ByteArray, key: ByteArray, data: ByteArray): ByteArray { try { val cipher = PaddedBufferedBlockCipher(CBCBlockCipher(AESEngine())) cipher.init(true, ParametersWithIV(KeyParameter(key), initVector)) val out = ByteArray(cipher.getOutputSize(data.size)) val processed = cipher.processBytes(data, 0, data.size, out, 0) cipher.doFinal(out, processed) return out } catch (e: Exception) { e.printStackTrace() } return ByteArray(0) } private fun decryptAes256Cbc(encKey: ByteArray, cipher: ByteArray, initVector: ByteArray): ByteArray? { try { val blockCipher = PaddedBufferedBlockCipher(CBCBlockCipher(AESEngine())) blockCipher.init(false, ParametersWithIV(KeyParameter(encKey), initVector)) val buffer = ByteArray(blockCipher.getOutputSize(cipher.size)) var len = blockCipher.processBytes(cipher, 0, cipher.size, buffer, 0) len += blockCipher.doFinal(buffer, len) return Arrays.copyOfRange(buffer, 0, len) } catch (e: Exception) { e.printStackTrace() } return null } }
2
null
6
8
0c876055cad9373c425230b8444978bee11e2a52
5,450
mew-wallet-android-biz-logic
MIT License
example-app/src/main/java/com/adyen/checkout/example/data/api/CheckoutApiService.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2019 <NAME> * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by arman on 10/10/2019. */ package com.adyen.checkout.example.data.api import com.adyen.checkout.components.core.PaymentMethodsApiResponse import com.adyen.checkout.example.BuildConfig import com.adyen.checkout.example.data.api.model.BalanceRequest import com.adyen.checkout.example.data.api.model.CancelOrderRequest import com.adyen.checkout.example.data.api.model.CreateOrderRequest import com.adyen.checkout.example.data.api.model.PaymentMethodsRequest import com.adyen.checkout.example.data.api.model.SessionRequest import com.adyen.checkout.sessions.core.SessionModel import org.json.JSONObject import retrofit2.Call import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Query internal interface CheckoutApiService { companion object { private const val defaultGradleUrl = "<YOUR_SERVER_URL>" fun isRealUrlAvailable(): Boolean { return BuildConfig.MERCHANT_SERVER_URL != defaultGradleUrl } } @POST("sessions") suspend fun sessionsAsync(@Body sessionRequest: SessionRequest): SessionModel @POST("paymentMethods") suspend fun paymentMethodsAsync(@Body paymentMethodsRequest: PaymentMethodsRequest): PaymentMethodsApiResponse @POST("payments") fun payments(@Body paymentsRequest: JSONObject): Call<JSONObject> @POST("payments") suspend fun paymentsAsync(@Body paymentsRequest: JSONObject): JSONObject @POST("payments/details") fun details(@Body detailsRequest: JSONObject): Call<JSONObject> @POST("payments/details") suspend fun detailsAsync(@Body detailsRequest: JSONObject): JSONObject @POST("paymentMethods/balance") suspend fun checkBalanceAsync(@Body request: BalanceRequest): JSONObject @POST("orders") suspend fun createOrderAsync(@Body orderRequest: CreateOrderRequest): JSONObject @POST("orders/cancel") suspend fun cancelOrderAsync(@Body request: CancelOrderRequest): JSONObject @DELETE("storedPaymentMethods/{recurringId}") suspend fun removeStoredPaymentMethodAsync( @Path("recurringId") recurringId: String, @Query("merchantAccount") merchantAccount: String, @Query("shopperReference") shopperReference: String, ): Response<Unit> }
31
null
66
96
1f000e27e07467f3a30bb3a786a43de62be003b2
2,469
adyen-android
MIT License
presentation/viewmodel/src/main/java/com/chocolate/viewmodel/base/StringsResource.kt
team-chocolate-cake
669,924,259
false
{"Kotlin": 522388}
package com.chocolate.viewmodel.base interface StringsResource { val emptyEmailMessage: String val emptyFullNameMessage: String val emptyPassword: String val sameUserDataMessage: String val noConnectionMessage: String val globalMessageError: String val successMessage: String val organizationNameAlreadyExist: String val organizationNameIsSoLongException: String val enterValidEmailAddress: String val invalidEmailOrPassword: String val invalidChannelName: String val invalidTopicName: String val channelAlreadyExist: String val invalidImage: String val cancel: String val createChannel: String val organizationNameNotFound: String val organizationNameCannotBeEmpty: String val organizationNameOrImageCannotBeEmpty: String val channelNameValidation: String val nullOrEmptyNewLanguage: String val failedSaveSelectedLanguage: String val theSameData: String val failedEmailWhenEmpty: String val failedFullNameWhenEmpty: String val messageDeletedSuccessfully: String val invalidUsername: String val invalidEmail: String val passwordMismatch: String val memberAlreadyExist: String val allFieldsAreRequired: String val savedForLater: String val topicDeletedSuccessfully: String }
1
Kotlin
2
4
8441d97fd75fcbb68ee25934022d914bc7fcc36d
1,311
Teamix
MIT License
codegen-client/src/main/kotlin/software/amazon/smithy/rust/codegen/client/smithy/endpoint/EndpointConfigCustomization.kt
awslabs
308,027,791
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package software.amazon.smithy.rust.codegen.client.smithy.endpoint import software.amazon.smithy.rust.codegen.client.smithy.ClientCodegenContext import software.amazon.smithy.rust.codegen.client.smithy.ClientRustModule import software.amazon.smithy.rust.codegen.client.smithy.generators.config.ConfigCustomization import software.amazon.smithy.rust.codegen.client.smithy.generators.config.ServiceConfig import software.amazon.smithy.rust.codegen.core.rustlang.Writable import software.amazon.smithy.rust.codegen.core.rustlang.rustTemplate import software.amazon.smithy.rust.codegen.core.rustlang.writable import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType.Companion.preludeScope /** * Customization which injects an Endpoints 2.0 Endpoint Resolver into the service config struct */ internal class EndpointConfigCustomization( private val codegenContext: ClientCodegenContext, private val typesGenerator: EndpointTypesGenerator, ) : ConfigCustomization() { private val runtimeConfig = codegenContext.runtimeConfig private val moduleUseName = codegenContext.moduleUseName() private val types = Types(runtimeConfig) private val codegenScope = arrayOf( *preludeScope, "DefaultEndpointResolver" to RuntimeType.smithyRuntime(runtimeConfig).resolve("client::orchestrator::endpoints::DefaultEndpointResolver"), "Endpoint" to RuntimeType.smithyHttp(runtimeConfig).resolve("endpoint::Endpoint"), "OldSharedEndpointResolver" to types.sharedEndpointResolver, "Params" to typesGenerator.paramsStruct(), "Resolver" to RuntimeType.smithyRuntime(runtimeConfig).resolve("client::config_override::Resolver"), "SharedEndpointResolver" to RuntimeType.smithyRuntimeApi(runtimeConfig).resolve("client::endpoint::SharedEndpointResolver"), "SmithyResolver" to types.resolveEndpoint, ) override fun section(section: ServiceConfig): Writable { return writable { val sharedEndpointResolver = "#{OldSharedEndpointResolver}<#{Params}>" val resolverTrait = "#{SmithyResolver}<#{Params}>" when (section) { is ServiceConfig.ConfigImpl -> { rustTemplate( """ /// Returns the endpoint resolver. pub fn endpoint_resolver(&self) -> #{SharedEndpointResolver} { self.runtime_components.endpoint_resolver().expect("resolver defaulted if not set") } """, *codegenScope, ) } ServiceConfig.BuilderImpl -> { // if there are no rules, we don't generate a default resolver—we need to also suppress those docs. val defaultResolverDocs = if (typesGenerator.defaultResolver() != null) { val endpointModule = ClientRustModule.Config.endpoint.fullyQualifiedPath() .replace("crate::", "$moduleUseName::") """ /// /// When unset, the client will used a generated endpoint resolver based on the endpoint resolution /// rules for `$moduleUseName`. /// /// ## Examples /// ```no_run /// use aws_smithy_http::endpoint; /// use $endpointModule::{Params as EndpointParams, DefaultResolver}; /// /// Endpoint resolver which adds a prefix to the generated endpoint /// ##[derive(Debug)] /// struct PrefixResolver { /// base_resolver: DefaultResolver, /// prefix: String /// } /// impl endpoint::ResolveEndpoint<EndpointParams> for PrefixResolver { /// fn resolve_endpoint(&self, params: &EndpointParams) -> endpoint::Result { /// self.base_resolver /// .resolve_endpoint(params) /// .map(|ep|{ /// let url = ep.url().to_string(); /// ep.into_builder().url(format!("{}.{}", &self.prefix, url)).build() /// }) /// } /// } /// let prefix_resolver = PrefixResolver { /// base_resolver: DefaultResolver::new(), /// prefix: "subdomain".to_string() /// }; /// let config = $moduleUseName::Config::builder().endpoint_resolver(prefix_resolver); /// ``` """ } else { "" } if (codegenContext.settings.codegenConfig.includeEndpointUrlConfig) { rustTemplate( """ /// Set the endpoint URL to use when making requests. /// /// Note: setting an endpoint URL will replace any endpoint resolver that has been set. /// /// ## Panics /// Panics if an invalid URL is given. pub fn endpoint_url(mut self, endpoint_url: impl #{Into}<#{String}>) -> Self { self.set_endpoint_url(#{Some}(endpoint_url.into())); self } /// Set the endpoint URL to use when making requests. /// /// Note: setting an endpoint URL will replace any endpoint resolver that has been set. /// /// ## Panics /// Panics if an invalid URL is given. pub fn set_endpoint_url(&mut self, endpoint_url: #{Option}<#{String}>) -> &mut Self { ##[allow(deprecated)] self.set_endpoint_resolver( endpoint_url.map(|url| { #{OldSharedEndpointResolver}::new( #{Endpoint}::immutable(url).expect("invalid endpoint URL") ) }) ); self } """, *codegenScope, ) } rustTemplate( """ /// Sets the endpoint resolver to use when making requests. /// /// Note: setting an endpoint resolver will replace any endpoint URL that has been set. /// $defaultResolverDocs pub fn endpoint_resolver(mut self, endpoint_resolver: impl $resolverTrait + 'static) -> Self { self.set_endpoint_resolver(#{Some}(#{OldSharedEndpointResolver}::new(endpoint_resolver))); self } /// Sets the endpoint resolver to use when making requests. /// /// When unset, the client will used a generated endpoint resolver based on the endpoint resolution /// rules for `$moduleUseName`. """, *codegenScope, ) rustTemplate( """ pub fn set_endpoint_resolver(&mut self, endpoint_resolver: #{Option}<$sharedEndpointResolver>) -> &mut Self { self.config.store_or_unset(endpoint_resolver); self } """, *codegenScope, ) } ServiceConfig.BuilderBuild -> { rustTemplate( "#{set_endpoint_resolver}(&mut resolver);", "set_endpoint_resolver" to setEndpointResolverFn(), ) } is ServiceConfig.OperationConfigOverride -> { rustTemplate( "#{set_endpoint_resolver}(&mut resolver);", "set_endpoint_resolver" to setEndpointResolverFn(), ) } else -> emptySection } } } private fun defaultResolver(): RuntimeType { // For now, fallback to a default endpoint resolver that always fails. In the future, // the endpoint resolver will be required (so that it can be unwrapped). return typesGenerator.defaultResolver() ?: RuntimeType.forInlineFun( "MissingResolver", ClientRustModule.Config.endpoint, ) { rustTemplate( """ ##[derive(Debug)] pub(crate) struct MissingResolver; impl MissingResolver { pub(crate) fn new() -> Self { Self } } impl<T> #{ResolveEndpoint}<T> for MissingResolver { fn resolve_endpoint(&self, _params: &T) -> #{Result} { Err(#{ResolveEndpointError}::message("an endpoint resolver must be provided.")) } } """, "ResolveEndpoint" to types.resolveEndpoint, "ResolveEndpointError" to types.resolveEndpointError, "Result" to types.smithyHttpEndpointModule.resolve("Result"), ) } } private fun setEndpointResolverFn(): RuntimeType = RuntimeType.forInlineFun("set_endpoint_resolver", ClientRustModule.config) { // TODO(enableNewSmithyRuntimeCleanup): Simplify the endpoint resolvers rustTemplate( """ fn set_endpoint_resolver(resolver: &mut #{Resolver}<'_>) { let endpoint_resolver = if resolver.is_initial() { Some(resolver.resolve_config::<#{OldSharedEndpointResolver}<#{Params}>>().cloned().unwrap_or_else(|| #{OldSharedEndpointResolver}::new(#{DefaultResolver}::new()) )) } else if resolver.is_latest_set::<#{OldSharedEndpointResolver}<#{Params}>>() { resolver.resolve_config::<#{OldSharedEndpointResolver}<#{Params}>>().cloned() } else { None }; if let Some(endpoint_resolver) = endpoint_resolver { let shared = #{SharedEndpointResolver}::new( #{DefaultEndpointResolver}::<#{Params}>::new(endpoint_resolver) ); resolver.runtime_components_mut().set_endpoint_resolver(#{Some}(shared)); } } """, *codegenScope, "DefaultResolver" to defaultResolver(), ) } }
352
null
144
388
26a914ece072bba2dd9b5b49003204b70e7666ac
11,818
smithy-rs
Apache License 2.0
src/main/kotlin/icu/windea/pls/lang/projectView/CwtConfigProjectViewDecorator.kt
DragonKnightOfBreeze
328,104,626
false
{"Kotlin": 3439993, "Java": 164698, "Lex": 42127, "HTML": 23760, "Shell": 2822}
package icu.windea.pls.lang.projectView import com.intellij.ide.projectView.* import com.intellij.ide.projectView.impl.nodes.* import icons.* import icu.windea.pls.ep.configGroup.* /** * 在项目视图中为规则分组所在的目录提供特定的图标和额外的信息文本。 */ class CwtConfigProjectViewDecorator: ProjectViewNodeDecorator { override fun decorate(node: ProjectViewNode<*>, data: PresentationData) { if(node is PsiDirectoryNode) { val file = node.virtualFile ?: return val fileProviders = CwtConfigGroupFileProvider.EP_NAME.extensionList val fileProvider = fileProviders.find { it.getRootDirectory(node.project) == file } ?: return if(data.locationString != null) return //忽略存在locationString的情况 data.setIcon(PlsIcons.ConfigGroupDirectory) if(node.parent is SyntheticLibraryElementNode) { data.locationString = fileProvider.getHintMessage() } } } }
11
Kotlin
5
39
b67714e5b7ca5f48c5197f6c8e4b093de679d6be
938
Paradox-Language-Support
MIT License
main/src/main/java/com/quxianggif/user/adapter/RecommendFollowingAdapter.kt
guolindev
167,902,491
false
null
/* * Copyright (C) guolin, Suzhou Quxiang Inc. Open source codes for study only. * Do not use for commercial purpose. * * 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.quxianggif.user.adapter import android.app.Activity import androidx.recyclerview.widget.RecyclerView import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.quxianggif.R import com.quxianggif.core.extension.showToast import com.quxianggif.core.model.User import com.quxianggif.core.util.GlobalUtil import com.quxianggif.network.model.Callback import com.quxianggif.network.model.FollowUser import com.quxianggif.network.model.Response import com.quxianggif.network.model.UnfollowUser import com.quxianggif.user.ui.UserHomePageActivity import com.quxianggif.util.glide.CustomUrl import jp.wasabeef.glide.transformations.CropCircleTransformation /** * 系统推荐关注用户列表的RecyclerView适配器。 * * @author guolin * @since 18/3/20 */ class RecommendFollowingAdapter(private val activity: Activity, private val userList: List<User>) : RecyclerView.Adapter<RecommendFollowingAdapter.RecommendFollowingViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecommendFollowingViewHolder { val view = LayoutInflater.from(activity).inflate(R.layout.recommend_following_item, parent, false) val holder = RecommendFollowingViewHolder(view) holder.rootLayout.setOnClickListener { val position = holder.adapterPosition val user = userList[position] UserHomePageActivity.actionStart(activity, holder.avatar, user.userId, user.nickname, user.avatar, user.bgImage) } holder.followsButton.setOnClickListener { val position = holder.adapterPosition val user = userList[position] if (user.isFollowing) { user.isFollowing = false unfollowUser(position) } else { user.isFollowing = true followUser(position) } notifyItemChanged(position) } return holder } override fun onBindViewHolder(holder: RecommendFollowingViewHolder, position: Int) { val user = userList[position] holder.nickname.text = user.nickname if (TextUtils.isEmpty(user.description)) { holder.description.text = GlobalUtil.getString(R.string.user_does_not_feed_anything) } else { holder.description.text = user.description } holder.feedsAndFollowersCount.text = String.format(GlobalUtil.getString(R.string.feeds_and_followers_count), GlobalUtil.getConvertedNumber(user.feedsCount), GlobalUtil.getConvertedNumber(user.followersCount)) if (user.isFollowing) { holder.followsButton.setBackgroundResource(R.drawable.followed_button_bg) } else { holder.followsButton.setBackgroundResource(R.drawable.follow_button_bg) } if (user.avatar.isBlank()) { Glide.with(activity) .load(R.drawable.avatar_default) .bitmapTransform(CropCircleTransformation(activity)) .placeholder(R.drawable.loading_bg_circle) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(holder.avatar) } else { Glide.with(activity) .load(CustomUrl(user.avatar)) .bitmapTransform(CropCircleTransformation(activity)) .placeholder(R.drawable.loading_bg_circle) .error(R.drawable.avatar_default) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(holder.avatar) } } /** * 元素的总数是List的数量。 */ override fun getItemCount(): Int { return userList.size } @Synchronized private fun followUser(position: Int) { val user = userList[position] FollowUser.getResponse(user.userId, object : Callback { override fun onResponse(response: Response) { val status = response.status if (status != 0) { user.isFollowing = false notifyItemChanged(position) if (status == 10208) { showToast(GlobalUtil.getString(R.string.follow_too_many)) } else { showToast(GlobalUtil.getString(R.string.follow_failed)) } } } override fun onFailure(e: Exception) { userList[position].isFollowing = false notifyItemChanged(position) showToast(GlobalUtil.getString(R.string.follow_failed)) } }) } @Synchronized private fun unfollowUser(position: Int) { val user = userList[position] UnfollowUser.getResponse(user.userId, object : Callback { override fun onResponse(response: Response) { if (response.status != 0) { user.isFollowing = true notifyItemChanged(position) showToast(GlobalUtil.getString(R.string.unfollow_failed)) } } override fun onFailure(e: Exception) { userList[position].isFollowing = true notifyItemChanged(position) showToast(GlobalUtil.getString(R.string.unfollow_failed)) } }) } class RecommendFollowingViewHolder(view: View) : RecyclerView.ViewHolder(view) { var rootLayout: LinearLayout = view as LinearLayout var avatar: ImageView = view.findViewById(R.id.avatar) var nickname: TextView = view.findViewById(R.id.nickname) var description: TextView = view.findViewById(R.id.description) var feedsAndFollowersCount: TextView = view.findViewById(R.id.feedsAndFollowersCount) var followsButton: Button = view.findViewById(R.id.followsButton) } companion object { const val TAG = "RecommendFollowingAdapter" } }
30
null
692
3,448
26227595483a8f2508f23d947b3fe99721346e0f
6,867
giffun
Apache License 2.0
app/src/main/java/com/rne1223/bitfit/LogsFragment.kt
rne1223
555,867,918
false
null
package com.rne1223.bitfit import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.launch private const val TAG = "LogsFragment" class LogsFragment() : Fragment() { private val foods = mutableListOf<Food>() private lateinit var logsRecyclerView: RecyclerView private lateinit var logsAdapter: FoodAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Change this statement to store the view in a variable instead of a return statement val view = inflater.inflate(R.layout.fragment_logs, container, false) // Add these configurations for the recyclerView and to configure the adapter val layoutManager = LinearLayoutManager(context) logsRecyclerView = view.findViewById(R.id.logs_recycler_view) logsRecyclerView.layoutManager = layoutManager logsRecyclerView.setHasFixedSize(true) logsAdapter = FoodAdapter(view.context, foods) logsRecyclerView.adapter = logsAdapter lifecycleScope.launch { (activity?.application as BitFitApplication).db.EventDao().getAll().collect { databaseList -> databaseList.map { entity -> Food( entity.foodName, entity.calories + " Calories", ) }.also { mappedList -> //Log.v(TAG, mappedList.toString()) foods.clear() foods.addAll(mappedList) logsAdapter.notifyDataSetChanged() } } } // Update the return statement to return the inflated view from above return view } companion object { fun newInstance(): LogsFragment{ return LogsFragment() } } }
1
Kotlin
0
0
5c0fb1c1fb61cabc144e27b6cf3300feacac1a4c
2,247
Bitfit2
Apache License 2.0
graph/graph-adapter-output-spring-data-neo4j-sdn6/src/test/kotlin/org/orkg/graph/adapter/output/neo4j/SpringDataNeo4jThingAdapterCachingTests.kt
TIBHannover
197,416,205
false
null
package eu.tib.orkg.prototype.statements.adapter.output.neo4j.spring import eu.tib.orkg.prototype.statements.domain.model.ThingId import eu.tib.orkg.prototype.statements.spi.ClassRepository import eu.tib.orkg.prototype.statements.spi.LiteralRepository import eu.tib.orkg.prototype.statements.spi.PredicateRepository import eu.tib.orkg.prototype.statements.spi.ResourceRepository import eu.tib.orkg.prototype.statements.spi.ThingRepository import io.mockk.clearMocks import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import java.util.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.orkg.statements.testing.createClass import org.orkg.statements.testing.createLiteral import org.orkg.statements.testing.createPredicate import org.orkg.statements.testing.createResource import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.CacheManager import org.springframework.cache.annotation.EnableCaching import org.springframework.cache.concurrent.ConcurrentMapCacheManager import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.util.AopTestUtils private val allCacheNames: Array<out String> = arrayOf( THING_ID_TO_THING_CACHE, CLASS_ID_TO_CLASS_CACHE, CLASS_ID_TO_CLASS_EXISTS_CACHE, LITERAL_ID_TO_LITERAL_CACHE, LITERAL_ID_TO_LITERAL_EXISTS_CACHE, PREDICATE_ID_TO_PREDICATE_CACHE, RESOURCE_ID_TO_RESOURCE_CACHE, RESOURCE_ID_TO_RESOURCE_EXISTS_CACHE, ) @ContextConfiguration @ExtendWith(SpringExtension::class) class SpringDataNeo4jThingAdapterCachingTests { private lateinit var mock: ThingRepository @Autowired private lateinit var adapter: ThingRepository @Autowired private lateinit var cacheManager: CacheManager // Supportive doubles and adapters, because the caches interact private lateinit var classMock: ClassRepository private lateinit var literalMock: LiteralRepository private lateinit var predicateMock: PredicateRepository private lateinit var resourceMock: ResourceRepository @Autowired private lateinit var classAdapter: ClassRepository @Autowired private lateinit var literalAdapter: LiteralRepository @Autowired private lateinit var predicateAdapter: PredicateRepository @Autowired private lateinit var resourceAdapter: ResourceRepository @BeforeEach fun resetState() { allCacheNames.forEach { name -> // Reset the cache. Throw NPE if we cannot find the cache, most likely because the name is wrong. cacheManager.getCache(name)!!.clear() } // Obtain access to the proxied object, which is our mock created in the configuration below. mock = AopTestUtils.getTargetObject(adapter) classMock = AopTestUtils.getTargetObject(classAdapter) literalMock = AopTestUtils.getTargetObject(literalAdapter) predicateMock = AopTestUtils.getTargetObject(predicateAdapter) resourceMock = AopTestUtils.getTargetObject(resourceAdapter) // Clear the internal state of the mock, since Spring's Application context is not cleared between tests. clearMocks(mock, classMock, literalMock, predicateMock, resourceMock) } @AfterEach fun verifyMocks() { // Verify that there we no more interactions with the repository confirmVerified(mock) } @Test fun `fetching a thing by ID should be cached`() { val thingId = ThingId("R1") val resource = createResource().copy(id = thingId) every { mock.findByThingId(thingId) } returns Optional.of(resource) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } // Obtain resource from repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Obtain the same resource again for several times assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) verify(exactly = 1) { mock.findByThingId(thingId) } } @Test fun `saving a class should evict it from the thing-id cache`() { val thingId = ThingId("R1") val `class` = createClass().copy(id = thingId) val modified = `class`.copy(label = "new label") every { mock.findByThingId(thingId) } returns Optional.of(`class`) andThen Optional.of(modified) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } every { classMock.save(modified) } returns Unit // Obtain class from Thing repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(`class`) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Save a modified version classAdapter.save(modified) verify { classAdapter.save(modified) } // required because of confirmVerified() // Obtaining the class again assertThat(adapter.findByThingId(thingId).get()).`as`("obtaining the updated version from the repository") .isEqualTo(modified) // Verify the loading happened (again) verify(exactly = 2) { mock.findByThingId(thingId) } } @Test fun `saving a literal should evict it from the thing-id cache`() { val thingId = ThingId("R1") val literal = createLiteral().copy(id = thingId) val modified = literal.copy(label = "new label") every { mock.findByThingId(thingId) } returns Optional.of(literal) andThen Optional.of(modified) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } every { literalMock.save(modified) } returns Unit // Obtain literal from Thing repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(literal) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Save a modified version literalAdapter.save(modified) verify { literalAdapter.save(modified) } // required because of confirmVerified() // Obtaining the literal again assertThat(adapter.findByThingId(thingId).get()).`as`("obtaining the updated version from the repository") .isEqualTo(modified) // Verify the loading happened (again) verify(exactly = 2) { mock.findByThingId(thingId) } } @Test fun `saving a predicate should evict it from the thing-id cache`() { val thingId = ThingId("R1") val predicate = createPredicate().copy(id = thingId) val modified = predicate.copy(label = "new label") every { mock.findByThingId(thingId) } returns Optional.of(predicate) andThen Optional.of(modified) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } every { predicateMock.save(modified) } returns Unit // Obtain predicate from Thing repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(predicate) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Save a modified version predicateAdapter.save(modified) verify { predicateAdapter.save(modified) } // required because of confirmVerified() // Obtaining the predicate again assertThat(adapter.findByThingId(thingId).get()).`as`("obtaining the updated version from the repository") .isEqualTo(modified) // Verify the loading happened (again) verify(exactly = 2) { mock.findByThingId(thingId) } } @Test fun `saving a resource should evict it from the thing-id cache`() { val thingId = ThingId("R1") val resource = createResource().copy(id = thingId) val modified = resource.copy(label = "new label") every { mock.findByThingId(thingId) } returns Optional.of(resource) andThen Optional.of(modified) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } every { resourceMock.save(modified) } returns Unit // Obtain resource from Thing repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Save a modified version resourceAdapter.save(modified) verify { resourceAdapter.save(modified) } // required because of confirmVerified() // Obtaining the resource again assertThat(adapter.findByThingId(thingId).get()) .`as`("obtaining the updated version from the repository") .isEqualTo(modified) // Verify the loading happened (again) verify(exactly = 2) { mock.findByThingId(thingId) } } @Test fun `deleting a predicate should evict it from the thing cache`() { val thingId = ThingId("R1") val predicate = createPredicate().copy(id = thingId) every { mock.findByThingId(thingId) } returns Optional.of(predicate) andThen Optional.of(predicate) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } every { predicateMock.deleteById(predicate.id) } returns Unit // Obtain predicate from Thing repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(predicate) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Obtain the same predicate again for several times assertThat(adapter.findByThingId(thingId).get()).isEqualTo(predicate) assertThat(adapter.findByThingId(thingId).get()).isEqualTo(predicate) verify(exactly = 1) { mock.findByThingId(thingId) } // Delete predicate from repository predicateAdapter.deleteById(predicate.id) // Verify the deletion happened verify(exactly = 1) { predicateMock.deleteById(predicate.id) } // Verify that the cache was evicted assertThat(adapter.findByThingId(thingId).get()).isEqualTo(predicate) verify(exactly = 2) { mock.findByThingId(thingId) } } @Test fun `deleting a resource should evict it from the thing cache`() { val thingId = ThingId("R1") val resource = createResource().copy(id = thingId) every { mock.findByThingId(thingId) } returns Optional.of(resource) andThen Optional.of(resource) andThenAnswer { throw IllegalStateException("If you see this message, the method was called more often than expected: Caching did not work!") } every { resourceMock.deleteById(resource.id) } returns Unit // Obtain resource from Thing repository assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) // Verify the loading happened verify(exactly = 1) { mock.findByThingId(thingId) } // Obtain the same predicate again for several times assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) verify(exactly = 1) { mock.findByThingId(thingId) } // Delete predicate from repository resourceAdapter.deleteById(resource.id) // Verify the deletion happened verify(exactly = 1) { resourceMock.deleteById(resource.id) } // Verify that the cache was evicted assertThat(adapter.findByThingId(thingId).get()).isEqualTo(resource) verify(exactly = 2) { mock.findByThingId(thingId) } } @Configuration @EnableCaching(proxyTargetClass = true) class CachingTestConfig { @Bean fun cacheManager(): CacheManager = ConcurrentMapCacheManager(*allCacheNames) @Bean fun mockedAdapter(): ThingRepository = mockk<SpringDataNeo4jThingAdapter>() // Supportive adapters / mocks @Bean fun mockedClassAdapter(): ClassRepository = mockk<SpringDataNeo4jClassAdapter>() @Bean fun mockedLiteralAdapter(): LiteralRepository = mockk<SpringDataNeo4jLiteralAdapter>() @Bean fun mockedPredicateAdapter(): PredicateRepository = mockk<SpringDataNeo4jPredicateAdapter>() @Bean fun mockedResourceAdapter(): ResourceRepository = mockk<SpringDataNeo4jResourceAdapter>() } }
0
Kotlin
2
5
ce3f24748dd2d9c06e6125e033bc7ae83122925f
13,303
orkg-backend
MIT License
common/src/test/java/com/pedro/common/Av1ParserTest.kt
pedroSG94
79,667,969
false
null
/* * Copyright (C) 2024 pedroSG94. * * 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.pedro.common import com.pedro.common.av1.Av1Parser import com.pedro.common.av1.ObuType import junit.framework.TestCase.assertEquals import org.junit.Assert.assertArrayEquals import org.junit.Test /** * Created by pedro on 17/12/23. */ class Av1ParserTest { private val parser = Av1Parser() @Test fun `GIVEN a byte header abu WHEN get type THEN get expected type`() { val header = 0x0a.toByte() val type = parser.getObuType(header) assertEquals(ObuType.SEQUENCE_HEADER, type) } @Test fun `GIVEN a long number WHEN convert in leb128 THEN get expected byte array`() { val num = 12345L val expected = byteArrayOf(-71, 96) val result = parser.writeLeb128(num) assertArrayEquals(expected, result) } @Test fun `GIVEN a av1data byte array WHEN get all obu THEN get expected obu`() { val av1data = byteArrayOf(0x0a, 0x0d, 0x00, 0x00, 0x00, 0x24, 0x4f, 0x7e, 0x7f, 0x00, 0x68, 0x83.toByte(), 0x00, 0x83.toByte(), 0x02) val header = byteArrayOf(0x0a) val leb128 = byteArrayOf(0x0d) val data = byteArrayOf(0x00, 0x00, 0x00, 0x24, 0x4f, 0x7e, 0x7f, 0x00, 0x68, 0x83.toByte(), 0x00, 0x83.toByte(), 0x02) val obuList = parser.getObus(av1data) assertEquals(1, obuList.size) assertArrayEquals(header, obuList[0].header) assertArrayEquals(leb128, obuList[0].leb128) assertArrayEquals(data, obuList[0].data) assertArrayEquals(av1data, obuList[0].getFullData()) } }
87
null
772
2,545
eca59948009d5a7b564f9a838c149b850898d089
2,048
RootEncoder
Apache License 2.0
camunda-example-domain/src/main/kotlin/br/com/camunda/example/domain/model/Transference.kt
ricardofpu
146,937,534
false
null
package br.com.camunda.example.domain.model import br.com.camunda.example.domain.entity.DBEntity import br.com.camunda.example.domain.enums.PaymentStatus import com.fasterxml.jackson.annotation.JsonIgnore import org.hibernate.annotations.GenericGenerator import java.math.BigDecimal import java.util.* import javax.persistence.AttributeConverter import javax.persistence.Convert import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.Table import javax.validation.constraints.NotNull @Entity @Table(name = "transference") data class Transference( @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator") val id: String = "", val transactionId: String, val description: String? = null, val priceAmount: Long, val priceScale: Int, val priceCurrency: String, @Convert(converter = PaymentStatusConverter::class) var status: PaymentStatus = PaymentStatus.PENDING, @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "origin_account_id") @NotNull val originAccount: Account, @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "destination_account_id") @NotNull val destinationAccount: Account ) : DBEntity() { var reason: String? = null var reversedAt: Date? = null companion object { class PaymentStatusConverter : AttributeConverter<PaymentStatus, String> { override fun convertToDatabaseColumn(paymentStatus: PaymentStatus?): String? { return paymentStatus?.name } override fun convertToEntityAttribute(value: String?): PaymentStatus? { return if (value == null) null else Arrays.stream(PaymentStatus.values()) .filter { p -> p.name == value } .findFirst() .orElseThrow { IllegalArgumentException() } } } } fun getAmountAsBigDecimal(): BigDecimal = BigDecimal.valueOf(priceAmount, priceScale) }
0
Kotlin
0
1
1e4179db133ce38e9c86f548887bfd55737a732d
2,234
spring-boot-camunda-example
Apache License 2.0
mylibrary/src/main/java/com/peimissionx/leilibrary/InvisibleFragment.kt
Lei10
429,278,054
false
{"Kotlin": 5026}
package com.peimissionx.leilibrary import android.content.pm.PackageManager import androidx.core.app.ActivityCompat.requestPermissions import androidx.fragment.app.Fragment import javax.security.auth.callback.Callback typealias PermissionCallback = (Boolean,List<String>) -> Unit class InvisibleFragment : Fragment() { private var callback : PermissionCallback ? = null fun requestNow (cb : PermissionCallback, vararg permissions : String) { callback = cb requestPermissions(permissions, 1) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == 1){ val deniedList = ArrayList<String>() for ((index, result) in grantResults.withIndex()){ if (result != PackageManager.PERMISSION_GRANTED){ deniedList.add(permissions[index]) } } val allGranted = deniedList.isEmpty() callback?.let { it(allGranted, deniedList) } } } }
0
Kotlin
0
0
dd49605494733eb937b8468c8c7771f623d822a0
1,099
PermissionX
Apache License 2.0
android-test-framework/testSrc/com/android/tools/idea/testing/AgpIntegrationTests.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.testing import com.android.testutils.junit4.OldAgpSuite import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.testing.AgpVersionSoftwareEnvironmentDescriptor.Companion.AGP_CURRENT import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.projectRoots.JavaSdkVersion.JDK_11 import com.intellij.openapi.projectRoots.JavaSdkVersion.JDK_17 import com.intellij.openapi.projectRoots.JavaSdkVersion.JDK_1_8 /** * An AGP Version definition to be used in AGP integration tests. */ enum class AgpVersionSoftwareEnvironmentDescriptor( /** * The version of the AG. `null` means the current `-dev` version. */ override val agpVersion: String?, /** * The version of Gradle to be used in integration tests for this AGP version. `null` means the latest/default version. */ override val gradleVersion: String?, /** * The version of the JDK to launch Gradle with. `null` means the current version used by the IDE. */ override val jdkVersion: JavaSdkVersion? = null, /** * The version of the Gradle Kotlin plugin to be used in integration tests for this AGP version. `null` means the default version used by * Android Studio. */ override val kotlinVersion: String? = null, /** * The compileSdk to use in this test. `null` means the project default. */ override val compileSdk: String? = null, /** * Builder model version to query. */ override val modelVersion: ModelVersion = ModelVersion.V2 ) : AgpVersionSoftwareEnvironment { AGP_31(agpVersion = "3.1.4", gradleVersion = "5.3.1", jdkVersion = JDK_11, kotlinVersion = "1.4.32", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_33_WITH_5_3_1(agpVersion = "3.3.2", gradleVersion = "5.3.1", jdkVersion = JDK_11, kotlinVersion = "1.4.32", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_33(agpVersion = "3.3.2", gradleVersion = "5.5", jdkVersion = JDK_11, kotlinVersion = "1.4.32", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_35_JDK_8(agpVersion = "3.5.0", gradleVersion = "5.5", jdkVersion = JDK_1_8, kotlinVersion = "1.4.32", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_35(agpVersion = "3.5.0", gradleVersion = "5.5", jdkVersion = JDK_11, kotlinVersion = "1.4.32", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_40(agpVersion = "4.0.0", gradleVersion = "6.7.1", jdkVersion = JDK_11, kotlinVersion = "1.7.20", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_41(agpVersion = "4.1.0", gradleVersion = "6.7.1", jdkVersion = JDK_11, kotlinVersion = "1.7.20", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_42(agpVersion = "4.2.0", gradleVersion = "6.7.1", jdkVersion = JDK_11, kotlinVersion = "1.7.20", modelVersion = ModelVersion.V1, compileSdk = "32"), // Version constraints set by KGP: // - KGP 1.8 only supports Gradle 6.8.3+ // - KGP 2.0 only supports AGP 7.1.3+ AGP_70(agpVersion = "7.0.0", gradleVersion = "7.0.2", jdkVersion = JDK_11, kotlinVersion = "1.9.22", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_71(agpVersion = "7.1.0", gradleVersion = "7.2", jdkVersion = JDK_17, kotlinVersion = "1.9.22", modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_72_V1(agpVersion = "7.2.0", gradleVersion = "7.3.3", jdkVersion = JDK_17, modelVersion = ModelVersion.V1, compileSdk = "32"), AGP_72(agpVersion = "7.2.0", gradleVersion = "7.3.3", jdkVersion = JDK_17, modelVersion = ModelVersion.V2, compileSdk = "32"), AGP_73(agpVersion = "7.3.0", gradleVersion = "7.4", jdkVersion = JDK_17, modelVersion = ModelVersion.V2), AGP_74(agpVersion = "7.4.1", gradleVersion = "7.5", jdkVersion = JDK_17, modelVersion = ModelVersion.V2), AGP_80(agpVersion = "8.0.2", gradleVersion = "8.0", jdkVersion = JDK_17, modelVersion = ModelVersion.V2), AGP_81(agpVersion = "8.1.0", gradleVersion = "8.0", jdkVersion = JDK_17, modelVersion = ModelVersion.V2), AGP_82(agpVersion = "8.2.0", gradleVersion = "8.2", jdkVersion = JDK_17, modelVersion = ModelVersion.V2), // Must be last to represent the newest version. AGP_LATEST(null, gradleVersion = null); override fun toString(): String { return "Agp($agpVersion, g=$gradleVersion, k=$kotlinVersion, m=$modelVersion)" } companion object { @JvmField val AGP_CURRENT = AGP_LATEST val selected: AgpVersionSoftwareEnvironmentDescriptor get() { if (OldAgpSuite.AGP_VERSION == null && OldAgpSuite.GRADLE_VERSION == null) return AGP_CURRENT val applicableAgpVersions = applicableAgpVersions() return applicableAgpVersions.singleOrNull() ?: error("Multiple AGP versions selected: $applicableAgpVersions. A parameterised test is required.") } } } enum class ModelVersion { V1, V2; companion object { val selected: ModelVersion get() = if (StudioFlags.GRADLE_SYNC_USE_V2_MODEL.get()) V2 else V1 } } class SnapshotContext( projectName: String, agpVersion: AgpVersionSoftwareEnvironmentDescriptor, override val snapshotDirectoryWorkspaceRelativePath: String, ) : SnapshotComparisonTest { private val name: String = "$projectName${agpVersion.agpSuffix()}${agpVersion.gradleSuffix()}${agpVersion.modelVersion}" override fun getName(): String = name } interface AgpIntegrationTestDefinition { val name: String val agpVersion: AgpVersionSoftwareEnvironmentDescriptor fun withAgpVersion(agpVersion: AgpVersionSoftwareEnvironmentDescriptor): AgpIntegrationTestDefinition fun displayName(): String = "$name${if (agpVersion != AGP_CURRENT) "-${agpVersion}" else ""}" fun isCompatible(): Boolean = agpVersion > AgpVersionSoftwareEnvironmentDescriptor.AGP_33_WITH_5_3_1 /* Not supported special cases */ } /** * Applies AGP versions selected for testing in the current test target to the list of test definitions. */ fun List<AgpIntegrationTestDefinition>.applySelectedAgpVersions(): List<AgpIntegrationTestDefinition> = applicableAgpVersions() .flatMap { version -> this.map { it.withAgpVersion(version) } } .filter { it.isCompatible() } .sortedWith(compareBy({ it.agpVersion.gradleVersion }, { it.agpVersion.agpVersion })) fun applicableAgpVersions() = AgpVersionSoftwareEnvironmentDescriptor.values() .filter { val pass = (OldAgpSuite.AGP_VERSION == null || (it.agpVersion ?: "LATEST") == OldAgpSuite.AGP_VERSION) && (OldAgpSuite.GRADLE_VERSION == null || (it.gradleVersion ?: "LATEST") == OldAgpSuite.GRADLE_VERSION) println("${it.name}($it) : $pass") pass } /** * Prints a message describing the currently running test to the standard output. */ fun IntegrationTestEnvironment.outputCurrentlyRunningTest(testDefinition: AgpIntegrationTestDefinition) { println("Testing: ${this.javaClass.simpleName}[${testDefinition.displayName()}]") } private fun AgpVersionSoftwareEnvironmentDescriptor.agpSuffix(): String = when (this) { AgpVersionSoftwareEnvironmentDescriptor.AGP_LATEST -> "_" AgpVersionSoftwareEnvironmentDescriptor.AGP_82 -> "_Agp_8.2_" AgpVersionSoftwareEnvironmentDescriptor.AGP_81 -> "_Agp_8.1_" AgpVersionSoftwareEnvironmentDescriptor.AGP_80 -> "_Agp_8.0_" AgpVersionSoftwareEnvironmentDescriptor.AGP_31 -> "_Agp_3.1_" AgpVersionSoftwareEnvironmentDescriptor.AGP_33_WITH_5_3_1 -> "_Agp_3.3_" AgpVersionSoftwareEnvironmentDescriptor.AGP_33 -> "_Agp_3.3_" AgpVersionSoftwareEnvironmentDescriptor.AGP_35_JDK_8 -> "_Agp_3.5_" AgpVersionSoftwareEnvironmentDescriptor.AGP_35 -> "_Agp_3.5_" AgpVersionSoftwareEnvironmentDescriptor.AGP_40 -> "_Agp_4.0_" AgpVersionSoftwareEnvironmentDescriptor.AGP_41 -> "_Agp_4.1_" AgpVersionSoftwareEnvironmentDescriptor.AGP_42 -> "_Agp_4.2_" AgpVersionSoftwareEnvironmentDescriptor.AGP_70 -> "_Agp_7.0_" AgpVersionSoftwareEnvironmentDescriptor.AGP_71 -> "_Agp_7.1_" AgpVersionSoftwareEnvironmentDescriptor.AGP_72_V1 -> "_Agp_7.2_" AgpVersionSoftwareEnvironmentDescriptor.AGP_72 -> "_Agp_7.2_" AgpVersionSoftwareEnvironmentDescriptor.AGP_73 -> "_Agp_7.3_" AgpVersionSoftwareEnvironmentDescriptor.AGP_74 -> "_Agp_7.4_" } private fun AgpVersionSoftwareEnvironmentDescriptor.gradleSuffix(): String { return gradleVersion?.let { "Gradle_${it}_" }.orEmpty() }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
8,831
android
Apache License 2.0
hooks/src/commonMain/kotlin/xyz/junerver/compose/hooks/constant.kt
junerver
767,292,867
false
{"Kotlin": 416351}
package xyz.junerver.compose.hooks import xyz.junerver.compose.hooks.useform.FormInstance /* Description: Author: Junerver Date: 2024/8/1-9:58 Email: <EMAIL> Version: v1.0 */ internal const val KEY_PREFIX = "HOOK_INTERNAL_" private const val CACHE_KEY_PREFIX = "${KEY_PREFIX}CACHE_MANAGER_" internal val String.cacheKey: String get() = "${CACHE_KEY_PREFIX}$this" private const val FORM_KEY_PREFIX = "${KEY_PREFIX}FORM_FIELD_" internal fun String.genFormFieldKey(formInstance: FormInstance) = "${FORM_KEY_PREFIX}${formInstance}_$this" private const val PERSISTENT_KEY_PREFIX = "${KEY_PREFIX}USE_PERSISTENT_" internal val String.persistentKey: String get() = "${PERSISTENT_KEY_PREFIX}$this"
0
Kotlin
5
56
35a1f9fcc56ca049a992ca33d961aab48d84e1a5
714
ComposeHooks
Apache License 2.0
Prime-Number/prime_test.kt
amrendranj
108,084,144
true
{"Kotlin": 2154, "Python": 1903, "Ruby": 1423, "C++": 1344, "Java": 1175, "JavaScript": 931, "PHP": 822, "Elixir": 696, "Erlang": 467, "Shell": 425, "C#": 295, "C": 244, "VHDL": 220, "Go": 200, "HTML": 149, "Swift": 123, "Visual Basic": 43}
/** * Language: Kotlin * Author: <NAME> * Github: https://github.com/szaboa * * Check if the first given argument is prime or not */ fun main(args: Array<String>) { if (args.size == 0) { println("Please provide a number as command-line argument") return } var isPrime = true var number: Int try{ number = args[0].toInt() }catch(e: NumberFormatException){ println("The provided imput is not a number") return } if (0.compareTo(number) > 0){ println("The provided number must be positive") } for (i in 2..number/2){ if (number % i == 0){ isPrime = false break } } if (isPrime){ println("The number $number is prime!") }else{ println("The number $number is not prime!") } }
0
Kotlin
1
0
6ddd9ff03c3a7a21da8e9a7aa17389b8fc5ab7dd
869
Hacktoberfest2017-1
MIT License
sdk/src/commonMain/kotlin/org/timemates/sdk/users/profile/types/User.kt
timemates
575,534,072
false
null
package io.timemates.sdk.users.profile.types import io.timemates.sdk.common.types.TimeMatesEntity import io.timemates.sdk.files.types.value.FileId import io.timemates.sdk.users.profile.types.value.EmailAddress import io.timemates.sdk.users.profile.types.value.UserDescription import io.timemates.sdk.users.profile.types.value.UserId import io.timemates.sdk.users.profile.types.value.UserName /** * Represents a user entity in the system. * * @property id The unique identifier of the user. * @property name The name of the user. * @property description The description of the user. * @property avatarFileId The unique identifier of the user's avatar file. * @property emailAddress The email address associated with the user (null if not available). */ public data class User( val id: UserId, val name: UserName, val description: UserDescription, val avatarFileId: FileId, val emailAddress: EmailAddress?, ) : TimeMatesEntity()
4
Kotlin
0
9
ede0c538935ec8f2c452d7cfb4d6747a1a1c81c7
956
sdk
MIT License
app/src/main/java/wannabit/io/cosmostaion/ui/option/tx/address/AddressBookViewHolder.kt
cosmostation
418,314,439
false
null
package wannabit.io.cosmostaion.ui.option.tx.address import android.content.Context import android.view.View import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import wannabit.io.cosmostaion.R import wannabit.io.cosmostaion.chain.allChains import wannabit.io.cosmostaion.common.visibleOrGone import wannabit.io.cosmostaion.database.AppDatabase import wannabit.io.cosmostaion.database.model.AddressBook import wannabit.io.cosmostaion.database.model.RefAddress import wannabit.io.cosmostaion.databinding.ItemAddressBookBinding class AddressBookViewHolder( val context: Context, private val binding: ItemAddressBookBinding ) : RecyclerView.ViewHolder(binding.root) { fun bookBind(addressBook: AddressBook, cnt: Int) { binding.apply { addressTitleLayout.visibleOrGone(adapterPosition == 0) topView.visibleOrGone(adapterPosition == 0) addressBookTitle.text = "Address book" addressBookCnt.text = cnt.toString() accountName.text = addressBook.bookName accountAddress.text = addressBook.address accountMemo.text = addressBook.memo } } fun accountBind(refAddress: RefAddress, position: Int, cnt: Int) { binding.apply { addressTitleLayout.visibleOrGone(position == 0) topView.visibleOrGone(position == 0) addressBookTitle.text = "My account" addressBookCnt.text = cnt.toString() CoroutineScope(Dispatchers.IO).launch { val account = AppDatabase.getInstance().baseAccountDao().selectAccount(refAddress.accountId) withContext(Dispatchers.Main) { accountName.text = account?.name accountAddress.text = refAddress.dpAddress allChains().firstOrNull { it.tag == refAddress.chainTag }?.let { chain -> if (!chain.isDefault) { chainBadge.visibility = View.VISIBLE chainBadge.text = context.getString(R.string.str_old) chainBadge.setBackgroundResource(R.drawable.round_box_deprecated) chainBadge.setTextColor( ContextCompat.getColor( context, R.color.color_base02 ) ) when (chain.tag) { "okt996_Keccak" -> { chainTypeBadge.text = context.getString(R.string.str_ethsecp256k1) chainTypeBadge.visibility = View.VISIBLE } "okt996_Secp" -> { chainTypeBadge.text = context.getString(R.string.str_secp256k1) chainTypeBadge.visibility = View.VISIBLE } else -> { chainTypeBadge.visibility = View.GONE } } } else { chainBadge.visibility = View.GONE chainTypeBadge.visibility = View.GONE } } } } } } fun evmBookBind(evmAddressBook: AddressBook, cnt: Int) { binding.apply { addressTitleLayout.visibleOrGone(adapterPosition == 0) topView.visibleOrGone(adapterPosition == 0) addressBookTitle.text = "Address book" addressBookCnt.text = cnt.toString() accountName.text = evmAddressBook.bookName accountAddress.text = evmAddressBook.address accountMemo.text = "" } } fun accountEvmBind(refEvmAddress: RefAddress, position: Int, cnt: Int) { binding.apply { addressTitleLayout.visibleOrGone(position == 0) topView.visibleOrGone(position == 0) addressBookTitle.text = "My account" addressBookCnt.text = cnt.toString() CoroutineScope(Dispatchers.IO).launch { val account = AppDatabase.getInstance().baseAccountDao() .selectAccount(refEvmAddress.accountId) withContext(Dispatchers.Main) { accountName.text = account?.name accountAddress.text = refEvmAddress.evmAddress } } } } }
1
null
43
83
b04f3615c7c7b4407d719e160155a8c03fbae3a9
4,849
cosmostation-android
MIT License
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/renderer/types/renderers/KaFunctionalTypeRenderer.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.renderer.types.renderers import org.jetbrains.kotlin.analysis.api.KaExperimentalApi import org.jetbrains.kotlin.analysis.api.KaSession import org.jetbrains.kotlin.analysis.api.renderer.types.KaTypeRenderer import org.jetbrains.kotlin.analysis.api.types.KaFunctionalType import org.jetbrains.kotlin.analysis.api.types.KaTypeNullability import org.jetbrains.kotlin.analysis.utils.printer.PrettyPrinter import org.jetbrains.kotlin.lexer.KtTokens @KaExperimentalApi public interface KaFunctionalTypeRenderer { public fun renderType( analysisSession: KaSession, type: KaFunctionalType, typeRenderer: KaTypeRenderer, printer: PrettyPrinter, ) public object AS_FUNCTIONAL_TYPE : KaFunctionalTypeRenderer { override fun renderType( analysisSession: KaSession, type: KaFunctionalType, typeRenderer: KaTypeRenderer, printer: PrettyPrinter, ) { printer { val annotationsRendered = checkIfPrinted { typeRenderer.annotationsRenderer.renderAnnotations(analysisSession, type, this) } if (annotationsRendered) printer.append(" ") if (annotationsRendered || type.nullability == KaTypeNullability.NULLABLE) append("(") " ".separated( { if (type.isSuspend) { typeRenderer.keywordsRenderer.renderKeyword(analysisSession, KtTokens.SUSPEND_KEYWORD, type, printer) } }, { if (type.hasContextReceivers) { typeRenderer.contextReceiversRenderer.renderContextReceivers(analysisSession, type, typeRenderer, printer) } }, { type.receiverType?.let { if (it is KaFunctionalType) printer.append("(") typeRenderer.renderType(analysisSession, it, printer) if (it is KaFunctionalType) printer.append(")") printer.append('.') } printCollection(type.parameterTypes, prefix = "(", postfix = ")") { typeRenderer.renderType(analysisSession, it, this) } append(" -> ") typeRenderer.renderType(analysisSession, type.returnType, printer) }, ) if (annotationsRendered || type.nullability == KaTypeNullability.NULLABLE) append(")") if (type.nullability == KaTypeNullability.NULLABLE) append("?") } } } public object AS_CLASS_TYPE : KaFunctionalTypeRenderer { override fun renderType( analysisSession: KaSession, type: KaFunctionalType, typeRenderer: KaTypeRenderer, printer: PrettyPrinter, ): Unit = printer { " ".separated( { typeRenderer.annotationsRenderer.renderAnnotations(analysisSession, type, printer) }, { typeRenderer.classIdRenderer.renderClassTypeQualifier(analysisSession, type, type.qualifiers, typeRenderer, printer) if (type.nullability == KaTypeNullability.NULLABLE) { append('?') } }, ) } } public object AS_CLASS_TYPE_FOR_REFLECTION_TYPES : KaFunctionalTypeRenderer { override fun renderType( analysisSession: KaSession, type: KaFunctionalType, typeRenderer: KaTypeRenderer, printer: PrettyPrinter, ) { val renderer = if (type.isReflectType) AS_CLASS_TYPE else AS_FUNCTIONAL_TYPE renderer.renderType(analysisSession, type, typeRenderer, printer) } } } @KaExperimentalApi public typealias KtFunctionalTypeRenderer = KaFunctionalTypeRenderer
184
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
4,360
kotlin
Apache License 2.0
kotlin/reakt-native-toolkit/src/jvmMain/kotlin/de/voize/reaktnativetoolkit/util/PlatformUtil.kt
voize-gmbh
568,889,436
false
{"Kotlin": 202340, "TypeScript": 77029, "Objective-C": 15383, "Objective-C++": 5071, "Ruby": 4276, "C++": 2053, "JavaScript": 1649, "Makefile": 1510, "Java": 679, "Shell": 643}
@file:JvmName("PlatformUtilJvm") package de.voize.reaktnativetoolkit.util internal actual fun uuid(): String { error("Not implemented for JVM target") }
5
Kotlin
3
90
f084a53352f8ea3f0b223f4f5eafaa19d17b6432
157
reakt-native-toolkit
Apache License 2.0
src/main/kotlin/org/equeim/bencode/Bencode.kt
equeim
315,091,944
false
{"Kotlin": 16533, "Java": 11219}
package org.equeim.bencode import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.serializer import java.io.ByteArrayOutputStream import java.io.InputStream import java.io.OutputStream import java.nio.charset.Charset import java.nio.charset.StandardCharsets import kotlin.coroutines.coroutineContext @Suppress("SpellCheckingInspection", "unused") object Bencode { suspend fun <T> decode(inputStream: InputStream, deserializer: DeserializationStrategy<T>, stringCharset: Charset = DEFAULT_CHARSET): T { return Decoder(inputStream, SharedDecoderState(stringCharset), coroutineContext).decodeSerializableValue(deserializer) } suspend fun <T> encode(value: T, outputStream: OutputStream, serializer: SerializationStrategy<T>, stringCharset: Charset = DEFAULT_CHARSET) { Encoder(outputStream, stringCharset, coroutineContext).encodeSerializableValue(serializer, value) } suspend fun <T> encode(value: T, serializer: SerializationStrategy<T>, stringCharset: Charset = DEFAULT_CHARSET): ByteArray { val outputStream = ByteArrayOutputStream() Encoder(outputStream, stringCharset, coroutineContext).encodeSerializableValue(serializer, value) return outputStream.toByteArray() } suspend inline fun <reified T> decode(inputStream: InputStream, stringCharset: Charset = DEFAULT_CHARSET): T = decode(inputStream, serializer(), stringCharset) suspend inline fun <reified T> encode(value: T, outputStream: OutputStream, stringCharset: Charset = DEFAULT_CHARSET) = encode(value, outputStream, serializer(), stringCharset) suspend inline fun <reified T> encode(value: T, stringCharset: Charset = DEFAULT_CHARSET) = encode(value, serializer(), stringCharset) val DEFAULT_CHARSET: Charset = StandardCharsets.UTF_8 }
0
Kotlin
0
1
97dccac52b8b72ee6a802f7c5efdc267c5251570
1,861
kotlinx-serialization-bencode
Apache License 2.0
plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/dto/GitLabGroupMemberDTO.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.api.dto import com.intellij.collaboration.api.dto.GraphQLFragment import org.jetbrains.plugins.gitlab.api.SinceGitLab @SinceGitLab("13.1") @GraphQLFragment("/graphql/fragment/groupMember.graphql") data class GitLabGroupMemberDTO( val group: GroupDTO? ) { val projectMemberships: List<GitLabProjectDTO> = group?.projects?.nodes ?: listOf() data class GroupDTO(val projects: GitLabProjectsDTO) }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
561
intellij-community
Apache License 2.0
app/src/main/java/com/malibin/morse/data/entity/ChatMessage.kt
cha7713
463,427,946
true
{"Kotlin": 121634, "PureBasic": 2910}
package com.malibin.morse.data.entity import com.malibin.morse.data.service.params.SendChatMessageParams import java.util.* /** * Created By Malibin * on 1월 27, 2021 */ data class ChatMessage( val message: String, val userNickname: String = "", val isPresenter: Boolean = false, val id: String = UUID.randomUUID().toString(), ) { enum class Color { BLACK, WHITE; } }
0
null
0
0
8103c56b8079224aba8eedc7a4a4af40a1b92b4c
405
morse_android_stove_camp
Apache License 2.0
app/src/main/java/com/dartharrmi/resipi/base/ResipiFragment.kt
jArrMi
283,382,558
false
null
package com.dartharrmi.resipi.base import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.PROTECTED import androidx.databinding.DataBindingUtil.inflate import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import com.dartharrmi.resipi.ui.livedata.Event import com.dartharrmi.resipi.ui.views.LoadingView abstract class ResipiFragment<DB : ViewDataBinding> : Fragment(), IBaseView { // Generic Loading View private val loadingView by lazy { LoadingView(getViewContext()) } protected val isLoadingObserver by lazy { Observer<Event<Boolean>> { loadingView.onLoadingResponse( it, activity?.window ) } } // View Context private lateinit var fragmentContext: Context // Data binding @VisibleForTesting(otherwise = PROTECTED) lateinit var dataBinding: DB //region Abstract Base Methods abstract fun getLayoutId(): Int abstract fun getVariablesToBind(): Map<Int, Any> abstract fun initObservers() @CallSuper open fun initView(inflater: LayoutInflater, container: ViewGroup?) { dataBinding = inflate(inflater, getLayoutId(), container, false) dataBinding.lifecycleOwner = this for ((variableId, value) in getVariablesToBind()) { dataBinding.setVariable(variableId, value) } dataBinding.executePendingBindings() } //endregion override fun onAttach(context: Context) { super.onAttach(context) fragmentContext = context } final override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { initObservers() initView(inflater, container) return dataBinding.root } //region IBaseView Implementation override fun isActive(): Boolean = isAdded override fun getViewContext(): Context = fragmentContext override fun showLoading() = loadingView.showLoading(activity?.window) override fun hideLoading() = loadingView.hideLoading() //endregion }
0
null
0
2
31898d545f6ae6dc23869502b41450ab734d877b
2,355
resipi
MIT License
src/main/kotlin/tk/roccodev/hiveapi/game/GameMap.kt
RoccoDev
126,229,924
false
null
package tk.roccodev.hiveapi.game class GameMap(val worldName: String, val mapName: String, val author: String, val addedAt: Int, val enumName: String)
0
Kotlin
0
1
6635189357b3e81f99320ef9b5ca6822fdb991bd
151
HiveAPIKt
MIT License
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/presentation/balance/assetActions/buy/BuyProviderChooserBottomSheet.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.wallet.impl.presentation.balance.assetActions.buy import android.content.Context import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import jp.co.soramitsu.common.utils.inflateChild import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.ClickHandler import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.DynamicListBottomSheet import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.DynamicListSheetAdapter import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.HolderCreator import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.ReferentialEqualityDiffCallBack import jp.co.soramitsu.core.models.Asset import jp.co.soramitsu.feature_wallet_impl.R import jp.co.soramitsu.wallet.impl.domain.model.BuyTokenRegistry typealias BuyProvider = BuyTokenRegistry.Provider<*> class BuyProviderChooserBottomSheet( context: Context, providers: List<BuyProvider>, private val asset: Asset, onClick: ClickHandler<BuyProvider> ) : DynamicListBottomSheet<BuyProvider>( context, Payload(providers), ReferentialEqualityDiffCallBack(), onClick ) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTitle(context.getString(R.string.wallet_asset_buy_with, asset.symbol.uppercase())) } override fun holderCreator(): HolderCreator<BuyProvider> = { BuyProviderHolder(it.inflateChild(R.layout.item_sheet_buy_provider)) } } private class BuyProviderHolder( itemView: View ) : DynamicListSheetAdapter.Holder<BuyProvider>(itemView) { override fun bind(item: BuyProvider, isSelected: Boolean, handler: DynamicListSheetAdapter.Handler<BuyProvider>) { super.bind(item, isSelected, handler) val text = itemView.findViewById<TextView>(R.id.itemSheetBuyProviderText) val image = itemView.findViewById<ImageView>(R.id.itemSheetBuyProviderImage) text.text = item.name image.setImageResource(item.icon) } }
8
null
30
89
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
2,056
fearless-Android
Apache License 2.0
app/src/main/kotlin/com/fibelatti/pinboard/features/posts/data/model/PendingSyncDto.kt
fibelatti
165,537,939
false
null
package com.fibelatti.pinboard.features.posts.data.model enum class PendingSyncDto { ADD, UPDATE, DELETE, }
5
Kotlin
10
95
c6ff28fea78b4785ea02eace40f5811c83e8e14a
121
pinboard-kotlin
Apache License 2.0
content-types/content-types-core-services/src/main/kotlin/org/orkg/contenttypes/domain/actions/IdentifierUpdater.kt
TIBHannover
197,416,205
false
{"Kotlin": 5947467, "Cypher": 219508, "Python": 4881, "Shell": 2767, "Groovy": 1936, "HTML": 240, "Batchfile": 82}
package org.orkg.contenttypes.domain.actions import org.orkg.common.ContributorId import org.orkg.common.ThingId import org.orkg.contenttypes.domain.associateIdentifiers import org.orkg.contenttypes.domain.identifiers.Identifier import org.orkg.graph.domain.GeneralStatement import org.orkg.graph.input.LiteralUseCases import org.orkg.graph.input.StatementUseCases class IdentifierUpdater( private val statementCollectionPropertyUpdater: StatementCollectionPropertyUpdater ) { constructor( statementService: StatementUseCases, literalService: LiteralUseCases, ) : this(StatementCollectionPropertyUpdater(literalService, statementService)) internal fun update( statements: Map<ThingId, List<GeneralStatement>>, contributorId: ContributorId, newIdentifiers: Map<String, List<String>>, identifierDefinitions: Set<Identifier>, subjectId: ThingId ) { val directStatements = statements[subjectId].orEmpty() val oldIdentifiers = directStatements.associateIdentifiers(identifierDefinitions) if (oldIdentifiers == newIdentifiers) return identifierDefinitions.forEach { identifier -> statementCollectionPropertyUpdater.update( statements = directStatements, contributorId = contributorId, subjectId = subjectId, predicateId = identifier.predicateId, literals = newIdentifiers[identifier.id].orEmpty().toSet() ) } } }
0
Kotlin
0
4
d09fafc9a4bd996623c9c5b198aa16160485d144
1,548
orkg-backend
MIT License
presentation/src/main/java/org/lotka/xenonx/presentation/screen/register/RegisterViewModel.kt
armanqanih
860,856,530
false
{"Kotlin": 193158}
package org.lotka.xenon.presentation.screen.auth.register import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import org.lotka.xenon.domain.usecase.auth.RegisterUserUseCase import org.lotka.xenon.domain.util.Resource import org.lotka.xenon.presentation.ui.navigation.ScreensNavigation import org.lotka.xenon.presentation.util.PasswordTextFieldState import org.lotka.xenon.presentation.util.StandardTextFieldState import org.lotka.xenon.presentation.util.UiEvent import javax.inject.Inject @HiltViewModel class RegisterViewModel @Inject constructor( private val registerUserUseCase: RegisterUserUseCase ) : ViewModel() { private val _state = MutableStateFlow(RegisterState()) val state = _state.asStateFlow() private val _userNameState = MutableStateFlow(StandardTextFieldState()) val userNameState = _userNameState.asStateFlow() private val _emailState = MutableStateFlow(StandardTextFieldState()) val emailState = _emailState.asStateFlow() private val _passwordState = MutableStateFlow(PasswordTextFieldState()) val passwordState = _passwordState.asStateFlow() private val _eventFlow = MutableSharedFlow<UiEvent>() val eventFlow = _eventFlow.asSharedFlow() fun onEvent(event: RegisterEvent) { when (event) { is RegisterEvent.EnterPassword -> { _passwordState.value = _passwordState.value.copy( text = event.password ) } is RegisterEvent.EnterUserName -> { _userNameState.value = _userNameState.value.copy( text = event.userName ) } is RegisterEvent.ShowSnakeBar -> { viewModelScope.launch { _eventFlow.emit(UiEvent.ShowSnakeBar(event.message)) } } is RegisterEvent.EnterEmail -> { _emailState.value = _emailState.value.copy( text = event.email ) } RegisterEvent.IsPasswordVisibility -> { _passwordState.value = _passwordState.value.copy( isPasswordVisible = !passwordState.value.isPasswordVisible ) } is RegisterEvent.Register -> { viewModelScope.launch { register() } } } } private suspend fun register() { _userNameState.value = _userNameState.value.copy(error = null) _emailState.value = _emailState.value.copy(error = null) _passwordState.value = _passwordState.value.copy(error = null) _state.value = _state.value.copy(isLoading = true) val username = userNameState.value.text val email = emailState.value.text val password = passwordState.value.text // Call the use case to register the user val registerResult = registerUserUseCase(username, email, password) // Update the UI with potential errors if (registerResult.userNameError != null) { _userNameState.value = _userNameState.value.copy( error = registerResult.userNameError) } if (registerResult.emailError != null) { _emailState.value = _emailState.value.copy( error = registerResult.emailError) } if (registerResult.passwordError != null) { _passwordState.value = _passwordState.value.copy( error = registerResult.passwordError) } // If there are no errors, proceed with registration _state.value = _state.value.copy(isLoading = false) try { // Collect the result from the use case registerResult.result?.collect{ result -> when (result) { is Resource.Success -> { // Set loading to false and handle success _state.value = _state.value.copy(isLoading = false) result.data?.let { _eventFlow.emit(UiEvent.ShowSnakeBar("You have successfully registered")) delay(2000) _eventFlow.emit(UiEvent.Navigate(ScreensNavigation.LoginScreen.route)) } } is Resource.Error -> { // Set loading to false and handle error _state.value = _state.value.copy(isLoading = false) _eventFlow.emit(UiEvent.ShowSnakeBar(result.message ?: "An unexpected error occurred")) } is Resource.Loading -> { // Set loading to true _state.value = _state.value.copy(isLoading = true) } null -> { _state.value = _state.value.copy(isLoading = false) } } } } catch (e: Exception) { // Handle any unexpected exceptions _state.value = _state.value.copy(isLoading = false) _eventFlow.emit(UiEvent.ShowSnakeBar("An internal error occurred: ${e.localizedMessage}")) } } }
0
Kotlin
0
0
760d2cfbd9854f53fd3a31f2a3f61426d8bf38f3
5,772
ModernNews
Apache License 2.0
samples/irs-demo/src/main/kotlin/net/corda/irs/flows/ExitServerFlow.kt
evisoft
75,185,334
false
null
package net.corda.irs.flows import co.paralleluniverse.fibers.Suspendable import co.paralleluniverse.strands.Strand import net.corda.core.crypto.Party import net.corda.core.flows.FlowLogic import net.corda.core.node.CordaPluginRegistry import net.corda.core.node.NodeInfo import net.corda.core.node.PluginServiceHub import net.corda.testing.node.MockNetworkMapCache import java.util.concurrent.TimeUnit object ExitServerFlow { // Will only be enabled if you install the Handler @Volatile private var enabled = false // This is not really a HandshakeMessage but needs to be so that the send uses the default session ID. This will // resolve itself when the flow session stuff is done. data class ExitMessage(val exitCode: Int) class Plugin: CordaPluginRegistry() { override val servicePlugins: List<Class<*>> = listOf(Service::class.java) } class Service(services: PluginServiceHub) { init { services.registerFlowInitiator(Broadcast::class, ::ExitServerHandler) enabled = true } } private class ExitServerHandler(val otherParty: Party) : FlowLogic<Unit>() { override fun call() { // Just to validate we got the message if (enabled) { val message = receive<ExitMessage>(otherParty).unwrap { it } System.exit(message.exitCode) } } } /** * This takes a Java Integer rather than Kotlin Int as that is what we end up with in the calling map and currently * we do not support coercing numeric types in the reflective search for matching constructors. */ class Broadcast(val exitCode: Int) : FlowLogic<Boolean>() { @Suspendable override fun call(): Boolean { if (enabled) { for (recipient in serviceHub.networkMapCache.partyNodes) { doNextRecipient(recipient) } // Sleep a little in case any async message delivery to other nodes needs to happen Strand.sleep(1, TimeUnit.SECONDS) System.exit(exitCode) } return enabled } @Suspendable private fun doNextRecipient(recipient: NodeInfo) { if (recipient.address is MockNetworkMapCache.MockAddress) { // Ignore } else { send(recipient.legalIdentity, ExitMessage(exitCode)) } } } }
22
null
1
1
4a9f5cafc1f2f09e8f612a09f30f9dfffd985a6c
2,485
corda
Apache License 2.0
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/extended/RedundantNullableChecker.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 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.fir.analysis.checkers.extended import org.jetbrains.kotlin.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.diagnostics.reportOn import org.jetbrains.kotlin.fir.analysis.checkers.SourceNavigator import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.checkers.toClassLikeSymbol import org.jetbrains.kotlin.fir.analysis.checkers.type.FirTypeRefChecker import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.REDUNDANT_NULLABLE import org.jetbrains.kotlin.fir.symbols.impl.FirTypeAliasSymbol import org.jetbrains.kotlin.fir.types.* object RedundantNullableChecker : FirTypeRefChecker() { override fun check(typeRef: FirTypeRef, context: CheckerContext, reporter: DiagnosticReporter) { if (typeRef !is FirResolvedTypeRef || typeRef.isMarkedNullable != true) return var symbol = typeRef.toClassLikeSymbol(context.session) if (symbol is FirTypeAliasSymbol) { while (symbol is FirTypeAliasSymbol) { val resolvedExpandedTypeRef = symbol.resolvedExpandedTypeRef if (resolvedExpandedTypeRef.type.isMarkedNullable) { reporter.reportOn(typeRef.source, REDUNDANT_NULLABLE, context) break } else { symbol = resolvedExpandedTypeRef.toClassLikeSymbol(context.session) } } } else { with(SourceNavigator.forElement(typeRef)) { if (typeRef.isRedundantNullable()) { reporter.reportOn(typeRef.source, REDUNDANT_NULLABLE, context) } } } } }
178
null
5771
48,021
093e432a97b4e7af469bc55a3d321dec964bc6de
1,908
kotlin
Apache License 2.0
src/main/kotlin/com/github/jk1/ytplugin/commands/model/CommandAssistResponse.kt
dzham
269,710,984
true
{"Kotlin": 191555, "CSS": 2865, "Java": 2255}
package com.github.jk1.ytplugin.commands.model import com.google.gson.JsonParser import java.io.InputStream import java.io.InputStreamReader /** * Main wrapper around youtrack command assist response response. It delegates further parsing * to CommandHighlightRange, CommandSuggestion and CommandPreview classes */ class CommandAssistResponse(stream: InputStream) { val highlightRanges: List<CommandHighlightRange> val suggestions: List<CommandSuggestion> val previews: List<CommandPreview> val timestamp = System.currentTimeMillis() init { val root = JsonParser().parse(InputStreamReader(stream, "UTF-8")).asJsonObject val ranges = root.getAsJsonObject("underline").getAsJsonArray("ranges") val suggests = root.getAsJsonObject("suggest").getAsJsonArray("items") val commands = root.getAsJsonObject("commands").getAsJsonArray("command") highlightRanges = ranges.map { CommandHighlightRange(it) } suggestions = suggests.map { CommandSuggestion(it) } previews = commands.map { CommandPreview(it) } } }
0
null
0
0
afe997a05dfb240616b5758f5a0d0c2bcc3199e2
1,086
youtrack-idea-plugin
Apache License 2.0
ospf-kotlin-utils/src/main/fuookami/ospf/kotlin/utils/math/symbol/Symbol.kt
fuookami
359,831,793
false
{"Kotlin": 2440181, "Python": 6629}
package fuookami.ospf.kotlin.utils.math.symbol class Symbol { }
0
Kotlin
0
4
b34cda509b31884e6a15d77f00a6134d001868de
64
ospf-kotlin
Apache License 2.0
integration-tests/tests/src/test/java/com/squareup/hephaestus/test/MergeInterfacesTest.kt
rharter
308,196,937
true
{"Kotlin": 102770}
package com.squareup.anvil.test import com.google.common.truth.Truth.assertThat import com.squareup.anvil.annotations.compat.MergeInterfaces import org.junit.Test internal class MergeInterfacesTest { @Test fun `contributed interfaces are merged`() { assertThat(CompositeAppComponent::class extends AppComponentInterface::class).isTrue() assertThat(CompositeAppComponent::class extends SubComponentInterface::class).isFalse() assertThat(CompositeSubComponent::class extends SubComponentInterface::class).isTrue() assertThat(CompositeSubComponent::class extends AppComponentInterface::class).isFalse() } @MergeInterfaces(AppScope::class) interface CompositeAppComponent @MergeInterfaces(SubScope::class) interface CompositeSubComponent }
0
Kotlin
0
0
b57fead06ee6c340d0d852d27b28d33a8115bf28
770
hephaestus
Apache License 2.0
GoogleLensClone-main/app/src/main/java/com/acash/googlelensclone/CameraActivity.kt
yyprince334
394,915,814
false
null
package com.acash.googlelensclone import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.content.ContextCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.android.synthetic.main.activity_camera.* import java.io.File const val CAMERA_PERMISSION_REQUEST_CODE = 4321 class CameraActivity : AppCompatActivity() { private lateinit var imageCapture: ImageCapture private var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_camera) checkCameraPermissions() btnCaptureImg.setOnClickListener{ takePicture() } btnChangeLens.setOnClickListener{ cameraSelector = if (cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) CameraSelector.DEFAULT_FRONT_CAMERA else CameraSelector.DEFAULT_BACK_CAMERA startCamera() } } private fun takePicture() { if(::imageCapture.isInitialized){ val file = File(externalMediaDirs.first(),"IMG_${System.currentTimeMillis()}.jpg") val outputFileOptions = ImageCapture.OutputFileOptions.Builder(file).build() imageCapture.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object:ImageCapture.OnImageSavedCallback{ override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) { Toast.makeText(this@CameraActivity,"Image Saved at ${file.absolutePath}",Toast.LENGTH_SHORT).show() } override fun onError(exception: ImageCaptureException) { Toast.makeText(this@CameraActivity,"Error Saving Image!Try Again",Toast.LENGTH_SHORT).show() } }) }else{ Toast.makeText(this,"Camera Not Found",Toast.LENGTH_SHORT).show() } } private fun checkCameraPermissions() { if(checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){ startCamera() } else requestPermissions(arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE) } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener( { val cameraProvider = cameraProviderFuture.get() val preview = Preview.Builder() .setTargetAspectRatio(AspectRatio.RATIO_16_9) .build() preview.setSurfaceProvider(previewView.surfaceProvider) imageCapture = ImageCapture.Builder() .setTargetAspectRatio(AspectRatio.RATIO_16_9) .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY) .build() cameraProvider.unbindAll() cameraProvider.bindToLifecycle(this,cameraSelector,preview,imageCapture) }, ContextCompat.getMainExecutor(this) ) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if(requestCode== CAMERA_PERMISSION_REQUEST_CODE){ if(permissions[0]==Manifest.permission.CAMERA && grantResults[0]==PackageManager.PERMISSION_GRANTED){ startCamera() }else{ MaterialAlertDialogBuilder(this).apply { setTitle("Permission Error") setMessage("Cannot Proceed Without Camera Permissions") setPositiveButton("OK"){_,_-> finish() } setCancelable(false) }.show() } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } }
0
Kotlin
0
1
07f79321125790aa2cf6768e1bcb1fd888534566
4,196
Google-Lens-Clone
Apache License 2.0
app/src/main/java/com/learning/composeexample/di/MainModule.kt
kerriganlove
578,924,719
false
{"Kotlin": 21991}
package com.learning.composeexample.di object MainModule { }
0
Kotlin
0
0
2d7f9fb2148b103977c16bd0652df1bdfb617e2b
61
ComposeExample
Apache License 2.0
platform/credential-store/src/credentialStore.kt
kishorechanti
152,908,241
false
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.text.StringUtil import com.intellij.util.EncryptionSupport import com.intellij.util.generateAesKey import com.intellij.util.io.toByteArray import java.nio.CharBuffer import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.security.SecureRandom import java.util.* import javax.crypto.spec.SecretKeySpec internal val LOG = Logger.getInstance(CredentialStore::class.java) private fun toOldKey(hash: ByteArray) = "old-hashed-key|" + Base64.getEncoder().encodeToString(hash) internal fun toOldKeyAsIdentity(hash: ByteArray) = CredentialAttributes(SERVICE_NAME_PREFIX, toOldKey(hash)) fun toOldKey(requestor: Class<*>, userName: String): CredentialAttributes { return CredentialAttributes(SERVICE_NAME_PREFIX, toOldKey(MessageDigest.getInstance("SHA-256").digest("${requestor.name}/$userName".toByteArray()))) } fun joinData(user: String?, password: OneTimeString?): ByteArray? { if (user == null && password == null) { return null } val builder = StringBuilder(user.orEmpty()) StringUtil.escapeChar(builder, '\\') StringUtil.escapeChar(builder, '@') if (password != null) { builder.append('@') password.appendTo(builder) } val buffer = Charsets.UTF_8.encode(CharBuffer.wrap(builder)) // clear password builder.setLength(0) return buffer.toByteArray() } fun splitData(data: String?): Credentials? { if (data.isNullOrEmpty()) { return null } val list = parseString(data!!, '@') return Credentials(list.getOrNull(0), list.getOrNull(1)) } private const val ESCAPING_CHAR = '\\' private fun parseString(data: String, delimiter: Char): List<String> { val part = StringBuilder() val result = ArrayList<String>(2) var i = 0 var c: Char? do { c = data.getOrNull(i++) if (c != null && c != delimiter) { if (c == ESCAPING_CHAR) { c = data.getOrNull(i++) } if (c != null) { part.append(c) continue } } result.add(part.toString()) part.setLength(0) if (i < data.length) { result.add(data.substring(i)) break } } while (c != null) return result } // check isEmpty before @JvmOverloads fun Credentials.serialize(storePassword: Boolean = true) = joinData(userName, if (storePassword) password else null)!! @Suppress("FunctionName") internal fun SecureString(value: CharSequence) = SecureString(Charsets.UTF_8.encode(CharBuffer.wrap(value)).toByteArray()) internal class SecureString(value: ByteArray) { companion object { private val encryptionSupport = EncryptionSupport(SecretKeySpec(generateAesKey(), "AES")) } private val data = encryptionSupport.encrypt(value) fun get(clearable: Boolean = true) = OneTimeString(encryptionSupport.decrypt(data), clearable = clearable) } internal val ACCESS_TO_KEY_CHAIN_DENIED = Credentials(null, null as OneTimeString?) internal fun createSecureRandom(): SecureRandom { try { return SecureRandom.getInstanceStrong() } catch (e: NoSuchAlgorithmException) { return SecureRandom() } }
1
null
1
1
8d34b0c0c3c3b451104c1cb8a7d99c424663f6b9
3,296
intellij-community
Apache License 2.0
library/src/test/java/io/github/anderscheow/validator/util/PredefinedRulesTest.kt
KirillAshikhmin
408,957,823
true
{"Kotlin": 129331, "Java": 99}
package io.github.anderscheow.validator.util import io.github.anderscheow.validator.Validation import io.github.anderscheow.validator.conditions.common.And import io.github.anderscheow.validator.conditions.common.Or import io.github.anderscheow.validator.conditions.common.matchAllRules import io.github.anderscheow.validator.conditions.common.matchAtLeastOneRule import io.github.anderscheow.validator.rules.common.* import io.github.anderscheow.validator.rules.regex.* import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.text.SimpleDateFormat import java.util.* class PredefinedRulesTest { @Before @Throws(Exception::class) fun setUp() { } @After @Throws(Exception::class) fun tearDown() { } /** * Extension for Validation */ @Test @Throws(Exception::class) fun validate_Validation_Contain() { val sample = "contain test" val invalidSample = "contain Test" val validation = Validation(sample).contain("test") assertTrue(validation.baseRules[0].javaClass == ContainRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_NotContain() { val sample = "contain Test" val invalidSample = "contain test" val validation = Validation(sample).notContain("test") assertTrue(validation.baseRules[0].javaClass == NotContainRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_EqualTo() { val sample = "test" val invalidSample = "Test" val validation = Validation(sample).equalTo("test") assertTrue(validation.baseRules[0].javaClass == EqualRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_NotEqualTo() { val sample = "Test" val invalidSample = "test" val validation = Validation(sample).notEqualTo("test") assertTrue(validation.baseRules[0].javaClass == NotEqualRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_WithinRange() { val sample = "Hello World" val invalidSample = "Hello" val validation = Validation(sample).withinRange(6, 15) assertTrue(validation.baseRules[0].javaClass == LengthRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_MinimumLength() { val sample = "Hello World" val invalidSample = "Hello" val validation = Validation(sample).minimumLength(6) assertTrue(validation.baseRules[0].javaClass == MinRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_MaximumLength() { val sample = "Hello" val invalidSample = "Hello World" val validation = Validation(sample).maximumLength(6) assertTrue(validation.baseRules[0].javaClass == MaxRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_Future() { val sample = "31/12/${Calendar.getInstance().get(Calendar.YEAR) + 1}" val validation = Validation(sample).future(SimpleDateFormat("dd/MM/yyyy")) assertTrue(validation.baseRules[0].javaClass == FutureRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) } @Test @Throws(Exception::class) fun validate_Validation_Past() { val sample = "31/12/${Calendar.getInstance().get(Calendar.YEAR) - 1}" val validation = Validation(sample).past(SimpleDateFormat("dd/MM/yyyy")) assertTrue(validation.baseRules[0].javaClass == PastRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) } @Test @Throws(Exception::class) fun validate_Validation_NotEmpty() { val sample = " " val invalidSample = "" val validation = Validation(sample).notEmpty() assertTrue(validation.baseRules[0].javaClass == NotEmptyRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_NotBlank() { val sample = "not blank" val invalidSample = " " val validation = Validation(sample).notBlank() assertTrue(validation.baseRules[0].javaClass == NotBlankRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_NotNull() { val sample = "not null" val invalidSample = null val validation = Validation(sample).notNull() assertTrue(validation.baseRules[0].javaClass == NotNullRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_Regex() { val sample = "[email protected]" val invalidSample = "hello_world.com" val validation = Validation(sample).regex("\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b") assertTrue(validation.baseRules[0].javaClass == RegexRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_Email() { val sample = "[email protected]" val invalidSample = "hello_world.com" val validation = Validation(sample).email() assertTrue(validation.baseRules[0].javaClass == EmailRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_AlphanumericOnly() { val sample = "helloworld123" val invalidSample = "hello world123" val validation = Validation(sample).alphanumericOnly() assertTrue(validation.baseRules[0].javaClass == AlphanumericRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_AlphabetOnly() { val sample = "helloworld" val invalidSample = "hello world123" val validation = Validation(sample).alphabetOnly() assertTrue(validation.baseRules[0].javaClass == AlphabetRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_DigitsOnly() { val sample = "123" val invalidSample = "hello world123" val validation = Validation(sample).digitsOnly() assertTrue(validation.baseRules[0].javaClass == DigitsRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_SymbolsOnly() { val sample = "!@#" val invalidSample = "hello world123" val validation = Validation(sample).symbolsOnly() assertEquals(validation.baseRules[0].getErrorMessage(), "Value does not contain symbols") assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_AllUppercase() { val sample = "HELLO WORLD" val invalidSample = "hello world" val validation = Validation(sample).allUppercase() assertEquals(validation.baseRules[0].getErrorMessage(), "Value is not all uppercase") assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test(expected = NullPointerException::class) @Throws(Exception::class) fun validate_Validation_AllUppercase_NPE() { val sample = "HELLO WORLD" val validation = Validation(sample).allUppercase() assertFalse(validation.baseRules[0].validate(null)) } @Test @Throws(Exception::class) fun validate_Validation_AllLowercase() { val sample = "hello world" val invalidSample = "HELLO WORLD" val validation = Validation(sample).allLowercase() assertEquals(validation.baseRules[0].getErrorMessage(), "Value is not all lowercase") assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test(expected = NullPointerException::class) @Throws(Exception::class) fun validate_Validation_AllLowercase_NPE() { val sample = "hello world" val validation = Validation(sample).allLowercase() assertFalse(validation.baseRules[0].validate(null)) } @Test @Throws(Exception::class) fun validate_Validation_StartsWith() { val sample = "hello world" val invalidSample = "world hello" val validation = Validation(sample).startsWith("hello") assertEquals(validation.baseRules[0].getErrorMessage(), "Value is not start with hello") assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test(expected = NullPointerException::class) @Throws(Exception::class) fun validate_Validation_StartsWith_NPE() { val sample = "hello world" val validation = Validation(sample).startsWith("hello") assertFalse(validation.baseRules[0].validate(null)) } @Test @Throws(Exception::class) fun validate_Validation_EndsWith() { val sample = "hello world" val invalidSample = "world hello" val validation = Validation(sample).endsWith("world") assertEquals(validation.baseRules[0].getErrorMessage(), "Value is not end with world") assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test(expected = NullPointerException::class) @Throws(Exception::class) fun validate_Validation_EndsWith_NPE() { val sample = "hello world" val validation = Validation(sample).endsWith("world") assertFalse(validation.baseRules[0].validate(null)) } @Test @Throws(Exception::class) fun validate_Validation_WithCreditCard() { val sample = "4111111111111111" val invalidSample = "5555555555554444" val validation = Validation(sample).withCreditCard(CreditCardRule.CreditCardRegex.VISA) assertTrue(validation.baseRules[0].javaClass == CreditCardRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_WithPassword() { val sample = "abc ABC 123 .," val invalidSample = "abc 123 ,./" val validation = Validation(sample).withPassword(PasswordRule.PasswordRegex.ALPHA_MIXED_CASE) assertTrue(validation.baseRules[0].javaClass == PasswordRule::class.java) assertTrue(validation.baseRules[0].validate(sample)) assertFalse(validation.baseRules[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_MatchAtLeastOneRule() { val sample = "[email protected]" val invalidSample = "hello@world_hello@world" val validation = Validation(sample).matchAtLeastOneRule(arrayOf( EmailRule(), MaxRule(15) )) assertTrue(validation.conditions[0].javaClass == Or::class.java) assertTrue(validation.conditions[0].baseRules[0].javaClass == EmailRule::class.java && validation.conditions[0].baseRules[1].javaClass == MaxRule::class.java) assertTrue(validation.conditions[0].validate(sample)) assertFalse(validation.conditions[0].validate(invalidSample)) } @Test @Throws(Exception::class) fun validate_Validation_MatchAllRules() { val sample = "[email protected]" val invalidSample = "hello@world_hello@world" val validation = Validation(sample).matchAllRules(arrayOf( EmailRule(), MaxRule(15) )) assertTrue(validation.conditions[0].javaClass == And::class.java) assertTrue(validation.conditions[0].baseRules[0].javaClass == EmailRule::class.java && validation.conditions[0].baseRules[1].javaClass == MaxRule::class.java) assertTrue(validation.conditions[0].validate(sample)) assertFalse(validation.conditions[0].validate(invalidSample)) } }
0
null
0
0
56c2e490fa06e491dd782b2bab0d222507b3eaf0
14,028
Validator
MIT License
src/main/kotlin/no/nav/amt/deltaker/bff/navansatt/NavAnsattConsumer.kt
navikt
701,285,451
false
{"Kotlin": 255205, "PLpgSQL": 635, "Dockerfile": 173}
package no.nav.amt.deltaker.bff.navansatt import com.fasterxml.jackson.module.kotlin.readValue import no.nav.amt.deltaker.bff.Environment import no.nav.amt.deltaker.bff.application.plugins.objectMapper import no.nav.amt.lib.kafka.Consumer import no.nav.amt.lib.kafka.ManagedKafkaConsumer import no.nav.amt.lib.kafka.config.KafkaConfig import no.nav.amt.lib.kafka.config.KafkaConfigImpl import no.nav.amt.lib.kafka.config.LocalKafkaConfig import org.apache.kafka.common.serialization.StringDeserializer import org.apache.kafka.common.serialization.UUIDDeserializer import org.slf4j.LoggerFactory import java.util.UUID class NavAnsattConsumer( private val navAnsattService: NavAnsattService, kafkaConfig: KafkaConfig = if (Environment.isLocal()) LocalKafkaConfig() else KafkaConfigImpl(), ) : Consumer<UUID, String?> { private val log = LoggerFactory.getLogger(javaClass) private val consumer = ManagedKafkaConsumer( topic = Environment.AMT_NAV_ANSATT_TOPIC, config = kafkaConfig.consumerConfig( keyDeserializer = UUIDDeserializer(), valueDeserializer = StringDeserializer(), groupId = Environment.KAFKA_CONSUMER_GROUP_ID, ), consume = ::consume, ) override suspend fun consume(key: UUID, value: String?) { if (value == null) { navAnsattService.slettNavAnsatt(key) log.info("Slettet navansatt med id $key") } else { val dto = objectMapper.readValue<NavAnsattDto>(value) navAnsattService.oppdaterNavAnsatt(dto.toModel()) log.info("Lagret navansatt med id $key") } } override fun run() = consumer.run() } data class NavAnsattDto( val id: UUID, val navident: String, val navn: String, ) { fun toModel() = NavAnsatt(id, navident, navn) }
0
Kotlin
0
0
e8b4fb5d324377fb51d952cc5a50a70102df1f0d
1,838
amt-deltaker-bff
MIT License
signer/src/main/java/com/uport/sdk/signer/UportHDSigner.kt
jimjag
205,325,614
true
{"Kotlin": 489456, "Java": 409}
package com.uport.sdk.signer import android.content.Context import android.content.Context.MODE_PRIVATE import com.uport.sdk.signer.encryption.KeyProtection import me.uport.sdk.core.decodeBase64 import me.uport.sdk.core.padBase64 import me.uport.sdk.core.toBase64 import me.uport.sdk.signer.getUncompressedPublicKeyWithPrefix import org.kethereum.bip39.entropyToMnemonic import org.kethereum.bip39.mnemonicToEntropy import org.kethereum.bip39.model.MnemonicWords import org.kethereum.bip39.toKey import org.kethereum.bip39.validate import org.kethereum.bip39.wordlists.WORDLIST_ENGLISH import org.kethereum.crypto.signMessage import org.kethereum.crypto.toAddress import org.kethereum.model.SignatureData import java.security.SecureRandom @Suppress("unused", "KDocUnresolvedReference") class UportHDSigner : UportSigner() { /** * Checks if there is ANY seed created or imported */ fun hasSeed(context: Context): Boolean { val prefs = context.getSharedPreferences(ETH_ENCRYPTED_STORAGE, MODE_PRIVATE) val allSeeds = prefs.all.keys .filter { label -> label.startsWith(SEED_PREFIX) } .filter { hasCorrespondingLevelKey(prefs, it) } return allSeeds.isNotEmpty() } /** * Creates a 128 bit seed and stores it at the [level] encryption level. * Calls back with the seed handle ([rootAddress]) and the Base64 encoded * [pubKey] corresponding to it, or a non-null [err] if something broke */ fun createHDSeed(context: Context, level: KeyProtection.Level, callback: (err: Exception?, rootAddress: String, pubKey: String) -> Unit) { val entropyBuffer = ByteArray(128 / 8) SecureRandom().nextBytes(entropyBuffer) val seedPhrase = entropyToMnemonic(entropyBuffer, WORDLIST_ENGLISH) return importHDSeed(context, level, seedPhrase, callback) } /** * Imports a given mnemonic [phrase] * The phrase is converted to its binary representation using bip39 rules * and stored at the provided [level] of encryption. * * A rootAddress is derived from the phrase and will be used to refer to this imported phrase for future signing. * * Then calls back with the derived 0x `rootAddress` and base64 encoded `public Key` * or a non-null err in case something goes wrong */ fun importHDSeed(context: Context, level: KeyProtection.Level, phrase: String, callback: (err: Exception?, address: String, pubKey: String) -> Unit) { try { val entropyBuffer = mnemonicToEntropy(phrase, WORDLIST_ENGLISH) val extendedRootKey = MnemonicWords(phrase).toKey(UPORT_ROOT_DERIVATION_PATH) val keyPair = extendedRootKey.keyPair val publicKeyBytes = keyPair.getUncompressedPublicKeyWithPrefix() val publicKeyString = publicKeyBytes.toBase64().padBase64() val address: String = keyPair.toAddress().hex val label = asSeedLabel(address) storeEncryptedPayload(context, level, label, entropyBuffer ) { err, _ -> //empty memory entropyBuffer.fill(0) if (err != null) { return@storeEncryptedPayload callback(err, "", "") } return@storeEncryptedPayload callback(null, address, publicKeyString) } } catch (seedImportError: Exception) { return callback(seedImportError, "", "") } } /** * Deletes a seed from storage. */ fun deleteSeed(context: Context, label: String) { val prefs = context.getSharedPreferences(ETH_ENCRYPTED_STORAGE, MODE_PRIVATE) prefs.edit() //store encrypted privatekey .remove(asSeedLabel(label)) //mark the key as encrypted with provided security level .remove(asLevelLabel(label)) .apply() } /** * Signs a transaction bundle using a key derived from a previously imported/created seed. * * In case the seed corresponding to the [rootAddress] requires user authentication to decrypt, * this method will launch the decryption UI with a [prompt] and schedule a callback with the signature data * after the decryption takes place; or a non-null error in case something goes wrong (or user cancels) * * The decryption UI can be a device lockscreen or fingerprint-dialog depending on the level of encryption * requested at seed creation/import. * * @param context The android activity from which the signature is requested or app context if it's encrypted using [KeyProtection.Level.SIMPLE]] protection * @param rootAddress the 0x ETH address used to refer to the previously imported/created seed * @param txPayload the base64 encoded byte array that represents the message to be signed * @param prompt A string that needs to be displayed to the user in case user-auth is requested * @param callback (error, signature) called after the transaction has been signed successfully or * with an error and empty data when it fails */ fun signTransaction(context: Context, rootAddress: String, derivationPath: String, txPayload: String, prompt: String, callback: (err: Exception?, sigData: SignatureData) -> Unit) { val (encryptionLayer, encryptedEntropy, storageError) = getEncryptionForLabel(context, asSeedLabel(rootAddress)) if (storageError != null) { //storage error is also thrown if the root seed does not exist return callback(storageError, EMPTY_SIGNATURE_DATA) } encryptionLayer.decrypt(context, prompt, encryptedEntropy) { decryptError, entropyBuff -> if (decryptError != null) { return@decrypt callback(decryptError, EMPTY_SIGNATURE_DATA) } try { val phrase = entropyToMnemonic(entropyBuff, WORDLIST_ENGLISH) val extendedKey = MnemonicWords(phrase).toKey(derivationPath) val keyPair = extendedKey.keyPair val txBytes = txPayload.decodeBase64() val sigData = keyPair.signMessage(txBytes) return@decrypt callback(null, sigData) } catch (signError: Exception) { return@decrypt callback(signError, EMPTY_SIGNATURE_DATA) } } } /** * Signs a uPort specific JWT bundle using a key derived from a previously imported/created seed. * * In case the seed corresponding to the [rootAddress] requires user authentication to decrypt, * this method will launch the decryption UI with a [prompt] and schedule a callback with the signature data * after the decryption takes place; or a non-null error in case something goes wrong (or user cancels) * * The decryption UI can be a device lockscreen or fingerprint-dialog depending on the level of encryption * requested at seed creation/import. * * @param context The android activity from which the signature is requested or app context if it's encrypted using [KeyProtection.Level.SIMPLE]] protection * @param rootAddress the 0x ETH address used to refer to the previously imported/created seed * @param data the base64 encoded byte array that represents the payload to be signed * @param prompt A string that needs to be displayed to the user in case user-auth is requested * @param callback (error, signature) called after the transaction has been signed successfully or * with an error and empty data when it fails */ fun signJwtBundle(context: Context, rootAddress: String, derivationPath: String, data: String, prompt: String, callback: (err: Exception?, sigData: SignatureData) -> Unit) { val (encryptionLayer, encryptedEntropy, storageError) = getEncryptionForLabel(context, asSeedLabel(rootAddress)) if (storageError != null) { return callback(storageError, SignatureData()) } encryptionLayer.decrypt(context, prompt, encryptedEntropy) { decryptError, entropyBuff -> if (decryptError != null) { return@decrypt callback(decryptError, SignatureData()) } try { val phrase = entropyToMnemonic(entropyBuff, WORDLIST_ENGLISH) val extendedKey = MnemonicWords(phrase).toKey(derivationPath) val keyPair = extendedKey.keyPair val payloadBytes = data.decodeBase64() val sig = signJwt(payloadBytes, keyPair) return@decrypt callback(null, sig) } catch (signError: Exception) { return@decrypt callback(signError, SignatureData()) } } } /** * Derives the ethereum address and public key using the given [derivationPath] starting from * the seed that generated the given [rootAddress] * * The respective seed must have been previously generated or imported. * * The results are passed back to the calling code using the provided [callback] */ fun computeAddressForPath(context: Context, rootAddress: String, derivationPath: String, prompt: String, callback: (err: Exception?, address: String, pubKey: String) -> Unit) { val (encryptionLayer, encryptedEntropy, storageError) = getEncryptionForLabel(context, asSeedLabel(rootAddress)) if (storageError != null) { return callback(storageError, "", "") } encryptionLayer.decrypt(context, prompt, encryptedEntropy) { decryptError, entropyBuff -> if (decryptError != null) { return@decrypt callback(decryptError, "", "") } try { val phrase = entropyToMnemonic(entropyBuff, WORDLIST_ENGLISH) val extendedKey = MnemonicWords(phrase).toKey(derivationPath) val keyPair = extendedKey.keyPair val publicKeyBytes = keyPair.getUncompressedPublicKeyWithPrefix() val publicKeyString = publicKeyBytes.toBase64().padBase64() val address: String = keyPair.toAddress().hex return@decrypt callback(null, address, publicKeyString) } catch (derivationError: Exception) { return@decrypt callback(derivationError, "", "") } } } /** * Decrypts the seed that generated the given [rootAddress] and returns it as a mnemonic phrase * * The respective seed must have been previously generated or imported. * * The result is passed back to the calling code using the provided [callback] */ fun showHDSeed(context: Context, rootAddress: String, prompt: String, callback: (err: Exception?, phrase: String) -> Unit) { val (encryptionLayer, encryptedEntropy, storageError) = getEncryptionForLabel(context, asSeedLabel(rootAddress)) if (storageError != null) { return callback(storageError, "") } encryptionLayer.decrypt(context, prompt, encryptedEntropy) { err, entropyBuff -> if (err != null) { return@decrypt callback(err, "") } try { val phrase = entropyToMnemonic(entropyBuff, WORDLIST_ENGLISH) return@decrypt callback(null, phrase) } catch (exception: Exception) { return@decrypt callback(exception, "") } } } /** * Verifies if a given phrase is a valid mnemonic phrase usable in seed generation */ fun validateMnemonic(phrase: String): Boolean = MnemonicWords(phrase).validate(WORDLIST_ENGLISH) /** * Returns a list of addresses representing the uport roots used as handles for seeds */ fun allHDRoots(context: Context): List<String> { val prefs = context.getSharedPreferences(ETH_ENCRYPTED_STORAGE, MODE_PRIVATE) //list all stored keys, keep a list of what looks like uport root addresses return prefs.all.keys .asSequence() .filter { label -> label.startsWith(SEED_PREFIX) } .filter { hasCorrespondingLevelKey(prefs, it) } .map { label: String -> label.substring(SEED_PREFIX.length) } .toList() } companion object { const val UPORT_ROOT_DERIVATION_PATH = "m/7696500'/0'/0'/0'" const val GENERIC_DEVICE_KEY_DERIVATION_PATH = "m/44'/60'/0'/0" const val GENERIC_RECOVERY_DERIVATION_PATH = "m/44'/60'/0'/1" } }
0
Kotlin
0
0
6de7b9351cdc0a99cc63ee9c1a8bda5040cc14d3
12,691
uport-android-signer
Apache License 2.0
src/main/java/morefirework/mod/render/entity/GunpowderPackProjectileRenderer.kt
Sparkierkan7
617,247,442
false
null
package morefirework.mod.render.entity import morefirework.mod.entity.projectile.GunpowderPackProjectile import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import net.minecraft.client.render.entity.EntityRendererFactory import net.minecraft.client.render.entity.FlyingItemEntityRenderer import net.minecraft.util.Identifier @Environment(EnvType.CLIENT) class GunpowderPackProjectileRenderer(context: EntityRendererFactory.Context?) : FlyingItemEntityRenderer<GunpowderPackProjectile>(context, 2f, false) { val TEXTURE = Identifier("textures/entity/projectile/firecracker.png") //does not really matter fun getTexture(GunpowderPackProjectile: GunpowderPackProjectile): Identifier? { return TEXTURE } }
0
Kotlin
0
0
298d3b06c408b2c93ef379b4ab693905d07270a7
743
more_explosives_mod
MIT License
server/src/main/kotlin/net/eiradir/server/hud/message/NoHudMessages.kt
Eiradir
635,460,745
false
null
package net.eiradir.server.hud.message enum class NoHudMessages { }
12
Kotlin
0
0
fd732d283c6c72bbd0d0127bb86e8daf7e5bf3cd
68
eiradir-server
MIT License
data/src/test/java/com/csosa/healiostest/data/BaseTest.kt
andrea-lab-com
348,485,933
false
null
package com.csosa.healiostest.data import android.content.Context import androidx.room.Room import androidx.test.core.app.ApplicationProvider import com.csosa.healiostest.data.helpers.HeliosRequestDispatcher import com.csosa.healiostest.data.local.HealiosDatabase import com.csosa.healiostest.data.local.dao.CommentsDao import com.csosa.healiostest.data.local.dao.PostsDao import com.csosa.healiostest.data.local.dao.UsersDao import com.csosa.healiostest.data.preferences.AppPreferences import com.csosa.healiostest.data.remote.api.HealiosApiService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Before import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.io.IOException import java.util.concurrent.TimeUnit internal open class BaseTest { private lateinit var mockWebServer: MockWebServer lateinit var heliosApiService: HealiosApiService private lateinit var okHttpClient: OkHttpClient private lateinit var loggingInterceptor: HttpLoggingInterceptor private lateinit var db: HealiosDatabase protected lateinit var postsDao: PostsDao protected lateinit var usersDao: UsersDao protected lateinit var commentsDao: CommentsDao protected lateinit var appPreferences: AppPreferences @Before open fun setup() { mockWebServer = MockWebServer() mockWebServer.dispatcher = HeliosRequestDispatcher() mockWebServer.start() loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } okHttpClient = buildOkHttpClient(loggingInterceptor) val baseUrl = mockWebServer.url("/") heliosApiService = Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create()) .build() .create(HealiosApiService::class.java) val context = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(context, HealiosDatabase::class.java).build() usersDao = db.usersDao() postsDao = db.postsDao() commentsDao = db.commentsDao() appPreferences = AppPreferences(context) } @After @Throws(IOException::class) open fun tearDown() { mockWebServer.shutdown() runBlocking(Dispatchers.IO) { db.clearAllTables() } db.close() } private fun buildOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build() } }
0
Kotlin
0
0
3d86591d0e71dd7ef3fdd4ced440ee97637365d9
2,949
android-mvvm
Apache License 2.0
app/src/main/java/com/officehunter/AppModule.kt
SonOfGillas
792,829,985
false
{"Kotlin": 59930}
package com.officehunter import android.content.Context import androidx.datastore.preferences.preferencesDataStore import androidx.room.Room import com.officehunter.data.database.TravelDiaryDatabase import com.officehunter.data.remote.OSMDataSource import com.officehunter.data.repositories.PlacesRepository import com.officehunter.data.repositories.ProfileRepository import com.officehunter.data.repositories.SettingsRepository import com.officehunter.ui.screens.addtravel.AddTravelViewModel import com.officehunter.ui.screens.settings.SettingsViewModel import com.officehunter.utils.LocationService import com.officehunter.ui.PlacesViewModel import com.officehunter.ui.screens.login.LoginViewModel import io.ktor.client.HttpClient import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val Context.dataStore by preferencesDataStore("settings") val appModule = module { single { get<Context>().dataStore } single { Room.databaseBuilder( get(), TravelDiaryDatabase::class.java, "office-hunter" ) // Sconsigliato per progetti seri! Lo usiamo solo qui per semplicità .fallbackToDestructiveMigration() .build() } single { HttpClient { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } } } single { OSMDataSource(get()) } single { LocationService(get()) } single { SettingsRepository(get()) } single { ProfileRepository(get()) } single { PlacesRepository( get<TravelDiaryDatabase>().placesDAO(), get<Context>().applicationContext.contentResolver ) } viewModel { AddTravelViewModel() } viewModel { SettingsViewModel(get()) } viewModel { LoginViewModel(get()) } viewModel { PlacesViewModel(get()) } }
0
Kotlin
0
0
a53e274f392f29b0abbf0ad02bc25806af103b15
2,086
OfficeHunter
MIT License
app/src/main/java/com/mg/relaxy/ui/home/categories/CategoryAdapter.kt
developersancho
229,278,424
false
null
package com.mg.relaxy.ui.home.categories import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.mg.relaxy.R import com.mg.relaxy.base.BaseViewHolder import com.mg.relaxy.databinding.ItemCategoryBinding import com.mg.remote.model.Category import com.mg.util.extensions.inflate class CategoryAdapter : ListAdapter<Category, CategoryAdapter.CategoryViewHolder>(DiffCallback()) { var onItemClick: ((Category) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder = CategoryViewHolder(parent.inflate(R.layout.item_category)) override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) { holder.apply { bind(getItem(position)) itemView.tag = getItem(position) } } inner class CategoryViewHolder(view: View) : BaseViewHolder<ItemCategoryBinding>(view) { fun bind(category: Category) { binding.item = category binding.cardCategory.setOnClickListener { onItemClick?.invoke(category) } } } } private class DiffCallback : DiffUtil.ItemCallback<Category>() { override fun areItemsTheSame(oldItem: Category, newItem: Category): Boolean { return oldItem.categoryId == newItem.categoryId } override fun areContentsTheSame(oldItem: Category, newItem: Category): Boolean { return oldItem == newItem } }
0
Kotlin
1
4
9511956d8a35008408ee80b70fd5f86595b34b1b
1,534
relaxy
Apache License 2.0
feature/common/src/main/java/com/andannn/melodify/feature/common/component/CircleBoderImage.kt
andannn
583,624,480
false
{"Kotlin": 367190, "Swift": 621}
package com.andannn.melodify.feature.common.component import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage @Composable fun CircleBorderImage( model: String, modifier: Modifier = Modifier, ) { AsyncImage( modifier = modifier .clip(shape = CircleShape) .border( shape = CircleShape, border = BorderStroke(2.dp, color = MaterialTheme.colorScheme.primary), ), model = model, contentDescription = "", ) }
9
Kotlin
0
0
af7243371f7ab2759dea94095c8fa1bfa1707f1c
863
Melodify
Apache License 2.0
src/com/koxudaxi/htmpy/HtmpyFielViewProviderFactory.kt
pauleveritt
288,542,769
false
{"Kotlin": 64625, "Lex": 6725, "Java": 160}
package com.koxudaxi.htmpy import com.intellij.lang.Language import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.FileViewProvider import com.intellij.psi.FileViewProviderFactory import com.intellij.psi.PsiManager class HtmpyFielViewProviderFactory : FileViewProviderFactory { override fun createFileViewProvider(virtualFile: VirtualFile, language: Language, psiManager: PsiManager, eventSystemEnabled: Boolean): FileViewProvider { assert(language.isKindOf(HtmpyLanguage.INSTANCE)) return HtmpyFileViewProvider(psiManager, virtualFile, eventSystemEnabled, language) } }
8
Kotlin
0
1
d2253eaa2d8a329b5757280765fb5c4586ed4797
731
htmpy-pycharm-plugin
MIT License
webglmath/src/main/kotlin/Vec4Array.kt
sracedorfman
438,745,663
false
null
package vision.gears.webglmath import org.khronos.webgl.Float32Array import org.khronos.webgl.get import org.khronos.webgl.set import org.khronos.webgl.WebGLRenderingContext as GL import org.khronos.webgl.WebGLUniformLocation import kotlin.reflect.KProperty import kotlin.random.Random import kotlin.math.pow import kotlin.math.sqrt class Vec4Array(backingStorage: Float32Array?, startIndex: Int = 0, endIndex: Int = 0) : VecArray() { constructor(size : Int) : this(null, size, size) {} override val storage = backingStorage?.subarray(startIndex*4, endIndex*4)?:Float32Array(startIndex*4) override fun set(vararg values : Float) : Vec4Array { for(i in 0 until storage.length) { storage[i] = values.getOrNull(i%4) ?: if(i%4 == 3) 1.0f else 0.0f } return this } operator fun get(i : Int) : Vec4{ return Vec4(storage, i*4) } fun subarray(begin : Int, end : Int) : Vec4Array { return Vec4Array(storage, begin*4, end*4) } fun setNormalized(b : Vec4Array) { for(i in 0 until storage.length step 4) { val l2 = b.storage[i ] * b.storage[i ] + b.storage[i+1] * b.storage[i+1] + b.storage[i+2] * b.storage[i+2] + b.storage[i+3] * b.storage[i+3] val linv = 1 / sqrt(l2) storage[i ] = b.storage[i ] * linv storage[i+1] = b.storage[i+1] * linv storage[i+2] = b.storage[i+2] * linv storage[i+3] = b.storage[i+3] * linv } } fun setTransformed(v : Vec4Array, m : Mat4) { for(i in 0 until storage.length step 4) { storage[i+0] = v.storage[i+0] * m.storage[ 0] + v.storage[i+1] * m.storage[ 1] + v.storage[i+2] * m.storage[ 2] + v.storage[i+3] * m.storage[ 3] storage[i+1] = v.storage[i+0] * m.storage[ 4] + v.storage[i+1] * m.storage[ 5] + v.storage[i+2] * m.storage[ 6] + v.storage[i+3] * m.storage[ 7] storage[i+2] = v.storage[i+0] * m.storage[ 8] + v.storage[i+1] * m.storage[ 9] + v.storage[i+2] * m.storage[10] + v.storage[i+3] * m.storage[11] storage[i+3] = v.storage[i+0] * m.storage[12] + v.storage[i+1] * m.storage[13] + v.storage[i+2] * m.storage[14] + v.storage[i+3] * m.storage[15] } } fun transformNormal(v : Vec3Array, m : Mat4) { for(i in 0 until storage.length step 3) { storage[i+0] = v.storage[i+0] * m.storage[ 0] + v.storage[i+1] * m.storage[ 1] + v.storage[i+2] * m.storage[ 2] storage[i+1] = v.storage[i+0] * m.storage[ 4] + v.storage[i+1] * m.storage[ 5] + v.storage[i+2] * m.storage[ 6] storage[i+2] = v.storage[i+0] * m.storage[ 8] + v.storage[i+1] * m.storage[ 9] + v.storage[i+2] * m.storage[10] } } operator fun provideDelegate( provider: UniformProvider, property: KProperty<*>) : Vec4Array { provider.register(property.name + "[0]", this) return this } operator fun getValue(provider: UniformProvider, property: KProperty<*>): Vec4Array { return this } operator fun setValue(provider: UniformProvider, property: KProperty<*>, value: Vec4Array) { set(value) } override fun commit(gl : GL, uniformLocation : WebGLUniformLocation, samplerIndex : Int){ gl.uniform4fv(uniformLocation, storage) } override val glType : Int get() = GL.FLOAT_VEC4 }
0
null
0
1
44fe7680826d154c8e85f6721f463bc2f4e615b0
3,508
kogphysics
MIT License
packages/patrol/android/src/main/kotlin/pl/leancode/patrol/contracts/HandlePermissionRequestKt.kt
leancodepl
496,206,645
false
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: contracts.proto // Generated files should ignore deprecation warnings @file:Suppress("DEPRECATION") package pl.leancode.patrol.contracts; @kotlin.jvm.JvmName("-initializehandlePermissionRequest") public inline fun handlePermissionRequest(block: pl.leancode.patrol.contracts.HandlePermissionRequestKt.Dsl.() -> kotlin.Unit): pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest = pl.leancode.patrol.contracts.HandlePermissionRequestKt.Dsl._create(pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest.newBuilder()).apply { block() }._build() /** * Protobuf type `patrol.HandlePermissionRequest` */ public object HandlePermissionRequestKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker public class Dsl private constructor( private val _builder: pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest.Builder ) { public companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest = _builder.build() /** * `.patrol.HandlePermissionRequest.Code code = 1;` */ public var code: pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest.Code @JvmName("getCode") get() = _builder.getCode() @JvmName("setCode") set(value) { _builder.setCode(value) } public var codeValue: kotlin.Int @JvmName("getCodeValue") get() = _builder.getCodeValue() @JvmName("setCodeValue") set(value) { _builder.setCodeValue(value) } /** * `.patrol.HandlePermissionRequest.Code code = 1;` */ public fun clearCode() { _builder.clearCode() } } } public inline fun pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest.copy(block: pl.leancode.patrol.contracts.HandlePermissionRequestKt.Dsl.() -> kotlin.Unit): pl.leancode.patrol.contracts.Contracts.HandlePermissionRequest = pl.leancode.patrol.contracts.HandlePermissionRequestKt.Dsl._create(this.toBuilder()).apply { block() }._build()
177
Dart
62
515
b2872ec307a95b81b0e0b81e048dafb73770cccd
2,389
patrol
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Paragraph.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline 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 me.localx.icons.straight.Icons public val Icons.Outline.Paragraph: ImageVector get() { if (_paragraph != null) { return _paragraph!! } _paragraph = Builder(name = "Paragraph", defaultWidth = 512.0.dp, defaultHeight = 512.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) { moveToRelative(24.0f, 0.0f) horizontalLineToRelative(-15.5f) curveTo(3.813f, 0.0f, 0.0f, 3.813f, 0.0f, 8.5f) reflectiveCurveToRelative(3.813f, 8.5f, 8.5f, 8.5f) horizontalLineToRelative(5.5f) verticalLineToRelative(7.0f) horizontalLineToRelative(2.0f) lineTo(16.0f, 2.0f) horizontalLineToRelative(3.0f) verticalLineToRelative(22.0f) horizontalLineToRelative(2.0f) lineTo(21.0f, 2.0f) horizontalLineToRelative(3.0f) lineTo(24.0f, 0.0f) close() moveTo(14.0f, 15.0f) horizontalLineToRelative(-5.5f) curveToRelative(-3.584f, 0.0f, -6.5f, -2.916f, -6.5f, -6.5f) reflectiveCurveToRelative(2.916f, -6.5f, 6.5f, -6.5f) horizontalLineToRelative(5.5f) verticalLineToRelative(13.0f) close() } } .build() return _paragraph!! } private var _paragraph: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,251
icons
MIT License
ProjectService/app/src/main/java/me/liuqingwen/android/projectservice/MyService.kt
spkingr
99,180,956
false
null
package me.liuqingwen.android.projectservice import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Intent import android.os.Binder import android.os.Build import android.os.IBinder import android.support.v4.app.NotificationCompat import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.notificationManager import java.util.* import kotlin.concurrent.timer class MyService : Service(), AnkoLogger { companion object { private const val JOB_NAME = "douban" private const val JOB_PERIOD = 60 * 60 * 1000L private const val NOTIFICATION_CHANNEL_ID = "1" private const val NOTIFICATION_CHANNEL_NAME = "Notification_douban" private const val NOTIFICATION_ID = 0 } override fun onBind(intent: Intent): IBinder { return MyBinder(); } inner class MyBinder(var refreshListener : ((Boolean) -> Unit)? = null): Binder() { private var isWorking = false private var disposable:Disposable? = null private var start = 0 private val count = 100 fun startFetchData() { if (this.isWorking) { return } this.refreshListener?.invoke(true) this.isWorking = true val date = Date() timer(name = MyService.JOB_NAME, daemon = true, startAt = date, period = MyService.JOB_PERIOD){ if([email protected]?.isDisposed == false) { [email protected]?.dispose() } [email protected] = APIService.getComingSoonObservable(start = [email protected], count = [email protected]) //.subscribeOn(Schedulers.io()) //Timer is not the main thread, so no need switch subscriber thread .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { [email protected]?.invoke(true) } .observeOn(AndroidSchedulers.mainThread()) .doOnComplete{ [email protected]?.invoke(false) } .subscribe { val movies = it.subjects if (movies.isNotEmpty()) { [email protected] += movies.size [email protected](movies) [email protected]() } } } } private fun updateCache(movies: List<Movie>) { GlobalCache.addMovies(movies) } private fun notifyUpdated() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(MyService.NOTIFICATION_CHANNEL_ID, MyService.NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT) [email protected](channel) } val notification = NotificationCompat.Builder(this@MyService, MyService.NOTIFICATION_CHANNEL_ID) .setContentTitle("Update") .setSmallIcon(R.drawable.ic_voice_chat_black_96dp) .setContentText("Movie list has updated successfully!") .setDefaults(NotificationCompat.FLAG_AUTO_CANCEL) .setAutoCancel(true) .build() [email protected](MyService.NOTIFICATION_ID, notification) } } }
0
Kotlin
30
94
43756ad5107521e8156b0e5afa9e83fd0c20092a
3,918
50-android-kotlin-projects-in-100-days
MIT License
DemoApp/app/src/main/java/app/demo/example/com/mytemplateapplication/app/BasePresenter.kt
bonafonteGuillermo
140,724,505
false
{"Kotlin": 22137}
package app.demo.example.com.mytemplateapplication.app import app.demo.example.com.mytemplateapplication.repository.IRepository /** * Created by <NAME> */ interface BasePresenter { var repository: IRepository fun onCreate() fun onDestroy() }
0
Kotlin
0
0
6bba0c1e9829beab1e2c90e421eb78ffa2d1ba3a
258
MVP-Dagger-RxBaseProject
Apache License 2.0
src/main/kotlin/org/teamvoided/reef/data/ReefTags.kt
TeamVoided
764,862,779
false
{"Kotlin": 42738, "Java": 5106}
package org.teamvoided.reef.data import net.minecraft.block.Block import net.minecraft.registry.RegistryKeys import net.minecraft.registry.tag.TagKey import net.minecraft.world.biome.Biome import org.teamvoided.reef.Reef.id object ReefTags { @JvmField val HAS_ERODED_PILLAR = biomeTag("has_eroded_pillar") @JvmField val HAS_VANILLA_ERODED_PILLAR = biomeTag("has_vanilla_eroded_pillar") @JvmField val HAS_ICEBERG = biomeTag("has_iceberg") private fun biomeTag(id: String): TagKey<Biome> = TagKey.of(RegistryKeys.BIOME, id(id)) fun create(id: String): TagKey<Block> = TagKey.of(RegistryKeys.BLOCK, id(id)) }
0
Kotlin
0
0
7c7d1612f00d67c62bcc22b35198b86818265457
644
Reef
MIT License
client/core/shared/src/commonTest/kotlin/com/oztechan/ccc/client/core/shared/util/DateUtilTest.kt
Oztechan
102,633,334
false
null
package com.oztechan.ccc.client.core.shared.util import com.oztechan.ccc.common.core.infrastructure.constants.DAY import com.oztechan.ccc.common.core.infrastructure.constants.SECOND import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.datetime.TimeZone import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue internal class DateUtilTest { @Test fun nowAsLongTest() = assertTrue { Clock.System.now().toEpochMilliseconds() <= nowAsLong() } @Test fun nowAsInstantTest() = assertTrue { Clock.System.now().toEpochMilliseconds() <= nowAsInstant().toEpochMilliseconds() } @Test fun nowAsDateStringTest() { val nowLong = nowAsLong() val nowInstant = nowAsInstant() assertEquals(nowInstant.toDateString(), nowAsDateString()) assertEquals(nowLong.toDateString(), nowAsDateString()) } @Test fun isItOver() { assertTrue { (nowAsLong() - DAY).isItOver() } assertTrue { (nowAsLong() - SECOND).isItOver() } assertFalse { (nowAsLong() + DAY).isItOver() } assertFalse { (nowAsLong() + SECOND).isItOver() } } @Test fun longToInstant() = assertEquals( 123.toLong().toInstant(), Instant.fromEpochMilliseconds(123) ) @Test fun toDateString() = assertEquals( "09:12 20.12.2020", 1608455548000.toDateString(TimeZone.UTC) ) @Test fun instantToDateString() = assertEquals( "09:12 20.12.2020", Instant.parse("2020-12-20T09:12:28Z").toDateString(TimeZone.UTC) ) @Test fun doubleDigits() { assertEquals("01", 1.toDoubleDigits()) assertEquals("05", 5.toDoubleDigits()) assertEquals("09", 9.toDoubleDigits()) assertEquals("10", 10.toDoubleDigits()) } }
28
Kotlin
27
248
ee238a8b43dcd30a4e28950b23a77656de093658
1,874
CCC
Apache License 2.0
2017/kotlin/day7-1/src/input.kt
sgravrock
47,810,570
false
null
fun parseInput(input: String): List<NodeSpec> { return input.split('\n') .filter { it.length > 0 } .map { parseLine(it) } } fun parseLine(line: String): NodeSpec { val tokens = line.replace(",", "") .split(' ') val childNames = if (tokens.size > 4) { tokens.subList(3, tokens.size) } else { emptyList() } return NodeSpec(tokens[0], childNames) } data class NodeSpec( val name: String, val childNames: List<String> )
0
Rust
0
0
d44655f1e2ade3cecbc6b16fbda8e3bf62e5156f
441
adventofcode
MIT License
src/main/kotlin/dev/sublab/hashing/hashers/Keccak.kt
sublabdev
566,122,886
false
{"Kotlin": 41517}
/** * * Copyright 2023 SUBSTRATE LABORATORY LLC <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package dev.sublab.hashing.hashers import com.appmattus.crypto.Algorithm import dev.sublab.hashing.Hashing import dev.sublab.hashing.InvalidHashOutputSizeException import dev.sublab.keccak.keccak private fun ByteArray.keccak(outputSize: Int) = when (outputSize) { 224 -> Algorithm.Keccak224.createDigest() 256 -> Algorithm.Keccak256.createDigest() 288 -> Algorithm.Keccak288.createDigest() 384 -> Algorithm.Keccak384.createDigest() 512 -> Algorithm.Keccak512.createDigest() else -> throw InvalidHashOutputSizeException(outputSize) } .apply { update(this@keccak) } .digest() /** * Hashing via Keccak using the provided output size * @param outputSize output size to use when hashing via Keccak */ private fun Hashing.keccak(outputSize: Int) = value.toByteArray().keccak(outputSize) /** * Hashing via [Algorithm.Keccak224] with output size of 224 */ fun Hashing.keccak224() = keccak(224) /** * Hashing via [Algorithm.Keccak256] with output size of 256 */ fun Hashing.keccak256() = keccak(256) /** * Hashing via [Algorithm.Keccak288] with output size of 288 */ fun Hashing.keccak288() = keccak(288) /** * Hashing via [Algorithm.Keccak384] with output size of 384 */ fun Hashing.keccak384() = keccak(384) /** * Hashing via [Algorithm.Keccak512] with output size of 512 */ fun Hashing.keccak512() = keccak(512) /** * Hashing via Keccak's F1600 */ fun Hashing.keccak1600() = value.toByteArray().keccak.f1600()
0
Kotlin
0
2
cb1a09abb11df072088ed379140894d9166e647c
2,122
hashing-kotlin
Apache License 2.0
app/src/main/java/com/zipdabang/zipdabang_android/module/my/data/remote/otherinfo/OtherInfoResult.kt
zipdabang
666,457,004
false
{"Kotlin": 1689597}
package com.zipdabang.zipdabang_android.module.my.data.remote.otherinfo import com.zipdabang.zipdabang_android.module.my.data.remote.otherinfo.MemberPreferCategoryDto data class OtherInfoResult( val caption: String, val checkFollowing: Boolean, val checkFollower : Boolean, val checkSelf: Boolean, val followerCount: Int, val followingCount: Int, val imageUrl: String, val memberId: Int, val memberPreferCategoryDto: MemberPreferCategoryDto, val nickname: String )
6
Kotlin
1
2
f25196bfdb02331aad716a2fb5765f813bb40673
506
android
The Unlicense
android/src/main/java/com/coursedesign/SizePackage.kt
CourseDesign
387,000,413
false
{"JSON with Comments": 1, "JSON": 8, "JavaScript": 4, "Text": 1, "Ignore List": 1, "Markdown": 1, "TSX": 4, "INI": 4, "Gradle": 4, "Shell": 2, "Batchfile": 2, "XML": 9, "Kotlin": 2, "Java Properties": 1, "Java": 3, "Swift": 1, "Ruby": 1, "C": 1, "OpenStep Property List": 2, "Objective-C": 3}
package com.coursedesign import android.view.View import com.facebook.react.ReactPackage import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ReactShadowNode import com.facebook.react.uimanager.ViewManager import java.util.* class SizePackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): MutableList<SizeModule> { return mutableListOf(SizeModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): MutableList<ViewManager<View, ReactShadowNode<*>>> { return Collections.emptyList() } }
2
TypeScript
0
0
370cb52de6f5ba1bd2f055783788ecb6375f6739
644
rn-system
MIT License
extension/engine-platform-8/src/main/kotlin/org/camunda/community/process_test_coverage/engine/platform8/ZeebeModelProvider.kt
camunda-community-hub
43,815,708
false
{"Kotlin": 167349, "Java": 80489, "JavaScript": 6580, "HTML": 2362, "CSS": 98}
package org.camunda.community.process_test_coverage.engine.platform8 import io.camunda.zeebe.model.bpmn.Bpmn.* import io.camunda.zeebe.model.bpmn.instance.FlowNode import io.camunda.zeebe.model.bpmn.instance.IntermediateThrowEvent import io.camunda.zeebe.model.bpmn.instance.LinkEventDefinition import io.camunda.zeebe.model.bpmn.instance.Process import io.camunda.zeebe.model.bpmn.instance.SequenceFlow import io.camunda.zeebe.process.test.assertions.BpmnAssert.getRecordStream import org.camunda.community.process_test_coverage.core.model.Model import org.camunda.bpm.model.xml.instance.ModelElementInstance import org.camunda.community.process_test_coverage.core.engine.ModelProvider import java.io.ByteArrayInputStream import java.util.stream.Collectors /** * Provider that is used to load processes from the engine. * The record stream from zeebe is used for this. */ class ZeebeModelProvider: ModelProvider { override fun getModel(key: String): Model { // find the process metatdata for the given process definition key val processMetadata = getRecordStream().deploymentRecords() .firstNotNullOfOrNull { it.value.processesMetadata.firstOrNull { p -> p.bpmnProcessId == key } } // find the deployed resource coresponding to the process metadata val resource = getRecordStream().deploymentRecords() .firstNotNullOfOrNull { it.value.resources.firstOrNull { res -> res.resourceName == processMetadata?.resourceName } } return resource?.let { val modelInstance = readModelFromStream(ByteArrayInputStream(resource.resource)) val definitionFlowNodes = getExecutableFlowNodes(modelInstance.getModelElementsByType(FlowNode::class.java), key) val definitionSequenceFlows = getExecutableSequenceNodes(modelInstance.getModelElementsByType(SequenceFlow::class.java), definitionFlowNodes) Model( key, definitionFlowNodes.size + definitionSequenceFlows.size, "${processMetadata!!.version}", convertToString(modelInstance) ) } ?: throw IllegalArgumentException() } private fun getExecutableFlowNodes(flowNodes: Collection<FlowNode>, processId: String): Set<FlowNode> { return flowNodes.stream() .filter { node: FlowNode? -> isExecutable(node, processId) } .collect(Collectors.toSet()) } private fun getExecutableSequenceNodes(sequenceFlows: Collection<SequenceFlow>, definitionFlowNodes: Set<FlowNode>): Set<SequenceFlow> { return sequenceFlows.stream() .filter { s: SequenceFlow -> definitionFlowNodes.contains(s.source) } .collect(Collectors.toSet()) } private fun isExecutable(node: ModelElementInstance?, processId: String): Boolean { if (node == null) { return false } return if (node is Process) { node.isExecutable && node.id == processId } else if (node is IntermediateThrowEvent) { node.eventDefinitions.none { it is LinkEventDefinition } } else { isExecutable(node.parentElement, processId) } } }
20
Kotlin
47
73
840e10eeccd1f075b0384ae0a90289086423883a
3,196
camunda-process-test-coverage
Apache License 2.0
app/src/main/java/com/gvkorea/gvktune/view/view/autotuning/listener/TuneButtonListener.kt
NewTurn2017
243,805,460
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 49, "XML": 71, "Java": 5, "Python": 33}
package com.gvkorea.gvktune.view.view.autotuning.listener import android.view.View import com.gvkorea.gvktune.R import com.gvkorea.gvktune.view.view.autotuning.presenter.TunePresenter class TuneButtonListener(val presenter: TunePresenter): View.OnClickListener { override fun onClick(v: View?) { when(v?.id){ R.id.btn_tune_start -> presenter.setTargetVolumeDialog() R.id.btn_tune_stop -> presenter.tuneStop() R.id.btn_showTable -> presenter.showTable() R.id.btn_showEQ -> presenter.showEQ() } } }
1
null
1
1
afaa1be61f6f1cc3fb6db213aaaa081483144ce5
570
GVKTUNE
MIT License
src/main/kotlin/com/roberthorrox/apiserver/ApiserverConfig.kt
RobertHorrox
191,661,976
false
null
package com.roberthorrox.apiserver import com.fasterxml.jackson.annotation.JsonProperty import io.dropwizard.Configuration class ApiserverConfig() : Configuration() { @JsonProperty("template") var template: String="" @JsonProperty("defaultName") var defaultName: String="Stranger" }
0
Kotlin
0
0
d7deb8e285d41150c1e85f2c9f457dfb874c7b32
301
KotlinDropReactive
Apache License 2.0
core/src/main/java/com/hrudhaykanth116/core/ui/components/AppImage.kt
hrudhaykanth116
300,963,083
false
{"Kotlin": 447216}
package com.hrudhaykanth116.core.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.BrushPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.hrudhaykanth116.core.R import com.hrudhaykanth116.core.ui.models.ImageParams @Composable fun AppImage( modifier: Modifier = Modifier, imageParams: ImageParams, ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(imageParams.image) .crossfade(true) .build(), contentDescription = stringResource(imageParams.contentDescriptionResId), modifier = modifier, placeholder = imageParams.placeHolder, contentScale = ContentScale.FillBounds, error = imageParams.provideErrorDrawable(), ) } @Composable fun RoundedImage( imageParams: ImageParams, modifier: Modifier = Modifier, spaceBetweenImageAndRound: Dp = 0.dp, ) { AppImage( imageParams = imageParams, modifier = modifier, // modifier = Modifier // .padding(spaceBetweenImageAndRound) // First padding will retain the size from incoming modifier. // .clip( // CircleShape // ) // .then( // modifier.border(2.dp, Color.Green, CircleShape) // // .padding(spaceBetweenImageAndRound) // Will squeeze the image inside i.e padding // ) ) } @Composable @Preview fun RoundImagePreview() { RoundedImage( imageParams = ImageParams( image = R.drawable.ic_filter, ), modifier = Modifier .size(100.dp) .background(color = Color.Green), spaceBetweenImageAndRound = 10.dp ) }
0
Kotlin
0
0
5672c21b3bc4d4c948fe96a5ab88f2d36c95deac
2,442
MAFET
MIT License
feature-nft-impl/src/main/java/jp/co/soramitsu/nft/impl/presentation/chooserecipient/ChooseNFTRecipientPresenter.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.nft.impl.presentation.chooserecipient import android.graphics.drawable.PictureDrawable import jp.co.soramitsu.account.api.domain.interfaces.AccountInteractor import jp.co.soramitsu.account.api.domain.model.address import jp.co.soramitsu.common.address.AddressIconGenerator import jp.co.soramitsu.common.address.createAddressModel import jp.co.soramitsu.common.base.errors.TitledException import jp.co.soramitsu.common.base.errors.ValidationException import jp.co.soramitsu.common.compose.component.AddressInputState import jp.co.soramitsu.common.compose.component.ButtonViewState import jp.co.soramitsu.common.compose.component.FeeInfoViewState import jp.co.soramitsu.common.resources.ClipboardManager import jp.co.soramitsu.common.resources.ResourceManager import jp.co.soramitsu.common.utils.applyFiatRate import jp.co.soramitsu.common.utils.formatCryptoDetail import jp.co.soramitsu.common.utils.formatFiat import jp.co.soramitsu.common.utils.requireValue import jp.co.soramitsu.common.utils.zipWithPrevious import jp.co.soramitsu.core.utils.utilityAsset import jp.co.soramitsu.feature_nft_impl.R import jp.co.soramitsu.nft.domain.NFTTransferInteractor import jp.co.soramitsu.nft.domain.models.NFT import jp.co.soramitsu.nft.impl.domain.usecase.transfer.ValidateNFTTransferUseCase import jp.co.soramitsu.nft.impl.navigation.InternalNFTRouter import jp.co.soramitsu.nft.impl.presentation.CoroutinesStore import jp.co.soramitsu.nft.impl.presentation.chooserecipient.contract.ChooseNFTRecipientCallback import jp.co.soramitsu.nft.impl.presentation.chooserecipient.contract.ChooseNFTRecipientScreenState import jp.co.soramitsu.nft.navigation.NFTNavGraphRoute import jp.co.soramitsu.runtime.multiNetwork.chain.ChainsRepository import jp.co.soramitsu.wallet.api.domain.fromValidationResult import jp.co.soramitsu.wallet.impl.domain.CurrentAccountAddressUseCase import jp.co.soramitsu.wallet.impl.domain.interfaces.WalletInteractor import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import java.math.BigDecimal import java.math.BigInteger import javax.inject.Inject class ChooseNFTRecipientPresenter @Inject constructor( private val addressIconGenerator: AddressIconGenerator, private val clipboardManager: ClipboardManager, private val chainsRepository: ChainsRepository, private val coroutinesStore: CoroutinesStore, private val accountInteractor: AccountInteractor, private val walletInteractor: WalletInteractor, private val resourceManager: ResourceManager, private val nftTransferInteractor: NFTTransferInteractor, private val validateNFTTransferUseCase: ValidateNFTTransferUseCase, private val currentAccountAddressUseCase: CurrentAccountAddressUseCase, private val internalNFTRouter: InternalNFTRouter ) : ChooseNFTRecipientCallback { private val tokenFlow = internalNFTRouter.createNavGraphRoutesFlow() .filterIsInstance<NFTNavGraphRoute.ChooseNFTRecipientScreen>() .map { destinationArgs -> destinationArgs.token } .shareIn(coroutinesStore.uiScope, SharingStarted.Eagerly, 1) private val addressInputFlow = MutableStateFlow("") private val selectedWalletIdFlow = MutableStateFlow<Long?>(null) private val isLoadingFlow = MutableStateFlow(false) private val currentToken: NFT? get() = tokenFlow.replayCache.lastOrNull() fun handleQRCodeResult(qrCodeContent: String) { val result = walletInteractor.tryReadAddressFromSoraFormat(qrCodeContent) ?: qrCodeContent selectedWalletIdFlow.value = null addressInputFlow.value = result } @OptIn(ExperimentalCoroutinesApi::class) fun createScreenStateFlow(coroutineScope: CoroutineScope): StateFlow<ChooseNFTRecipientScreenState> { return tokenFlow.zipWithPrevious().flatMapLatest { (prevToken, currentToken) -> privateCreateScreenStateFlow(prevToken, currentToken).catch { internalNFTRouter.openErrorsScreen( title = resourceManager.getString(R.string.common_error_general_title), message = resourceManager.getString(R.string.common_error_network) ) } }.stateIn(coroutineScope, SharingStarted.Lazily, ChooseNFTRecipientScreenState.default) } @OptIn(FlowPreview::class) @Suppress("ChainWrapping") private fun privateCreateScreenStateFlow(prevToken: NFT?, currentToken: NFT): Flow<ChooseNFTRecipientScreenState> { return flow { val addressInputHelperFlow = addressInputFlow.debounce(DEFAULT_DEBOUNCE_TIMEOUT).map { it.trim() } val isLoadingHelperFlow = isLoadingFlow.map { if (prevToken == null || prevToken.tokenId == currentToken.tokenId) { it } else { false } } combine( addressInputHelperFlow, createAddressIconFlow(currentToken, addressInputHelperFlow, AddressIconGenerator.SIZE_MEDIUM), createSelectedAccountIconFlow(currentToken, AddressIconGenerator.SIZE_SMALL), createFeeInfoViewState(currentToken, addressInputHelperFlow), isLoadingHelperFlow ) { addressInput, addressIcon, selectedWalletIcon, feeInfoViewState, isLoading -> val isPreviewButtonEnabled = addressInput.isNotBlank() && currentToken.isUserOwnedToken && feeInfoViewState.feeAmount != null && !isLoading return@combine ChooseNFTRecipientScreenState( selectedWalletIcon = selectedWalletIcon, addressInputState = AddressInputState( title = resourceManager.getString(R.string.send_to), input = addressInput, image = addressIcon, editable = false, showClear = false ), buttonState = ButtonViewState( text = resourceManager.getString(R.string.common_preview), enabled = isPreviewButtonEnabled ), feeInfoState = feeInfoViewState, isLoading = isLoading ) }.collect(this) } } private suspend fun createAddressIconFlow( token: NFT, receiverAddressFlow: Flow<String>, sizeInDp: Int ): Flow<Any> { val chain = chainsRepository.getChain(token.chainId) return receiverAddressFlow.map { receiverAddress -> if (!walletInteractor.validateSendAddress(chain.id, receiverAddress)) { return@map R.drawable.ic_address_placeholder } return@map addressIconGenerator.createAddressModel( isEthereumBased = chain.isEthereumBased, accountAddress = receiverAddress, sizeInDp = sizeInDp ).image } } private suspend fun createSelectedAccountIconFlow(token: NFT, sizeInDp: Int): Flow<PictureDrawable> { val chain = chainsRepository.getChain(token.chainId) return walletInteractor.selectedAccountFlow(chain.id).map { walletAccount -> addressIconGenerator.createAddressModel( isEthereumBased = chain.isEthereumBased, accountAddress = walletAccount.address, sizeInDp = sizeInDp ).image } } @OptIn(ExperimentalCoroutinesApi::class) private suspend fun createFeeInfoViewState(token: NFT, addressInputFlow: Flow<String>): Flow<FeeInfoViewState> { val (chainId, utilityAssetId) = chainsRepository.getChain(token.chainId) .run { id to requireNotNull(utilityAsset?.id) } val networkFeeHelperFlow = addressInputFlow.map { receiver -> val isReceiverAddressValid = walletInteractor.validateSendAddress( chainId = token.chainId, address = receiver ) return@map if (isReceiverAddressValid) { token to receiver } else { token to (currentAccountAddressUseCase(token.chainId) ?: "") } }.flatMapLatest { (token, receiver) -> nftTransferInteractor.networkFeeFlow( token = token, receiver = receiver, canReceiverAcceptToken = false ) } return combine( networkFeeHelperFlow, walletInteractor.assetFlow(chainId, utilityAssetId) ) { networkFeeResult, utilityAsset -> val tokenSymbol = utilityAsset.token.configuration.symbol val tokenFiatRate = utilityAsset.token.fiatRate val tokenFiatSymbol = utilityAsset.token.fiatSymbol val networkFee = networkFeeResult.getOrNull() ?: return@combine FeeInfoViewState.default return@combine FeeInfoViewState( feeAmount = networkFee.formatCryptoDetail(tokenSymbol), feeAmountFiat = networkFee.applyFiatRate(tokenFiatRate)?.formatFiat(tokenFiatSymbol), ) } } override fun onAddressInput(input: String) { selectedWalletIdFlow.value = null addressInputFlow.value = input } override fun onAddressInputClear() { selectedWalletIdFlow.value = null addressInputFlow.value = "" } override fun onNextClick() { val token = currentToken ?: return val receiver = addressInputFlow.value.trim() isLoadingFlow.value = true coroutinesStore.uiScope.launch { val chain = chainsRepository.getChain(token.chainId) val utilityAssetId = chain.utilityAsset?.id ?: return@launch val utilityAsset = walletInteractor.getCurrentAsset(chain.id, utilityAssetId) val selectedAccountAddress = accountInteractor.selectedMetaAccount().address(chain) ?: return@launch val tokenBalance = nftTransferInteractor.balance(token).getOrElse { BigInteger.ZERO } val fee = nftTransferInteractor.networkFeeFlow( token, receiver, false ).first().getOrElse { BigDecimal.ZERO } val validationProcessResult = validateNFTTransferUseCase( chain = chain, recipient = receiver, ownAddress = selectedAccountAddress, utilityAsset = utilityAsset, fee = fee.toBigInteger(), skipEdValidation = false, balance = tokenBalance, confirmedValidations = emptyList(), ) // error occurred inside validation validationProcessResult.exceptionOrNull()?.let { showError(it) return@launch } val validationResult = validationProcessResult.requireValue() ValidationException.fromValidationResult(validationResult, resourceManager)?.let { showError(it) return@launch } // all checks have passed - go to next step val isReceiverAddressValid = walletInteractor.validateSendAddress( chainId = token.chainId, address = receiver ) if (!isReceiverAddressValid || !token.isUserOwnedToken) { return@launch } internalNFTRouter.openNFTSendScreen(token, addressInputFlow.value.trim()) }.invokeOnCompletion { isLoadingFlow.value = false } } private fun showError(throwable: Throwable) { when (throwable) { is ValidationException -> { val (title, text) = throwable internalNFTRouter.openErrorsScreen(title, text) } is TitledException -> { internalNFTRouter.openErrorsScreen(throwable.title, throwable.message.orEmpty()) } else -> { throwable.message?.let { internalNFTRouter.openErrorsScreen(message = it) } } } } override fun onQrClick() { internalNFTRouter.openQRCodeScanner() } override fun onContactsClick() { val chainId = currentToken?.chainId ?: return internalNFTRouter.openContacts(chainId).onEach { selectedWalletIdFlow.value = null addressInputFlow.value = it }.launchIn(coroutinesStore.uiScope) } override fun onWalletsClick() { val chainId = currentToken?.chainId ?: return internalNFTRouter.openWalletSelectionScreen(selectedWalletIdFlow.value).onEach { metaAccountId -> coroutinesStore.uiScope.launch(Dispatchers.IO) { selectedWalletIdFlow.value = metaAccountId val metaAccount = accountInteractor.getMetaAccount(metaAccountId) val chain = chainsRepository.getChain(chainId) val address = metaAccount.address(chain) ?: return@launch addressInputFlow.value = address } }.launchIn(coroutinesStore.uiScope) } override fun onPasteClick() { clipboardManager.getFromClipboard()?.let { buffer -> selectedWalletIdFlow.value = null addressInputFlow.value = buffer } } private companion object { const val DEFAULT_DEBOUNCE_TIMEOUT = 300L } }
15
null
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
14,559
fearless-Android
Apache License 2.0
compiler/testData/diagnostics/tests/enum/EnumWOParenthesesConsistencyTopLevel.kt
JetBrains
3,432,266
false
null
class Context { enum class EnumerationAAA() { ENTRY } enum class EnumerationAAB() { ENTRY; } enum class EnumerationAAC() { ENTRY1, ENTRY2; } enum class EnumerationAAD() { ENTRY1, ENTRY2(); } enum class EnumerationAAE() { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } enum class EnumerationABA(arg: UserKlass = UserKlass()) { ENTRY } enum class EnumerationABB(arg: UserKlass = UserKlass()) { ENTRY; } enum class EnumerationABC(arg: UserKlass = UserKlass()) { ENTRY1, ENTRY2; } enum class EnumerationABD(arg: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); } enum class EnumerationABE(arg: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } enum class EnumerationACA(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY } enum class EnumerationACB(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY; } enum class EnumerationACC(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2; } enum class EnumerationACD(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); } enum class EnumerationACE(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } enum class EnumerationADA(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) } enum class EnumerationADB(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) } enum class EnumerationADC(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) } enum class EnumerationADD(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) abstract fun abstractFunc() } enum class EnumerationAEA(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) } enum class EnumerationAEB(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) } enum class EnumerationAEC(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) } enum class EnumerationAED(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) abstract fun abstractFunc() } enum class EnumerationBAA constructor() { ENTRY } enum class EnumerationBAB constructor() { ENTRY; } enum class EnumerationBAC constructor() { ENTRY1, ENTRY2; } enum class EnumerationBAD constructor() { ENTRY1, ENTRY2(); } enum class EnumerationBAE constructor() { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } enum class EnumerationBBA constructor(arg: UserKlass = UserKlass()) { ENTRY } enum class EnumerationBBB constructor(arg: UserKlass = UserKlass()) { ENTRY; } enum class EnumerationBBC constructor(arg: UserKlass = UserKlass()) { ENTRY1, ENTRY2; } enum class EnumerationBBD constructor(arg: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); } enum class EnumerationBBE constructor(arg: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } enum class EnumerationBCA constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY } enum class EnumerationBCB constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY; } enum class EnumerationBCC constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2; } enum class EnumerationBCD constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); } enum class EnumerationBCE constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } enum class EnumerationBDA constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) } enum class EnumerationBDB constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) } enum class EnumerationBDC constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) } enum class EnumerationBDD constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) abstract fun abstractFunc() } enum class EnumerationBEA constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) } enum class EnumerationBEB constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) } enum class EnumerationBEC constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1, ENTRY2(); constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) } enum class EnumerationBED constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg: UserKlass = UserKlass()) : this(arg, UserKlass()) constructor() : this(UserKlass(), UserKlass()) abstract fun abstractFunc() } enum class EnumerationCAA { ENTRY; constructor() } enum class EnumerationCAB { ENTRY1, ENTRY2; constructor() } enum class EnumerationCAC { ENTRY1, ENTRY2(); constructor() } enum class EnumerationCAD { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor() abstract fun abstractFunc() } enum class EnumerationCBA { ENTRY; constructor(arg: UserKlass = UserKlass()) } enum class EnumerationCBB { ENTRY1, ENTRY2; constructor(arg: UserKlass = UserKlass()) } enum class EnumerationCBC { ENTRY1, ENTRY2(); constructor(arg: UserKlass = UserKlass()) } enum class EnumerationCBD { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg: UserKlass = UserKlass()) abstract fun abstractFunc() } enum class EnumerationCCA { ENTRY; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) } enum class EnumerationCCB { ENTRY1, ENTRY2; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) } enum class EnumerationCCC { ENTRY1, ENTRY2(); constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) } enum class EnumerationCCD { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) abstract fun abstractFunc() } enum class EnumerationCDA { ENTRY; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) } enum class EnumerationCDB { ENTRY1, ENTRY2; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) } enum class EnumerationCDC { ENTRY1, ENTRY2(); constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) } enum class EnumerationCDD { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) abstract fun abstractFunc() } enum class EnumerationCEA { ENTRY; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) constructor() } enum class EnumerationCEB { ENTRY1, ENTRY2; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) constructor() } enum class EnumerationCEC { ENTRY1, ENTRY2(); constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) constructor() } enum class EnumerationCED { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; constructor(arg1: UserKlass = UserKlass(), arg2: UserKlass = UserKlass()) constructor(arg: UserKlass = UserKlass()) constructor() abstract fun abstractFunc() } enum class EnumerationDA { ENTRY } enum class EnumerationDB { ENTRY; } enum class EnumerationDC { ENTRY1, ENTRY2; } enum class EnumerationDD { ENTRY1, ENTRY2(); } enum class EnumerationDE { ENTRY1 { override fun abstractFunc() { TODO("Not yet implemented") } }, ENTRY2() { override fun abstractFunc() { TODO("Not yet implemented") } }; abstract fun abstractFunc() } } class UserKlass
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
14,559
kotlin
Apache License 2.0
statistics/src/main/java/com/duckduckgo/app/statistics/api/RefreshRetentionAtbPlugin.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2021 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.app.statistics.api import com.duckduckgo.app.global.plugins.PluginPoint import com.duckduckgo.di.scopes.AppObjectGraph import com.squareup.anvil.annotations.ContributesTo import dagger.Module import dagger.multibindings.Multibinds interface RefreshRetentionAtbPlugin { /** * Will be called right after we have refreshed the ATB retention on search */ fun onSearchRetentionAtbRefreshed() /** * Will be called right after we have refreshed the ATB retention on search */ fun onAppRetentionAtbRefreshed() } class RefreshRetentionAtbPluginPoint( private val plugins: Set<@JvmSuppressWildcards RefreshRetentionAtbPlugin> ) : PluginPoint<RefreshRetentionAtbPlugin> { override fun getPlugins(): Collection<RefreshRetentionAtbPlugin> { return plugins.sortedBy { it.javaClass.simpleName } } } @Module @ContributesTo(AppObjectGraph::class) abstract class RefreshRetentionAtbPluginModule { @Multibinds abstract fun bindRefreshRetentionAtbPlugins(): Set<@JvmSuppressWildcards RefreshRetentionAtbPlugin> }
41
null
671
2,413
7e23d4cc5aa890bd727d977f8ac438239915509d
1,683
Android
Apache License 2.0
project-system-gradle/testSrc/com/android/tools/idea/gradle/navigation/runsGradleVersionCatalogAndDeclarative/VersionCatalogGoToDeclarationHandlerTest.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.navigation.runsGradleVersionCatalogAndDeclarative import com.android.tools.idea.gradle.navigation.VersionCatalogGoToDeclarationHandler import com.android.tools.idea.testing.AndroidGradleProjectRule import com.android.tools.idea.testing.TestProjectPaths import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import com.intellij.openapi.application.runReadAction import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.psi.PsiManager import com.intellij.testFramework.ExtensionTestUtil import com.intellij.workspaceModel.core.fileIndex.impl.WorkspaceFileIndexImpl import org.jetbrains.kotlin.idea.core.script.dependencies.KotlinScriptWorkspaceFileIndexContributor import org.junit.Rule import org.junit.Test /** Tests for [VersionCatalogGoToDeclarationHandler]. */ class VersionCatalogGoToDeclarationHandlerTest { @get:Rule val projectRule = AndroidGradleProjectRule() private val project get() = projectRule.project @Test fun testGoToDeclarationInToml() { val disposable = projectRule.fixture.testRootDisposable val ep = WorkspaceFileIndexImpl.EP_NAME val filteredExtensions = ep.extensionList.filter { it !is KotlinScriptWorkspaceFileIndexContributor } ExtensionTestUtil.maskExtensions(ep, filteredExtensions, disposable) projectRule.loadProject(TestProjectPaths.SIMPLE_APPLICATION_VERSION_CATALOG_KTS) // Check Go To Declaration within the TOML file // Navigate from version.ref string to corresponding version variable checkUsage( "gradle/libs.versions.toml", "version.ref = \"gua|va\"", "guava = \"19.0\"" ) // Same, but for a variable with dashes checkUsage( "gradle/libs.versions.toml", "version.ref = \"cons|traint-layout\"", "constraint-layout = \"1.0.2\"" ) // Navigate from library name in a bundle array to corresponding library checkUsage( "gradle/libs.versions.toml", "both = [\"constraint-layout\", \"|guava\"]", "guava = { module = \"com.google.guava:guava\", version.ref = \"guava\" }" ) // Same, but for a library variable with dashes checkUsage( "gradle/libs.versions.toml", "both = [\"const|raint-layout\", \"guava\"]", "constraint-layout = { module = \"com.android.support.constraint:constraint-layout\", version.ref = \"constraint-layout\" }" ) // Same, but for a library variable with dashes checkUsage( "gradle/libs.versions.toml", "both = [\"const|raint-layout\", \"guava\"]", "constraint-layout = { module = \"com.android.support.constraint:constraint-layout\", version.ref = \"constraint-layout\" }" ) } @Test fun testGotoCatalogDeclarationInKts() { val disposable = projectRule.fixture.testRootDisposable val ep = WorkspaceFileIndexImpl.EP_NAME val filteredExtensions = ep.extensionList.filter { it !is KotlinScriptWorkspaceFileIndexContributor } ExtensionTestUtil.maskExtensions(ep, filteredExtensions, disposable) projectRule.loadProject(TestProjectPaths.SIMPLE_APPLICATION_VERSION_CATALOG_KTS) // Navigate from KTS catalog reference to TOML library checkUsage( "app/build.gradle.kts", "api(libs.|guava)", "guava = { module = \"com.google.guava:guava\", version.ref = \"guava\" }" ) // Navigate from KTS catalog reference to TOML library, with a dotted name (mapped to dashed name in TOML) checkUsage( "app/build.gradle.kts", "libs.constraint.la|yout", "constraint-layout = { module = \"com.android.support.constraint:constraint-layout\", version.ref = \"constraint-layout\" }" ) // Same, but clicking on an earlier part in the reference; there isn't an exact TOML library for the group, so we // need to pick the first one checkUsage( "app/build.gradle.kts", "libs.cons|traint.layout", "constraint-layout = { module = \"com.android.support.constraint:constraint-layout\", version.ref = \"constraint-layout\" }" ) // Navigate to the appropriate plugin in TOML checkUsage( "app/build.gradle.kts", "alias(libs.plu|gins.kotlinAndroid)", "kotlinAndroid = { id = \"org.jetbrains.kotlin.android\", version.ref = \"kotlinVersion\" }" ) // Navigate from a KTS plugin reference to the plugin in the TOML file checkUsage( "app/build.gradle.kts", "alias(libs.plugins.android.appli|cation)", "android-application = { id = \"com.android.application\", version.ref = \"agpVersion\" }" ) // Navigate to the appropriate bundle in TOML checkUsage( "app/build.gradle.kts", "api(libs.b|undles.both)", "both = [\"constraint-layout\", \"guava\"]" ) // Navigate to the appropriate bundle in TOML checkUsage( "app/build.gradle.kts", "api(libs.bundles.|both)", "both = [\"constraint-layout\", \"guava\"]" ) // Navigate from a KTS to second catalog checkUsage( "app/build.gradle.kts", "testImplementation(libsTest.j|unit)", "junit = { module = \"junit:junit\", version.ref = \"junit\" }" ) // Navigate special case when first letter after delimiter is capital case checkUsage( "app/build.gradle.kts", "api(libs.guava.co|mmon)", "guava-Common = { module = \"com.google.guava:guava\", version.ref = \"guava\" }" ) } @Test fun testGotoCatalogDeclarationInGroovy() { projectRule.loadProject(TestProjectPaths.SIMPLE_APPLICATION_MULTI_VERSION_CATALOG) // Navigate from groovy catalog reference to TOML library checkUsage( "app/build.gradle", "api libs.|guava", "guava = { module = \"com.google.guava:guava\", version.ref = \"guava\" }" ) // Navigate from groovy catalog reference to TOML library, with a dotted name (mapped to dashed name in TOML) checkUsage( "app/build.gradle", "libs.constraint.la|yout", "constraint-layout = { module = \"com.android.support.constraint:constraint-layout\", version.ref = \"constraint-layout\" }" ) // Same, but clicking on an earlier part in the reference; there isn't an exact TOML library for the group, so we // need to pick the first one checkUsage( "app/build.gradle", "libs.cons|traint.layout", "constraint-layout = { module = \"com.android.support.constraint:constraint-layout\", version.ref = \"constraint-layout\" }" ) // Navigate to the appropriate plugin in TOML checkUsage( "app/build.gradle", "alias libs.plug|ins.android.application", "android-application = { id = \"com.android.application\", version.ref = \"gradlePlugins-agp\" }" ) // Navigate from a ksp plugin reference to the plugin in the TOML file checkUsage( "app/build.gradle", "alias libs.plugins.andr|oid.application", "android-application = { id = \"com.android.application\", version.ref = \"gradlePlugins-agp\" }" ) // Navigate to the appropriate bundle in TOML checkUsage( "app/build.gradle", "api libs.b|undles.both", "both = [\"constraint-layout\", \"guava\"]" ) // Navigate to the appropriate bundle in TOML checkUsage( "app/build.gradle", "api libs.bundles.|both", "both = [\"constraint-layout\", \"guava\"]" ) // Navigate from a groovy build file to another catalog checkUsage( "app/build.gradle", "testImplementation libsTest.j|unit", "junit = { module = \"junit:junit\", version.ref = \"junit\" }" ) checkUsage( "app/build.gradle", "testImplementation libsTest.bund|les.junit", "junit = [\"junit\"]" ) // Navigate special case when first letter after delimiter is capital case checkUsage( "app/build.gradle", "api libs.guava.co|mmon", "guava-Common = { module = \"com.google.guava:guava\", version.ref = \"guava\" }" ) } private fun checkUsage(relativePath: String, caretContext: String, expected: String) { val root = StandardFileSystems.local().findFileByPath(project.basePath!!)!! val source = root.findFileByRelativePath(relativePath)!! runReadAction { val psiFile = PsiManager.getInstance(project).findFile(source)!! // Figure out the caret offset in the file given a substring from the source with "|" somewhere in that // substring indicating the exact spot of the caret val text = runReadAction { psiFile.text } val caretDelta = caretContext.indexOf('|') assertWithMessage("The caretContext must include | somewhere to point to the caret position").that(caretDelta).isNotEqualTo(-1) val withoutCaret = caretContext.substring(0, caretDelta) + caretContext.substring(caretDelta + 1) val index = text.indexOf(withoutCaret) assertWithMessage("Did not find `$withoutCaret` in $relativePath").that(index).isNotEqualTo(-1) val caret = index + caretDelta val handler = VersionCatalogGoToDeclarationHandler() val element = psiFile.findElementAt(caret) val target = handler.getGotoDeclarationTarget(element, null) assertWithMessage("Didn't find a go to destination from $caretContext").that(target).isNotNull() assertThat(target?.text?.substringBefore("\n")).isEqualTo(expected) } } }
5
Kotlin
230
948
10110983c7e784122d94c7467e9d243aba943bf4
9,962
android
Apache License 2.0
app/src/main/java/mustafaozhan/github/com/mycurrencies/ui/main/fragment/calculator/CalculatorFragment.kt
hirenpatel868
242,063,783
true
{"Kotlin": 110645}
package mustafaozhan.github.com.mycurrencies.ui.main.fragment.calculator import android.annotation.SuppressLint import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.jakewharton.rxbinding2.widget.textChanges import io.reactivex.rxkotlin.addTo import kotlinx.android.synthetic.main.item_currency.view.txt_amount import mustafaozhan.github.com.mycurrencies.R import mustafaozhan.github.com.mycurrencies.base.fragment.BaseViewBindingFragment import mustafaozhan.github.com.mycurrencies.databinding.FragmentCalculatorBinding import mustafaozhan.github.com.mycurrencies.extensions.addText import mustafaozhan.github.com.mycurrencies.extensions.checkAd import mustafaozhan.github.com.mycurrencies.extensions.dropDecimal import mustafaozhan.github.com.mycurrencies.extensions.reObserve import mustafaozhan.github.com.mycurrencies.extensions.replaceNonStandardDigits import mustafaozhan.github.com.mycurrencies.extensions.setBackgroundByName import mustafaozhan.github.com.mycurrencies.extensions.tryToSelect import mustafaozhan.github.com.mycurrencies.function.whether import mustafaozhan.github.com.mycurrencies.function.whetherNot import mustafaozhan.github.com.mycurrencies.model.Rates import mustafaozhan.github.com.mycurrencies.room.AppDatabase import mustafaozhan.github.com.mycurrencies.ui.main.fragment.settings.SettingsFragment import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread /** * Created by Mustafa Ozhan on 2018-07-12. */ @Suppress("TooManyFunctions") class CalculatorFragment : BaseViewBindingFragment<CalculatorViewModel, FragmentCalculatorBinding>() { companion object { fun newInstance(): CalculatorFragment = CalculatorFragment() } override fun getLayoutResId(): Int = R.layout.fragment_calculator override fun bind() { binding = FragmentCalculatorBinding.inflate(layoutInflater) } private val calculatorFragmentAdapter: CalculatorFragmentAdapter by lazy { CalculatorFragmentAdapter() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setSupportActionBar(binding.toolbarFragmentMain) initViews() setListeners() setKeyboard() initViewState() setRx() initLiveData() } override fun onResume() { super.onResume() initData() binding.adView.checkAd(R.string.banner_ad_unit_id_main, viewModel.isRewardExpired) } private fun setRx() { binding.txtInput.textChanges() .map { it.toString() } .subscribe({ input -> viewModel.calculateOutput(input) }, { throwable -> logException(throwable) }) .addTo(compositeDisposable) } private fun initViewState() = viewModel.calculatorViewStateLiveData .reObserve(this, Observer { calculatorViewState -> when (calculatorViewState) { CalculatorViewState.Loading -> binding.loadingView.smoothToShow() is CalculatorViewState.Success -> onSearchSuccess(calculatorViewState.rates) is CalculatorViewState.OfflineSuccess -> { onSearchSuccess(calculatorViewState.rates) calculatorViewState.rates.date?.let { toasty(getString(R.string.database_success_with_date, it)) } ?: run { toasty(getString(R.string.database_success)) } } CalculatorViewState.Error -> { viewModel.currencyListLiveData .value ?.size ?.whether { it > 1 } ?.let { snacky(getString(R.string.rate_not_available_offline), getString(R.string.change)) { binding.layoutBar.spinnerBase.expand() } } calculatorFragmentAdapter.refreshList(mutableListOf(), viewModel.mainData.currentBase) binding.loadingView.smoothToHide() } is CalculatorViewState.MaximumInput -> { toasty(getString(R.string.max_input)) binding.txtInput.text = calculatorViewState.input.dropLast(1) binding.loadingView.smoothToHide() } CalculatorViewState.FewCurrency -> { snacky(getString(R.string.choose_at_least_two_currency), getString(R.string.select)) { replaceFragment(SettingsFragment.newInstance(), true) } calculatorFragmentAdapter.refreshList(mutableListOf(), viewModel.mainData.currentBase) binding.loadingView.smoothToHide() } } }) @SuppressLint("SetTextI18n") private fun initLiveData() { viewModel.currencyListLiveData.reObserve(this, Observer { currencyList -> currencyList?.let { updateBar(currencyList.map { it.name }) calculatorFragmentAdapter.refreshList(currencyList, viewModel.mainData.currentBase) binding.loadingView.smoothToHide() } }) viewModel.outputLiveData.reObserve(this, Observer { output -> with(binding.layoutBar) { txtSymbol.text = viewModel.getCurrencyByName( viewModel.mainData.currentBase.toString() )?.symbol output.toString() .whetherNot { isEmpty() } ?.apply { txtOutput.text = "= ${replaceNonStandardDigits()} " } ?: run { txtOutput.text = "" txtSymbol.text = "" } } }) } private fun onSearchSuccess(rates: Rates) { viewModel.currencyListLiveData.value?.let { currencyList -> currencyList.forEach { it.rate = viewModel.calculateResultByCurrency(it.name, rates) } calculatorFragmentAdapter.refreshList(currencyList, viewModel.mainData.currentBase) } binding.loadingView.smoothToHide() } private fun initViews() = with(binding) { loadingView.bringToFront() context?.let { ctx -> recyclerViewMain.layoutManager = LinearLayoutManager(ctx) recyclerViewMain.adapter = calculatorFragmentAdapter } calculatorFragmentAdapter.onItemClickListener = { currency, itemView: View, _: Int -> txtInput.text = itemView.txt_amount.text.toString().dropDecimal() viewModel.updateCurrentBase(currency.name) viewModel.calculateOutput(itemView.txt_amount.text.toString().dropDecimal()) viewModel.currencyListLiveData .value ?.whether { indexOf(currency) < layoutBar.spinnerBase.getItems<String>().size } ?.apply { layoutBar.spinnerBase.tryToSelect(indexOf(currency)) } ?: run { layoutBar.spinnerBase.expand() } layoutBar.ivBase.setBackgroundByName(currency.name) } calculatorFragmentAdapter.onItemLongClickListener = { currency, _ -> snacky( "${viewModel.getClickedItemRate(currency.name)} ${currency.getVariablesOneLine()}", setIcon = currency.name, isLong = false) true } } private fun updateBar(spinnerList: List<String>) = with(binding.layoutBar) { if (spinnerList.size < 2) { snacky( context?.getString(R.string.choose_at_least_two_currency), context?.getString(R.string.select)) { replaceFragment(SettingsFragment.newInstance(), true) } spinnerBase.setItems("") ivBase.setBackgroundByName("transparent") } else { spinnerBase.setItems(spinnerList) spinnerBase.tryToSelect(spinnerList.indexOf(viewModel.verifyCurrentBase(spinnerList).toString())) ivBase.setBackgroundByName(spinnerBase.text.toString()) } } private fun setListeners() = with(binding.layoutBar) { spinnerBase.setOnItemSelectedListener { _, _, _, item -> viewModel.updateCurrentBase(item.toString()) viewModel.calculateOutput(binding.txtInput.text.toString()) ivBase.setBackgroundByName(item.toString()) } layoutBar.setOnClickListener { with(spinnerBase) { whether { isActivated } ?.apply { collapse() } ?: run { expand() } } } } private fun setKeyboard() = with(binding) { layoutKeyboard.btnSeven.setOnClickListener { txtInput.addText("7") } layoutKeyboard.btnEight.setOnClickListener { txtInput.addText("8") } layoutKeyboard.btnNine.setOnClickListener { txtInput.addText("9") } layoutKeyboard.btnDivide.setOnClickListener { txtInput.addText("/") } layoutKeyboard.btnFour.setOnClickListener { txtInput.addText("4") } layoutKeyboard.btnFive.setOnClickListener { txtInput.addText("5") } layoutKeyboard.btnSix.setOnClickListener { txtInput.addText("6") } layoutKeyboard.btnMultiply.setOnClickListener { txtInput.addText("*") } layoutKeyboard.btnOne.setOnClickListener { txtInput.addText("1") } layoutKeyboard.btnTwo.setOnClickListener { txtInput.addText("2") } layoutKeyboard.btnThree.setOnClickListener { txtInput.addText("3") } layoutKeyboard.btnMinus.setOnClickListener { txtInput.addText("-") } layoutKeyboard.btnDot.setOnClickListener { txtInput.addText(".") } layoutKeyboard.btnZero.setOnClickListener { txtInput.addText("0") } layoutKeyboard.btnPercent.setOnClickListener { txtInput.addText("%") } layoutKeyboard.btnPlus.setOnClickListener { txtInput.addText("+") } layoutKeyboard.btnTripleZero.setOnClickListener { txtInput.addText("000") } layoutKeyboard.btnZero.setOnClickListener { txtInput.addText("0") } layoutKeyboard.btnAc.setOnClickListener { binding.txtInput.text = "" binding.layoutBar.txtOutput.text = "" binding.layoutBar.txtSymbol.text = "" } layoutKeyboard.btnDelete.setOnClickListener { binding.txtInput .text .toString() .whetherNot { isEmpty() } ?.apply { binding.txtInput.text = substring(0, length - 1) } } } private fun initData() = viewModel.apply { refreshData() if (loadResetData() && !mainData.firstRun) { doAsync { AppDatabase.database.clearAllTables() resetFirstRun() uiThread { persistResetData(false) refreshData() getCurrencies() } } } else { getCurrencies() } } }
0
null
0
0
dbaf69dbbc30050f3b63e41aa4b487bff7802a86
11,260
androidCCC
Apache License 2.0
app/src/main/java/com/xiaoxin/toolkit/repository/HitokotoRepository.kt
XiaoXin956
474,917,723
false
null
package com.xiaoxin.toolkit.repository import com.google.gson.reflect.TypeToken import com.xiaoxin.basic.utils.GsonUtils import com.xiaoxin.toolkit.bean.Hitokoto class HitokotoRepository : BaseRepository() { suspend fun getHitokoto( url: String, queryMap: Map<String, Any> ): Hitokoto? { var hitokoto: Hitokoto? = null retrofitManager .getMethod .setUrl(url) .setQueryMap(queryMap) .requestT( success = { hitokoto = GsonUtils.toObject(it.toString(), object : TypeToken<Hitokoto>() {}.type) }, error = { hitokoto = Hitokoto() hitokoto?.run { id=-1 this.hitokoto = "未知" } } ) return hitokoto } }
0
Kotlin
0
4
bdbf05f52535978e947e3c1f0803e0f9dc4377d2
903
Toolkit
Apache License 2.0
walletlibrary/src/main/java/com/microsoft/walletlibrary/mappings/issuance/ClaimAttestationMapping.kt
microsoft
567,422,889
false
null
/**--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ package com.microsoft.walletlibrary.mappings.issuance import com.microsoft.did.sdk.credential.service.models.attestations.ClaimAttestation import com.microsoft.walletlibrary.requests.requirements.ClaimRequirement import com.microsoft.walletlibrary.requests.requirements.RequestedClaim /** * Maps ClaimAttestation object from VC SDK to RequestedClaim in library */ internal fun ClaimAttestation.toRequestedClaim(): RequestedClaim { return RequestedClaim(false, this.claim, this.required) } // Maps ClaimAttestation object from VC SDK to ClaimRequirement in library internal fun ClaimAttestation.toClaimRequirement(): ClaimRequirement { return ClaimRequirement(this.claim, this.required, this.type) }
2
Kotlin
8
9
5978f33741ddf4dcd51533552487eaeb81ee6e75
1,065
entra-verifiedid-wallet-library-android
MIT License
app/src/main/java/com/example/busschedule/StopScheduleFragment.kt
S-H-U-R-A
610,439,279
false
null
package com.example.busschedule import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.coroutineScope import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.busschedule.databinding.StopScheduleFragmentBinding import com.example.busschedule.viewmodels.BusScheduleViewModel import com.example.busschedule.viewmodels.BusScheduleViewModelFactory import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class StopScheduleFragment: Fragment() { private val viewModel: BusScheduleViewModel by activityViewModels<BusScheduleViewModel> { BusScheduleViewModelFactory( (requireActivity().applicationContext as BusScheduleApplication).dataBase.scheduleDao() ) } //PROPIEDAD ESTATICA companion object { var STOP_NAME = "stopName" } //VARIABLE DE VINCULACIÓN PROTEGIDA private var _binding: StopScheduleFragmentBinding? = null private val binding get() = _binding!! private lateinit var recyclerView: RecyclerView private lateinit var stopName: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //SE RECUPERAN LOS ARGUMENTOS PASADOS arguments?.let { stopName = it.getString(STOP_NAME).toString() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { //SE INFLA EL DISEÑO _binding = StopScheduleFragmentBinding.inflate(inflater, container, false) val view = binding.root return view } @OptIn(DelicateCoroutinesApi::class) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //SE ASIGNAN LOS VALORES recyclerView = binding.recyclerView //ESTO SE PUEDE HACER DESDE EL XML recyclerView.layoutManager = LinearLayoutManager( requireContext() ) val busStopAdapter = BusStopAdapter {} recyclerView.adapter = busStopAdapter /* GlobalScope.launch(Dispatchers.IO) { busStopAdapter.submitList( viewModel.scheduleForStopName(stopName) ) }*/ lifecycle.coroutineScope.launch { viewModel.scheduleForStopName(stopName).collect(){ schedules -> busStopAdapter.submitList( schedules ) } } } //SE LIBERA EL RECURSO CUANDO SE DESTRUYE EL FRAGMENTO override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
1
0
69db61c5515fea6cecc50574100d43e78f95bdc0
3,011
BusSchedule-Use-ViewBinding-Flow-Room-ListAdapter-RecyclerView-Navigation
Apache License 2.0
src/main/java/com/jakeesveld/zoos/repo/AnimalRepository.kt
JakeEsveldDevelopment
191,630,930
true
{"Kotlin": 9592, "Java": 343}
package com.jakeesveld.zoos.repo import com.jakeesveld.zoos.model.Animal import com.jakeesveld.zoos.view.AnimalCount import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository import java.util.ArrayList interface AnimalRepository : CrudRepository<Animal, Long> { @get:Query(value = "SELECT a.animaltype, COUNT(z.zooid) as countzoos FROM animal a INNER JOIN zooanimals z ON a.animalid=z.animalid GROUP BY a.animalid, a.animaltype", nativeQuery = true) val animalCounts: MutableList<AnimalCount> }
0
Kotlin
0
0
fe5d6cc5dadbde7120768780c9aa8672d6725eeb
560
java-zoos
MIT License
api/src/commonMain/kotlin/app/meetacy/sdk/users/UserRepository.kt
meetacy
604,657,616
false
null
package app.meetacy.sdk.users import app.meetacy.sdk.AuthorizedMeetacyApi import app.meetacy.sdk.MeetacyApi import app.meetacy.sdk.types.auth.Token import app.meetacy.sdk.types.user.RegularUser import app.meetacy.sdk.types.user.SelfUser import app.meetacy.sdk.types.user.User public sealed interface UserRepository { public companion object { public fun of( token: Token, user: User, api: MeetacyApi ): UserRepository = of(user, api.authorized(token)) public fun of( user: User, api: AuthorizedMeetacyApi ): UserRepository = when (user) { is RegularUser -> RegularUserRepository(user, api.base) is SelfUser -> SelfUserRepository(user, api) } } }
2
Kotlin
1
22
761eda8c772c1549d28312eb44040b59c101e0d2
781
sdk
MIT License
reimagined/src/main/kotlin/dev/olshevski/navigation/reimagined/NavTransitionScope.kt
olshevski
455,126,442
false
null
package dev.olshevski.navigation.reimagined import androidx.compose.animation.AnimatedContentScope import androidx.compose.animation.AnimatedContentScope.SlideDirection import androidx.compose.animation.ContentTransform import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.SizeTransform import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.VisibilityThreshold import androidx.compose.animation.core.spring import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically import androidx.compose.ui.unit.IntOffset @ExperimentalAnimationApi interface NavTransitionScope { /** * This defines a horizontal/vertical exit transition to completely slide out of the * [AnimatedNavHost] container. The offset amount is dynamically calculated based on the current * size of the [AnimatedNavHost] and the new target size. This offset gets passed * to [targetOffset] lambda. By default, [targetOffset] uses this offset as is, but it can be * customized to slide a distance based on the offset. [slideOutOfContainer] is a * convenient alternative to [slideOutHorizontally] and [slideOutVertically] when the incoming * and outgoing content differ in size. Otherwise, it would be equivalent to * [slideOutHorizontally] and [slideOutVertically] with an offset of the full width/height. * * [towards] specifies the slide direction. Content can be slided out of the container towards * [SlideDirection.Left], [SlideDirection.Right], [SlideDirection.Up] and [SlideDirection.Down]. * * [animationSpec] defines the animation that will be used to animate the slide-out. */ fun slideOutOfContainer( towards: SlideDirection, animationSpec: FiniteAnimationSpec<IntOffset> = spring( visibilityThreshold = IntOffset.VisibilityThreshold ), targetOffset: (offsetForFullSlide: Int) -> Int = { it } ): ExitTransition /** * This defines a horizontal/vertical slide-in that is specific to [AnimatedNavHost] from the * edge of the container. The offset amount is dynamically calculated based on the current * size of the [AnimatedNavHost] and its content alignment. This offset (may be positive or * negative based on the direction of the slide) is then passed to [initialOffset]. By default, * [initialOffset] will be using the offset calculated from the system to slide the content in. * [slideIntoContainer] is a convenient alternative to [slideInHorizontally] and * [slideInVertically] when the incoming and outgoing content * differ in size. Otherwise, it would be equivalent to [slideInHorizontally] and * [slideInVertically] with an offset of the full width/height. * * [towards] specifies the slide direction. Content can be slided into the container towards * [SlideDirection.Left], [SlideDirection.Right], [SlideDirection.Up] and [SlideDirection.Down]. * * [animationSpec] defines the animation that will be used to animate the slide-in. */ fun slideIntoContainer( towards: SlideDirection, animationSpec: FiniteAnimationSpec<IntOffset> = spring( visibilityThreshold = IntOffset.VisibilityThreshold ), initialOffset: (offsetForFullSlide: Int) -> Int = { it } ): EnterTransition /** * Customizes the [SizeTransform] of a given [ContentTransform]. */ infix fun ContentTransform.using(sizeTransform: SizeTransform?): ContentTransform } @ExperimentalAnimationApi internal class NavTransitionScopeImpl<S>( private val animatedContentScope: AnimatedContentScope<S> ) : NavTransitionScope { override fun slideOutOfContainer( towards: SlideDirection, animationSpec: FiniteAnimationSpec<IntOffset>, targetOffset: (offsetForFullSlide: Int) -> Int ) = animatedContentScope.slideOutOfContainer(towards, animationSpec, targetOffset) override fun slideIntoContainer( towards: SlideDirection, animationSpec: FiniteAnimationSpec<IntOffset>, initialOffset: (offsetForFullSlide: Int) -> Int ) = animatedContentScope.slideIntoContainer(towards, animationSpec, initialOffset) override fun ContentTransform.using(sizeTransform: SizeTransform?) = with(animatedContentScope) { using(sizeTransform) } } @Deprecated( message = "Renamed to NavTransitionScope for simplicity", replaceWith = ReplaceWith("NavTransitionScope") ) @OptIn(ExperimentalAnimationApi::class) typealias AnimatedNavHostTransitionScope = NavTransitionScope
5
null
8
507
665ddfce244666e2a6679b9ca1a5363b49a623b7
4,884
compose-navigation-reimagined
MIT License
moove/legacy-moove/src/main/kotlin/io/charlescd/moove/legacy/moove/controller/CredentialConfigurationController.kt
ZupIT
249,519,503
false
null
/* * * * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package io.charlescd.moove.legacy.moove.controller import io.charlescd.moove.commons.representation.CredentialConfigurationRepresentation import io.charlescd.moove.legacy.moove.request.configuration.CreateCdConfigurationRequest import io.charlescd.moove.legacy.moove.request.configuration.CreateRegistryConfigurationRequest import io.charlescd.moove.legacy.moove.request.configuration.TestRegistryConnectionRequest import io.charlescd.moove.legacy.moove.service.CredentialConfigurationService import io.swagger.annotations.Api import io.swagger.annotations.ApiImplicitParam import io.swagger.annotations.ApiOperation import javax.validation.Valid import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* @Api(value = "Credential Configuration Endpoints", tags = ["Credential Configuration"]) @RestController @RequestMapping("/config") class CredentialConfigurationController(val credentialConfigurationService: CredentialConfigurationService) { @ApiOperation(value = "Create Registry Config") @ApiImplicitParam( name = "createRegistryConfigRequest", value = "Create Registry Config", required = true, dataType = "CreateRegistryConfigurationRequest" ) @ResponseStatus(HttpStatus.CREATED) @PostMapping("/registry") fun createRegistryConfig( @RequestHeader("x-workspace-id") workspaceId: String, @RequestHeader(value = "Authorization", required = false) authorization: String?, @RequestHeader(value = "x-charles-token", required = false) token: String?, @Valid @RequestBody createRegistryConfigRequest: CreateRegistryConfigurationRequest ): CredentialConfigurationRepresentation { return this.credentialConfigurationService.createRegistryConfig(createRegistryConfigRequest, workspaceId, authorization, token) } @ApiOperation(value = "Create CD Config") @ApiImplicitParam( name = "createCdConfigRequest", value = "Create CD Config", required = true, dataType = "CreateCdConfigurationRequest" ) @ResponseStatus(HttpStatus.CREATED) @PostMapping("/cd") fun createCdConfig( @RequestHeader("x-workspace-id") workspaceId: String, @RequestHeader(value = "Authorization", required = false) authorization: String?, @RequestHeader(value = "x-charles-token", required = false) token: String?, @Valid @RequestBody createCdConfigRequest: CreateCdConfigurationRequest ): CredentialConfigurationRepresentation { return this.credentialConfigurationService.createCdConfig(createCdConfigRequest, workspaceId, authorization, token) } @ApiOperation(value = "Get configurations by Type") @GetMapping fun getConfigurationsByType(@RequestHeader("x-workspace-id") workspaceId: String): Map<String, List<CredentialConfigurationRepresentation>> { return this.credentialConfigurationService.getConfigurationsByType(workspaceId) } @ApiOperation(value = "Get configurations by id") @GetMapping("/{id}") fun getConfigurationById( @RequestHeader("x-workspace-id") workspaceId: String, @PathVariable id: String ): CredentialConfigurationRepresentation { return this.credentialConfigurationService.getConfigurationById(id, workspaceId) } @ApiOperation(value = "Test Registry Config") @ApiImplicitParam( name = "createRegistryConfigRequest", value = "Create Registry Config", required = true, dataType = "CreateRegistryConfigurationRequest" ) @ResponseStatus(HttpStatus.OK) @PostMapping("/registry/validation") fun configurationValidation( @RequestHeader("x-workspace-id") workspaceId: String, @Valid @RequestBody request: CreateRegistryConfigurationRequest, @RequestHeader(value = "Authorization", required = false) authorization: String?, @RequestHeader(value = "x-charles-token", required = false) token: String? ) { this.credentialConfigurationService.testRegistryConfiguration(workspaceId, request, authorization, token) } @ApiOperation(value = "Test Registry Connection") @ApiImplicitParam( name = "testRegistryConnectionRequest", value = "Test Registry Connection", required = true, dataType = "TestRegistryConnectionRequest" ) @ResponseStatus(HttpStatus.OK) @PostMapping("/registry/connection-validation") fun connectionValidation( @RequestHeader("x-workspace-id") workspaceId: String, @Valid @RequestBody request: TestRegistryConnectionRequest ) { this.credentialConfigurationService.testRegistryConnection(workspaceId, request) } }
93
null
76
343
a65319e3712dba1612731b44346100e89cd26a60
5,388
charlescd
Apache License 2.0
Recorder/src/main/java/com/team10415/ftc_recorder/Recorder.kt
team10415
306,190,325
false
{"Java": 58923, "Kotlin": 55363}
package com.team10415.ftc_recorder import android.util.Log import com.qualcomm.robotcore.util.ReadWriteFile import org.firstinspires.ftc.robotcore.internal.system.AppUtil abstract class Recorder : TeleOpRunner() { abstract val name: String abstract val inputs: List<Record.Input> var content = "" override fun loop() { super.loop() content += Record(gamepad1).export(inputs) + "\n" + Record(gamepad2).export(inputs) + "\n\n" //Log.i("iteration", Record(gamepad1).export(inputs) + "\n" + Record(gamepad2).export(inputs) + "\n\n") if (gamepad1.a) Log.i("content", content) } override fun stop() { super.stop() val filename = "$name-path.txt" val file = AppUtil.getInstance().getSettingsFile(filename) ReadWriteFile.writeFile( file, content ) Log.i("content", content) } }
1
null
1
1
9b8fa829b6935ebe18e12ffbde12310bbc6beb22
896
UltimateGoal
MIT License
lib/src/main/java/graphql/nadel/engine/transform/NadelTypeRenameResultTransform.kt
atlassian-labs
121,346,908
false
{"Kotlin": 2134819, "Java": 8400}
package graphql.nadel.engine.transform import graphql.introspection.Introspection import graphql.nadel.Service import graphql.nadel.ServiceExecutionHydrationDetails import graphql.nadel.ServiceExecutionResult import graphql.nadel.engine.NadelExecutionContext import graphql.nadel.engine.blueprint.NadelOverallExecutionBlueprint import graphql.nadel.engine.transform.NadelTypeRenameResultTransform.State import graphql.nadel.engine.transform.query.NadelQueryPath import graphql.nadel.engine.transform.query.NadelQueryTransformer import graphql.nadel.engine.transform.result.NadelResultInstruction import graphql.nadel.engine.transform.result.NadelResultKey import graphql.nadel.engine.transform.result.json.JsonNode import graphql.nadel.engine.transform.result.json.JsonNodes import graphql.nadel.engine.util.JsonMap import graphql.nadel.engine.util.queryPath import graphql.normalized.ExecutableNormalizedField internal class NadelTypeRenameResultTransform : NadelTransform<State> { data class State( val typeRenamePath: NadelQueryPath, ) override suspend fun isApplicable( executionContext: NadelExecutionContext, executionBlueprint: NadelOverallExecutionBlueprint, services: Map<String, Service>, service: Service, overallField: ExecutableNormalizedField, hydrationDetails: ServiceExecutionHydrationDetails?, ): State? { return if (overallField.fieldName == Introspection.TypeNameMetaFieldDef.name) { State( typeRenamePath = overallField.queryPath, ) } else { null } } override suspend fun transformField( executionContext: NadelExecutionContext, transformer: NadelQueryTransformer, executionBlueprint: NadelOverallExecutionBlueprint, service: Service, field: ExecutableNormalizedField, state: State, ): NadelTransformFieldResult { return NadelTransformFieldResult.unmodified(field) } override suspend fun getResultInstructions( executionContext: NadelExecutionContext, executionBlueprint: NadelOverallExecutionBlueprint, service: Service, overallField: ExecutableNormalizedField, underlyingParentField: ExecutableNormalizedField?, result: ServiceExecutionResult, state: State, nodes: JsonNodes, ): List<NadelResultInstruction> { val parentNodes = nodes.getNodesAt( underlyingParentField?.queryPath ?: NadelQueryPath.root, flatten = true, ) return parentNodes.mapNotNull { parentNode -> @Suppress("UNCHECKED_CAST") val parentMap = parentNode.value as? JsonMap ?: return@mapNotNull null val underlyingTypeName = parentMap[overallField.resultKey] as String? ?: return@mapNotNull null val overallTypeName = executionBlueprint.getOverallTypeName( service = service, underlyingTypeName = underlyingTypeName, ) NadelResultInstruction.Set( subject = parentNode, key = NadelResultKey(overallField.resultKey), newValue = JsonNode(overallTypeName), ) } } }
26
Kotlin
23
157
e8e1b6d42c3b9858662bd5bd7727b3738ad5c1d3
3,305
nadel
Apache License 2.0
src/testSmoke/kotlin/uk/gov/justice/hmpps/offenderevents/smoketest/SmokeTestConfiguration.kt
ministryofjustice
232,552,985
false
{"Kotlin": 202399, "HTML": 15034, "Shell": 3481, "Mustache": 1803, "Dockerfile": 1264}
package uk.gov.justice.digital.hmpps.indexer.smoketest import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Import import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient.Builder @ConditionalOnProperty(name = ["smoketest.enabled"], havingValue = "true") @EnableWebSecurity @Import(OAuth2ClientAutoConfiguration::class) class SmokeTestConfiguration(@Value("\${smoketest.endpoint.url}") private val smokeTestUrl: String) { private val webClientBuilder: Builder = WebClient.builder() @Bean fun smokeTestWebClient(authorizedClientManager: OAuth2AuthorizedClientManager): WebClient = webClientBuilder .baseUrl(smokeTestUrl) .apply( ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager).also { it.setDefaultClientRegistrationId("smoketest-service") }.oauth2Configuration() ) .build() @Bean fun authorizedClientManager( clientRegistrationRepository: ClientRegistrationRepository, oAuth2AuthorizedClientService: OAuth2AuthorizedClientService ): OAuth2AuthorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager( clientRegistrationRepository, oAuth2AuthorizedClientService ).apply { setAuthorizedClientProvider(OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build()) } }
4
Kotlin
1
2
675d4298d1e1fce4dc1138728828d2b807325427
2,342
prison-to-probation-update
MIT License
src/main/kotlin/flavor/pie/kludge/uuids.kt
pie-flavor
92,704,480
false
null
package flavor.pie.kludge import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.entity.living.player.User import org.spongepowered.api.profile.GameProfile import org.spongepowered.api.profile.GameProfileManager import org.spongepowered.api.service.user.UserStorageService import org.spongepowered.api.Server import java.util.UUID import java.util.concurrent.CompletableFuture /** * Returns the [Player] with this [UUID], or null if there is none. * @see Server.getPlayer */ fun UUID.player(): Player? = !Server.getPlayer(this) internal val service: UserStorageService? by Service /** * Returns the [User] with this [UUID], or null if there is none. * @see UserStorageService.get */ fun UUID.user(): User? = !service?.get(this) /** * Returns the [GameProfile] with this [UUID], or null if there is none. * @see GameProfileManager.get */ fun UUID.profile(): CompletableFuture<GameProfile> = GameProfileManager.get(this) /** * Turns this string into a [UUID]. * @see UUID.fromString */ fun String.toUUID(): UUID = UUID.fromString(this)
0
Kotlin
2
8
07c6d0a8596682e1f91639cc974430c52b0d0d78
1,082
Kludge
MIT License
di/di_dagger/di_dagger_common/src/androidMain/kotlin/siarhei/luskanau/iot/doorbell/dagger/common/CommonModule.kt
siarhei-luskanau
79,257,367
false
null
package siarhei.luskanau.iot.doorbell.dagger.common import android.app.Application import android.content.Context import androidx.startup.AppInitializer import androidx.work.WorkManager import dagger.Module import dagger.Provides import javax.inject.Provider import javax.inject.Singleton import siarhei.luskanau.iot.doorbell.common.DefaultDoorbellsDataSource import siarhei.luskanau.iot.doorbell.common.DeviceInfoProvider import siarhei.luskanau.iot.doorbell.common.DoorbellsDataSource import siarhei.luskanau.iot.doorbell.common.ImagesDataSourceFactory import siarhei.luskanau.iot.doorbell.common.ImagesDataSourceFactoryImpl import siarhei.luskanau.iot.doorbell.common.IpAddressProvider import siarhei.luskanau.iot.doorbell.data.AndroidDeviceInfoProvider import siarhei.luskanau.iot.doorbell.data.AndroidIpAddressProvider import siarhei.luskanau.iot.doorbell.data.AndroidThisDeviceRepository import siarhei.luskanau.iot.doorbell.data.AppBackgroundServices import siarhei.luskanau.iot.doorbell.data.ScheduleWorkManagerService import siarhei.luskanau.iot.doorbell.data.repository.CameraRepository import siarhei.luskanau.iot.doorbell.data.repository.DoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.FirebaseDoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.ImageRepository import siarhei.luskanau.iot.doorbell.data.repository.InternalStorageImageRepository import siarhei.luskanau.iot.doorbell.data.repository.JetpackCameraRepository import siarhei.luskanau.iot.doorbell.data.repository.PersistenceRepository import siarhei.luskanau.iot.doorbell.data.repository.StubDoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.StubUptimeRepository import siarhei.luskanau.iot.doorbell.data.repository.ThisDeviceRepository import siarhei.luskanau.iot.doorbell.data.repository.UptimeFirebaseRepository import siarhei.luskanau.iot.doorbell.data.repository.UptimeRepository import siarhei.luskanau.iot.doorbell.persistence.DefaultPersistenceRepository import siarhei.luskanau.iot.doorbell.workmanager.DefaultScheduleWorkManagerService import siarhei.luskanau.iot.doorbell.workmanager.WorkManagerInitializer @Suppress("TooManyFunctions") @Module class CommonModule { @Provides @Singleton fun provideContext(application: Application): Context = application.applicationContext @Provides @Singleton fun provideWorkManager(context: Provider<Context>): WorkManager = AppInitializer.getInstance(context.get()) .initializeComponent(WorkManagerInitializer::class.java) @Provides @Singleton fun provideImageRepository(context: Provider<Context>): ImageRepository = InternalStorageImageRepository(context = context.get()) @Provides @Singleton fun provideDoorbellRepository(thisDeviceRepository: ThisDeviceRepository): DoorbellRepository = if (thisDeviceRepository.isEmulator()) { StubDoorbellRepository() } else { FirebaseDoorbellRepository() } @Provides @Singleton fun providePersistenceRepository(context: Provider<Context>): PersistenceRepository = DefaultPersistenceRepository(context = context.get()) @Provides @Singleton fun provideScheduleWorkManagerService( workManager: Provider<WorkManager> ): ScheduleWorkManagerService = DefaultScheduleWorkManagerService(workManager = { workManager.get() }) @Provides @Singleton fun provideCameraRepository( context: Provider<Context>, imageRepository: Provider<ImageRepository> ): CameraRepository = JetpackCameraRepository( context = context.get(), imageRepository = imageRepository.get() ) @Provides @Singleton fun provideUptimeRepository(thisDeviceRepository: ThisDeviceRepository): UptimeRepository = if (thisDeviceRepository.isEmulator()) { StubUptimeRepository() } else { UptimeFirebaseRepository() } @Provides @Singleton fun provideDoorbellsDataSource( doorbellRepository: Provider<DoorbellRepository> ): DoorbellsDataSource = DefaultDoorbellsDataSource( doorbellRepository = doorbellRepository.get() ) @Provides @Singleton fun provideDeviceInfoProvider(context: Provider<Context>): DeviceInfoProvider = AndroidDeviceInfoProvider(context = context.get()) @Provides @Singleton fun provideIpAddressProvider(): IpAddressProvider = AndroidIpAddressProvider() @Provides @Singleton fun provideImagesDataSourceFactory( doorbellRepository: Provider<DoorbellRepository> ): ImagesDataSourceFactory = ImagesDataSourceFactoryImpl( doorbellRepository = doorbellRepository.get() ) @Provides @Singleton fun provideThisDeviceRepository( context: Provider<Context>, deviceInfoProvider: Provider<DeviceInfoProvider>, cameraRepository: Provider<CameraRepository>, ipAddressProvider: Provider<IpAddressProvider> ): ThisDeviceRepository = AndroidThisDeviceRepository( context = context.get(), deviceInfoProvider = deviceInfoProvider.get(), cameraRepository = cameraRepository.get(), ipAddressProvider = ipAddressProvider.get() ) @Provides @Singleton fun provideAppBackgroundServices( doorbellRepository: Provider<DoorbellRepository>, thisDeviceRepository: Provider<ThisDeviceRepository>, scheduleWorkManagerService: Provider<ScheduleWorkManagerService> ): AppBackgroundServices = AppBackgroundServices( doorbellRepository = doorbellRepository.get(), thisDeviceRepository = thisDeviceRepository.get(), scheduleWorkManagerService = scheduleWorkManagerService.get() ) }
0
null
0
2
801b8abab13c718fd6e383907c752e0b0425a8fc
5,921
android-iot-doorbell
MIT License
teacher_app/app/src/main/java/io/github/kabirnayeem99/dumarketingadmin/presentation/view/gallery/GalleryImageFragment.kt
kabirnayeem99
360,781,364
false
null
package io.github.kabirnayeem99.dumarketingadmin.presentation.view.gallery import android.os.Bundle import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.StaggeredGridLayoutManager import dagger.hilt.android.AndroidEntryPoint import io.github.kabirnayeem99.dumarketingadmin.R import io.github.kabirnayeem99.dumarketingadmin.common.base.BaseFragment import io.github.kabirnayeem99.dumarketingadmin.common.ktx.showErrorMessage import io.github.kabirnayeem99.dumarketingadmin.common.ktx.showMessage import io.github.kabirnayeem99.dumarketingadmin.data.model.GalleryData import io.github.kabirnayeem99.dumarketingadmin.databinding.FragmentGalleryImageBinding import io.github.kabirnayeem99.dumarketingadmin.presentation.view.adapter.GalleryDataAdapter import io.github.kabirnayeem99.dumarketingadmin.presentation.viewmodel.GalleryViewModel import kotlinx.coroutines.flow.collect @AndroidEntryPoint class GalleryImageFragment : BaseFragment<FragmentGalleryImageBinding>() { override val layoutRes: Int get() = R.layout.fragment_gallery_image private val galleryDataAdapter: GalleryDataAdapter by lazy { GalleryDataAdapter { deleteGalleryData(it) } } private val galleryViewModel: GalleryViewModel by activityViewModels() override fun onCreated(savedInstanceState: Bundle?) { setUpRecyclerView() addGalleryImageClickListener() subscribeObservers() } private fun subscribeObservers() { lifecycleScope.launchWhenCreated { galleryViewModel.getGalleryDataList() galleryViewModel.galleryDataList.observe(viewLifecycleOwner) { galleryDataList -> galleryDataAdapter.differ.submitList(galleryDataList) } galleryViewModel.errorMessage.collect { showErrorMessage(it) } galleryViewModel.message.collect { showMessage(it) } galleryViewModel.isLoading.collect { if (it) loadingIndicator.show() else loadingIndicator.dismiss() } } } private fun setUpRecyclerView() { binding.rvGallery.apply { adapter = galleryDataAdapter layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL).apply { gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS } } } private fun addGalleryImageClickListener() { binding.btnAddGalleryImage.setOnClickListener { findNavController().navigate(R.id.action_galleryImageFragment_to_addGalleryImageFragment) } } private fun deleteGalleryData(galleryData: GalleryData) = galleryViewModel.deleteGalleryData(galleryData) }
4
null
2
5
d07f00410c975dba19c83a959b3a5aeff9074b7a
2,922
du_marketing_sms
Apache License 2.0
app/src/main/java/dev/zezula/books/ui/screen/signin/SignInScreen.kt
zezulaon
589,699,261
false
{"Kotlin": 433845}
package dev.zezula.books.ui.screen.signin import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import dev.zezula.books.R import dev.zezula.books.ui.screen.about.AboutCard import dev.zezula.books.ui.theme.MyLibraryTheme import dev.zezula.books.util.PHONE_MOTO_G5_PLUS @Composable fun SignInRoute( viewModel: SignInViewModel, onSignInSuccess: () -> Unit, onGoogleSignIn: () -> Unit, onEmailSignIn: () -> Unit, onContactClicked: () -> Unit, onReleaseNotesClicked: () -> Unit, ) { val snackbarHostState = remember { SnackbarHostState() } val uiState by viewModel.uiState.collectAsStateWithLifecycle() if (uiState.isUserSignedIn) { val latestOnSignInSuccess by rememberUpdatedState(onSignInSuccess) LaunchedEffect(uiState) { latestOnSignInSuccess() } } uiState.uiMessage?.let { msg -> val text = stringResource(msg) LaunchedEffect(snackbarHostState, viewModel, msg, text) { snackbarHostState.showSnackbar(text) viewModel.snackbarMessageShown() } } SignInScreen( uiState = uiState, snackbarHostState = snackbarHostState, onGoogleSignInClick = { onGoogleSignIn() viewModel.onGoogleSignInClick() }, onEmailSignInClick = onEmailSignIn, onAnonymousSignInClick = { viewModel.signInAnonymously() }, onContactClicked = onContactClicked, onReleaseNotesClicked = onReleaseNotesClicked, ) } @Composable fun SignInScreen( uiState: SignInUiState, onGoogleSignInClick: () -> Unit, onEmailSignInClick: () -> Unit, onAnonymousSignInClick: () -> Unit, onContactClicked: () -> Unit, onReleaseNotesClicked: () -> Unit, modifier: Modifier = Modifier, snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, ) { Scaffold( modifier = modifier, snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, ) { innerPadding -> Box( modifier = Modifier .fillMaxWidth() .padding(innerPadding), ) { if (uiState.isSignInProgress) { LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) } Column( modifier = Modifier .padding(16.dp), ) { Box( modifier = Modifier .weight(2f) .fillMaxWidth(), contentAlignment = Alignment.Center, ) { AboutCard( onContactUsClicked = onContactClicked, onReleaseNotesClicked = onReleaseNotesClicked, ) } Box( modifier = Modifier .weight(1f) .fillMaxWidth(), contentAlignment = Alignment.Center, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp), ) { Button( modifier = Modifier.width(220.dp), onClick = onGoogleSignInClick, enabled = uiState.isSignInProgress.not(), ) { Text(text = stringResource(id = R.string.btn_google_sign_in)) } Text(text = stringResource(id = R.string.sign_in_label_or)) TextButton( onClick = onEmailSignInClick, enabled = uiState.isSignInProgress.not(), ) { Text(text = stringResource(id = R.string.btn_email_sign_in)) } } } } } } } @Preview( showBackground = true, showSystemUi = true, device = PHONE_MOTO_G5_PLUS, ) @Composable private fun DefaultPreview() { MyLibraryTheme { SignInScreen( uiState = SignInUiState(isSignInProgress = false), onGoogleSignInClick = {}, onAnonymousSignInClick = {}, onContactClicked = {}, onReleaseNotesClicked = {}, onEmailSignInClick = {}, ) } }
1
Kotlin
0
6
3ff0d9f6be840e87170f2aa76f5e7758eb4380f3
5,591
my-library
Apache License 2.0
Android/app/src/main/java/sample/sdk/breez/page/home/sendonchain/SendOnChainAction.kt
breez
681,972,081
false
{"Kotlin": 132212, "Rust": 2438, "Python": 1484}
package sample.sdk.breez.page.home.sendonchain import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import sample.sdk.breez.R import sample.sdk.breez.page.BreezSdkSampleTheme @Composable fun SendOnChainAction( onOnChainClick: (Long, String) -> Unit, ) { var amount by remember { mutableStateOf(TextFieldValue("3000")) } var address by remember { mutableStateOf(TextFieldValue("bc1…")) } Column( horizontalAlignment = Alignment.CenterHorizontally, ) { TextField( modifier = Modifier.padding( start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp, ), value = amount, onValueChange = { amount = it }, label = { Text(stringResource(R.string.send_on_chain_amount)) }, ) TextField( modifier = Modifier.padding( start = 16.dp, end = 16.dp, top = 4.dp, bottom = 4.dp, ), value = address, onValueChange = { address = it }, label = { Text(stringResource(R.string.send_on_chain_address)) }, ) Button( modifier = Modifier.padding( start = 16.dp, end = 16.dp, top = 4.dp, bottom = 16.dp, ), onClick = { onOnChainClick(amount.text.toLong(), address.text) }, ) { Text(stringResource(R.string.send_on_chain)) } } } @[Composable Preview( showBackground = true, heightDp = 200, widthDp = 300, )] fun SendOnChainActionPreview() { BreezSdkSampleTheme { SendOnChainAction { _, _ -> } } }
1
Kotlin
1
1
3d1d51830315e0ceb54eca79cd43d14c10ec71f4
2,541
breez-sdk-examples
MIT License
app/src/main/java/com/vultisig/wallet/ui/components/DigitString.kt
vultisig
789,965,982
false
{"Kotlin": 1656023, "Ruby": 1713}
package com.vultisig.wallet.ui.components import androidx.annotation.StringRes import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import com.vultisig.wallet.R @Composable internal fun digitStringToWords(@StringRes id: Int, vararg formatArgs: Any): String { val resources = LocalContext.current.resources; val formattedString = resources.getString(id, *formatArgs) val digitWords = resources.getStringArray(R.array.digit_words) return formattedString.map { when (it) { in '0'..'9' -> digitWords[it.toString().toInt()] else -> it.toString() } }.joinToString("") }
58
Kotlin
2
6
106410f378751c6ab276120fcc74c1036b46ab6e
665
vultisig-android
Apache License 2.0
app/src/main/java/com/erzhan/mystock/presentation/company_info/CompanyInfoEvent.kt
anarkulov
510,068,982
false
{"Kotlin": 41588}
package com.erzhan.mystock.presentation.company_info sealed class CompanyInfoEvent { object OnRefresh: CompanyInfoEvent() }
0
Kotlin
0
0
c1d4a5057aa9df49dc970f3f87762304743a41e4
128
MyStock
MIT License
libraries/stdlib/common/src/generated/_Ranges.kt
cpovirk
119,830,321
true
{"Markdown": 42, "Gradle": 275, "XML": 1445, "Gradle Kotlin DSL": 126, "Java Properties": 13, "Shell": 9, "Ignore List": 10, "Batchfile": 8, "Git Attributes": 1, "Proguard": 7, "Kotlin": 36648, "Java": 5146, "Protocol Buffer": 9, "Text": 7652, "JavaScript": 235, "JAR Manifest": 2, "Roff": 207, "Roff Manpage": 26, "JSON": 17, "INI": 75, "AsciiDoc": 1, "HTML": 375, "Groovy": 25, "Maven POM": 85, "CSS": 1, "JFlex": 2, "Ant Build System": 50, "ANTLR": 1}
@file:kotlin.jvm.JvmMultifileClass @file:kotlin.jvm.JvmName("RangesKt") package kotlin.ranges // // NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt // See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib // import kotlin.comparisons.* /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("intRangeContains") public expect operator fun ClosedRange<Int>.contains(value: Byte): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("longRangeContains") public expect operator fun ClosedRange<Long>.contains(value: Byte): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("shortRangeContains") public expect operator fun ClosedRange<Short>.contains(value: Byte): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("doubleRangeContains") public expect operator fun ClosedRange<Double>.contains(value: Byte): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("floatRangeContains") public expect operator fun ClosedRange<Float>.contains(value: Byte): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("intRangeContains") public expect operator fun ClosedRange<Int>.contains(value: Double): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("longRangeContains") public expect operator fun ClosedRange<Long>.contains(value: Double): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("byteRangeContains") public expect operator fun ClosedRange<Byte>.contains(value: Double): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("shortRangeContains") public expect operator fun ClosedRange<Short>.contains(value: Double): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("floatRangeContains") public expect operator fun ClosedRange<Float>.contains(value: Double): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("intRangeContains") public expect operator fun ClosedRange<Int>.contains(value: Float): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("longRangeContains") public expect operator fun ClosedRange<Long>.contains(value: Float): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("byteRangeContains") public expect operator fun ClosedRange<Byte>.contains(value: Float): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("shortRangeContains") public expect operator fun ClosedRange<Short>.contains(value: Float): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("doubleRangeContains") public expect operator fun ClosedRange<Double>.contains(value: Float): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("longRangeContains") public expect operator fun ClosedRange<Long>.contains(value: Int): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("byteRangeContains") public expect operator fun ClosedRange<Byte>.contains(value: Int): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("shortRangeContains") public expect operator fun ClosedRange<Short>.contains(value: Int): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("doubleRangeContains") public expect operator fun ClosedRange<Double>.contains(value: Int): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("floatRangeContains") public expect operator fun ClosedRange<Float>.contains(value: Int): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("intRangeContains") public expect operator fun ClosedRange<Int>.contains(value: Long): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("byteRangeContains") public expect operator fun ClosedRange<Byte>.contains(value: Long): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("shortRangeContains") public expect operator fun ClosedRange<Short>.contains(value: Long): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("doubleRangeContains") public expect operator fun ClosedRange<Double>.contains(value: Long): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("floatRangeContains") public expect operator fun ClosedRange<Float>.contains(value: Long): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("intRangeContains") public expect operator fun ClosedRange<Int>.contains(value: Short): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("longRangeContains") public expect operator fun ClosedRange<Long>.contains(value: Short): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("byteRangeContains") public expect operator fun ClosedRange<Byte>.contains(value: Short): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("doubleRangeContains") public expect operator fun ClosedRange<Double>.contains(value: Short): Boolean /** * Checks if the specified [value] belongs to this range. */ @kotlin.jvm.JvmName("floatRangeContains") public expect operator fun ClosedRange<Float>.contains(value: Short): Boolean /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Int.downTo(to: Byte): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Long.downTo(to: Byte): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Byte.downTo(to: Byte): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Short.downTo(to: Byte): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Char.downTo(to: Char): CharProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Int.downTo(to: Int): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Long.downTo(to: Int): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Byte.downTo(to: Int): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Short.downTo(to: Int): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Int.downTo(to: Long): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Long.downTo(to: Long): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Byte.downTo(to: Long): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Short.downTo(to: Long): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Int.downTo(to: Short): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Long.downTo(to: Short): LongProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Byte.downTo(to: Short): IntProgression /** * Returns a progression from this value down to the specified [to] value with the step -1. * * The [to] value has to be less than this value. */ public expect infix fun Short.downTo(to: Short): IntProgression /** * Returns a progression that goes over the same range in the opposite direction with the same step. */ public expect fun IntProgression.reversed(): IntProgression /** * Returns a progression that goes over the same range in the opposite direction with the same step. */ public expect fun LongProgression.reversed(): LongProgression /** * Returns a progression that goes over the same range in the opposite direction with the same step. */ public expect fun CharProgression.reversed(): CharProgression /** * Returns a progression that goes over the same range with the given step. */ public expect infix fun IntProgression.step(step: Int): IntProgression /** * Returns a progression that goes over the same range with the given step. */ public expect infix fun LongProgression.step(step: Long): LongProgression /** * Returns a progression that goes over the same range with the given step. */ public expect infix fun CharProgression.step(step: Int): CharProgression internal expect fun Int.toByteExactOrNull(): Byte? internal expect fun Long.toByteExactOrNull(): Byte? internal expect fun Short.toByteExactOrNull(): Byte? internal expect fun Double.toByteExactOrNull(): Byte? internal expect fun Float.toByteExactOrNull(): Byte? internal expect fun Long.toIntExactOrNull(): Int? internal expect fun Double.toIntExactOrNull(): Int? internal expect fun Float.toIntExactOrNull(): Int? internal expect fun Double.toLongExactOrNull(): Long? internal expect fun Float.toLongExactOrNull(): Long? internal expect fun Int.toShortExactOrNull(): Short? internal expect fun Long.toShortExactOrNull(): Short? internal expect fun Double.toShortExactOrNull(): Short? internal expect fun Float.toShortExactOrNull(): Short? /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Int.until(to: Byte): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Long.until(to: Byte): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Byte.until(to: Byte): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Short.until(to: Byte): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to `'\u0000'` the returned range is empty. */ public expect infix fun Char.until(to: Char): CharRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Int.MIN_VALUE] the returned range is empty. */ public expect infix fun Int.until(to: Int): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Long.until(to: Int): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Int.MIN_VALUE] the returned range is empty. */ public expect infix fun Byte.until(to: Int): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Int.MIN_VALUE] the returned range is empty. */ public expect infix fun Short.until(to: Int): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Long.MIN_VALUE] the returned range is empty. */ public expect infix fun Int.until(to: Long): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Long.MIN_VALUE] the returned range is empty. */ public expect infix fun Long.until(to: Long): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Long.MIN_VALUE] the returned range is empty. */ public expect infix fun Byte.until(to: Long): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. * * If the [to] value is less than or equal to [Long.MIN_VALUE] the returned range is empty. */ public expect infix fun Short.until(to: Long): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Int.until(to: Short): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Long.until(to: Short): LongRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Byte.until(to: Short): IntRange /** * Returns a range from this value up to but excluding the specified [to] value. */ public expect infix fun Short.until(to: Short): IntRange /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeastComparable */ public expect fun <T: Comparable<T>> T.coerceAtLeast(minimumValue: T): T /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeast */ public expect fun Byte.coerceAtLeast(minimumValue: Byte): Byte /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeast */ public expect fun Short.coerceAtLeast(minimumValue: Short): Short /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeast */ public expect fun Int.coerceAtLeast(minimumValue: Int): Int /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeast */ public expect fun Long.coerceAtLeast(minimumValue: Long): Long /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeast */ public expect fun Float.coerceAtLeast(minimumValue: Float): Float /** * Ensures that this value is not less than the specified [minimumValue]. * * @return this value if it's greater than or equal to the [minimumValue] or the [minimumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtLeast */ public expect fun Double.coerceAtLeast(minimumValue: Double): Double /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMostComparable */ public expect fun <T: Comparable<T>> T.coerceAtMost(maximumValue: T): T /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMost */ public expect fun Byte.coerceAtMost(maximumValue: Byte): Byte /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMost */ public expect fun Short.coerceAtMost(maximumValue: Short): Short /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMost */ public expect fun Int.coerceAtMost(maximumValue: Int): Int /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMost */ public expect fun Long.coerceAtMost(maximumValue: Long): Long /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMost */ public expect fun Float.coerceAtMost(maximumValue: Float): Float /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * @sample samples.comparisons.ComparableOps.coerceAtMost */ public expect fun Double.coerceAtMost(maximumValue: Double): Double /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceInComparable */ public expect fun <T: Comparable<T>> T.coerceIn(minimumValue: T?, maximumValue: T?): T /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Byte.coerceIn(minimumValue: Byte, maximumValue: Byte): Byte /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Short.coerceIn(minimumValue: Short, maximumValue: Short): Short /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Int.coerceIn(minimumValue: Int, maximumValue: Int): Int /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Long.coerceIn(minimumValue: Long, maximumValue: Long): Long /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Float.coerceIn(minimumValue: Float, maximumValue: Float): Float /** * Ensures that this value lies in the specified range [minimumValue]..[maximumValue]. * * @return this value if it's in the range, or [minimumValue] if this value is less than [minimumValue], or [maximumValue] if this value is greater than [maximumValue]. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Double.coerceIn(minimumValue: Double, maximumValue: Double): Double /** * Ensures that this value lies in the specified [range]. * * @return this value if it's in the [range], or `range.start` if this value is less than `range.start`, or `range.endInclusive` if this value is greater than `range.endInclusive`. * @sample samples.comparisons.ComparableOps.coerceInFloatingPointRange */ @SinceKotlin("1.1") public expect fun <T: Comparable<T>> T.coerceIn(range: ClosedFloatingPointRange<T>): T /** * Ensures that this value lies in the specified [range]. * * @return this value if it's in the [range], or `range.start` if this value is less than `range.start`, or `range.endInclusive` if this value is greater than `range.endInclusive`. * @sample samples.comparisons.ComparableOps.coerceInComparable */ public expect fun <T: Comparable<T>> T.coerceIn(range: ClosedRange<T>): T /** * Ensures that this value lies in the specified [range]. * * @return this value if it's in the [range], or `range.start` if this value is less than `range.start`, or `range.endInclusive` if this value is greater than `range.endInclusive`. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Int.coerceIn(range: ClosedRange<Int>): Int /** * Ensures that this value lies in the specified [range]. * * @return this value if it's in the [range], or `range.start` if this value is less than `range.start`, or `range.endInclusive` if this value is greater than `range.endInclusive`. * @sample samples.comparisons.ComparableOps.coerceIn */ public expect fun Long.coerceIn(range: ClosedRange<Long>): Long
0
Kotlin
0
1
b6ca9118ffe142e729dd17deeecfb35badba1537
23,371
kotlin
Apache License 2.0
app/src/main/java/com/bossed/waej/ui/ItemMsgActivity.kt
Ltow
710,230,789
false
{"Kotlin": 2304560, "Java": 395495, "HTML": 71364}
package com.bossed.waej.ui import android.content.Intent import android.os.Bundle import android.view.View import android.widget.RelativeLayout import com.blankj.utilcode.util.BarUtils import com.blankj.utilcode.util.ToastUtils import com.bossed.waej.R import com.bossed.waej.base.BaseActivity import com.bossed.waej.http.Api import com.bossed.waej.http.BaseResourceObserver import com.bossed.waej.http.UrlConstants import com.bossed.waej.javebean.ItemMsgBean import com.bossed.waej.util.* import com.gyf.immersionbar.ImmersionBar import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_item_msg.* class ItemMsgActivity : BaseActivity(), OnNoRepeatClickListener { private var shopId = -1 private var cateId = -1 private var marketPrice = 0.0f private var costPrice = 0.0f private var madeFee = 0.0f private var madeMoney = 0.0f override fun getLayoutId(): Int { return R.layout.activity_item_msg } override fun initView(savedInstanceState: Bundle?) { ImmersionBar.with(this).statusBarDarkFont(true).init() val layoutParams: RelativeLayout.LayoutParams = iv_back.layoutParams as RelativeLayout.LayoutParams layoutParams.topMargin = BarUtils.getStatusBarHeight() iv_back.layoutParams = layoutParams getItemMsg() } override fun initListener() { } override fun onRepeatClick(v: View?) { when (v?.id) { R.id.iv_back -> { if (DoubleClicksUtils.get().isFastDoubleClick) return onBackPressed() } R.id.tv_shelves -> { if (DoubleClicksUtils.get().isFastDoubleClick) return shelves() } } } private fun getItemMsg() { LoadingUtils.showLoading(this, "加载中...") Api.getInstance().getApiService() .getItemMsg(intent.getIntExtra("id", -1)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : BaseResourceObserver<ItemMsgBean>() { override fun onComplete() { LoadingUtils.dismissLoading() } override fun onSubscribe(d: Disposable) { } override fun onNext(t: ItemMsgBean) { when (t.code) { 200 -> { shopId = t.data.shopId shopId = t.data.cateId marketPrice = t.data.marketPrice costPrice = t.data.costPrice madeFee = t.data.madeFee madeMoney = t.data.madeMoney tv_name.text = t.data.name tv_briefIntroduction.text = t.data.briefIntroduction tv_marketPrice.text = t.data.marketPrice.toString() tv_virtualPrice.text = t.data.virtualPrice.toString() tv_details.text = t.data.details GlideUtils.get() .loadItemPic(this@ItemMsgActivity, t.data.mainPicture, iv_item) } 401 -> { PopupWindowUtils.get().showLoginOutTimePop(this@ItemMsgActivity) } 703 -> { PopupWindowUtils.get() .showSetConfirmAlertDialog(mContext, t.msg, "去购买", "") { mContext.startActivity( Intent( mContext, BuyProductActivity::class.java ) ) } } else -> { ToastUtils.showShort(t.msg) } } } override fun onError(throwable: Throwable) { ToastUtils.showShort(throwable.message) LoadingUtils.dismissLoading() } }) } private fun shelves() { LoadingUtils.showLoading(this, "加载中...") val params = ArrayList<HashMap<String, Any>>() val hashMap = HashMap<String, Any>() hashMap["cateId"] = cateId hashMap["costPrice"] = costPrice hashMap["id"] = intent.getIntExtra("id", -1) hashMap["madeFee"] = madeFee hashMap["madeMoney"] = madeMoney hashMap["marketPrice"] = marketPrice hashMap["name"] = tv_name.text hashMap["shopId"] = shopId hashMap["status"] = 2 params.add(hashMap) RetrofitUtils.get().putJson( UrlConstants.UpDateItemStatusUrl, params,this, object : RetrofitUtils.OnCallBackListener { override fun onSuccess(s: String) { ToastUtils.showShort("上架成功") finish() } override fun onFailed(e: String) { ToastUtils.showShort(e) } }) } }
0
Kotlin
0
0
8c2e9928f6c47484bec7a5beca32ed4b10200f9c
5,495
wananexiu
Mulan Permissive Software License, Version 2
solutions/src/test/kotlin/y2016/Y2016D05Test.kt
Jadarma
324,646,170
false
null
package y2016 import io.github.jadarma.aoc.test.AdventSpec import io.kotest.core.spec.DisplayName @DisplayName("Y2016D05 How About a Nice Game of Chess?") class Y2016D05Test : AdventSpec(Y2016D05(), { partOne { "abc" shouldOutput "18f47a30" } partTwo { "abc" shouldOutput "05ace8e3" } })
0
Kotlin
0
3
3f36fc11261dee5583947dc1e1fbaa1e7d656b47
322
advent-of-code-kotlin
MIT License
app/src/main/java/com/project_christopher/bibliotheca/Components/Preferences.kt
Project-Christopher
389,983,234
false
null
package com.project_christopher.bibliotheca.Components import org.json.JSONObject class Preferences { class Pair(var key: String, var value: String) var favorite = false var state = 0 var comments = "" val customFields = ArrayList<Pair>() companion object { fun parsePreferences(jsonObject: JSONObject): Preferences { val preferences = Preferences() if(jsonObject.has("favorite")) preferences.favorite = jsonObject.getBoolean("favorite") if(jsonObject.has("state")) preferences.state = jsonObject.getInt("state") if(jsonObject.has("comments")) preferences.comments = jsonObject.getString("comments") if(jsonObject.has("custom_fields")) { val array = jsonObject.getJSONArray("custom_fields") for(i in 0 until array.length()){ val obj = array[i] as JSONObject if(obj.has("key") && obj.has("value")) preferences.customFields.add(Pair(obj.getString("key"), obj.getString("value"))) } } return preferences } } }
0
Kotlin
0
0
fca605f7b10fbcbdb1a288ec80f7c310fa29cecb
1,202
android-bibliotheca
Apache License 2.0
app/src/main/java/com/project_christopher/bibliotheca/Components/Preferences.kt
Project-Christopher
389,983,234
false
null
package com.project_christopher.bibliotheca.Components import org.json.JSONObject class Preferences { class Pair(var key: String, var value: String) var favorite = false var state = 0 var comments = "" val customFields = ArrayList<Pair>() companion object { fun parsePreferences(jsonObject: JSONObject): Preferences { val preferences = Preferences() if(jsonObject.has("favorite")) preferences.favorite = jsonObject.getBoolean("favorite") if(jsonObject.has("state")) preferences.state = jsonObject.getInt("state") if(jsonObject.has("comments")) preferences.comments = jsonObject.getString("comments") if(jsonObject.has("custom_fields")) { val array = jsonObject.getJSONArray("custom_fields") for(i in 0 until array.length()){ val obj = array[i] as JSONObject if(obj.has("key") && obj.has("value")) preferences.customFields.add(Pair(obj.getString("key"), obj.getString("value"))) } } return preferences } } }
0
Kotlin
0
0
fca605f7b10fbcbdb1a288ec80f7c310fa29cecb
1,202
android-bibliotheca
Apache License 2.0
shared/src/commonMain/kotlin/com/czech/breakingbad/util/MessageInfoQueueUtil.kt
Czeach
439,389,096
false
{"Kotlin": 78963, "Swift": 345}
package com.czech.breakingbad.util class MessageInfoQueueUtil() { /** * Does this particular GenericMessageInfo already exist in the queue? We don't want duplicates */ fun doesMessageAlreadyExistInQueue(queue: Queue<MessageInfo>, messageInfo: MessageInfo): Boolean{ for(item in queue.items){ if (item.id == messageInfo.id){ return true } } return false } }
0
Kotlin
0
1
1375fb8b5c8e4a96212337d5bef22a7f6458be63
443
Breaking-Bad
MIT License
src/main/kotlin/me/fanhua/piggies/gui/ui/IBasePosUI.kt
imfanhua
516,849,087
false
{"Kotlin": 142668}
package me.fanhua.piggies.gui.ui import me.fanhua.piggies.gui.GUISize import org.bukkit.entity.Player abstract class IBasePosUI(x: Int, y: Int) : IBaseUI() { var x by observable(x) var y by observable(y) protected var size: GUISize? = null override fun draw(canvas: IUICanvas) { redraw = false canvas.diff(x, y).let { size = it.size whenDraw(it) } } override fun use(clicker: Player, type: ActionType, x: Int, y: Int): Boolean = size.let { size -> if (size == null || this.x > x || this.y > y) false else whenUse(clicker, type, x - this.x, y - this.y, size) } protected open fun whenDraw(canvas: IUICanvas) {} protected open fun whenUse(clicker: Player, type: ActionType, x: Int, y: Int, size: GUISize): Boolean = false }
0
Kotlin
0
3
2d84db3566dd791861c340438d5db3d7ee9cf503
760
piggies
MIT License
app/src/main/java/com/appbusters/robinpc/constitutionofindia/ui/intermediate/adapter/MiddleListAdapter.kt
kumar4Vipul
213,992,183
false
{"XML": 69, "Gradle": 3, "Java Properties": 2, "Text": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Ignore List": 1, "Java": 2, "Kotlin": 83}
package com.appbusters.robinpc.constitutionofindia.ui.intermediate.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.appbusters.robinpc.constitutionofindia.R import com.appbusters.robinpc.constitutionofindia.data.model.Part import com.appbusters.robinpc.constitutionofindia.ui.intermediate.adapter.holder.MiddleHolder class MiddleListAdapter(comparator: DiffUtil.ItemCallback<Part>): ListAdapter<Part, MiddleHolder>(comparator), MiddleHolder.PartClickedListener { private lateinit var partClickListener: OnPartClickListener override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MiddleHolder { return MiddleHolder(LayoutInflater.from(parent.context) .inflate(R.layout.row_middle_list, parent, false)) } override fun onBindViewHolder(holder: MiddleHolder, position: Int) { getItem(position)?.let { holder.setPart(it) holder.setPartClickListener(this) } } fun setPartClickListener(partClickListener: OnPartClickListener) { this.partClickListener = partClickListener } override fun onPartClicked(part: Part) { partClickListener.onPartClicked(part) } interface OnPartClickListener { fun onPartClicked(part: Part) } }
1
null
1
1
82a916316ac6822023392991f1efc74ff2ed571f
1,399
Indian-Constitution-App
Apache License 2.0
supports/foundation/nativeBridge/nativeBridge-annotation/src/commonMain/kotlin/com.subscribe.nativebridge/event/EventHandler.kt
xiezhihua120
716,495,624
false
{"Kotlin": 40223, "Swift": 342, "Shell": 124}
package com.subscribe.nativebridge.event /** * Created on 2023/9/25 * @author:xiezh * @function:事件容器 */ interface EventHandler { /** * JS处理模块 */ val module: String /** * JS处理方法 */ val method: String /** * 发送事件 */ fun send( reqId: String, module: String, method: String, data: ByteArray ) }
0
Kotlin
0
0
6c5948c66f41f43040b6967ae4c9d62f42ac03de
386
KmpProject
Apache License 2.0
AgoraEduUIKit/src/main/java/com/agora/edu/component/teachaids/component/AgoraEduTeachAidContainerComponent.kt
AgoraIO-Community
330,886,965
false
null
package com.agora.edu.component.teachaids.component import android.content.Context import android.os.Looper import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.ViewGroup import android.view.ViewTreeObserver import android.widget.LinearLayout import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.UNSET import androidx.core.content.ContextCompat import com.agora.edu.component.common.AbsAgoraEduConfigComponent import com.agora.edu.component.common.IAgoraUIProvider import com.agora.edu.component.teachaids.AgoraTeachAidCountDownWidget import com.agora.edu.component.teachaids.AgoraTeachAidIClickerWidget import com.agora.edu.component.teachaids.AgoraTeachAidWidgetActiveStateChangeData import com.agora.edu.component.teachaids.AgoraTeachAidWidgetInteractionPacket import com.agora.edu.component.teachaids.AgoraTeachAidWidgetInteractionSignal.ActiveState import com.agora.edu.component.teachaids.AgoraTeachAidWidgetInteractionSignal.NeedRelayout import com.agora.edu.component.teachaids.vote.AgoraTeachAidVoteWidget import io.agora.agoraeducore.core.context.EduContextRoomInfo import io.agora.agoraeducore.core.internal.framework.impl.handler.RoomHandler import io.agora.agoraeducore.core.internal.framework.impl.managers.AgoraWidgetActiveObserver import io.agora.agoraeducore.core.internal.framework.utils.GsonUtil import io.agora.agoraeducore.core.internal.log.LogX import io.agora.agoraeducore.core.internal.transport.AgoraTransportEvent import io.agora.agoraeducore.core.internal.transport.AgoraTransportEventId.* import io.agora.agoraeducore.core.internal.transport.AgoraTransportManager import io.agora.agoraeducore.core.internal.transport.OnAgoraTransportListener import io.agora.agoraeducore.extensions.widgets.AgoraBaseWidget import io.agora.agoraeducore.extensions.widgets.bean.AgoraWidgetDefaultId.* import io.agora.agoraeducore.extensions.widgets.bean.AgoraWidgetMessageObserver import io.agora.agoraeduuikit.config.FcrUIConfig import io.agora.agoraeduuikit.databinding.AgoraEduTeachAidContainerComponentBinding /** * author : cjw * date : 2022/2/16 * description : */ class AgoraEduTeachAidContainerComponent : AbsAgoraEduConfigComponent<FcrUIConfig>, OnAgoraTransportListener { private val tag = "AgoraEduTeachAidsContainerComponent" constructor(context: Context) : super(context) constructor(context: Context, attr: AttributeSet) : super(context, attr) constructor(context: Context, attr: AttributeSet, defStyleAttr: Int) : super(context, attr, defStyleAttr) private val binding = AgoraEduTeachAidContainerComponentBinding.inflate( LayoutInflater.from(context), this, true ) private val teachAidWidgets = mutableMapOf<String, AgoraBaseWidget>() private val widgetActiveObserver = object : AgoraWidgetActiveObserver { override fun onWidgetActive(widgetId: String) { createWidget(widgetId) } override fun onWidgetInActive(widgetId: String) { destroyWidget(widgetId) } } // listen msg of countDownWidget closeSelf private val teachAidWidgetMsgObserver = object : AgoraWidgetMessageObserver { override fun onMessageReceived(msg: String, id: String) { val packet = GsonUtil.jsonToObject<AgoraTeachAidWidgetInteractionPacket>(msg) packet?.let { when (packet.signal) { ActiveState -> {//设置active状态,是否关闭当前widget: 0关闭 1激活 val data = GsonUtil.jsonToObject<AgoraTeachAidWidgetActiveStateChangeData>(packet.body.toString()) if (data?.active == true) { //老师端设置widget的active状态 eduContext?.widgetContext()?.setWidgetActive(widgetId = id, roomProperties = data.properties) return } //处理inactive的情况 // if widget is countdown/iclicker/vote, remove widget and its data. eduContext?.widgetContext()?.setWidgetInActive(widgetId = id, isRemove = true) } NeedRelayout -> { // only the vote needs to be relayout, because it contain a recyclerView. if (id == Polling.id) { widgetDirectParentLayoutListener[id]?.let { relayoutWidget(binding.root, it.first, id) } } else { } } } } } } // listen joinRoomSuccess event private val roomHandler = object : RoomHandler() { override fun onJoinRoomSuccess(roomInfo: EduContextRoomInfo) { super.onJoinRoomSuccess(roomInfo) // check widget init status if (eduContext?.widgetContext()?.getWidgetActive(CountDown.id) == true) { createWidget(CountDown.id) } if (eduContext?.widgetContext()?.getWidgetActive(Selector.id) == true) { createWidget(Selector.id) } if (eduContext?.widgetContext()?.getWidgetActive(Polling.id) == true) { createWidget(Polling.id) } if (eduContext?.widgetContext()?.getWidgetActive(AgoraCloudDisk.id) == true) { createWidget(AgoraCloudDisk.id) } } } private fun createWidget(widgetId: String) { if (teachAidWidgets.contains(widgetId)) { LogX.w(tag, "'$widgetId' is already created, can not repeat create!") return } when (widgetId) {//for scene builder CountDown.id -> { if (!getUIConfig().counter.isVisible) { return } } Selector.id -> { if (!getUIConfig().popupQuiz.isVisible) { return } } Polling.id -> { if (!getUIConfig().poll.isVisible) { return } } } LogX.w(tag, "create teachAid that of '$widgetId'") val widgetConfig = eduContext?.widgetContext()?.getWidgetConfig(widgetId) widgetConfig?.let { config -> val widget = eduContext?.widgetContext()?.create(config) widget?.let { LogX.w(tag, "successfully created '$widgetId'") when (widgetId) { CountDown.id -> { (it as? AgoraTeachAidCountDownWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.addWidgetMessageObserver(observer, widgetId) } } Selector.id -> { (it as? AgoraTeachAidIClickerWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.addWidgetMessageObserver(observer, widgetId) } } Polling.id -> { (it as? AgoraTeachAidVoteWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.addWidgetMessageObserver(observer, widgetId) } } } // record widget teachAidWidgets[widgetId] = widget // create widgetContainer and add to binding.root(allWidgetsContainer) val widgetContainer = managerWidgetsContainer(allWidgetsContainer = binding.root, widgetId = widgetId) LogX.i(tag, "successfully created '$widgetId' container") widgetContainer?.let { group -> LogX.w(tag, "initialize '$widgetId'") // init widget ui widget.init(group) } } } } /** * 新增widget只用传前两个参数 * 删除widget全部参数都传 */ private fun managerWidgetsContainer( allWidgetsContainer: ViewGroup, widgetId: String, willRemovedWidgetDirectParent: ViewGroup? = null ): ViewGroup? { return if (willRemovedWidgetDirectParent == null) { // widget's direct parentView val widgetDirectParent = LinearLayout(context) val params = layoutWidgetDirectParent(allWidgetsContainer, widgetDirectParent, widgetId) ContextCompat.getMainExecutor(context).execute { allWidgetsContainer.addView(widgetDirectParent, params) } widgetDirectParent } else { widgetDirectParentLayoutListener[widgetId]?.second?.let { willRemovedWidgetDirectParent.viewTreeObserver.removeOnGlobalLayoutListener(it) } widgetDirectParentLayoutListener.remove(widgetId) ContextCompat.getMainExecutor(context).execute { allWidgetsContainer.removeView(willRemovedWidgetDirectParent) } null } } // key: widgetId value: whether to actively change the position of widget(or widget direct parentView) private val changeWidgetPositionBySelf = mutableMapOf<String, Boolean>() private val widgetDirectParentLayoutListener = mutableMapOf<String, Pair<ViewGroup, ViewTreeObserver.OnGlobalLayoutListener>>() /** * layout widget's direct parentView position * @param widgetDirectParent widget's direct parentView * @param widgetId */ private fun layoutWidgetDirectParent( allWidgetsContainer: ViewGroup, widgetDirectParent: LinearLayout, widgetId: String ): ConstraintLayout.LayoutParams { widgetDirectParent.gravity = Gravity.CENTER val params = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT ) params.startToStart = allWidgetsContainer.id params.topToTop = allWidgetsContainer.id // default center params.endToEnd = allWidgetsContainer.id params.bottomToBottom = allWidgetsContainer.id // try to get widgetDirectParent's width/height and relayout it val layoutListener = object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (widgetDirectParent.width > 0 && widgetDirectParent.height > 0) { // 当本次onGlobalLayout回掉是由于主动改变layoutParams导致的时,则忽略 if (changeWidgetPositionBySelf[widgetId] == true) { changeWidgetPositionBySelf[widgetId] = false return } changeWidgetPositionBySelf[widgetId] = true relayoutWidget(allWidgetsContainer, widgetDirectParent, widgetId) } } } widgetDirectParent.viewTreeObserver.addOnGlobalLayoutListener(layoutListener) // record for remove widgetDirectParentLayoutListener[widgetId] = Pair(widgetDirectParent, layoutListener) return params } private fun relayoutWidget(allWidgetsContainer: ViewGroup, widgetDirectParent: ViewGroup, widgetId: String) { // make sure frame info is latest; if frame is not empty, // update widgetDirectParent position follow frame val frame = eduContext?.widgetContext()?.getWidgetSyncFrame(widgetId) ?: return val medWidth = allWidgetsContainer.width - (widgetDirectParent.width ?: 0) val medHeight = allWidgetsContainer.height - (widgetDirectParent.height ?: 0) val left = medWidth * frame.x!! val top = medHeight * frame.y!! LogX.i( "$tag->parentWidth:${allWidgetsContainer.width}, parentHeight:${allWidgetsContainer.height}, " + "width:${widgetDirectParent.width}, height:${widgetDirectParent.height}, " + "medWidth:$medWidth, medHeight:$medHeight" ) val params = widgetDirectParent.layoutParams as? ConstraintLayout.LayoutParams params?.endToEnd = UNSET params?.bottomToBottom = UNSET params?.leftMargin = left.toInt() params?.topMargin = top.toInt() if (Thread.currentThread().id != Looper.getMainLooper().thread.id) { widgetDirectParent.layoutParams = params } else { ContextCompat.getMainExecutor(context).execute { widgetDirectParent.layoutParams = params } } } private fun destroyWidget(widgetId: String) { // remove from map val widget = teachAidWidgets.remove(widgetId) // remove UIDataProviderListener when (widgetId) { CountDown.id -> { (widget as? AgoraTeachAidCountDownWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, widgetId) } } Selector.id -> { (widget as? AgoraTeachAidIClickerWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, widgetId) } } Polling.id -> { (widget as? AgoraTeachAidVoteWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, widgetId) } } AgoraCloudDisk.id -> { (widget as? AgoraTeachAidVoteWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, widgetId) } } } widget?.let { widget -> ContextCompat.getMainExecutor(binding.root.context).execute { widget.release() widget.container?.let { group -> managerWidgetsContainer(binding.root, widgetId, group) } } } } init { AgoraTransportManager.addListener(EVENT_ID_TOOL_COUNTDOWN, this) AgoraTransportManager.addListener(EVENT_ID_TOOL_SELECTOR, this) AgoraTransportManager.addListener(EVENT_ID_TOOL_POLLING, this) AgoraTransportManager.addListener(EVENT_ID_TOOL_CLOUD, this) } override fun initView(agoraUIProvider: IAgoraUIProvider) { super.initView(agoraUIProvider) eduContext?.roomContext()?.addHandler(roomHandler) addAndRemoveActiveObserver() eduContext?.widgetContext()?.addWidgetMessageObserver(teachAidWidgetMsgObserver, CountDown.id) eduContext?.widgetContext()?.addWidgetMessageObserver(teachAidWidgetMsgObserver, Selector.id) eduContext?.widgetContext()?.addWidgetMessageObserver(teachAidWidgetMsgObserver, Polling.id) // eduContext?.widgetContext()?.addWidgetMessageObserver(teachAidWidgetMsgObserver, AgoraCloudDisk.id) } override fun release() { super.release() eduContext?.roomContext()?.removeHandler(roomHandler) teachAidWidgets.forEach { // remove UIDataProviderListener when (it.key) { CountDown.id -> { (it.value as? AgoraTeachAidCountDownWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, CountDown.id) } } Selector.id -> { (it.value as? AgoraTeachAidIClickerWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, Selector.id) } } Polling.id -> { (it.value as? AgoraTeachAidVoteWidget)?.getWidgetMsgObserver()?.let { observer -> eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, Polling.id) } } // AgoraCloudDisk.id -> { // (it.value as? AgoraVoteWidget)?.getWidgetMsgObserver()?.let { observer -> // eduContext?.widgetContext()?.removeWidgetMessageObserver(observer, AgoraCloudDisk.id) // } // } } it.value.release() } teachAidWidgets.clear() addAndRemoveActiveObserver(add = false) AgoraTransportManager.removeListener(EVENT_ID_TOOL_COUNTDOWN) AgoraTransportManager.removeListener(EVENT_ID_TOOL_SELECTOR) AgoraTransportManager.removeListener(EVENT_ID_TOOL_POLLING) AgoraTransportManager.removeListener(EVENT_ID_TOOL_CLOUD) // clear data about position changeWidgetPositionBySelf.clear() widgetDirectParentLayoutListener.forEach { it.value.first.viewTreeObserver.removeOnGlobalLayoutListener(it.value.second) } widgetDirectParentLayoutListener.clear() } private fun addAndRemoveActiveObserver(add: Boolean = true) { if (add) { eduContext?.widgetContext()?.addWidgetActiveObserver(widgetActiveObserver, CountDown.id) eduContext?.widgetContext()?.addWidgetActiveObserver(widgetActiveObserver, Selector.id) eduContext?.widgetContext()?.addWidgetActiveObserver(widgetActiveObserver, Polling.id) eduContext?.widgetContext()?.addWidgetActiveObserver(widgetActiveObserver, AgoraCloudDisk.id) } else { eduContext?.widgetContext()?.removeWidgetActiveObserver(widgetActiveObserver, CountDown.id) eduContext?.widgetContext()?.removeWidgetActiveObserver(widgetActiveObserver, Selector.id) eduContext?.widgetContext()?.removeWidgetActiveObserver(widgetActiveObserver, Polling.id) eduContext?.widgetContext()?.removeWidgetActiveObserver(widgetActiveObserver, AgoraCloudDisk.id) } } override fun onTransport(event: AgoraTransportEvent) { when (event.eventId) { EVENT_ID_TOOL_COUNTDOWN -> { createWidget(CountDown.id) } EVENT_ID_TOOL_SELECTOR -> { createWidget(Selector.id) } EVENT_ID_TOOL_POLLING -> { createWidget(Polling.id) } EVENT_ID_TOOL_CLOUD -> { handleCloudDiskLifeCycle()//处理云盘点击事件,创建云盘widget } else -> { LogX.e(tag, "receive unexpected event: ${GsonUtil.toJson(event)}") } } } /** * 管理云盘生命周期 * 当cloudDiskWidget实例不存在时,直接新建;如果存在则设置widget的container课件(不可见的设置是cloudDiskWidget自身设置的) * manager cloudDiskWidget's lifeCycle * if the instance of cloudDiskWidget not exists in local, create it; but if it exists, set the container of * cloudDiskWidget visibility is VISIBLE */ private fun handleCloudDiskLifeCycle() { if (teachAidWidgets.contains(AgoraCloudDisk.id)) { LogX.i(tag, "AgoraCloudWidget is exists in local, set container visibility is VISIBLE!") teachAidWidgets[AgoraCloudDisk.id]?.container?.visibility = VISIBLE return } createWidget(AgoraCloudDisk.id) } override fun updateUIForConfig(config: FcrUIConfig) { } override fun getUIConfig(): FcrUIConfig { return getTemplateUIConfig() } }
5
Kotlin
19
8
9fb07495275f2da4aa0b579005c7eacfd444defb
19,643
CloudClass-Android
MIT License
data/src/commonMain/kotlin/io/gaitian/telekot/data/model/InputMediaPhoto.kt
galik-ya
668,662,208
false
null
package io.gaitian.telekot.data.model import kotlinx.serialization.Serializable /** * Represents a photo to be sent * * @see <a href="https://core.telegram.org/bots/api#inputmediaphoto">Telegram Bot API | InputMediaPhoto</a> */ @Serializable data class InputMediaPhoto( override val media: String, override val caption: String?, override val parseMode: String?, override val captionEntities: List<MessageEntity>?, /** * Pass True if the photo needs to be covered with a spoiler animation */ val hasSpoiler: Boolean? ): InputMedia { override val type = InputMedia.Type.PHOTO }
0
Kotlin
0
0
fb8f376eb9f2322622aec3a4aa305fcf169a2e08
626
telekot
Apache License 2.0
app/src/main/java/com/android/vocab/provider/bean/AntonymWord.kt
adityaDave2017
97,935,213
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Proguard": 1, "Java": 3, "XML": 29, "Kotlin": 24, "SQL": 1}
package com.android.vocab.provider.bean import android.os.Parcel import android.os.Parcelable @Suppress("unused") class AntonymWord(wordId: Long, word: String, typeId: Long, meaning: String, frequency: Int, createTime: Long, lastAccessTime: Long, val antonymId: Long ): Word(wordId, word, typeId, meaning, frequency, createTime, lastAccessTime) { constructor(parcel: Parcel) : this( parcel.readLong(), parcel.readString(), parcel.readLong(), parcel.readString(), parcel.readInt(), parcel.readLong(), parcel.readLong(), parcel.readLong() ) override fun writeToParcel(parcel: Parcel, flags: Int) { super.writeToParcel(parcel, flags) parcel.writeLong(antonymId) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<SynonymWord> { override fun createFromParcel(parcel: Parcel): SynonymWord { return SynonymWord(parcel) } override fun newArray(size: Int): Array<SynonymWord?> { return arrayOfNulls(size) } } }
1
null
1
1
5b760d3ac0ddbbc312a83c70f2bcf5ed727b5895
1,297
my-vocab
MIT License