path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/volovyk/guerrillamail/data/emails/remote/mailtm/entity/Message.kt
oleksandrvolovyk
611,731,548
false
{"Kotlin": 158288, "Java": 767}
package volovyk.guerrillamail.data.emails.remote.mailtm.entity import volovyk.guerrillamail.data.emails.model.Email import volovyk.guerrillamail.util.Base64Encoder import java.util.Date data class Message( val id: String, val from: From, val text: String?, val html: List<String>?, val subject: String, val createdAt: Date ) { data class From( val address: String, val name: String? ) } fun Message.toEmail(base64Encoder: Base64Encoder) = Email( id = this.id, from = this.from.address, subject = this.subject, body = this.text ?: "", htmlBody = base64Encoder.encodeToBase64String(this.html?.getOrNull(0) ?: ""), date = this.createdAt.toString(), viewed = false )
0
Kotlin
0
1
0e204bb437a6cfd837cd0bb911a29f0fc43164ce
741
guerrilla-mail-android-client
MIT License
src/main/kotlin/ee/ut/lahendus/intellij/LahendusProjectActionNotifier.kt
alexisalliksaar
777,245,963
false
{"Kotlin": 88105, "HTML": 2311}
package ee.ut.lahendus.intellij import com.intellij.util.messages.Topic import ee.ut.lahendus.intellij.data.CourseExercise import ee.ut.lahendus.intellij.data.DetailedExercise import ee.ut.lahendus.intellij.data.Submission interface LahendusProjectActionNotifier { fun courseExercises(courseExercises: List<CourseExercise>?) {} fun detailedExercise(detailedExercise: DetailedExercise) {} fun latestSubmissionOrNull(submission: Submission?) {} fun awaitLatestSubmission(detailedExercise: DetailedExercise, submission: Submission) {} fun solutionSubmittedSuccessfully() {} fun requestFailed(message: String) {} fun networkErrorMessage() {} companion object { @Topic.ProjectLevel val LAHENDUS_PROJECT_ACTION_TOPIC : Topic<LahendusProjectActionNotifier> = Topic.create( "Lahendus api project topic", LahendusProjectActionNotifier::class.java ) } }
0
Kotlin
0
0
6e3a722d26e4207ada806dd2283a3a628998e455
957
lahendus-intellij-plugin
MIT License
app/src/main/java/com/se7en/jetmessenger/viewmodels/StoryViewModel.kt
ashar-7
297,098,336
false
null
package com.se7en.jetmessenger.viewmodels import androidx.compose.runtime.mutableStateMapOf import androidx.lifecycle.ViewModel import com.se7en.jetmessenger.data.models.Story import com.se7en.jetmessenger.data.models.StoryStatus import com.se7en.jetmessenger.data.models.User import kotlin.random.Random class StoryViewModel: ViewModel() { val stories = mutableStateMapOf<User, Story>() fun getStories(users: List<User>) = users.map { user -> getStory(user) }.sortedWith { o1, o2 -> // sort the list so that the unseen stories appear first return@sortedWith when { o1.status == o2.status -> 0 o1.status == StoryStatus.AVAILABLE_NOT_SEEN -> -1 o2.status == StoryStatus.AVAILABLE_NOT_SEEN -> 1 else -> 0 } } fun updateStoryStatus(user: User, newStatus: StoryStatus) { getStory(user).status = newStatus } private fun getStory(user: User) = stories.getOrPut(user, { val id = Random.nextInt(1, 1000) val hour = Random.nextInt(1, 24) Story( user = user, status = StoryStatus.AVAILABLE_NOT_SEEN, imageUrl = "https://picsum.photos/id/$id/300/300", thumbnailUrl = "https://picsum.photos/id/$id/100/150", time = "${hour}h" ) }) }
1
Kotlin
14
93
e5a973f67034be4b9610dc88abc70992d833f750
1,415
JetMessenger
Apache License 2.0
src/main/kotlin/com/github/goldsubmarine/restfulhelper/contributor/KotlinRequestMappingContributor.kt
GoldSubmarine
394,201,620
false
null
package com.viartemev.requestmapper.contributor import com.intellij.openapi.project.Project import com.intellij.psi.PsiAnnotation import com.intellij.psi.search.GlobalSearchScope.projectScope import org.jetbrains.kotlin.asJava.toLightAnnotation import org.jetbrains.kotlin.idea.stubindex.KotlinAnnotationsIndex class KotlinRequestMappingContributor : RequestMappingByNameContributor() { override fun getAnnotationSearchers(annotationName: String, project: Project): Sequence<PsiAnnotation> { return KotlinAnnotationsIndex .getInstance() .get(annotationName, project, projectScope(project)) .asSequence() .mapNotNull { it.toLightAnnotation() } } }
9
null
6
9
9d187542a38548a353625ea06201075d001ef8b9
714
RestfulHelper
MIT License
app/src/main/java/com/kcteam/features/login/api/global_config/ConfigFetchApi.kt
DebashisINT
558,234,039
false
null
package com.breezefieldsaleszazuteam.features.login.api.global_config import com.breezefieldsaleszazuteam.app.NetworkConstant import com.breezefieldsaleszazuteam.features.login.model.globalconfig.ConfigFetchResponseModel import io.reactivex.Observable import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.POST /** * Created by Saikat on 14-01-2019. */ interface ConfigFetchApi { @POST("Configuration/fetch") fun getConfigResponse(): Observable<ConfigFetchResponseModel> /** * Companion object to create the GithubApiService */ companion object Factory { fun create(): ConfigFetchApi { val retrofit = Retrofit.Builder() .client(NetworkConstant.setTimeOut()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(NetworkConstant.BASE_URL) .build() return retrofit.create(ConfigFetchApi::class.java) } } }
0
null
1
1
e6114824d91cba2e70623631db7cbd9b4d9690ed
1,152
NationalPlastic
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/core/adapters/BitcoinBaseAdapter.kt
horizontalsystems
142,825,178
false
null
package io.deus.wallet.core.adapters import io.deus.wallet.core.AdapterState import io.deus.wallet.core.AppLogger import io.deus.wallet.core.BalanceData import io.deus.wallet.core.IAdapter import io.deus.wallet.core.IBalanceAdapter import io.deus.wallet.core.IReceiveAdapter import io.deus.wallet.core.ITransactionsAdapter import io.deus.wallet.core.UnsupportedFilterException import io.deus.wallet.entities.LastBlockInfo import io.deus.wallet.entities.TransactionDataSortMode import io.deus.wallet.entities.Wallet import io.deus.wallet.entities.transactionrecords.TransactionRecord import io.deus.wallet.entities.transactionrecords.bitcoin.BitcoinIncomingTransactionRecord import io.deus.wallet.entities.transactionrecords.bitcoin.BitcoinOutgoingTransactionRecord import io.deus.wallet.entities.transactionrecords.bitcoin.BitcoinTransactionRecord import io.deus.wallet.modules.transactions.FilterTransactionType import io.deus.wallet.modules.transactions.TransactionLockInfo import io.horizontalsystems.bitcoincore.AbstractKit import io.horizontalsystems.bitcoincore.BitcoinCore import io.horizontalsystems.bitcoincore.core.IPluginData import io.horizontalsystems.bitcoincore.models.Address import io.horizontalsystems.bitcoincore.models.TransactionDataSortType import io.horizontalsystems.bitcoincore.models.TransactionFilterType import io.horizontalsystems.bitcoincore.models.TransactionInfo import io.horizontalsystems.bitcoincore.models.TransactionStatus import io.horizontalsystems.bitcoincore.models.TransactionType import io.horizontalsystems.bitcoincore.rbf.ReplacementTransaction import io.horizontalsystems.bitcoincore.rbf.ReplacementTransactionInfo import io.horizontalsystems.bitcoincore.storage.FullTransaction import io.horizontalsystems.bitcoincore.storage.UnspentOutput import io.horizontalsystems.bitcoincore.storage.UnspentOutputInfo import io.horizontalsystems.core.BackgroundManager import io.horizontalsystems.hodler.HodlerOutputData import io.horizontalsystems.hodler.HodlerPlugin import io.horizontalsystems.marketkit.models.Token import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.subjects.PublishSubject import java.math.BigDecimal import java.math.RoundingMode import java.util.Date abstract class BitcoinBaseAdapter( open val kit: AbstractKit, open val syncMode: BitcoinCore.SyncMode, backgroundManager: BackgroundManager, val wallet: Wallet, private val confirmationsThreshold: Int, protected val decimal: Int = 8 ) : IAdapter, ITransactionsAdapter, IBalanceAdapter, IReceiveAdapter, BackgroundManager.Listener { init { backgroundManager.registerListener(this) } abstract val satoshisInBitcoin: BigDecimal override fun willEnterForeground() { super.willEnterForeground() kit.onEnterForeground() } override fun didEnterBackground() { super.didEnterBackground() kit.onEnterBackground() } // // Adapter implementation // private var syncState: AdapterState = AdapterState.Syncing() set(value) { if (value != field) { field = value adapterStateUpdatedSubject.onNext(Unit) } } override val transactionsState get() = syncState override val balanceState get() = syncState override val lastBlockInfo: LastBlockInfo? get() = kit.lastBlockInfo?.let { LastBlockInfo(it.height, it.timestamp) } override val receiveAddress: String get() = kit.receiveAddress() override val isMainNet: Boolean = true protected val balanceUpdatedSubject: PublishSubject<Unit> = PublishSubject.create() protected val lastBlockUpdatedSubject: PublishSubject<Unit> = PublishSubject.create() protected val adapterStateUpdatedSubject: PublishSubject<Unit> = PublishSubject.create() protected val transactionRecordsSubject: PublishSubject<List<TransactionRecord>> = PublishSubject.create() override val balanceUpdatedFlowable: Flowable<Unit> get() = balanceUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override val lastBlockUpdatedFlowable: Flowable<Unit> get() = lastBlockUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override val transactionsStateUpdatedFlowable: Flowable<Unit> get() = adapterStateUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override val balanceStateUpdatedFlowable: Flowable<Unit> get() = adapterStateUpdatedSubject.toFlowable(BackpressureStrategy.BUFFER) override fun getTransactionRecordsFlowable( token: Token?, transactionType: FilterTransactionType, address: String?, ): Flowable<List<TransactionRecord>> = when (address) { null -> getTransactionRecordsFlowable(token, transactionType) else -> Flowable.empty() } private fun getTransactionRecordsFlowable(token: Token?, transactionType: FilterTransactionType): Flowable<List<TransactionRecord>> { val observable: Observable<List<TransactionRecord>> = when (transactionType) { FilterTransactionType.All -> { transactionRecordsSubject } FilterTransactionType.Incoming -> { transactionRecordsSubject .map { records -> records.filter { it is BitcoinIncomingTransactionRecord || (it is BitcoinOutgoingTransactionRecord && it.sentToSelf) } } .filter { it.isNotEmpty() } } FilterTransactionType.Outgoing -> { transactionRecordsSubject .map { records -> records.filter { it is BitcoinOutgoingTransactionRecord } } .filter { it.isNotEmpty() } } FilterTransactionType.Swap, FilterTransactionType.Approve -> { Observable.empty() } } return observable.toFlowable(BackpressureStrategy.BUFFER) } override val debugInfo: String = "" override val balanceData: BalanceData get() = BalanceData(balance, balanceTimeLocked, balanceNotRelayed) private val balance: BigDecimal get() = satoshiToBTC(kit.balance.spendable) private val balanceTimeLocked: BigDecimal get() = satoshiToBTC(kit.balance.unspendableTimeLocked) private val balanceNotRelayed: BigDecimal get() = satoshiToBTC(kit.balance.unspendableNotRelayed) override fun start() { kit.start() } override fun stop() { kit.stop() } override fun refresh() { kit.refresh() } override fun getTransactionsAsync( from: TransactionRecord?, token: Token?, limit: Int, transactionType: FilterTransactionType, address: String?, ) = when (address) { null -> getTransactionsAsync(from, token, limit, transactionType) else -> Single.just(listOf()) } private fun getTransactionsAsync( from: TransactionRecord?, token: Token?, limit: Int, transactionType: FilterTransactionType ): Single<List<TransactionRecord>> { return try { kit.transactions(from?.uid, getBitcoinTransactionTypeFilter(transactionType), limit).map { it.map { tx -> transactionRecord(tx) } } } catch (e: UnsupportedFilterException) { Single.just(listOf()) } } private fun getBitcoinTransactionTypeFilter(transactionType: FilterTransactionType): TransactionFilterType? { return when (transactionType) { FilterTransactionType.All -> null FilterTransactionType.Incoming -> TransactionFilterType.Incoming FilterTransactionType.Outgoing -> TransactionFilterType.Outgoing else -> throw UnsupportedFilterException() } } override fun getRawTransaction(transactionHash: String): String? { return kit.getRawTransaction(transactionHash) } fun speedUpTransactionInfo(transactionHash: String): ReplacementTransactionInfo? { return kit.speedUpTransactionInfo(transactionHash) } fun cancelTransactionInfo(transactionHash: String): ReplacementTransactionInfo? { return kit.cancelTransactionInfo(transactionHash) } fun speedUpTransaction(transactionHash: String, minFee: Long): Pair<ReplacementTransaction, BitcoinTransactionRecord> { val replacement = kit.speedUpTransaction(transactionHash, minFee) return Pair(replacement, transactionRecord(replacement.info)) } fun cancelTransaction(transactionHash: String, minFee: Long): Pair<ReplacementTransaction, BitcoinTransactionRecord> { val replacement = kit.cancelTransaction(transactionHash, minFee) return Pair(replacement, transactionRecord(replacement.info)) } fun send(replacementTransaction: ReplacementTransaction): FullTransaction { return kit.send(replacementTransaction) } protected fun setState(kitState: BitcoinCore.KitState) { syncState = when (kitState) { is BitcoinCore.KitState.Synced -> { AdapterState.Synced } is BitcoinCore.KitState.NotSynced -> { AdapterState.NotSynced(kitState.exception) } is BitcoinCore.KitState.ApiSyncing -> { AdapterState.SearchingTxs(kitState.transactions) } is BitcoinCore.KitState.Syncing -> { val progress = (kitState.progress * 100).toInt() val lastBlockDate = if (syncMode is BitcoinCore.SyncMode.Blockchair) null else kit.lastBlockInfo?.timestamp?.let { Date(it * 1000) } AdapterState.Syncing(progress, lastBlockDate) } } } fun send( amount: BigDecimal, address: String, memo: String?, feeRate: Int, unspentOutputs: List<UnspentOutputInfo>?, pluginData: Map<Byte, IPluginData>?, transactionSorting: TransactionDataSortMode?, rbfEnabled: Boolean, logger: AppLogger ): Single<Unit> { val sortingType = getTransactionSortingType(transactionSorting) return Single.create { emitter -> try { logger.info("call btc-kit.send") kit.send( address = address, memo = memo, value = (amount * satoshisInBitcoin).toLong(), senderPay = true, feeRate = feeRate, sortType = sortingType, unspentOutputs = unspentOutputs, pluginData = pluginData ?: mapOf(), rbfEnabled = rbfEnabled ) emitter.onSuccess(Unit) } catch (ex: Exception) { emitter.onError(ex) } } } fun availableBalance( feeRate: Int, address: String?, memo: String?, unspentOutputs: List<UnspentOutputInfo>?, pluginData: Map<Byte, IPluginData>? ): BigDecimal { return try { val maximumSpendableValue = kit.maximumSpendableValue(address, memo, feeRate, unspentOutputs, pluginData ?: mapOf()) satoshiToBTC(maximumSpendableValue, RoundingMode.CEILING) } catch (e: Exception) { BigDecimal.ZERO } } fun minimumSendAmount(address: String?): BigDecimal? { return try { satoshiToBTC(kit.minimumSpendableValue(address).toLong(), RoundingMode.CEILING) } catch (e: Exception) { null } } fun bitcoinFeeInfo( amount: BigDecimal, feeRate: Int, address: String?, memo: String?, unspentOutputs: List<UnspentOutputInfo>?, pluginData: Map<Byte, IPluginData>? ): BitcoinFeeInfo? { return try { val satoshiAmount = (amount * satoshisInBitcoin).toLong() kit.sendInfo( value = satoshiAmount, address = address, memo = memo, senderPay = true, feeRate = feeRate, unspentOutputs = unspentOutputs, pluginData = pluginData ?: mapOf() ).let { BitcoinFeeInfo( unspentOutputs = it.unspentOutputs, fee = satoshiToBTC(it.fee), changeValue = satoshiToBTC(it.changeValue), changeAddress = it.changeAddress ) } } catch (e: Exception) { null } } fun validate(address: String, pluginData: Map<Byte, IPluginData>?) { kit.validateAddress(address, pluginData ?: mapOf()) } fun transactionRecord(transaction: TransactionInfo): BitcoinTransactionRecord { val from = transaction.inputs.find { input -> input.address?.isNotBlank() == true }?.address var transactionLockInfo: TransactionLockInfo? = null val lockedOutput = transaction.outputs.firstOrNull { it.pluginId == HodlerPlugin.id } if (lockedOutput != null) { val hodlerOutputData = lockedOutput.pluginData as? HodlerOutputData hodlerOutputData?.approxUnlockTime?.let { approxUnlockTime -> val lockedValueBTC = satoshiToBTC(lockedOutput.value) transactionLockInfo = TransactionLockInfo( Date(approxUnlockTime * 1000), hodlerOutputData.addressString, lockedValueBTC, hodlerOutputData.lockTimeInterval ) } } val memo = transaction.outputs.firstOrNull { it.memo != null }?.memo return when (transaction.type) { TransactionType.Incoming -> { BitcoinIncomingTransactionRecord( source = wallet.transactionSource, token = wallet.token, uid = transaction.uid, transactionHash = transaction.transactionHash, transactionIndex = transaction.transactionIndex, blockHeight = transaction.blockHeight, confirmationsThreshold = confirmationsThreshold, timestamp = transaction.timestamp, fee = satoshiToBTC(transaction.fee), failed = transaction.status == TransactionStatus.INVALID, lockInfo = transactionLockInfo, conflictingHash = transaction.conflictingTxHash, showRawTransaction = transaction.status == TransactionStatus.NEW || transaction.status == TransactionStatus.INVALID, amount = satoshiToBTC(transaction.amount), from = from, memo = memo ) } TransactionType.Outgoing -> { val to = transaction.outputs.find { output -> output.value > 0 && output.address != null && !output.mine }?.address BitcoinOutgoingTransactionRecord( source = wallet.transactionSource, token = wallet.token, uid = transaction.uid, transactionHash = transaction.transactionHash, transactionIndex = transaction.transactionIndex, blockHeight = transaction.blockHeight, confirmationsThreshold = confirmationsThreshold, timestamp = transaction.timestamp, fee = satoshiToBTC(transaction.fee), failed = transaction.status == TransactionStatus.INVALID, lockInfo = transactionLockInfo, conflictingHash = transaction.conflictingTxHash, showRawTransaction = transaction.status == TransactionStatus.NEW || transaction.status == TransactionStatus.INVALID, amount = satoshiToBTC(transaction.amount).negate(), to = to, sentToSelf = false, memo = memo, replaceable = transaction.rbfEnabled && transaction.blockHeight == null && transaction.conflictingTxHash == null ) } TransactionType.SentToSelf -> { val to = transaction.outputs.firstOrNull { !it.changeOutput }?.address ?: transaction.outputs.firstOrNull()?.address BitcoinOutgoingTransactionRecord( source = wallet.transactionSource, token = wallet.token, uid = transaction.uid, transactionHash = transaction.transactionHash, transactionIndex = transaction.transactionIndex, blockHeight = transaction.blockHeight, confirmationsThreshold = confirmationsThreshold, timestamp = transaction.timestamp, fee = satoshiToBTC(transaction.fee), failed = transaction.status == TransactionStatus.INVALID, lockInfo = transactionLockInfo, conflictingHash = transaction.conflictingTxHash, showRawTransaction = transaction.status == TransactionStatus.NEW || transaction.status == TransactionStatus.INVALID, amount = satoshiToBTC(transaction.amount).negate(), to = to, sentToSelf = true, memo = memo, replaceable = transaction.rbfEnabled && transaction.blockHeight == null && transaction.conflictingTxHash == null ) } } } val statusInfo: Map<String, Any> get() = kit.statusInfo() private fun satoshiToBTC(value: Long, roundingMode: RoundingMode = RoundingMode.HALF_EVEN): BigDecimal { return BigDecimal(value).divide(satoshisInBitcoin, decimal, roundingMode) } private fun satoshiToBTC(value: Long?): BigDecimal? { return satoshiToBTC(value ?: return null) } companion object { fun getTransactionSortingType(sortType: TransactionDataSortMode?): TransactionDataSortType = when (sortType) { TransactionDataSortMode.Bip69 -> TransactionDataSortType.Bip69 else -> TransactionDataSortType.Shuffle } } } data class BitcoinFeeInfo( val unspentOutputs: List<UnspentOutput>, val fee: BigDecimal, val changeValue: BigDecimal?, val changeAddress: Address? )
191
null
363
879
27b9d133fb4afdf266f961585fe2ac27e51ec915
19,007
unstoppable-wallet-android
MIT License
library/src/main/java/just4fun/modularity/android/AndroidContainer.kt
just-4-fun
105,467,191
false
null
package just4fun.modularity.android import android.app.Activity import android.app.Application import android.app.Notification import android.app.Service import android.content.Intent import android.util.Log import just4fun.kotlinkit.* import just4fun.modularity.android.ActivityState.DESTROYED import just4fun.modularity.android.async.AndroidThreadContext import just4fun.modularity.android.async.AndroidThreadContextBuilder import just4fun.modularity.core.BaseModule import just4fun.modularity.core.ModuleContainer import just4fun.modularity.core.multisync.ThreadInfo.info import kotlin.reflect.KClass /* CONTAINER */ /** A module container for Android. * An instance should be created in [Application.onCreate] callback with the [Application] instance passed to the constructor as [appContext]. * * */ abstract class AndroidContainer(val appContext: Application): ModuleContainer() { /** The reference to the topmost [Activity] if any. */ val uiContext: Activity? get() = ui.primary // override val ThreadContexts by lazy { AndroidThreadContextBuilder() } internal val ui = ActivityTracker(this).apply { appContext.registerActivityLifecycleCallbacks(this) } internal var float: FloatManager? = null private val refs = mutableListOf<AndroidModuleReference<*>>()// no need to sync since is called from main thread private var reconfig: Boolean = false override val debugInfo: AndroidDebugInfo? = null init { DEBUG = isDebug() if (DEBUG) logFun = { priority, id, msg -> Log.println(priority, id.toString(), "${time} ${info.get()} [$id]:: $msg") } if (checkFloat()) float = FloatManager(this) } /** Instead of [onPopulated] */ open protected fun onContainerPopulated() {} /** Instead of [onEmpty] */ open protected fun onContainerEmpty() {} /** The callback captures most general UI events (events of all app's [Activity]s). See [UiPhase]. */ open protected fun onUiPhaseChange(phase: UiPhase) {} /** Puts the app into Foreground so that it wouldn't be killed by the system. The action is based on [Service.startForeground] and utilizes internal [FloatService]. */ fun startForeground(id: Int, notification: Notification) = float?.startForeground(id, notification) /** Puts the app back into Background. The action is based on [Service.stopForeground] and utilizes internal [FloatService]. */ fun stopForeground(removeNotification: Boolean) = float?.stopForeground(removeNotification) /* internal */ override fun <M: BaseModule> moduleReference(moduleKClass: KClass<M>, bindID: Any?): AndroidModuleReference<M> = AndroidModuleReference(moduleKClass, bindID) override fun onCreateThreadContext() = AndroidThreadContext(false).apply { ownerToken = this } internal fun uiPhaseChange(value: UiPhase) { if (value >= UiPhase.HIDDEN && !isEmpty) float?.start() Safely { onUiPhaseChange(value) } if (value <= UiPhase.SHOWN) float?.stop() } /** Use [onContainerPopulated] */ override final fun onPopulated() { if (ui.phase >= UiPhase.HIDDEN) float?.start() onContainerPopulated() } /** Use [onContainerEmpty] */ override final fun onEmpty() { onContainerEmpty() float?.stop() } internal fun activityStateChange(activity: Activity, primary: Boolean, state: ActivityState) { debugInfo?.onActivityStateChange(activity, primary, state.toString()) if (state == DESTROYED) { if (activity.isChangingConfigurations) { reconfig = true refs.forEach { if (it.activity == activity) it.activity = null } } else removeUiRef(activity) } else if (reconfig) { removeUiRef(null) reconfig = false } } /* Ui Ref mgt */ private fun removeUiRef(activity: Activity?) = refs.retainAll { (it.activity != activity).apply { if (!this) it.unbindModule() } } internal fun <M: UIModule<*>> addUiRef(activity: Activity, moduleKClass: KClass<M>, bindId: Any?): M { fun matches(ref: AndroidModuleReference<*>, a: Activity, c: KClass<*>, b: Any?) = ref.moduleKClass == c && ref.activity == a && ref.bindID == b // log("UiConns", "${refs.size}") @Suppress("UNCHECKED_CAST") return refs.find { matches(it, activity, moduleKClass, bindId) }?.module as? M ?: run { ui.onActivityCreating(activity) val ref = moduleReference(moduleKClass, bindId).apply { this.activity = activity } val module = ref.bindModule() refs += ref module } } /* misc */ private fun checkFloat(): Boolean { val clas: Class<*> = FloatService::class.java val intent = Intent(appContext, clas) val resolvers = appContext.packageManager.queryIntentServices(intent, 0) val registered = resolvers?.isNotEmpty() ?: false if (!registered) Safely { throw Exception("${clas.simpleName} service ensures application operation and needs to be declared in AndroidManifest.xml\n<service android:name=\"${clas.name}\"/>") } return registered } private fun isDebug() = Safely { val clas = Class.forName(appContext.packageName + ".BuildConfig") val valueF = clas.getDeclaredField("DEBUG") valueF.isAccessible = true valueF.getBoolean(null) } ?: false /* Reference */ open inner class AndroidModuleReference<M: BaseModule>(moduleKClass: KClass<M>, bindID: Any?): ModuleReference<M>(moduleKClass, bindID) { internal var activity: Any? = null } open inner class AndroidDebugInfo: DebugInfo() { // TODO open fun onActivityStateChange(activity: Activity, primary: Boolean, state: String) { // val reconfiguring = activity.isChangingConfigurations // val finishing = activity.isFinishing // val id = activity.hashCode().toString(16) // val reason = if (finishing) "finishing" else if (reconfiguring) "reconfiguring" else "other" // log("${activity::class.simpleName}", "id= $id; prim= $primary; reason= $reason; state= $state") } } }
0
Kotlin
0
1
97db4f732238098065ad71b7141f6bfa7a680bd0
5,786
modularity
Apache License 2.0
app/src/main/java/things/dev/MainActivityViewModel.kt
MasonFlint44
366,555,725
false
null
package things.dev import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import things.dev.wifi.WifiScanResult enum class FabAlignmentMode { CENTER, END, } class MainActivityViewModel : ViewModel() { val pageIndex: MutableLiveData<Int> by lazy { MutableLiveData<Int>(0) } val fabEnabled: MutableLiveData<Boolean> by lazy { MutableLiveData<Boolean>(false) } val fabAlignment: MutableLiveData<FabAlignmentMode> by lazy { MutableLiveData<FabAlignmentMode>(FabAlignmentMode.END) } val scanResults: MutableLiveData<List<WifiScanResult>> by lazy { MutableLiveData<List<WifiScanResult>>() } val loading: MutableLiveData<Boolean> by lazy { MutableLiveData<Boolean>(false) } }
0
Kotlin
0
0
ec79726ae0491aaba24b65f96f71665a4cbac36f
774
makethings-io-companion-app
Apache License 2.0
test_runner/src/main/kotlin/ftl/client/junit/CreateJUnitTestCase.kt
Flank
84,221,974
false
null
package ftl.reports.api import com.google.api.services.testing.model.ToolResultsStep import com.google.api.services.toolresults.model.StackTrace import com.google.api.services.toolresults.model.TestCase import ftl.reports.xml.model.JUnitTestCase internal fun createJUnitTestCases( testCases: List<TestCase>, toolResultsStep: ToolResultsStep, overheadTime: Double ): List<JUnitTestCase> = testCases.map { testCase -> createJUnitTestCase( testCase = testCase, toolResultsStep = toolResultsStep, overheadTime = overheadTime ) } private fun createJUnitTestCase( testCase: TestCase, toolResultsStep: ToolResultsStep, overheadTime: Double ): JUnitTestCase { val stackTraces = mapOf( testCase.status to testCase.stackTraces?.map(StackTrace::getException) ) return JUnitTestCase( name = testCase.testCaseReference.name, classname = testCase.testCaseReference.className, time = (testCase.elapsedTime.millis() + overheadTime).format(), failures = stackTraces["failed"], errors = stackTraces["error"], // skipped = true is represented by null. skipped = false is "absent" skipped = if (testCase.status == "skipped") null else "absent" ).apply { if (errors != null || failures != null) { webLink = getWebLink(toolResultsStep, testCase.testCaseId) } if (testCase.flaky) { flaky = true } } } private fun getWebLink(toolResultsStep: ToolResultsStep, testCaseId: String): String { return "https://console.firebase.google.com/project/${toolResultsStep.projectId}/" + "testlab/histories/${toolResultsStep.historyId}/" + "matrices/${toolResultsStep.executionId}/" + "executions/${toolResultsStep.stepId}/" + "testcases/$testCaseId" }
64
null
119
676
b40904b4e74a670cf72ee53dc666fc3a801e7a95
1,867
flank
Apache License 2.0
library/src/main/java/ru/yoomoney/sdk/kassa/payments/tokenize/TokenizeUseCaseImpl.kt
yoomoney
140,608,545
false
null
/* * The MIT License (MIT) * Copyright © 2021 NBCO YooMoney LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the “Software”), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package ru.yoomoney.sdk.kassa.payments.tokenize import ru.yoomoney.sdk.kassa.payments.model.AbstractWallet import ru.yoomoney.sdk.kassa.payments.model.NoConfirmation import ru.yoomoney.sdk.kassa.payments.model.PaymentOption import ru.yoomoney.sdk.kassa.payments.model.Result import ru.yoomoney.sdk.kassa.payments.model.SelectedOptionNotFoundException import ru.yoomoney.sdk.kassa.payments.model.WalletInfo import ru.yoomoney.sdk.kassa.payments.model.YooMoney import ru.yoomoney.sdk.kassa.payments.payment.CheckPaymentAuthRequiredGateway import ru.yoomoney.sdk.kassa.payments.payment.GetLoadedPaymentOptionListRepository import ru.yoomoney.sdk.kassa.payments.payment.tokenize.TokenizeInputModel import ru.yoomoney.sdk.kassa.payments.payment.tokenize.TokenizeInstrumentInputModel import ru.yoomoney.sdk.kassa.payments.payment.tokenize.TokenizeOutputModel import ru.yoomoney.sdk.kassa.payments.payment.tokenize.TokenizePaymentOptionInputModel import ru.yoomoney.sdk.kassa.payments.payment.tokenize.TokenizeRepository import ru.yoomoney.sdk.kassa.payments.paymentAuth.PaymentAuthTokenRepository private const val CANNOT_TOKENIZE_ABSTRACT_WALLET = "can not tokenize abstract wallet" internal class TokenizeUseCaseImpl( private val getLoadedPaymentOptionListRepository: GetLoadedPaymentOptionListRepository, private val tokenizeRepository: TokenizeRepository, private val checkPaymentAuthRequiredGateway: CheckPaymentAuthRequiredGateway, private val paymenPaymentAuthTokenRepository: PaymentAuthTokenRepository ) : TokenizeUseCase { override suspend fun tokenize(model: TokenizeInputModel): Tokenize.Action { val option = getLoadedPaymentOptionListRepository .getLoadedPaymentOptions() .find { it.id == model.paymentOptionId } ?: return Tokenize.Action.TokenizeFailed(SelectedOptionNotFoundException(model.paymentOptionId)) check(option !is AbstractWallet) { CANNOT_TOKENIZE_ABSTRACT_WALLET } return when { isPaymentAuthRequired(option) -> Tokenize.Action.PaymentAuthRequired(option.charge) else -> { val result = when (model) { is TokenizePaymentOptionInputModel -> { tokenizeRepository.getToken( paymentOption = option, paymentOptionInfo = model.paymentOptionInfo ?: WalletInfo(), confirmation = model.confirmation, savePaymentMethod = model.savePaymentMethod, savePaymentInstrument = model.savePaymentInstrument ) } is TokenizeInstrumentInputModel -> { tokenizeRepository.getToken( instrumentBankCard = model.instrumentBankCard, amount = option.charge, savePaymentMethod = model.savePaymentMethod, csc = model.csc, confirmation = model.confirmation ) } } when (result) { is Result.Success -> Tokenize.Action.TokenizeSuccess( TokenizeOutputModel( token = result.value, option = option, instrumentBankCard = model.instrumentBankCard ) ) is Result.Fail -> Tokenize.Action.TokenizeFailed(result.value) }.also { model.allowWalletLinking.takeUnless { it }?.let { paymenPaymentAuthTokenRepository.paymentAuthToken = null } model.allowWalletLinking?.let { paymenPaymentAuthTokenRepository.isUserAccountRemember = model.allowWalletLinking } } } } } private fun isPaymentAuthRequired(option: PaymentOption) = option is YooMoney && checkPaymentAuthRequiredGateway.checkPaymentAuthRequired() }
9
null
21
35
421619230cce92280641ea943c5ecb00f3dd8827
5,323
yookassa-android-sdk
MIT License
core/src/main/java/com/jonnyhsia/appcore/ui/CommonDiffCallback.kt
jonnyhsia
180,696,112
false
null
package com.jonnyhsia.appcore.ui import androidx.recyclerview.widget.DiffUtil open class CommonDiffCallback( protected var old: List<*>? = null, protected var new: List<*>? = null ) : DiffUtil.Callback() { override fun getOldListSize() = old?.size ?: 0 override fun getNewListSize() = new?.size ?: 0 /** * 是否为同一个 item */ override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return old?.getOrNull(oldItemPosition) === new?.getOrNull(newItemPosition) } /** * item 内容是否改变 */ override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return old?.getOrNull(oldItemPosition).hashCode() == new?.getOrNull(newItemPosition).hashCode() } fun changeData(oldData: List<*>, newData: List<*>): CommonDiffCallback { old = oldData new = newData return this } internal fun getNewList(): List<*>? { return new } }
1
Kotlin
1
2
c161f153bb9065274aaf03bff7c688fbdd4d7f96
1,010
Memories
MIT License
plugins/analyzers/chronolens-decapsulations/src/main/kotlin/org/chronolens/decapsulations/AbstractDecapsulationAnalyzer.kt
andreihh
83,168,079
false
{"Kotlin": 478074, "Java": 3908}
/* * Copyright 2018-2023 Andrei Heidelbacher <[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 org.chronolens.decapsulations import java.util.ServiceLoader import org.chronolens.model.QualifiedSourceNodeId import org.chronolens.model.SourcePath import org.chronolens.model.SourceTree import org.chronolens.model.Variable internal abstract class AbstractDecapsulationAnalyzer { protected abstract fun canProcess(sourcePath: SourcePath): Boolean protected abstract fun getField( sourceTree: SourceTree, nodeId: QualifiedSourceNodeId<*> ): QualifiedSourceNodeId<Variable>? protected abstract fun getVisibility( sourceTree: SourceTree, nodeId: QualifiedSourceNodeId<*> ): Int protected abstract fun isConstant( sourceTree: SourceTree, nodeId: QualifiedSourceNodeId<*> ): Boolean companion object { private val analyzers = ServiceLoader.load(AbstractDecapsulationAnalyzer::class.java) private fun findAnalyzer( sourceTree: SourceTree, id: QualifiedSourceNodeId<*>, ): AbstractDecapsulationAnalyzer? { if (id !in sourceTree) return null val sourcePath = id.sourcePath return analyzers.find { it.canProcess(sourcePath) } } fun getField( sourceTree: SourceTree, nodeId: QualifiedSourceNodeId<*> ): QualifiedSourceNodeId<Variable>? = findAnalyzer(sourceTree, nodeId)?.getField(sourceTree, nodeId) fun getVisibility(sourceTree: SourceTree, nodeId: QualifiedSourceNodeId<*>): Int? = findAnalyzer(sourceTree, nodeId)?.getVisibility(sourceTree, nodeId) fun isConstant(sourceTree: SourceTree, nodeId: QualifiedSourceNodeId<*>): Boolean = findAnalyzer(sourceTree, nodeId)?.isConstant(sourceTree, nodeId) == true } }
0
Kotlin
1
6
8855da7749ef52596ccef39344f59d66b9512399
2,299
chronolens
Apache License 2.0
src/main/kotlin/com/stilllynnthecloset/kotlr/json/response/user/UserFollowingWrapperJsonAdapter.kt
StillLynnTheCloset
257,834,160
true
{"Kotlin": 510488}
package com.stilllynnthecloset.kotlr.json.response.blog import com.squareup.moshi.FromJson import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonDataException import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonReader.Token.BEGIN_ARRAY import com.squareup.moshi.JsonReader.Token.BEGIN_OBJECT import com.squareup.moshi.JsonReader.Token.NULL import com.squareup.moshi.JsonReader.Token.STRING import com.squareup.moshi.JsonWriter import com.squareup.moshi.Moshi import com.squareup.moshi.ToJson import com.stilllynnthecloset.kotlr.adapter import com.stilllynnthecloset.kotlr.listAdapter import com.stilllynnthecloset.kotlr.response.WrapperInterface import com.stilllynnthecloset.kotlr.response.type.blog.ResponseBlogBlocks /** * BlogLikesWrapperJsonAdapter - An adapter to (de-)serialize the response wrapper object for a [ResponseBlogBlocks]. * * @author highthunder * @since 2021-06-02 */ internal class BlogBlocksWrapperJsonAdapter(moshi: Moshi) : JsonAdapter<WrapperInterface<ResponseBlogBlocks.Body>>() { private val stringAdapter: JsonAdapter<String?> = moshi.adapter() private val responseAdapter: JsonAdapter<ResponseBlogBlocks.Body> = moshi.adapter() private val listOfAnyAdapter: JsonAdapter<List<Any>> = moshi.listAdapter() @FromJson override fun fromJson(reader: JsonReader): WrapperInterface<ResponseBlogBlocks.Body> { return when (reader.peek()) { BEGIN_OBJECT -> ResponseBlogBlocks.Wrapper(body = responseAdapter.fromJson(reader)) STRING -> ResponseBlogBlocks.Wrapper(error = stringAdapter.fromJson(reader)) BEGIN_ARRAY -> ResponseBlogBlocks.Wrapper(error = listOfAnyAdapter.fromJson(reader).toString()) NULL -> ResponseBlogBlocks.Wrapper() else -> throw JsonDataException( "Expected a field of type Object, String, List, or null but got ${reader.peek()}" ) } } @ToJson override fun toJson(writer: JsonWriter, value: WrapperInterface<ResponseBlogBlocks.Body>?) { if (value?.error != null) { stringAdapter.toJson(writer, value.error) } else { responseAdapter.toJson(writer, value?.body) } } }
4
Kotlin
3
0
bd6c60c6da4bbe270aa1a0f4ce8bdbc2a993ba05
2,230
kotlr
MIT License
src/main/kotlin/io/battlesnake/core/SnakeContext.kt
pambrose
174,429,917
false
{"Gradle": 2, "INI": 2, "Markdown": 2, "YAML": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Makefile": 1, "JSON": 1, "Java": 2, "XML": 1, "Kotlin": 13, "HTTP": 1}
/* * Copyright © 2021 <NAME> (<EMAIL>) * * 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. */ @file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction") package io.battlesnake.core import io.ktor.application.* import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.TimeSource open class SnakeContext { private val clock = TimeSource.Monotonic private var gameStartTime = clock.markNow() var computeTime = 0.nanoseconds internal set var moveCount = 0L internal set lateinit var gameId: String internal set lateinit var snakeId: String internal set lateinit var call: ApplicationCall internal set internal fun resetStartTime() { gameStartTime = clock.markNow() } internal fun assignIds(gameId: String, snakeId: String) { this.gameId = gameId this.snakeId = snakeId } internal fun assignRequestResponse(call: ApplicationCall) { this.call = call } val elapsedGameTime get() = gameStartTime.elapsedNow() }
0
Kotlin
2
3
bdeecd4e0c733a5498ec8a60a70d71beacdf402d
1,514
battlesnake-quickstart
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsppudautomationapi/controller/OffenderController.kt
ministryofjustice
709,230,604
false
null
package uk.gov.justice.digital.hmpps.hmppsppudautomationapi.controller import io.swagger.v3.oas.annotations.Hidden import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.Parameter import jakarta.validation.Valid import jakarta.validation.ValidationException import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import org.springframework.web.context.annotation.RequestScope import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.CreateOffenderRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.CreateOrUpdateReleaseRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.CreateOrUpdateSentenceRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.CreateRecallRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.OffenderSearchRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.UpdateOffenceRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.request.UpdateOffenderRequest import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.response.CreateOffenderResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.response.CreateOrUpdateReleaseResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.response.CreateRecallResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.response.CreateSentenceResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.response.GetOffenderResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.domain.response.OffenderSearchResponse import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.ppud.PpudClient import java.util.UUID @RestController @RequestScope @PreAuthorize("hasRole('ROLE_PPUD_AUTOMATION__RECALL__READWRITE')") @RequestMapping(produces = [MediaType.APPLICATION_JSON_VALUE]) internal class OffenderController(private val ppudClient: PpudClient) { companion object { private val log = LoggerFactory.getLogger(this::class.java) } @PostMapping("/offender/search") @Operation( summary = "Search Offenders", description = "Search for offenders that match the specified criteria.", ) suspend fun search( @Valid @RequestBody(required = true) criteria: OffenderSearchRequest, ): ResponseEntity<OffenderSearchResponse> { log.info("Offender search endpoint hit") ensureSearchCriteriaProvided(criteria) val results = ppudClient.searchForOffender(criteria.croNumber, criteria.nomsId, criteria.familyName, criteria.dateOfBirth) return ResponseEntity(OffenderSearchResponse(results), HttpStatus.OK) } @GetMapping("/offender/{id}") @Operation( summary = "Get Offender", description = "Retrieve data for a specific offender.", ) suspend fun get( @PathVariable(required = true) id: String, @Parameter( description = "Only required for testing/diagnostic purposes. If true, this will mean that releases " + "that are titled as 'Not Specified - Not Specified' will be included.", ) @RequestParam(required = false) includeEmptyReleases: Boolean = false, ): ResponseEntity<GetOffenderResponse> { log.info("Offender get endpoint hit") val offender = ppudClient.retrieveOffender(id, includeEmptyReleases) return ResponseEntity(GetOffenderResponse(offender), HttpStatus.OK) } @PostMapping("/offender") @Operation( summary = "Create Offender", description = "Create a new offender.", ) suspend fun createOffender( @Valid @RequestBody(required = true) createOffenderRequest: CreateOffenderRequest, ): ResponseEntity<CreateOffenderResponse> { log.info("Offender creation endpoint hit") val offender = ppudClient.createOffender(createOffenderRequest) return ResponseEntity(CreateOffenderResponse(offender), HttpStatus.CREATED) } @PutMapping("/offender/{offenderId}") @Operation( summary = "Update Offender", description = "Update an existing offender.", ) suspend fun updateOffender( @PathVariable(required = true) offenderId: String, @Valid @RequestBody(required = true) offenderRequest: UpdateOffenderRequest, ) { log.info("Offender update endpoint hit") ppudClient.updateOffender(offenderId, offenderRequest) } @PostMapping("/offender/{offenderId}/sentence") @Operation( summary = "Create Sentence", description = "Create a new sentence against an existing offender.", ) suspend fun createSentence( @PathVariable(required = true) offenderId: String, @Valid @RequestBody(required = true) createOrUpdateSentenceRequest: CreateOrUpdateSentenceRequest, ): ResponseEntity<CreateSentenceResponse> { log.info("Sentence create endpoint hit") val sentence = ppudClient.createSentence(offenderId, createOrUpdateSentenceRequest) return ResponseEntity(CreateSentenceResponse(sentence), HttpStatus.CREATED) } @Operation( summary = "Update Sentence", description = "Update an existing sentence on an offender.", ) @PutMapping("/offender/{offenderId}/sentence/{sentenceId}") suspend fun updateSentence( @PathVariable(required = true) offenderId: String, @PathVariable(required = true) sentenceId: String, @Valid @RequestBody(required = true) createOrUpdateSentenceRequest: CreateOrUpdateSentenceRequest, ) { log.info("Sentence update endpoint hit") ppudClient.updateSentence(offenderId, sentenceId, createOrUpdateSentenceRequest) } @Operation( summary = "Update Offence", description = "Update an offence that is associated with a sentence on an offender." + " An offence will always exist if the sentence exists, so 'Create Offence' is not required.", ) @PutMapping("/offender/{offenderId}/sentence/{sentenceId}/offence") suspend fun updateOffence( @PathVariable(required = true) offenderId: String, @PathVariable(required = true) sentenceId: String, @Valid @RequestBody(required = true) request: UpdateOffenceRequest, ) { log.info("Offence update endpoint hit") ppudClient.updateOffence(offenderId, sentenceId, request) } @Operation( summary = "Create or Update a Release and Post Release", description = "Create a new release and post release, or update an existing release and post release when the release matches the key values.", ) @PostMapping("/offender/{offenderId}/sentence/{sentenceId}/release") suspend fun createOrUpdateRelease( @PathVariable(required = true) offenderId: String, @PathVariable(required = true) sentenceId: String, @Valid @RequestBody(required = true) createOrUpdateReleaseRequest: CreateOrUpdateReleaseRequest, ): ResponseEntity<CreateOrUpdateReleaseResponse> { log.info("Release create or update endpoint hit") val createdOrUpdatedRelease = ppudClient.createOrUpdateRelease(offenderId, sentenceId, createOrUpdateReleaseRequest) return ResponseEntity(CreateOrUpdateReleaseResponse(createdOrUpdatedRelease), HttpStatus.OK) } @PostMapping("/offender/{offenderId}/release/{releaseId}/recall") @Operation( summary = "Create Recall", description = "Create a recall against an existing offender.", ) suspend fun createRecall( @PathVariable(required = true) offenderId: String, @PathVariable(required = true) releaseId: String, @Valid @RequestBody(required = true) createRecallRequest: CreateRecallRequest, ): ResponseEntity<CreateRecallResponse> { log.info("Offender recall endpoint hit") val recall = ppudClient.createRecall(offenderId, releaseId, createRecallRequest) return ResponseEntity(CreateRecallResponse(recall), HttpStatus.CREATED) } @Hidden @PreAuthorize("hasRole('ROLE_PPUD_AUTOMATION__TESTS__READWRITE')") @DeleteMapping("/offender") suspend fun deleteTestOffenders( @RequestParam(required = true) familyNamePrefix: String, @RequestParam(required = true) testRunId: UUID, ) { log.info("Offender deletion endpoint hit") ppudClient.deleteOffenders(familyName = "$familyNamePrefix-$testRunId") } private fun ensureSearchCriteriaProvided(criteria: OffenderSearchRequest) { if (!criteria.containsCriteria) { throw ValidationException("Valid search criteria must be specified") } } }
0
null
1
3
f617b7f5b0ebf596029a794475696e0466747c5a
9,075
hmpps-ppud-automation-api
MIT License
zzsong-sms-server/src/test/kotlin/com/zzsong/study/coroutine/sms/server/provider/ihuyi/IhuyiSmsProviderTest.kt
cckmit
521,080,028
false
{"Kotlin": 46208, "Java": 44413}
package com.zzsong.study.coroutine.sms.server.provider.ihuyi import cn.idealframework.kotlin.toJsonString import com.zzsong.study.coroutine.sms.server.domain.model.template.ProviderTemplateDo import com.zzsong.study.coroutine.sms.server.provider.SendRequest import kotlinx.coroutines.runBlocking import org.junit.Ignore import org.junit.Test /** * @author 宋志宗 on 2022/1/28 */ @Ignore class IhuyiSmsProviderTest { companion object { private val properties = IhuyiProperties().also { it.appId = "xxx";it.appKey = "xxx" } private val provider = IhuyiSmsProvider(properties) } @Test fun send() = runBlocking { val template = ProviderTemplateDo() .also { it.templateId = 269454731720523776 it.setProviderCode("ihuyi") it.setProviderTemplate("") it.setContent("您的验证码是:\${code}。请不要把验证码泄露给其他人。") } val request = SendRequest() .also { it.template = template it.mobiles = listOf("18256928780") it.params = mapOf("code" to "1825") } val send = provider.send(request) println(send.toJsonString()) } }
0
null
0
0
e95f98f6bac1b044d53314db00f9a64246ff7439
1,118
zzsong-sms
MIT License
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress3030006.kt
pointillion
428,683,199
true
{"Kotlin": 538588, "HTML": 47353, "CSS": 17418, "JavaScript": 79}
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position val dress3030006 = PartialDressBlueprint( id = 3030006, name = "エリクトニウス", baseRarity = 4, character = Character.Lalafin, attribute = Attribute.Space, damageType = DamageType.Normal, position = Position.Middle, positionValue = 24050, stats = StatData( hp = 1026, actPower = 176, normalDefense = 86, specialDefense = 56, agility = 185, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 33790, actPower = 2900, normalDefense = 1420, specialDefense = 930, agility = 3060, ), actParameters = mapOf( ActType.Act1 to ActBlueprint( name = "打撃", type = ActType.Act1, apCost = 1, icon = 1, parameters = listOf( ActParameters( values = listOf(88, 92, 96, 101, 105), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), ActType.Act2 to ActBlueprint( name = "キラめきの打撃", type = ActType.Act2, apCost = 2, icon = 89, parameters = listOf( ActParameters( values = listOf(88, 92, 96, 101, 105), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(20, 20, 20, 20, 20), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), ActType.Act3 to ActBlueprint( name = "奮起の独奏", type = ActType.Act3, apCost = 3, icon = 8, parameters = listOf( ActParameters( values = listOf(10, 12, 14, 17, 20), times = listOf(2, 2, 2, 2, 2), ), ActParameters( values = listOf(165, 173, 181, 189, 198), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), ActType.ClimaxAct to ActBlueprint( name = "必殺!ギガシャリンブレイク!", type = ActType.ClimaxAct, apCost = 2, icon = 1, parameters = listOf( ActParameters( values = listOf(164, 172, 181, 189, 197), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = listOf( listOf( StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.SpecialDefense, 1), ), listOf( StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.Agility, 7), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 3), StatBoost(StatBoostType.NormalDefense, 7), StatBoost(StatBoostType.NormalDefense, 3), StatBoost(StatBoostType.Agility, 8), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Hp, 4), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Act1Level, 0), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 8), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 5), ), listOf( StatBoost(StatBoostType.Hp, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Agility, 9), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.NormalDefense, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.Agility, 11), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.SpecialDefense, 6), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), ), ), friendshipPanels = listOf( StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), ), remakeParameters = listOf( StatData( hp = 6300, actPower = 420, normalDefense = 300, specialDefense = 120, agility = 180, ), StatData( hp = 10500, actPower = 700, normalDefense = 500, specialDefense = 200, agility = 300, ), StatData( hp = 16800, actPower = 1120, normalDefense = 800, specialDefense = 320, agility = 480, ), StatData( hp = 21000, actPower = 1400, normalDefense = 1000, specialDefense = 400, agility = 600, ), ), )
0
null
0
0
53479fe3d1f4a067682509376afd87bdd205d19d
10,776
relive-simulator
MIT License
app/src/main/kotlin/com/fashare/mvvm_juejin/viewmodel/ArticleVM.kt
fashare2015
102,467,998
false
null
package com.fashare.mvvm_juejin.viewmodel import android.databinding.ObservableField import android.support.v7.widget.RecyclerView import android.view.View import com.fashare.databinding.TwoWayListVM import com.fashare.databinding.adapters.annotation.HeaderResHolder import com.fashare.databinding.adapters.annotation.ResHolder import com.fashare.mvvm_juejin.R import com.fashare.mvvm_juejin.model.article.ArticleBean import com.fashare.mvvm_juejin.model.comment.CommentListBean import com.fashare.mvvm_juejin.repo.Composers import com.fashare.mvvm_juejin.repo.JueJinApis import com.fashare.mvvm_juejin.view.detail.ArticleActivity import com.fashare.net.ApiFactory /** * Created by apple on 2017/9/16. */ @ResHolder(R.layout.item_article_comment_list) @HeaderResHolder(R.layout.header_article) class ArticleVM(val rv: RecyclerView) : TwoWayListVM<CommentListBean.Item>() { val article = ObservableField<ArticleBean>(ArticleBean("", "")) override val loadTask = { lastItem: CommentListBean.Item?-> ApiFactory.getApi(JueJinApis.Comment::class.java) .getComments(article.get().objectId?: "", lastItem?.createdAt?: "") .compose(Composers.handleError()) .map { it.comments } } override val headerData = HeaderVM() @ResHolder(R.layout.header_item_home) class HeaderVM : TwoWayListVM<ArticleBean>() { val html = ObservableField<String>("") val article = ObservableField<ArticleBean>(ArticleBean("", "")) override val loadTask = { lastItem: ArticleBean? -> ApiFactory.getApi(JueJinApis:: class.java) .getRelatedEntry(entryId = article.get()?.objectId?: "") .compose(Composers.handleError()) .map{ it.entrylist?: emptyList() } } override val onItemClick = ArticleActivity.START } val scrollToComment = View.OnClickListener { val header = rv.layoutManager.findViewByPosition(0) header?.apply{ if(this.height > 0) rv.smoothScrollBy(0, this.height - rv.computeVerticalScrollOffset()) } } }
8
null
60
402
182ec504145e326eb5f448879f558933b1a94799
2,145
MVVM-JueJin
MIT License
app/src/main/java/com/devcommop/myapplication/ui/components/shorts/ShortsViewModel.kt
pareekdevansh
648,905,400
false
null
package com.devcommop.myapplication.ui.components.shorts import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.devcommop.myapplication.data.local.RuntimeQueries import com.devcommop.myapplication.data.model.ShortItem import com.devcommop.myapplication.data.repository.Repository import com.devcommop.myapplication.utils.CommonUtils import com.devcommop.myapplication.utils.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ShortsViewModel @Inject constructor(private val repository: Repository) : ViewModel() { private val TAG = "##@@ShortsViewModel" private var _eventFlow = MutableSharedFlow<UIEvents>() val event = _eventFlow.asSharedFlow() private var _videos = MutableStateFlow(ShortsFeedState(shortsList = mutableListOf())) val videos get() = _videos private var _currentPlayingIndex = MutableStateFlow<Int?>(null) val currentPlayingIndex get() = _currentPlayingIndex init { _currentPlayingIndex.value = null // reset currentPlayingIndex fetchShorts() } fun postShorts(videoUri : Uri?) = viewModelScope.launch { val currentUser = RuntimeQueries.currentUser if(videoUri != null && currentUser != null ){ var short = ShortItem( id = CommonUtils.getAutoId(), createdBy = currentUser.uid, timestamp = System.currentTimeMillis().toString(), mediaUrl = videoUri.toString(), thumbnail = null, lastPlayedPosition = 0, title = "${currentUser.userName} ${System.currentTimeMillis()} }", description = null, likes = 0, comments = 0, views = 0, likesList = null, commentsList = null, tags = null, duration = 0 ) repository.postShorts(short, currentUser) } else{ return@launch } } fun onEvent(event : ShortsScreenEvents ){ event.apply{ when( this ){ is ShortsScreenEvents.Refresh -> { fetchShorts() } is ShortsScreenEvents.LikeShort -> { //TODO: Like short with event.value as shortItem } is ShortsScreenEvents.CommentShort -> { //TODO: comment short with event.value as shortItem } is ShortsScreenEvents.ReportShort -> { //TODO: report short with event.value as shortItem } is ShortsScreenEvents.ShareShort -> { //TODO: share short with event.value as shortItem } is ShortsScreenEvents.DeleteShort -> { //TODO: delete short with event.value as shortItem } } } } fun getUserByUserId(id :String ){ viewModelScope.launch { val response = repository.getUserById(id) when(response){ is Resource.Success -> { } is Resource.Error -> { _eventFlow.emit(UIEvents.ShowSnackbar(response.message?: "Unknown error occurred")) } is Resource.Loading -> { _eventFlow.emit(UIEvents.ShowProgressBar) } } } } fun fetchShorts() { viewModelScope.launch { when(val response = repository.fetchShortsFromDB()){ is Resource.Success -> { // Log.d(TAG, "fetchShorts: ${response.data}") //TODO: UI event show shorts response.data?.let{ _videos.value = ShortsFeedState(shortsList = it.toMutableList()) } ?: kotlin.run { _videos.value = ShortsFeedState(shortsList = mutableListOf()) } } is Resource.Error -> { // show snackbarUi event _eventFlow.emit(UIEvents.ShowSnackbar(response.message?: "Unknown error occurred")) } is Resource.Loading -> { // show circular progress bar _eventFlow.emit(UIEvents.ShowProgressBar) } } } } // repository.createShortsEntryInFirestoreDB() // @param videoIndex The index of the video to be played // @param playbackPosition The position of the last video fun onPlayVideoClick(playbackPosition: Long, videoIndex: Int) { when (_currentPlayingIndex.value) { // video is not playing at the moment null -> _currentPlayingIndex.value = videoIndex // this video is already playing videoIndex -> { _currentPlayingIndex.value = null videos.value = ShortsFeedState(videos.value.shortsList.toMutableList()).also { state -> val list = state.shortsList list[videoIndex] = list[videoIndex].copy(lastPlayedPosition = playbackPosition) } } // video is playing, and we're requesting new video to play else -> { videos.value = ShortsFeedState(videos.value.shortsList.toMutableList()).also { state -> val list = state.shortsList list[_currentPlayingIndex.value!!] = list[_currentPlayingIndex.value!!].copy(lastPlayedPosition = playbackPosition) } _currentPlayingIndex.value = videoIndex } } } sealed class UIEvents{ object ShowProgressBar : UIEvents() data class ShowSnackbar(val message: String) : UIEvents() } }
0
Kotlin
0
0
d0fda60a15fe2c7bd93596cf6582fccdbccb788a
6,171
Social-Jaw
MIT License
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
CJChen98
344,656,994
false
null
/* * Copyright 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.layout.padding import androidx.compose.material.FabPosition import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat import androidx.lifecycle.viewmodel.compose.viewModel import com.example.androiddevchallenge.ui.page.CountDownTimerPage import com.example.androiddevchallenge.ui.theme.MyTheme class MainActivity : AppCompatActivity() { @ExperimentalAnimationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) val insetsController = WindowCompat.getInsetsController(window, window.decorView) window.decorView.post { insetsController?.let { it.isAppearanceLightStatusBars = true } } setContent { MyTheme { MyApp() } } } } // Start building your app here! @ExperimentalAnimationApi @Composable fun MyApp() { val viewModel: TimeViewModel = viewModel() val showFloatButton by viewModel.showFloatButton.collectAsState() Surface(color = MaterialTheme.colors.background) { Scaffold( modifier = Modifier.padding(top = 12.dp), topBar = { TopAppBar( title = { Text(text = stringResource(id = R.string.app_name)) }, elevation = 0.dp, backgroundColor = MaterialTheme.colors.background ) }, floatingActionButton = { AnimatedVisibility(visible = showFloatButton) { if (showFloatButton) { FloatingActionButton( onClick = { viewModel.setTime() }, modifier = Modifier.padding(10.dp) ) { Icon( painter = painterResource(id = R.drawable.ic_ok), contentDescription = "ok" ) } } } }, floatingActionButtonPosition = FabPosition.Center ) { CountDownTimerPage(viewModel) } } }
0
Kotlin
0
0
98dd847fdc7f5efca8e4a3c010e51e4e971890d1
3,795
android-dev-challenge-compose-week2
Apache License 2.0
store/src/test/kotlin/com/example/leslie/reducer/UpdateReducerTest.kt
leslieharland
135,650,274
false
{"Gradle": 6, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 98, "XML": 55, "Java": 1}
/** * Copyright (C) 2017 Cesar Valiente & Corey Shaw * * https://github.com/CesarValiente * https://github.com/coshaw * * 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.example.leslie.reducer import com.example.leslie.store.Listing import com.example.leslie.store.UpdateAction import com.example.leslie.store.reducer.UpdateReducer import org.hamcrest.CoreMatchers.not import org.junit.Assert.assertThat import org.junit.Test import org.hamcrest.CoreMatchers.`is` as iz class UpdateReducerTest { @Test fun should_not_shouldReduceItem_when_ReorderItemsAction() { val item1 = createItem(1) val item2 = createItem(2) val item3 = createItem(3) val itemsList = listOf(item1, item2, item3) val reorderItemsAction = UpdateAction.ReorderItemsAction(itemsList) val shouldReduceItem = UpdateReducer.shouldReduceItem(reorderItemsAction, item1) assertThat(shouldReduceItem, iz(false)) } @Test fun should_changeItemFields_when_UpdateFavoriteAction() { val item = createItem(1) val updateFavoriteAction = UpdateAction.UpdateText(localId = item.localId, text = "hello") val reducedItem = UpdateReducer.changeItemFields(updateFavoriteAction, item) as Listing assertThat(reducedItem, iz(not(item))) assertThat(reducedItem.text, iz(item.text)) } }
0
Kotlin
0
0
8688f1031b5f66b88ce2974ca99e95ec8e25d9a4
1,891
Carousell-Kotlin
Apache License 2.0
androidutilskt/src/main/java/com/lindroid/androidutilskt/extension/RegexUtil.kt
Lindroy
172,827,942
false
null
@file:JvmName("RegexUtil") package com.lindroid.androidutilskt.extension import android.util.Patterns /** * @author Lin * @date 2019/3/14 * @function 正则表达式工具类 * @Description */ private fun String.checkWithRegex(pattern: String): Boolean { return Regex(pattern).matches(this) } /**校验内地手机号码**/ val String.isMobile: Boolean get() = checkWithRegex("^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(16[6])|(17[0,1,3,5-8])|(18[0-9])|(19[8,9]))\\d{8}$") /**校验电子邮箱**/ val String.isEmail: Boolean get() = checkWithRegex(Patterns.EMAIL_ADDRESS.pattern()) /**校验网络链接**/ val String.isWebUrl: Boolean // get() = checkWithRegex(Patterns.WEB_URL.pattern()) get() = checkWithRegex("[a-zA-z]+://[^\\s]*") /**校验数字**/ val String.isNumber: Boolean get() = checkWithRegex("^[0-9]*$") /**校验正整数**/ val String.isPositiveInt: Boolean get() = checkWithRegex("""^[1-9]\d*${'$'}""") /**校验负整数**/ val String.isNegativeInt: Boolean get() = checkWithRegex("""^-[1-9]\d*${'$'}""") /**校验字母(无关大小写)**/ val String.isLetter: Boolean get() = checkWithRegex("^[A-Za-z]+$") /**校验大写字母**/ val String.isUpperCaseLetter: Boolean get() = checkWithRegex("^[A-Z]+$") /**校验小写字母**/ val String.isLowerCaseLetter: Boolean get() = checkWithRegex("^[a-z]+$") /**校验汉字**/ val String.isChinese: Boolean get() = checkWithRegex("^[\\u4e00-\\u9fa5]+$") /**校验QQ号码**/ val String.isQQ: Boolean get() = checkWithRegex("[1-9][0-9]{4,14}") /**校验澳门手机号码**/ val String.isMacaoMobile: Boolean get() = checkWithRegex("[6]\\d{7}")
0
null
19
48
5d6832813a4a0dba7290ad5ef92959f638ea51ab
1,524
AndroidUtilsKt
Apache License 2.0
app/src/androidTest/java/com/hydrofish/app/AchievementScreenIntegrationTest.kt
HydroFish-Waterloo
748,731,716
false
{"Kotlin": 273974}
package com.hydrofish.app import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.lifecycle.MutableLiveData import androidx.navigation.NavHostController import com.hydrofish.app.ui.composables.tabs.AchievementsScreen import com.hydrofish.app.utils.IUserSessionRepository import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.`when` class AchievementScreenIntegrationTest { private lateinit var mockUserSessionRepository: IUserSessionRepository @get:Rule val composeTestRule = createComposeRule() @Before fun setup() { mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java) Mockito.`when`(mockUserSessionRepository.isLoggedIn).thenReturn(MutableLiveData(false)) Mockito.`when`(mockUserSessionRepository.scoreLiveData).thenReturn(MutableLiveData(1)) } @Test fun testAchievementScreen_WhenUserLoggedIn() { val navController = Mockito.mock(NavHostController::class.java) `when`(mockUserSessionRepository.isLoggedIn).thenReturn(MutableLiveData(true)) composeTestRule.setContent { AchievementsScreen(userSessionRepository = mockUserSessionRepository, navController = navController) } composeTestRule.onNodeWithText("Achievements").assertIsDisplayed() } @Test fun testAchievementScreen_WhenUserNotLoggedIn() { val navController = Mockito.mock(NavHostController::class.java) `when`(mockUserSessionRepository.isLoggedIn).thenReturn(MutableLiveData(false)) composeTestRule.setContent { AchievementsScreen(userSessionRepository = mockUserSessionRepository, navController = navController) } composeTestRule.onNodeWithText("Please log in to access this page").assertIsDisplayed() } }
3
Kotlin
0
0
eadfc258a70804250726e316fcbde37f50265d5a
1,964
HydroFish
MIT License
app/src/main/java/org/rfcx/incidents/view/guardian/checklist/classifierupload/ClassifierUploadFragment.kt
rfcx
104,899,135
false
{"Kotlin": 1176262, "Java": 1049}
package org.rfcx.incidents.view.guardian.checklist.classifierupload import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.viewModel import org.rfcx.incidents.R import org.rfcx.incidents.data.remote.common.GuardianModeNotCompatibleException import org.rfcx.incidents.data.remote.common.NoActiveClassifierException import org.rfcx.incidents.data.remote.common.OperationTimeoutException import org.rfcx.incidents.data.remote.common.SoftwareNotCompatibleException import org.rfcx.incidents.databinding.FragmentClassifierUploadBinding import org.rfcx.incidents.entity.guardian.file.GuardianFile import org.rfcx.incidents.view.guardian.GuardianDeploymentEventListener class ClassifierUploadFragment : Fragment(), ChildrenClickedListener { lateinit var binding: FragmentClassifierUploadBinding private val viewModel: ClassifierUploadViewModel by viewModel() private val classifierUploadAdapter by lazy { ClassifierUploadAdapter(this) } private var mainEvent: GuardianDeploymentEventListener? = null private lateinit var dialogBuilder: AlertDialog override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mainEvent = context as GuardianDeploymentEventListener binding = DataBindingUtil.inflate(inflater, R.layout.fragment_classifier_upload, container, false) binding.lifecycleOwner = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewModel = viewModel mainEvent?.let { it.showToolbar() it.hideThreeDots() it.setToolbarTitle(getString(R.string.classifier_title)) } binding.classifierRecyclerView.apply { adapter = classifierUploadAdapter layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) addItemDecoration( DividerItemDecoration( context, DividerItemDecoration.VERTICAL ) ) } binding.nextButton.setOnClickListener { mainEvent?.next() } viewModel.getGuardianClassifier() lifecycleScope.launch { viewModel.guardianClassifierState.collectLatest { if (it.isEmpty()) { binding.noClassifierText.visibility = View.VISIBLE binding.classifierRecyclerView.visibility = View.GONE } else { binding.noClassifierText.visibility = View.GONE binding.classifierRecyclerView.visibility = View.VISIBLE classifierUploadAdapter.files = it } } } lifecycleScope.launch { viewModel.errorClassifierState.collectLatest { when (it) { is OperationTimeoutException -> { dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.BaseAlertDialog).apply { setTitle(null) setMessage(R.string.classifier_service_reboot_message) setPositiveButton(R.string.restart) { _, _ -> viewModel.restartService() } setNegativeButton(R.string.no) { _, _ -> dialogBuilder.dismiss() } }.create() dialogBuilder.show() } is SoftwareNotCompatibleException -> { showAlert(it.message) } is GuardianModeNotCompatibleException -> { showAlert(it.message) } is NoActiveClassifierException -> { binding.noActiveWarnTextView.visibility = View.VISIBLE binding.nextButton.isEnabled = false } else -> { if (::dialogBuilder.isInitialized) { dialogBuilder.dismiss() } binding.noActiveWarnTextView.visibility = View.GONE binding.nextButton.isEnabled = true } } } } } private fun showAlert(text: String) { if (::dialogBuilder.isInitialized && dialogBuilder.isShowing) { return } dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.BaseAlertDialog).apply { setTitle(null) setMessage(text) setPositiveButton(R.string.go_back) { _, _ -> dialogBuilder.dismiss() mainEvent?.back() } }.create() dialogBuilder.show() } companion object { @JvmStatic fun newInstance() = ClassifierUploadFragment() } override fun onUploadClick(selectedFile: GuardianFile) { viewModel.updateOrUploadClassifier(selectedFile) } override fun onActivateClick(selectedFile: GuardianFile) { viewModel.activateClassifier(selectedFile) } override fun onDeActivateClick(selectedFile: GuardianFile) { viewModel.deActivateClassifier(selectedFile) } }
29
Kotlin
0
0
804d56b8c7475e51299db5fde9207ae783820bf9
6,081
guardian-app-android
Apache License 2.0
app/src/main/java/com/skyyo/samples/features/textSpans/TextSpansScreen.kt
Skyyo
385,529,955
false
{"Kotlin": 557302}
package com.skyyo.samples.features.textSpans import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.* import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.skyyo.samples.features.textSpans.composables.* private const val CORNER_RADIUS_VALUE = 20f // done using https://saket.me/compose-custom-text-spans/ and https://github.com/saket/ExtendedSpans @OptIn(ExperimentalTextApi::class) @Composable fun TextSpansScreen() { var isCorrect by remember { mutableStateOf(true) } Column( modifier = Modifier .fillMaxSize() .background(color = Color.White) .systemBarsPadding() .padding(horizontal = 20.dp), verticalArrangement = remember { Arrangement.spacedBy(20.dp) } ) { val text = remember { buildAnnotatedString { append("Where is the proud pirate? ") withAnnotation("squiggles", annotation = "ignored") { withStyle(SpanStyle(color = Color.Magenta)) { append("The rough shipmate fiery fights the dagger.") } } append(" Belay! Pieces o' yellow fever are forever dead.") } } SquiggleUnderlineText(text = text, fontSize = 24.sp, lineHeight = 30.sp) AnimatedSquiggleUnderlineText(text = text, fontSize = 24.sp, lineHeight = 30.sp) AnimatedSquiggleWavelengthUnderlineText( text = text, isCorrect = isCorrect, fontSize = 24.sp, lineHeight = 30.sp ) Button(onClick = { isCorrect = !isCorrect }) { Text(text = if (isCorrect) "Incorrect" else "Correct") } HighlightedText( text = text, cornerRadius = remember { CornerRadius(CORNER_RADIUS_VALUE, CORNER_RADIUS_VALUE) }, highlightColor = Color.Cyan, highlightBorderColor = Color.DarkGray, padding = remember { SimplePaddingValues(horizontal = 2.dp, vertical = 2.dp) }, fontSize = 24.sp, lineHeight = 30.sp ) UnderlinedText(text = text, fontSize = 24.sp, lineHeight = 30.sp) } }
10
Kotlin
5
77
1319c3d29da4865d6f1931ee18137cdfc1715891
2,513
samples
MIT License
native/objcexport-header-generator/impl/analysis-api/src/org/jetbrains/kotlin/objcexport/getObjCFileClassOrProtocolName.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
package org.jetbrains.kotlin.objcexport import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportFileName import org.jetbrains.kotlin.backend.konan.objcexport.toIdentifier import org.jetbrains.kotlin.name.NameUtils private const val PART_CLASS_NAME_SUFFIX = "Kt" fun ObjCExportContext.getObjCFileClassOrProtocolName(file: KtResolvedObjCExportFile): ObjCExportFileName { val name = (NameUtils.getPackagePartClassNamePrefix(file.fileName) + PART_CLASS_NAME_SUFFIX).toIdentifier() return exportSession.getObjCFileName(name) }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
540
kotlin
Apache License 2.0
common/src/main/java/com/mobdao/common/di/CommonModule.kt
diegohkd
764,734,288
false
{"Kotlin": 231913}
package com.mobdao.common.di import com.mobdao.common.utils.factories.MoshiFactory import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module abstract class CommonModule { companion object { @Singleton @Provides fun provideMoshi(moshiFactory: MoshiFactory): Moshi = moshiFactory.create() } }
0
Kotlin
0
0
d77fb786275828ce06805903d8a3aea991f1148b
499
AdoptAPet
Apache License 2.0
src/main/kotlin/me/aberrantfox/hotbot/commands/utility/XKCDCommands.kt
the-programmers-hangout
251,075,497
false
null
package me.aberrantfox.hotbot.commands.utility import khttp.get import me.aberrantfox.hotbot.utility.randomInt import me.aberrantfox.kjdautils.api.dsl.CommandSet import me.aberrantfox.kjdautils.api.dsl.arg import me.aberrantfox.kjdautils.api.dsl.commands import me.aberrantfox.kjdautils.internal.command.arguments.IntegerArg import me.aberrantfox.kjdautils.internal.command.arguments.SentenceArg import java.net.URLEncoder @CommandSet("fun") fun xkcdCommands() = commands { command("xkcd") { description = "Returns the XKCD comic number specified, or a random comic if you don't supply a number." expect(arg(IntegerArg("Comic Number"), true, { randomInt(1, getAmount()) })) execute { val target = it.args.component1() as Int val link = if (target <= getAmount() && target > 0) { produceURL(target) } else { "Please enter a valid comic number between 1 and ${getAmount()}" } it.respond(link) } } command("xkcd-latest") { description = "Grabs the latest XKCD comic." execute { it.respond("https://xkcd.com/" + getAmount()) } } command("xkcd-search") { description = "Returns a XKCD comic that most closely matches your query." expect(SentenceArg("Query")) execute { val what = it.args.component1() as String it.respond(produceURL(search(what))) } } } private fun search(what: String): Int { val comicNumberParseRegex = "(?:\\S+\\s+){2}(\\S+)".toRegex() return comicNumberParseRegex.find( get("https://relevantxkcd.appspot.com/process?action=xkcd&query=" + URLEncoder.encode( what, "UTF-8")).text)!!.groups[1]?.value!!.toInt() } private fun getAmount() = get("https://xkcd.com/info.0.json").jsonObject.getInt("num") private fun produceURL(comicNumber: Int) = "http://xkcd.com/$comicNumber/"
2
Kotlin
0
1
2edd95266192b03b60454573dcfd2d5d785c6af5
2,044
HotBot
MIT License
app/src/androidTest/java/com/waffiq/countryPicker/CountryPickerButtonInstrumentedTest.kt
waffiqaziz
871,890,420
false
{"Kotlin": 58456}
package com.waffiq.countryPicker import android.content.Context import android.content.Intent import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import androidx.test.core.app.launchActivity import androidx.test.espresso.Espresso.onView import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.waffiq.countryPicker.countryPicker.R.id.rv_country import com.waffiq.countryPicker.countryPicker.R.id.tv_country_id import com.waffiq.countryPicker.utils.EspressoIdlingResource import com.waffiq.countryPicker.R.id.cpb_test import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class CountryPickerButtonInstrumentedTest { private lateinit var scenario: ActivityScenario<TestActivity> private val context: Context = ApplicationProvider.getApplicationContext() @get:Rule val activityRule = ActivityScenarioRule(TestActivity::class.java) @Before fun setUp() { IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource) } @After fun tearDown() { IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource) } @Test fun testCountryPickerDialogOpens() { scenario = launchActivity(Intent(context, TestActivity::class.java)) // Click the CountryPickerButton onView(withId(cpb_test)).perform(click()) // Check if the RecyclerView with country list is displayed onView(withId(rv_country)).check(matches(isDisplayed())) } @Test fun testCountrySelectionUpdatesButton() { scenario = launchActivity(Intent(context, TestActivity::class.java)) // Click the CountryPickerButton to open the dialog onView(withId(cpb_test)).perform(click()) // Select the first country in the list onView(withText("Andorra")).perform(click()) // Check if the button text is updated with selected country onView(withId(tv_country_id)).check(matches(withText("AD"))) } }
0
Kotlin
0
0
9680f16e975419c8f4c254ae2cccc8160e5f43e6
2,304
country-picker-android
Apache License 2.0
library/dialog/src/main/java/com/github/lany192/dialog/InputDialog.kt
lany192
131,839,448
false
{"Java": 1058768, "Kotlin": 166891, "C": 31335, "JavaScript": 10242, "C++": 4391, "CMake": 3813, "CSS": 999, "HTML": 422}
package com.github.lany192.dialog import android.text.TextUtils import android.text.method.MovementMethod import android.view.View import android.view.WindowManager import androidx.annotation.ColorRes import com.github.lany192.dialog.databinding.DialogInputBinding import com.github.lany192.extension.toast import com.github.lany192.interfaces.OnSimpleListener import com.github.lany192.utils.KeyboardWatcher class InputDialog : BaseDialog<DialogInputBinding>() { @ColorRes var titleColor = R.color.text_1level var titleSize = 16f var title: CharSequence? = null @ColorRes var messageColor = R.color.text_3level var message: CharSequence? = null var messageSize = 14f var movementMethod: MovementMethod? = null @ColorRes var rightTextColor = 0 var rightButton: CharSequence? = null var rightClickListener: OnSimpleListener? = null override fun bottomStyle(): Boolean { return true } // override fun getDialogHeight(): Int { // return WindowManager.LayoutParams.MATCH_PARENT // } override fun getTheme(): Int { return R.style.InputDialogTheme } override fun init() { activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) dialog?.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) if (TextUtils.isEmpty(title)) { binding.title.visibility = View.GONE } else { binding.title.text = title binding.title.textSize = titleSize binding.title.visibility = View.VISIBLE binding.title.setTextColorId(titleColor) } KeyboardWatcher(requireActivity()) { showKeyboard, keyboardHeight, floatMode -> toast("键盘板状态:$showKeyboard, 高度:$keyboardHeight") binding.panel.layoutParams.height = keyboardHeight } } override fun onStart() { super.onStart() val dialog = dialog if (dialog != null) { activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) dialog?.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) } } }
0
Java
3
34
1f7cc9fd1b799607ff8b89b3811aaf61fa1c0b73
2,217
box
Apache License 2.0
app/src/main/java/ch/abwesend/privatecontacts/view/screens/contactdetail/ContactDetailScreen.kt
fgubler
462,182,037
false
{"Kotlin": 1159351, "Java": 369326}
/* * Private Contacts * Copyright (c) 2022. * <NAME> */ package ch.abwesend.privatecontacts.view.screens.contactdetail import androidx.annotation.StringRes import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.padding import androidx.compose.material.Divider import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Sync import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import ch.abwesend.privatecontacts.R import ch.abwesend.privatecontacts.domain.ContactDetailInitializationWorkaround import ch.abwesend.privatecontacts.domain.lib.flow.AsyncResource import ch.abwesend.privatecontacts.domain.model.contact.ContactType import ch.abwesend.privatecontacts.domain.model.contact.IContact import ch.abwesend.privatecontacts.domain.model.contact.asEditable import ch.abwesend.privatecontacts.domain.model.result.ContactChangeError import ch.abwesend.privatecontacts.domain.model.result.ContactDeleteResult import ch.abwesend.privatecontacts.domain.model.result.ContactSaveResult import ch.abwesend.privatecontacts.domain.model.result.ContactValidationError import ch.abwesend.privatecontacts.domain.model.result.generic.ErrorResult import ch.abwesend.privatecontacts.domain.model.result.generic.SuccessResult import ch.abwesend.privatecontacts.view.components.FullScreenError import ch.abwesend.privatecontacts.view.components.LoadingIndicatorFullScreen import ch.abwesend.privatecontacts.view.components.buttons.BackIconButton import ch.abwesend.privatecontacts.view.components.buttons.EditIconButton import ch.abwesend.privatecontacts.view.components.buttons.MoreActionsIconButton import ch.abwesend.privatecontacts.view.components.contactmenu.ChangeContactTypeErrorDialog import ch.abwesend.privatecontacts.view.components.contactmenu.ChangeContactTypeMenuItem import ch.abwesend.privatecontacts.view.components.contactmenu.DeleteContactMenuItem import ch.abwesend.privatecontacts.view.components.contactmenu.DeleteContactsResultDialog import ch.abwesend.privatecontacts.view.components.contactmenu.ExportContactsMenuItem import ch.abwesend.privatecontacts.view.components.contactmenu.ExportContactsResultDialog import ch.abwesend.privatecontacts.view.model.ContactTypeChangeMenuConfig import ch.abwesend.privatecontacts.view.model.config.ButtonConfig import ch.abwesend.privatecontacts.view.model.screencontext.IContactDetailScreenContext import ch.abwesend.privatecontacts.view.routing.Screen import ch.abwesend.privatecontacts.view.screens.BaseScreen import ch.abwesend.privatecontacts.view.util.collectWithEffect import ch.abwesend.privatecontacts.view.util.composeIfError import ch.abwesend.privatecontacts.view.util.composeIfInactive import ch.abwesend.privatecontacts.view.util.composeIfLoading import ch.abwesend.privatecontacts.view.util.composeIfReady import ch.abwesend.privatecontacts.view.viewmodel.ContactDetailViewModel import kotlinx.coroutines.FlowPreview import kotlin.contracts.ExperimentalContracts @ExperimentalFoundationApi @ExperimentalMaterialApi @ExperimentalComposeUiApi @FlowPreview @ExperimentalContracts object ContactDetailScreen { @Composable fun Screen(screenContext: IContactDetailScreenContext) { val viewModel = screenContext.contactDetailViewModel val contactResource: AsyncResource<IContact> by viewModel.selectedContact.collectAsState() BaseScreen( screenContext = screenContext, selectedScreen = Screen.ContactDetail, topBar = { ContactDetailTopBar(screenContext = screenContext, contact = contactResource.valueOrNull) } ) { padding -> LaunchedEffect(Unit) { if (!ContactDetailInitializationWorkaround.hasOpenedContact) { screenContext.navigateUp() } } val modifier = Modifier.padding(padding) contactResource .composeIfError { NoContactLoadedError(viewModel = viewModel, modifier = modifier) } .composeIfInactive { NoContactLoaded(modifier = modifier, navigateUp = screenContext::navigateUp) } .composeIfLoading { LoadingIndicatorFullScreen(textAfterIndicator = R.string.loading_contacts, modifier = modifier) } .composeIfReady { ContactDetailScreenContent.ScreenContent(contact = it, modifier = modifier) } } DeleteResultObserver(viewModel = viewModel, onSuccess = screenContext::navigateUp) TypeChangeResultObserver(viewModel = viewModel, onSuccess = screenContext::navigateUp) ExportResultObserver(viewModel) } @Composable private fun DeleteResultObserver(viewModel: ContactDetailViewModel, onSuccess: () -> Unit) { var deletionErrors: List<ContactChangeError> by remember { mutableStateOf(emptyList()) } DeleteContactsResultDialog(numberOfErrors = deletionErrors.size, numberOfAttemptedChanges = 1) { deletionErrors = emptyList() } viewModel.deleteResult.collectWithEffect { result -> when (result) { is ContactDeleteResult.Success -> onSuccess() is ContactDeleteResult.Failure -> deletionErrors = result.errors } } } @Composable private fun TypeChangeResultObserver(viewModel: ContactDetailViewModel, onSuccess: () -> Unit) { var validationErrors: List<ContactValidationError> by remember { mutableStateOf(emptyList()) } var errors: List<ContactChangeError> by remember { mutableStateOf(emptyList()) } val changeSuccessful = validationErrors.isEmpty() && errors.isEmpty() ChangeContactTypeErrorDialog( validationErrors = validationErrors, errors = errors, numberOfAttemptedChanges = 1, numberOfSuccessfulChanges = if (changeSuccessful) 1 else 0 ) { validationErrors = emptyList() errors = emptyList() } viewModel.typeChangeResult.collectWithEffect { result -> when (result) { is ContactSaveResult.Success -> onSuccess() is ContactSaveResult.ValidationFailure -> validationErrors = result.validationErrors is ContactSaveResult.Failure -> errors = result.errors } } } @Composable private fun ExportResultObserver(viewModel: ContactDetailViewModel) { var numberOfExportErrors: Int by remember { mutableIntStateOf(0) } var dialogVisible: Boolean by remember { mutableStateOf(false) } if (dialogVisible) { ExportContactsResultDialog(numberOfErrors = numberOfExportErrors, numberOfAttemptedChanges = 1) { dialogVisible = false } } viewModel.exportResult.collectWithEffect { result -> numberOfExportErrors = when (result) { is SuccessResult -> result.value.failedContacts.size is ErrorResult -> 1 } dialogVisible = true } } @Composable private fun ContactDetailTopBar( screenContext: IContactDetailScreenContext, contact: IContact?, ) { @StringRes val title = R.string.screen_contact_details var dropDownMenuExpanded: Boolean by remember { mutableStateOf(false) } TopAppBar( title = { Text( text = contact?.displayName ?: stringResource(id = title), maxLines = 1, overflow = TextOverflow.Ellipsis, ) }, navigationIcon = { BackIconButton { screenContext.navigateUp() } }, actions = { if (contact != null) { EditIconButton { screenContext.navigateToContactEditScreen(contact) } MoreActionsIconButton { dropDownMenuExpanded = true } ActionsMenu( viewModel = screenContext.contactDetailViewModel, contact = contact, expanded = dropDownMenuExpanded ) { dropDownMenuExpanded = false } } } ) } @Composable fun ActionsMenu( viewModel: ContactDetailViewModel, contact: IContact, expanded: Boolean, onCloseMenu: () -> Unit, ) { val hasWritePermission = remember { viewModel.hasContactWritePermission } DropdownMenu(expanded = expanded, onDismissRequest = onCloseMenu) { DropdownMenuItem( onClick = { viewModel.reloadContact(contact) onCloseMenu() }, content = { Text(stringResource(id = R.string.refresh)) } ) Divider() ContactType.entries.forEach { targetType -> ChangeContactTypeMenuItem( viewModel = viewModel, contact = contact, targetType = targetType, enabled = hasWritePermission || !targetType.androidPermissionRequired, onCloseMenu = onCloseMenu, ) } DeleteMenuItem(viewModel, contact, onCloseMenu) Divider() ExportMenuItem(viewModel, contact, onCloseMenu) } } @Composable private fun ChangeContactTypeMenuItem( viewModel: ContactDetailViewModel, contact: IContact, targetType: ContactType, enabled: Boolean, onCloseMenu: () -> Unit, ) { if (contact.type != targetType) { val config = ContactTypeChangeMenuConfig.fromTargetType(targetType) val editableContact = contact.asEditable() ChangeContactTypeMenuItem( contacts = setOf(editableContact), config = config, enabled = enabled ) { changeContact -> if (changeContact) { viewModel.changeContactType(editableContact, targetType) } onCloseMenu() } } } @Composable private fun DeleteMenuItem( viewModel: ContactDetailViewModel, contact: IContact, onCloseMenu: () -> Unit, ) { DeleteContactMenuItem(numberOfContacts = 1) { delete -> if (delete) { viewModel.deleteContact(contact) } onCloseMenu() } } @Composable private fun NoContactLoaded(modifier: Modifier = Modifier, navigateUp: () -> Unit) { FullScreenError( errorMessage = R.string.no_contact_selected, modifier = modifier, buttonConfig = ButtonConfig( label = R.string.back, icon = Icons.Default.ArrowBack, onClick = navigateUp ) ) } @Composable private fun NoContactLoadedError(viewModel: ContactDetailViewModel, modifier: Modifier = Modifier) { FullScreenError( errorMessage = R.string.no_contact_selected_error, modifier = modifier, buttonConfig = ButtonConfig( label = R.string.reload_contact, icon = Icons.Default.Sync, ) { viewModel.reloadContact() } ) } @Composable private fun ExportMenuItem( viewModel: ContactDetailViewModel, contact: IContact, onCloseMenu: () -> Unit, ) { ExportContactsMenuItem( contacts = setOf(contact), onCancel = onCloseMenu, onExportContact = { targetFile, vCardVersion -> viewModel.exportContact(targetFile, vCardVersion, contact) onCloseMenu() } ) } }
1
Kotlin
3
9
e2bee11f232db2728c98e434dad5148ef0497dbf
12,826
PrivateContacts
Apache License 2.0
library/src/main/java/com/pedro/library/base/StreamBase.kt
pedroSG94
79,667,969
false
null
package com.pedro.library.base import android.content.Context import android.graphics.SurfaceTexture import android.media.MediaCodec import android.media.MediaFormat import android.media.projection.MediaProjection import android.os.Build import android.util.Range import android.util.Size import android.view.MotionEvent import android.view.Surface import android.view.SurfaceView import android.view.TextureView import androidx.annotation.RequiresApi import com.pedro.encoder.Frame import com.pedro.encoder.audio.AudioEncoder import com.pedro.encoder.audio.GetAacData import com.pedro.encoder.input.audio.GetMicrophoneData import com.pedro.encoder.input.video.CameraHelper import com.pedro.encoder.video.FormatVideoEncoder import com.pedro.encoder.video.GetVideoData import com.pedro.encoder.video.VideoEncoder import com.pedro.library.base.recording.BaseRecordController import com.pedro.library.base.recording.RecordController import com.pedro.library.util.AndroidMuxerRecordController import com.pedro.library.util.sources.AudioManager import com.pedro.library.util.sources.VideoManager import com.pedro.library.view.GlStreamInterface import java.nio.ByteBuffer /** * Created by pedro on 21/2/22. * * Allow: * - video source camera1, camera2 or screen. * - audio source microphone or internal. * - Rotation on realtime. */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) abstract class StreamBase( context: Context, videoSource: VideoManager.Source, audioSource: AudioManager.Source ): GetVideoData, GetAacData, GetMicrophoneData { //video and audio encoders private val videoEncoder by lazy { VideoEncoder(this) } private val audioEncoder by lazy { AudioEncoder(this) } //video render private val glInterface = GlStreamInterface(context) //video and audio sources private val videoManager = VideoManager(context, videoSource) private val audioManager by lazy { AudioManager(this, audioSource) } //video/audio record private var recordController: BaseRecordController = AndroidMuxerRecordController() var isStreaming = false private set var isOnPreview = false private set val isRecording: Boolean get() = recordController.isRunning val videoSource = videoManager.source val audioSource = audioManager.source init { glInterface.init() } /** * Necessary only one time before start preview, stream or record. * If you want change values stop preview, stream and record is necessary. * * @return True if success, False if failed */ @JvmOverloads fun prepareVideo(width: Int, height: Int, bitrate: Int, fps: Int = 30, iFrameInterval: Int = 2, avcProfile: Int = -1, avcProfileLevel: Int = -1): Boolean { val videoResult = videoManager.createVideoManager(width, height, fps) if (videoResult) { glInterface.setEncoderSize(width, height) return videoEncoder.prepareVideoEncoder(width, height, fps, bitrate, 0, iFrameInterval, FormatVideoEncoder.SURFACE, avcProfile, avcProfileLevel) } return videoResult } /** * Necessary only one time before start stream or record. * If you want change values stop stream and record is necessary. * * @return True if success, False if failed */ @JvmOverloads fun prepareAudio(sampleRate: Int, isStereo: Boolean, bitrate: Int, echoCanceler: Boolean = false, noiseSuppressor: Boolean = false): Boolean { val audioResult = audioManager.createAudioManager(sampleRate, isStereo, echoCanceler, noiseSuppressor) if (audioResult) { return audioEncoder.prepareAudioEncoder(bitrate, sampleRate, isStereo, audioManager.getMaxInputSize()) } return audioResult } /** * Start stream. * * Must be called after prepareVideo and prepareAudio */ fun startStream(endPoint: String) { isStreaming = true rtpStartStream(endPoint) if (!isRecording) startSources() else videoEncoder.requestKeyframe() } /** * Stop stream. * * @return True if encoders prepared successfully with previous parameters. False other way * If return is false you will need call prepareVideo and prepareAudio manually again before startStream or StartRecord * * Must be called after prepareVideo and prepareAudio. */ fun stopStream(): Boolean { isStreaming = false rtpStopStream() if (!isRecording) { stopSources() return prepareEncoders() } return true } /** * Start record. * * Must be called after prepareVideo and prepareAudio. */ fun startRecord(path: String, listener: RecordController.Listener) { recordController.startRecord(path, listener) if (!isStreaming) startSources() else videoEncoder.requestKeyframe() } /** * @return True if encoders prepared successfully with previous parameters. False other way * If return is false you will need call prepareVideo and prepareAudio manually again before startStream or StartRecord * * Must be called after prepareVideo and prepareAudio. */ fun stopRecord(): Boolean { recordController.stopRecord() if (!isStreaming) { stopSources() return prepareEncoders() } return true } /** * Start preview in the selected TextureView. * Must be called after prepareVideo. */ fun startPreview(textureView: TextureView) { startPreview(Surface(textureView.surfaceTexture), textureView.width, textureView.height) } /** * Start preview in the selected SurfaceView. * Must be called after prepareVideo. */ fun startPreview(surfaceView: SurfaceView) { startPreview(surfaceView.holder.surface, surfaceView.width, surfaceView.height) } /** * Start preview in the selected SurfaceTexture. * Must be called after prepareVideo. */ fun startPreview(surfaceTexture: SurfaceTexture, width: Int, height: Int) { startPreview(Surface(surfaceTexture), width, height) } /** * Start preview in the selected Surface. * Must be called after prepareVideo. */ fun startPreview(surface: Surface, width: Int, height: Int) { if (!surface.isValid) throw IllegalArgumentException("Make sure the Surface is valid") isOnPreview = true if (!glInterface.running) glInterface.start() if (!videoManager.isRunning()) { videoManager.start(glInterface.getSurfaceTexture()) } glInterface.attachPreview(surface) glInterface.setPreviewResolution(width, height) } /** * Stop preview. * Must be called after prepareVideo. */ fun stopPreview() { isOnPreview = false if (!isStreaming && !isRecording) videoManager.stop() glInterface.deAttachPreview() if (!isStreaming && !isRecording) glInterface.stop() } /** * Change video source to Camera1 or Camera2. * Must be called after prepareVideo. */ fun changeVideoSourceCamera(source: VideoManager.Source) { glInterface.setForceRender(false) videoManager.changeSourceCamera(source) } /** * Change video source to Screen. * Must be called after prepareVideo. */ fun changeVideoSourceScreen(mediaProjection: MediaProjection) { glInterface.setForceRender(true) videoManager.changeSourceScreen(mediaProjection) } /** * Disable video stopping process video frames from video source. * You can return to camera/screen video using changeVideoSourceCamera/changeVideoSourceScreen * * @NOTE: * This isn't recommended because it isn't supported in all servers/players. * Use BlackFilterRender to send only black images is recommended. */ fun changeVideoSourceDisabled() { glInterface.setForceRender(false) videoManager.changeVideoSourceDisabled() } /** * Change audio source to Microphone. * Must be called after prepareAudio. */ fun changeAudioSourceMicrophone() { audioManager.changeSourceMicrophone() } /** * Change audio source to Internal. * Must be called after prepareAudio. */ @RequiresApi(Build.VERSION_CODES.Q) fun changeAudioSourceInternal(mediaProjection: MediaProjection) { audioManager.changeSourceInternal(mediaProjection) } /** * Disable audio stopping process audio frames from audio source. * You can return to microphone/internal audio using changeAudioSourceMicrophone/changeAudioSourceInternal * * @NOTE: * This isn't recommended because it isn't supported in all servers/players. * Use mute and unMute to send empty audio is recommended */ fun changeAudioSourceDisabled() { audioManager.changeAudioSourceDisabled() } /** * Set a custom size of audio buffer input. * If you set 0 or less you can disable it to use library default value. * Must be called before of prepareAudio method. * * @param size in bytes. Recommended multiple of 1024 (2048, 4096, 8196, etc) */ fun setAudioMaxInputSize(size: Int) { audioManager.setMaxInputSize(size) } /** * Mute microphone or internal audio. * Must be called after prepareAudio. */ fun mute() { audioManager.mute() } /** * Mute microphone or internal audio. * Must be called after prepareAudio. */ fun unMute() { audioManager.unMute() } /** * Check if microphone or internal audio is muted. * Must be called after prepareAudio. */ fun isMuted(): Boolean = audioManager.isMuted() /** * Switch between front or back camera if using Camera1 or Camera2. * Must be called after prepareVideo. */ fun switchCamera() { videoManager.switchCamera() } /** * get if using front or back camera with Camera1 or Camera2. * Must be called after prepareVideo. */ fun getCameraFacing(): CameraHelper.Facing = videoManager.getCameraFacing() /** * Get camera resolutions. * * @param source select camera source (Camera1 or Camera2) of the required resolutions. * @param facing indicate if resolutions provide from front camera or back camera. */ fun getCameraResolutions(source: VideoManager.Source, facing: CameraHelper.Facing): List<Size> { return videoManager.getCameraResolutions(source, facing) } /** * Set exposure to Camera1 or Camera2. Ignored with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun setExposure(level: Int) { videoManager.setExposure(level) } /** * @return exposure of Camera1 or Camera2. 0 with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will return 0. */ fun getExposure(): Int = videoManager.getExposure() /** * Enable lantern using Camera1 or Camera2. Ignored with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun enableLantern() { videoManager.enableLantern() } /** * Disable lantern using Camera1 or Camera2. Ignored with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun disableLantern() { videoManager.disableLantern() } /** * @return lantern state using Camera1 or Camera2. False with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will return false. */ fun isLanternEnabled(): Boolean = videoManager.isLanternEnabled() /** * Enable auto focus using Camera1 or Camera2. Ignored with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun enableAutoFocus() { videoManager.enableAutoFocus() } /** * Disable auto focus using Camera1 or Camera2. Ignored with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun disableAutoFocus() { videoManager.disableAutoFocus() } /** * @return auto focus state using Camera1 or Camera2. False with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will return false. */ fun isAutoFocusEnabled(): Boolean = videoManager.isAutoFocusEnabled() /** * Set zoom to Camera1 or Camera2. Ignored with other video source. * This method is used with onTouch event to implement zoom with gestures. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun setZoom(event: MotionEvent) { videoManager.setZoom(event) } /** * Set zoom to Camera1 or Camera2. Ignored with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will be ignored. */ fun setZoom(level: Float) { videoManager.setZoom(level) } /** * @return zoom range (min and max) using Camera1 or Camera2. Range(0f, 0f) with other video source * * Must be called with isOnPreview, isStreaming or isRecording true or will return Range(0f, 0f). */ fun getZoomRange(): Range<Float> = videoManager.getZoomRange() /** * @return current zoom using Camera1 or Camera2. 0f with other video source. * * Must be called with isOnPreview, isStreaming or isRecording true or will return 0f. */ fun getZoom(): Float = videoManager.getZoom() /** * Change stream orientation depend of activity orientation. * This method affect ro preview and stream. * Must be called after prepareVideo. */ fun setOrientation(orientation: Int) { glInterface.setCameraOrientation(orientation) } /** * Retries to connect with the given delay. You can pass an optional backupUrl * if you'd like to connect to your backup server instead of the original one. * Given backupUrl replaces the original one. */ @JvmOverloads fun reTry(delay: Long, reason: String, backupUrl: String? = null): Boolean { val result = shouldRetry(reason) if (result) { videoEncoder.requestKeyframe() reConnect(delay, backupUrl) } return result } /** * Get glInterface used to render video. * This is useful to send filters to stream. * Must be called after prepareVideo. */ fun getGlInterface(): GlStreamInterface = glInterface fun setRecordController(recordController: BaseRecordController) { if (!isRecording) this.recordController = recordController } /** * return surface texture that can be used to render and encode custom data. Return null if video not prepared. * start and stop rendering must be managed by the user. */ fun getSurfaceTexture(): SurfaceTexture { if (videoSource != VideoManager.Source.DISABLED) { throw IllegalStateException("getSurfaceTexture only available with VideoManager.Source.DISABLED") } return glInterface.getSurfaceTexture() } protected fun setVideoMime(videoMime: String) { recordController.setVideoMime(videoMime) videoEncoder.type = videoMime } protected fun getVideoResolution() = Size(videoEncoder.width, videoEncoder.height) protected fun getVideoFps() = videoEncoder.fps private fun startSources() { if (!glInterface.running) glInterface.start() if (!videoManager.isRunning()) { videoManager.start(glInterface.getSurfaceTexture()) } audioManager.start() videoEncoder.start() audioEncoder.start() glInterface.addMediaCodecSurface(videoEncoder.inputSurface) } private fun stopSources() { if (!isOnPreview) videoManager.stop() audioManager.stop() videoEncoder.stop() audioEncoder.stop() glInterface.removeMediaCodecSurface() if (!isOnPreview) glInterface.stop() if (!isRecording) recordController.resetFormats() } private fun prepareEncoders(): Boolean { return videoEncoder.prepareVideoEncoder() && audioEncoder.prepareAudioEncoder() } override fun inputPCMData(frame: Frame) { audioEncoder.inputPCMData(frame) } override fun onVideoFormat(mediaFormat: MediaFormat) { recordController.setVideoFormat(mediaFormat) } override fun onAudioFormat(mediaFormat: MediaFormat) { recordController.setAudioFormat(mediaFormat) } override fun onSpsPpsVps(sps: ByteBuffer, pps: ByteBuffer, vps: ByteBuffer?) { onSpsPpsVpsRtp(sps.duplicate(), pps.duplicate(), vps?.duplicate()) } override fun getVideoData(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) { getH264DataRtp(h264Buffer, info) recordController.recordVideo(h264Buffer, info) } override fun getAacData(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { getAacDataRtp(aacBuffer, info) recordController.recordAudio(aacBuffer, info) } protected abstract fun audioInfo(sampleRate: Int, isStereo: Boolean) protected abstract fun rtpStartStream(endPoint: String) protected abstract fun rtpStopStream() protected abstract fun setAuthorization(user: String?, password: String?) protected abstract fun onSpsPpsVpsRtp(sps: ByteBuffer, pps: ByteBuffer, vps: ByteBuffer?) protected abstract fun getH264DataRtp(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) protected abstract fun getAacDataRtp(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) protected abstract fun shouldRetry(reason: String): Boolean protected abstract fun reConnect(delay: Long, backupUrl: String?) abstract fun setReTries(reTries: Int) abstract fun hasCongestion(): Boolean abstract fun setLogs(enabled: Boolean) abstract fun setCheckServerAlive(enabled: Boolean) @Throws(RuntimeException::class) abstract fun resizeCache(newSize: Int) abstract fun getCacheSize(): Int abstract fun getSentAudioFrames(): Long abstract fun getSentVideoFrames(): Long abstract fun getDroppedAudioFrames(): Long abstract fun getDroppedVideoFrames(): Long abstract fun resetSentAudioFrames() abstract fun resetSentVideoFrames() abstract fun resetDroppedAudioFrames() abstract fun resetDroppedVideoFrames() }
235
null
749
2,244
0ed4e5cb08235f5189b84cbef1690ca98beb16f0
17,775
RootEncoder
Apache License 2.0
wrapper/Android/AutoE2E/app/src/main/java/com/example/autoe2e/lib/mock/DocumentNode.kt
CreeJee
230,300,137
false
{"JSON": 9, "YAML": 3, "Prisma": 1, "Text": 2, "Ignore List": 4, "Markdown": 2, "JSON with Comments": 2, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 19, "XML": 17, "Java": 3, "JavaScript": 2, "GraphQL": 1, "HTML": 1, "robots.txt": 1, "TSX": 7, "CSS": 2}
package com.example.autoe2e.lib.mock import com.example.autoe2e.lib.types.DocumentNode fun findNode(node: DocumentNode?, nodeUid: Int): DocumentNode? { //tree search //window.children if (node is DocumentNode) { if (node.uid == nodeUid) { return node } for (child in node.children) { val found = findNode(child, nodeUid) if (found !== null) { return found } } } return null }
9
TypeScript
0
1
1a8706d3c2c8b30f514e719e41cfb8bcd878ad2d
494
AutoE2E
MIT License
api/src/main/kotlin/hr/from/josipantolis/seriouscallersonly/api/dsl/Extensions.kt
Antolius
257,456,041
false
null
package hr.from.josipantolis.seriouscallersonly.api.dsl import hr.from.josipantolis.seriouscallersonly.api.* import java.net.URL @DslMarker annotation class BotMarker @BotMarker interface CallScriptExtensions { val String.channel: Channel get() = Channel(id = this) val String.user: User get() = User(id = this) val String.cmd: Command get() = Command(cmd = this) fun channelProtocol(channel: Channel, init: ChannelProtocolBuilder.() -> Unit): ChannelProtocol fun commandProtocol( cmd: Command, cb: suspend ReplierCtx.(msg: Event.CommandInvoked) -> ReplyBuilder ): CommandProtocol fun privateMessageReplier( cb: suspend ReplierCtx.(msg: Event.PrivateMessageReceived) -> ReplyBuilder ): EventReplier.PrivateMessageReceivedReplier fun homeTabVisitReplier( cb: suspend ReplierCtx.(msg: Event.HomeTabVisited) -> ReplyBuilder ): EventReplier.HomeTabVisitedReplier fun botJoinedChannelReplier( cb: suspend ReplierCtx.(msg: Event.BotJoinedChannel) -> ReplyBuilder ): EventReplier.BotJoinedChannelReplier } class CallScriptExtensionsRoot : CallScriptExtensions { override fun channelProtocol(channel: Channel, init: ChannelProtocolBuilder.() -> Unit): ChannelProtocol { val builder = ChannelProtocolBuilder(channel) builder.init() return builder.build() } override fun commandProtocol( cmd: Command, cb: suspend ReplierCtx.(msg: Event.CommandInvoked) -> ReplyBuilder ) = CommandProtocol( command = cmd, onCommandInvoked = EventReplier.CommandInvokedReplier { ReplierCtx().cb(it).build() } ) override fun privateMessageReplier( cb: suspend ReplierCtx.(msg: Event.PrivateMessageReceived) -> ReplyBuilder ) = EventReplier.PrivateMessageReceivedReplier { ReplierCtx().cb(it).build() } override fun homeTabVisitReplier( cb: suspend ReplierCtx.(msg: Event.HomeTabVisited) -> ReplyBuilder ) = EventReplier.HomeTabVisitedReplier { ReplierCtx().cb(it).build() } override fun botJoinedChannelReplier( cb: suspend ReplierCtx.(msg: Event.BotJoinedChannel) -> ReplyBuilder ) = EventReplier.BotJoinedChannelReplier { ReplierCtx().cb(it).build() } } @BotMarker class ChannelProtocolBuilder(private val channel: Channel) { private var timerProtocol: TimerProtocol? = null private var onPublicMessage: EventReplier.PublicMessagePostedReplier? = null private var onUserJoined: EventReplier.UserJoinedChannelReplier? = null fun build() = ChannelProtocol( channel = channel, onUserJoined = onUserJoined, onPublicMessage = onPublicMessage, timerProtocol = timerProtocol ) fun onTimer(cron: String, cb: suspend ReplierCtx.(msg: Event.Timer) -> ReplyBuilder) { timerProtocol = TimerProtocol( cron = cron, onTimer = EventReplier.TimerReplier { ReplierCtx().cb(it).build() } ) } fun onPublicMessage(cb: suspend ReplierCtx.(msg: Event.PublicMessagePosted) -> ReplyBuilder) { onPublicMessage = EventReplier.PublicMessagePostedReplier { ReplierCtx().cb(it).build() } } fun onUserJoined(cb: suspend ReplierCtx.(msg: Event.UserJoinedChannel) -> ReplyBuilder) { onUserJoined = EventReplier.UserJoinedChannelReplier { ReplierCtx().cb(it).build() } } } @BotMarker interface ReplyBuilder { suspend fun build(): Reply } @BotMarker open class ReplierCtx { suspend fun replyPublicly(init: suspend MessageBlocksBuilder.() -> Unit): MessageBuilder { val blocks = MessageBlocksBuilder() blocks.init() return MessageBuilder(Visibility.Public, blocks) } suspend fun replyPrivatelyTo(user: User, init: suspend MessageBlocksBuilder.() -> Unit): MessageBuilder { val blocks = MessageBlocksBuilder() blocks.init() return MessageBuilder(Visibility.Ephemeral(user), blocks) } suspend fun replacePreviousMessageWith(init: suspend MessageBlocksBuilder.() -> Unit): ReplacementMessageBuilder { val blocks = MessageBlocksBuilder() blocks.init() return ReplacementMessageBuilder(blocks) } } @BotMarker class MessageBlocksBuilder { private val blocks = mutableListOf<MessageBlockBuilder>() suspend fun build() = blocks.map { it.build() } val String.md: Element.Text.Markdown get() = Element.Text.Markdown(text = this) val String.txt: Element.Text.Plain get() = Element.Text.Plain(text = this) val String.url: URL get() = URL(this) operator fun MessageBlockBuilder.unaryPlus() { [email protected] += this } val divider = object : MessageBlockBuilder { override suspend fun build() = Block.Divider } suspend fun section( txt: Element.Text.Plain, init: suspend SectionBlockBuilder.() -> Unit = {} ): SectionBlockBuilder { val builder = SectionBlockBuilder(txt) builder.init() return builder } suspend fun section( md: Element.Text.Markdown, init: suspend SectionBlockBuilder.() -> Unit = {} ): SectionBlockBuilder { val builder = SectionBlockBuilder(md) builder.init() return builder } suspend fun actions(init: suspend ActionsBlockBuilder.() -> Unit): ActionsBlockBuilder { val builder = ActionsBlockBuilder() builder.init() return builder } suspend fun context(init: suspend ContextBlockBuilder.() -> Unit): ContextBlockBuilder { val builder = ContextBlockBuilder() builder.init() return builder } fun image(img: Pair<URL, String>) = object : MessageBlockBuilder { override suspend fun build(): Block.Image { val (url, altText) = img return Block.Image(url = url, altText = altText) } } } interface AndThener : ReplyBuilder { suspend fun andThen(cb: suspend ReplierCtx.() -> ReplyBuilder): OnResponser } interface OnResponser : ReplyBuilder { suspend fun onResponse(cb: suspend ReplierCtx.(msg: Event.Interaction.UserResponded) -> ReplyBuilder): AndThener } abstract class ChainableReplyBuilder : AndThener, OnResponser { protected var andThen: Replier? = null protected var onReply: EventReplier.InteractionReplier.UserRespondedReplier? = null override suspend fun andThen(cb: suspend ReplierCtx.() -> ReplyBuilder): OnResponser { andThen = Replier { ReplierCtx().cb().build() } return this } override suspend fun onResponse(cb: suspend ReplierCtx.(msg: Event.Interaction.UserResponded) -> ReplyBuilder): AndThener { onReply = EventReplier.InteractionReplier.UserRespondedReplier { ReplierCtx().cb(it).build() } return this } } class MessageBuilder( private val visibleTo: Visibility, private val blocks: MessageBlocksBuilder ) : ChainableReplyBuilder() { override suspend fun build() = Reply.Message( blocks = blocks.build(), visibleTo = visibleTo, andThen = andThen, onReply = onReply ) } class ReplacementMessageBuilder(private val blocks: MessageBlocksBuilder) : ChainableReplyBuilder() { override suspend fun build() = Reply.ReplacementMessage( blocks = blocks.build(), andThen = andThen, onReply = onReply ) } @BotMarker interface MessageBlockBuilder { suspend fun build(): MessageBlock } class SectionBlockBuilder(private val text: Element.Text) : MessageBlockBuilder { private val fields = mutableListOf<Element.Text>() var accessory: AccessoryBuilder? = null val String.md: Element.Text.Markdown get() = Element.Text.Markdown(text = this) val String.txt: Element.Text.Plain get() = Element.Text.Plain(text = this) val String.url: URL get() = URL(this) operator fun Element.Text.unaryPlus() { fields += this } override suspend fun build() = Block.Section( text = text, fields = if (fields.isNotEmpty()) fields else null, accessory = accessory?.build() ) fun image(img: Pair<URL, String>) = object : AccessoryBuilder { override suspend fun build(): SectionElement { val (url, altText) = img return Element.Image(url, altText) } } val button = ButtonPicker() suspend fun select(txt: Element.Text.Plain, init: suspend SelectBuilder.() -> Unit): AccessoryBuilder { val builder = SelectBuilder(txt) builder.init() return builder } suspend fun overflow(init: suspend OverflowBuilder.() -> Unit): AccessoryBuilder { val builder = OverflowBuilder() builder.init() return builder } } class ActionsBlockBuilder : MessageBlockBuilder { private val elements = mutableListOf<ActionBuilder>() operator fun ActionBuilder.unaryPlus() { [email protected] += this } val String.txt: Element.Text.Plain get() = Element.Text.Plain(text = this) override suspend fun build() = Block.Actions( elements = elements.map { it.build() } ) val button = ButtonPicker() suspend fun overflow(init: suspend OverflowBuilder.() -> Unit): ActionBuilder { val builder = OverflowBuilder() builder.init() return builder } } class ContextBlockBuilder : MessageBlockBuilder { private val elements = mutableListOf<ContextElement>() operator fun ContextElement.unaryPlus() { elements += this } val String.md: Element.Text.Markdown get() = Element.Text.Markdown(text = this) val String.txt: Element.Text.Plain get() = Element.Text.Plain(text = this) val String.url: URL get() = URL(this) fun image(img: Pair<URL, String>): ContextElement { val (url, altText) = img return Element.Image(url, altText) } override suspend fun build() = Block.Context(elements) } class ButtonPicker { suspend operator fun invoke( txt: Element.Text.Plain, cb: suspend ReplierCtx.(msg: Event.Interaction.ButtonClicked) -> ReplyBuilder ) = builder(txt, ButtonStyle.DEFAULT, cb) suspend fun primary( txt: Element.Text.Plain, cb: suspend ReplierCtx.(msg: Event.Interaction.ButtonClicked) -> ReplyBuilder ) = builder(txt, ButtonStyle.PRIMARY, cb) suspend fun danger( txt: Element.Text.Plain, cb: suspend ReplierCtx.(msg: Event.Interaction.ButtonClicked) -> ReplyBuilder ) = builder(txt, ButtonStyle.DANGER, cb) private suspend fun builder( txt: Element.Text.Plain, style: ButtonStyle, cb: suspend ReplierCtx.(msg: Event.Interaction.ButtonClicked) -> ReplyBuilder ) = object : ButtonBuilder { override suspend fun build() = Element.Button( text = txt, style = style, onClick = EventReplier.InteractionReplier.ButtonClickedReplier { ReplierCtx().cb(it).build() } ) } } @BotMarker interface AccessoryBuilder { suspend fun build(): SectionElement } @BotMarker interface ActionBuilder { suspend fun build(): ActionElement } interface ButtonBuilder : AccessoryBuilder, ActionBuilder { override suspend fun build(): Element.Button } class SelectBuilder(private val txt: Element.Text.Plain) : AccessoryBuilder { private val options = mutableListOf<OptionBuilder>() operator fun OptionBuilder.unaryPlus() { options += this } val String.txt: Element.Text.Plain get() = Element.Text.Plain(text = this) override suspend fun build() = Element.Select( placeholder = txt, options = options.map { it.build() } ) fun option(txt: Element.Text.Plain, cb: suspend ReplierCtx.(msg: Event.Interaction.OptionPicked) -> ReplyBuilder) = OptionBuilder(txt, cb) } class OptionBuilder( private val txt: Element.Text.Plain, private val cb: suspend ReplierCtx.(msg: Event.Interaction.OptionPicked) -> ReplyBuilder ) { suspend fun build() = Option( text = txt, onPick = EventReplier.InteractionReplier.OptionPickedReplier { ReplierCtx().cb(it).build() } ) } class OverflowBuilder : AccessoryBuilder, ActionBuilder { private val options = mutableListOf<OptionBuilder>() operator fun OptionBuilder.unaryPlus() { options += this } val String.txt: Element.Text.Plain get() = Element.Text.Plain(text = this) fun option(txt: Element.Text.Plain, cb: suspend ReplierCtx.(msg: Event.Interaction.OptionPicked) -> ReplyBuilder) = OptionBuilder(txt, cb) override suspend fun build() = Element.Overflow( options = options.map { it.build() } ) }
0
Kotlin
0
2
49bca9f3edb7d386fae77a6404babc6ace18a87f
12,843
serious-callers-only
MIT License
app/src/main/java/com/hakmar/employeelivetracking/features/store_detail_tasks/ui/screen/StoreOutsideScreen.kt
enginemre
584,733,724
false
null
package com.hakmar.employeelivetracking.features.store_detail_tasks.ui.screen import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.core.screen.ScreenKey import cafe.adriel.voyager.hilt.getScreenModel import cafe.adriel.voyager.hilt.getViewModel import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import com.hakmar.employeelivetracking.R import com.hakmar.employeelivetracking.common.presentation.graphs.HomeDestination import com.hakmar.employeelivetracking.common.presentation.graphs.StoreDetailDestination import com.hakmar.employeelivetracking.common.presentation.ui.MainViewModel import com.hakmar.employeelivetracking.common.presentation.ui.components.AppBarState import com.hakmar.employeelivetracking.common.presentation.ui.components.CustomSnackbarVisuals import com.hakmar.employeelivetracking.common.presentation.ui.components.DevicePreviews import com.hakmar.employeelivetracking.common.presentation.ui.components.LargeButton import com.hakmar.employeelivetracking.common.presentation.ui.components.LocalSnackbarHostState import com.hakmar.employeelivetracking.common.presentation.ui.theme.EmployeeLiveTrackingTheme import com.hakmar.employeelivetracking.common.presentation.ui.theme.Natural110 import com.hakmar.employeelivetracking.common.presentation.ui.theme.spacing import com.hakmar.employeelivetracking.features.store_detail_tasks.ui.component.StoreCheckCard import com.hakmar.employeelivetracking.features.store_detail_tasks.ui.event.StoreOutsideEvent import com.hakmar.employeelivetracking.features.store_detail_tasks.ui.event.TaskValidated import com.hakmar.employeelivetracking.features.store_detail_tasks.ui.viewmodel.StoreOutsideScreenModel import com.hakmar.employeelivetracking.util.UiEvent import com.hakmar.employeelivetracking.util.getContainerColor import com.hakmar.employeelivetracking.util.getContentColor class StoreOutsideScreen(val storeCode: String) : Screen { override val key: ScreenKey get() = StoreDetailDestination.StoreOutside.base @Composable override fun Content() { val mainViewModel: MainViewModel = getViewModel() val viewModel = getScreenModel<StoreOutsideScreenModel, StoreOutsideScreenModel.Factory> { factory -> factory.create(storeCode) } val state by viewModel.state.collectAsStateWithLifecycle() val checkList = viewModel.checkList val snackbarHostState = LocalSnackbarHostState.current val context = LocalContext.current val title = stringResource(id = R.string.store_outside_title) val navigator = LocalNavigator.currentOrThrow LaunchedEffect(key1 = Unit) { mainViewModel.updateAppBar( AppBarState( isNavigationButton = true, title = title, navigationClick = { navigator.pop() } ) ) } LaunchedEffect(key1 = Unit) { viewModel.uiEvent.collect { event -> when (event) { is UiEvent.ShowSnackBar -> { snackbarHostState.showSnackbar( CustomSnackbarVisuals( message = event.message.asString(context), contentColor = getContentColor(event.type), containerColor = getContainerColor(event.type) ) ) } is UiEvent.Navigate<*> -> { when (event.route) { HomeDestination.StoreDetail.base -> { navigator.pop() mainViewModel.postEvent(TaskValidated.StoreOutsideValidated) } } } else -> Unit } } } LazyColumn { state.headers.forEach { header -> item( contentType = "header" ) { Text( modifier = Modifier .fillMaxWidth() .padding( horizontal = MaterialTheme.spacing.small, vertical = MaterialTheme.spacing.small ), text = header, style = MaterialTheme.typography.bodyMedium.copy( color = Natural110, fontWeight = FontWeight.W500, fontSize = 16.sp, lineHeight = 24.sp ) ) } items(checkList.filter { it.type == header }) { checkItem -> StoreCheckCard( modifier = Modifier.padding( vertical = MaterialTheme.spacing.small, horizontal = MaterialTheme.spacing.small ), checked = checkItem.completed, description = checkItem.description, onChecked = { viewModel.onEvent(StoreOutsideEvent.OnChecked(checkItem)) } ) } } item { LargeButton( modifier = Modifier .fillMaxWidth() .padding( horizontal = MaterialTheme.spacing.small, vertical = MaterialTheme.spacing.medium ), text = stringResource(id = R.string.okey), onClick = { viewModel.onEvent(StoreOutsideEvent.CompleteCheck) }) } } } } @DevicePreviews @Composable private fun StoreOutsideScreenPrev() { EmployeeLiveTrackingTheme { LazyColumn { listOf( "Claim requested credentials", "Claim received credentials", "Pending Requests" ).forEach { header -> item( contentType = "header" ) { Text( modifier = Modifier .fillMaxWidth() .padding( horizontal = MaterialTheme.spacing.small, vertical = MaterialTheme.spacing.small ), text = header, style = MaterialTheme.typography.bodyMedium.copy( color = Natural110, fontWeight = FontWeight.W500, fontSize = 16.sp, lineHeight = 24.sp ) ) } items( count = 10 ) { StoreCheckCard( modifier = Modifier.padding( vertical = MaterialTheme.spacing.small, horizontal = MaterialTheme.spacing.small ), checked = true, description = "sdsadkfdlsşkfldsaşakldsflşkdfsaşlkdfs", onChecked = {} ) } } item { LargeButton( modifier = Modifier .fillMaxWidth() .padding( horizontal = MaterialTheme.spacing.small, vertical = MaterialTheme.spacing.medium ), text = "Onayla", onClick = { }) } } } }
0
Kotlin
0
0
5e348e0a5aac89b4e60607a14a4ef9bbd68545a5
8,781
employee_live_tracking
The Unlicense
app/src/main/java/com/mathroda/messengerclone/ui/messages/components/MessengerCloneMessagesComposer.kt
MathRoda
516,097,712
false
null
package com.erdi.messengerclone.ui.messages.components import android.widget.Toast import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.getstream.sdk.chat.utils.MediaStringUtil import com.erdi.messengerclone.R import com.erdi.messengerclone.ui.messages.util.ComposerIcon import com.erdi.messengerclone.ui.messages.util.CustomMessageInput import com.erdi.messengerclone.ui.theme.BottomSelected import io.getstream.chat.android.client.models.* import io.getstream.chat.android.common.composer.MessageComposerState import io.getstream.chat.android.common.state.MessageMode import io.getstream.chat.android.common.state.ValidationError import io.getstream.chat.android.compose.ui.components.composer.CoolDownIndicator import io.getstream.chat.android.compose.ui.components.composer.MessageInputOptions import io.getstream.chat.android.compose.ui.components.suggestions.commands.CommandSuggestionList import io.getstream.chat.android.compose.ui.components.suggestions.mentions.MentionSuggestionList import io.getstream.chat.android.compose.ui.messages.composer.* import io.getstream.chat.android.compose.ui.theme.ChatTheme import io.getstream.chat.android.compose.ui.util.mirrorRtl import io.getstream.chat.android.compose.viewmodel.messages.MessageComposerViewModel @Composable fun MessengerCloneMessagesComposer( viewModel: MessageComposerViewModel, modifier: Modifier = Modifier, onSendMessage: (Message) -> Unit = { viewModel.sendMessage(it) }, onAttachmentsClick: () -> Unit = {}, onValueChange: (String) -> Unit = { viewModel.setMessageInput(it) }, onAttachmentRemoved: (Attachment) -> Unit = { viewModel.removeSelectedAttachment(it) }, onCancelAction: () -> Unit = { viewModel.dismissMessageActions() }, onMentionSelected: (User) -> Unit = { viewModel.selectMention(it) }, onCommandSelected: (Command) -> Unit = { viewModel.selectCommand(it) }, onAlsoSendToChannelSelected: (Boolean) -> Unit = { viewModel.setAlsoSendToChannel(it) }, headerContent: @Composable ColumnScope.(MessageComposerState) -> Unit = { DefaultMessageComposerHeaderContent( messageComposerState = it, onCancelAction = onCancelAction ) }, footerContent: @Composable ColumnScope.(MessageComposerState) -> Unit = { DefaultMessageComposerFooterContent( messageComposerState = it, onAlsoSendToChannelSelected = onAlsoSendToChannelSelected ) }, mentionPopupContent: @Composable (List<User>) -> Unit = { DefaultMentionPopupContent( mentionSuggestions = it, onMentionSelected = onMentionSelected ) }, commandPopupContent: @Composable (List<Command>) -> Unit = { DefaultCommandPopupContent( commandSuggestions = it, onCommandSelected = onCommandSelected ) }, integrations: @Composable RowScope.(MessageComposerState) -> Unit = { DefaultComposerIntegration( messageInputState = it, onAttachmentsClick = onAttachmentsClick, ownCapabilities = it.ownCapabilities ) }, label: @Composable (MessageComposerState) -> Unit = { DefaultComposerLabel(it.ownCapabilities) }, input: @Composable RowScope.(MessageComposerState) -> Unit = { DefaultComposerInputContent( messageComposerState = it, onValueChange = onValueChange, onAttachmentRemoved = onAttachmentRemoved, label = label, ) }, trailingContent: @Composable (MessageComposerState) -> Unit = { DefaultMessageComposerTrailingContent( value = it.inputValue, coolDownTime = it.coolDownTime, validationErrors = it.validationErrors, attachments = it.attachments, ownCapabilities = it.ownCapabilities, onSendMessage = { input, attachments -> val message = viewModel.buildNewMessage(input, attachments) onSendMessage(message) } ) }, ) { val messageComposerState by viewModel.messageComposerState.collectAsState() MessageComposer( modifier = modifier, onSendMessage = { text, attachments -> val messageWithData = viewModel.buildNewMessage(text, attachments) onSendMessage(messageWithData) }, onMentionSelected = onMentionSelected, onCommandSelected = onCommandSelected, onAlsoSendToChannelSelected = onAlsoSendToChannelSelected, headerContent = headerContent, footerContent = footerContent, mentionPopupContent = mentionPopupContent, commandPopupContent = commandPopupContent, integrations = integrations, input = input, trailingContent = trailingContent, messageComposerState = messageComposerState, onCancelAction = onCancelAction ) } /** * Represents the default content shown at the top of the message composer component. * * @param messageComposerState The state of the message composer. * @param onCancelAction Handler for the cancel button on Message actions, such as Edit and Reply. */ @Composable fun DefaultMessageComposerHeaderContent( messageComposerState: MessageComposerState, onCancelAction: () -> Unit, ) { val activeAction = messageComposerState.action if (activeAction != null) { MessageInputOptions( modifier = Modifier .fillMaxWidth() .padding(top = 8.dp, bottom = 6.dp, start = 8.dp, end = 8.dp), activeAction = activeAction, onCancelAction = onCancelAction ) } } /** * Represents the default content shown at the bottom of the message composer component. * * @param messageComposerState The state of the message composer. * @param onAlsoSendToChannelSelected Handler when the user checks the also send to channel checkbox. */ @Composable fun DefaultMessageComposerFooterContent( messageComposerState: MessageComposerState, onAlsoSendToChannelSelected: (Boolean) -> Unit, ) { if (messageComposerState.messageMode is MessageMode.MessageThread) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { Checkbox( checked = messageComposerState.alsoSendToChannel, onCheckedChange = { onAlsoSendToChannelSelected(it) }, colors = CheckboxDefaults.colors(ChatTheme.colors.primaryAccent) ) Spacer(modifier = Modifier.width(8.dp)) Text( text = stringResource(R.string.stream_compose_message_composer_show_in_channel), color = ChatTheme.colors.textLowEmphasis, textAlign = TextAlign.Center, style = ChatTheme.typography.body ) } } } /** * Represents the default mention suggestion list popup shown above the message composer. * * @param mentionSuggestions The list of users that can be used to autocomplete the current mention input. * @param onMentionSelected Handler when the user taps on a mention suggestion item. */ @Composable internal fun DefaultMentionPopupContent( mentionSuggestions: List<User>, onMentionSelected: (User) -> Unit, ) { MentionSuggestionList( users = mentionSuggestions, onMentionSelected = { onMentionSelected(it) } ) } /** * Represents the default command suggestion list popup shown above the message composer. * * @param commandSuggestions The list of available commands in the channel. * @param onCommandSelected Handler when the user taps on a command suggestion item. */ @Composable internal fun DefaultCommandPopupContent( commandSuggestions: List<Command>, onCommandSelected: (Command) -> Unit, ) { CommandSuggestionList( commands = commandSuggestions, onCommandSelected = { onCommandSelected(it) } ) } /** * Composable that represents the message composer integrations (special actions). * * Currently just shows the Attachment picker action. * * @param messageInputState The state of the input. * @param onAttachmentsClick Handler when the user selects attachments. * @param onCommandsClick Handler when the user selects commands. * @param ownCapabilities Set of capabilities the user is given for the current channel. * For a full list @see [io.getstream.chat.android.client.models.ChannelCapabilities]. */ @Composable internal fun DefaultComposerIntegration( messageInputState: MessageComposerState, onAttachmentsClick: () -> Unit, ownCapabilities: Set<String>, ) { val hasTextInput = messageInputState.inputValue.isNotEmpty() val hasAttachments = messageInputState.attachments.isNotEmpty() val hasCommandInput = messageInputState.inputValue.startsWith("/") val hasCommandSuggestions = messageInputState.commandSuggestions.isNotEmpty() val hasMentionSuggestions = messageInputState.mentionSuggestions.isNotEmpty() val isAttachmentsButtonEnabled = !hasCommandInput && !hasCommandSuggestions && !hasMentionSuggestions val isCommandsButtonEnabled = !hasTextInput && !hasAttachments val canSendMessage = ownCapabilities.contains(ChannelCapabilities.SEND_MESSAGE) val canSendAttachments = ownCapabilities.contains(ChannelCapabilities.UPLOAD_FILE) AnimatedVisibility( visible = !hasTextInput ) { if (canSendMessage) { Row( modifier = Modifier .height(44.dp) .padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically ) { if (canSendAttachments) { ComposerIcon( modifier = Modifier.size(30.dp), enabled = false, painter = painterResource(id = R.drawable.ic_four_points) ) { } ComposerIcon( modifier = Modifier.size(38.dp), enabled = false, painter = painterResource(id = R.drawable.ic_new_camera) ) { } ComposerIcon( enabled = isAttachmentsButtonEnabled, painter = painterResource(id = R.drawable.ic_gallery) ) { onAttachmentsClick() } ComposerIcon( modifier = Modifier.size(38.dp), enabled = false, painter = painterResource(id = R.drawable.ic_mic) ) { } } } } else { Spacer(modifier = Modifier.width(12.dp)) } } } /** * Default input field label that the user can override in [MessageComposer]. * * @param ownCapabilities Set of capabilities the user is given for the current channel. * For a full list @see [io.getstream.chat.android.client.models.ChannelCapabilities]. */ @Composable internal fun DefaultComposerLabel(ownCapabilities: Set<String>) { val text = if (ownCapabilities.contains(ChannelCapabilities.SEND_MESSAGE)) { "Aa" } else { stringResource(id = R.string.stream_compose_cannot_send_messages_label) } Text( text = text, color = ChatTheme.colors.textLowEmphasis ) } /** * Represents the default input content of the Composer. * * @param label Customizable composable that represents the input field label (hint). * @param messageComposerState The state of the message input. * @param onValueChange Handler when the input field value changes. * @param onAttachmentRemoved Handler when the user taps on the cancel/delete attachment action. */ @Composable fun RowScope.DefaultComposerInputContent( messageComposerState: MessageComposerState, onValueChange: (String) -> Unit, onAttachmentRemoved: (Attachment) -> Unit, label: @Composable (MessageComposerState) -> Unit, ) { CustomMessageInput( modifier = Modifier .fillMaxWidth() .padding(vertical = 6.dp, horizontal = 4.dp) .weight(1f), label = label, messageComposerState = messageComposerState, onValueChange = onValueChange, onAttachmentRemoved = onAttachmentRemoved, innerTrailingContent = { IconButton( modifier = Modifier .size(18.dp), content = { Icon( painter = painterResource(id = R.drawable.ic_emoji), contentDescription = null, tint = BottomSelected, ) }, onClick = { } ) } ) } /** * Represents the default trailing content for the Composer, which represent a send button or a cooldown timer. * * @param value The input value. * @param coolDownTime The amount of time left in cool-down mode. * @param attachments The selected attachments. * @param validationErrors List of errors for message validation. * @param onSendMessage Handler when the user wants to send a message. * @param ownCapabilities Set of capabilities the user is given for the current channel. * For a full list @see [io.getstream.chat.android.client.models.ChannelCapabilities]. */ @Composable internal fun DefaultMessageComposerTrailingContent( value: String, coolDownTime: Int, attachments: List<Attachment>, validationErrors: List<ValidationError>, ownCapabilities: Set<String>, onSendMessage: (String, List<Attachment>) -> Unit, ) { val isSendButtonEnabled = ownCapabilities.contains(ChannelCapabilities.SEND_MESSAGE) val isInputValid by lazy { (value.isNotBlank() || attachments.isNotEmpty()) && validationErrors.isEmpty() } val description = stringResource(id = R.string.stream_compose_cd_send_button) if (coolDownTime > 0) { CoolDownIndicator(coolDownTime = coolDownTime) } else { IconButton( modifier = Modifier.semantics { contentDescription = description }, enabled = isSendButtonEnabled && isInputValid, content = { val layoutDirection = LocalLayoutDirection.current Icon( modifier = Modifier.mirrorRtl(layoutDirection = layoutDirection), painter = painterResource(id = R.drawable.ic_send), contentDescription = stringResource(id = R.string.stream_compose_send_message), tint = BottomSelected ) }, onClick = { if (isInputValid) { onSendMessage(value, attachments) } } ) } } /** * Shows a [Toast] with an error if one of the following constraints are violated: * * - The message length exceeds the maximum allowed message length. * - The number of selected attachments is too big. * - At least one of the attachments is too big. * * @param validationErrors The list of validation errors for the current user input. */ @Composable private fun MessageInputValidationError(validationErrors: List<ValidationError>, snackbarHostState: SnackbarHostState) { if (validationErrors.isNotEmpty()) { val firstValidationError = validationErrors.first() val errorMessage = when (firstValidationError) { is ValidationError.MessageLengthExceeded -> { stringResource( R.string.stream_compose_message_composer_error_message_length, firstValidationError.maxMessageLength ) } is ValidationError.AttachmentCountExceeded -> { stringResource( R.string.stream_compose_message_composer_error_attachment_count, firstValidationError.maxAttachmentCount ) } is ValidationError.AttachmentSizeExceeded -> { stringResource( R.string.stream_compose_message_composer_error_file_size, MediaStringUtil.convertFileSizeByteCount(firstValidationError.maxAttachmentSize) ) } is ValidationError.ContainsLinksWhenNotAllowed -> { stringResource( R.string.stream_compose_message_composer_error_sending_links_not_allowed, ) } } val context = LocalContext.current LaunchedEffect(validationErrors.size) { if (firstValidationError is ValidationError.ContainsLinksWhenNotAllowed) { snackbarHostState.showSnackbar( message = errorMessage, actionLabel = context.getString(R.string.stream_compose_ok), duration = SnackbarDuration.Indefinite ) } else { Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show() } } } }
1
null
12
96
f6bb09079f35e14e7fceb1bfbad1fa49e9c58daa
17,766
Messenger-clone
Apache License 2.0
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsQuickActionsToolbarPopup.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.actions import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.HelpTooltip import com.intellij.ide.actions.GotoClassPresentationUpdater.getActionTitlePluralized import com.intellij.ide.ui.customization.CustomActionsSchema import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.actions.IconWithTextAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsActions import com.intellij.openapi.vcs.VcsBundle import com.intellij.util.ui.JBInsets import java.awt.Color import java.awt.Insets import java.awt.Point import java.awt.event.MouseEvent import javax.swing.FocusManager import javax.swing.JComponent /** * Vcs quick popup action which is shown in the new toolbar and has two different presentations * depending on vcs repo availability */ open class VcsQuickActionsToolbarPopup : IconWithTextAction(), CustomComponentAction, DumbAware { inner class MyActionButtonWithText( action: AnAction, presentation: Presentation, place: String, ) : ActionButtonWithText(action, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { override fun getInactiveTextColor(): Color = foreground override fun getInsets(): Insets = JBInsets(0, 0, 0, 0) override fun updateToolTipText() { val shortcut = KeymapUtil.getShortcutText("Vcs.QuickListPopupAction") val classesTabName = java.lang.String.join("/", getActionTitlePluralized()) if (Registry.`is`("ide.helptooltip.enabled")) { HelpTooltip.dispose(this) HelpTooltip() .setTitle(VcsBundle.message("Vcs.Toolbar.ShowMoreActions.description")) .setShortcut(shortcut) .installOn(this) } else { toolTipText = VcsBundle.message("Vcs.Toolbar.ShowMoreActions.description", shortcutText, classesTabName) } } fun getShortcut(): String { val shortcuts = KeymapUtil.getActiveKeymapShortcuts(VcsActions.VCS_OPERATIONS_POPUP).shortcuts return KeymapUtil.getShortcutsText(shortcuts) } } open fun getName(project: Project): String? { return null } protected fun updateVcs(project: Project?, e: AnActionEvent): Boolean { if (project == null || e.place !== ActionPlaces.MAIN_TOOLBAR || getName(project) == null || !ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(getName(project))) { e.presentation.isEnabledAndVisible = false return false } return true } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { return object : ActionButtonWithText(this, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { override fun getInactiveTextColor(): Color { return foreground } override fun getInsets(): Insets { return JBInsets(0, 0, 0, 0) } } } override fun actionPerformed(e: AnActionEvent) { val group = DefaultActionGroup() CustomActionsSchema.getInstance().getCorrectedAction(VcsActions.VCS_OPERATIONS_POPUP)?.let { group.add( it) } if (group.childrenCount == 0) return val dataContext = DataManager.getInstance().getDataContext(FocusManager.getCurrentManager().focusOwner) val popup = JBPopupFactory.getInstance().createActionGroupPopup( VcsBundle.message("action.Vcs.Toolbar.QuickListPopupAction.text"), group, dataContext, JBPopupFactory.ActionSelectionAid.NUMBERING, true, null, -1, { action: AnAction? -> true }, ActionPlaces.RUN_TOOLBAR_LEFT_SIDE) val component = e.inputEvent.component popup.showUnderneathOf(component) } override fun update(e: AnActionEvent) { val presentation = e.presentation if (e.project == null || e.place !== ActionPlaces.MAIN_TOOLBAR || ProjectLevelVcsManager.getInstance(e.project!!).hasActiveVcss()) { presentation.isEnabledAndVisible = false return } presentation.isEnabledAndVisible = true presentation.icon = AllIcons.Vcs.BranchNode presentation.text = VcsBundle.message("action.Vcs.Toolbar.ShowMoreActions.text") + " " } companion object { private fun showPopup(e: AnActionEvent, popup: ListPopup) { val mouseEvent = e.inputEvent if (mouseEvent is MouseEvent) { val source = mouseEvent.getSource() if (source is JComponent) { val topLeftCorner = source.locationOnScreen val bottomLeftCorner = Point(topLeftCorner.x, topLeftCorner.y + source.height) popup.setLocation(bottomLeftCorner) popup.show(source) } } } } }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
5,221
intellij-community
Apache License 2.0
jdk_17_maven/cs/rest/familie-tilbake/src/main/kotlin/no/nav/familie/tilbake/behandling/steg/Varselssteg.kt
WebFuzzing
94,008,854
false
null
package no.nav.familie.tilbake.behandling.steg import no.nav.familie.tilbake.behandlingskontroll.BehandlingskontrollService import no.nav.familie.tilbake.behandlingskontroll.Behandlingsstegsinfo import no.nav.familie.tilbake.behandlingskontroll.domain.Behandlingssteg import no.nav.familie.tilbake.behandlingskontroll.domain.Behandlingsstegstatus import no.nav.familie.tilbake.behandlingskontroll.domain.Venteårsak import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.UUID @Service class Varselssteg(private val behandlingskontrollService: BehandlingskontrollService) : IBehandlingssteg { private val logger = LoggerFactory.getLogger(this::class.java) @Transactional override fun utførSteg(behandlingId: UUID) { logger.info("Behandling $behandlingId er på ${Behandlingssteg.VARSEL} steg") logger.info( "Behandling $behandlingId venter på ${Venteårsak.VENT_PÅ_BRUKERTILBAKEMELDING}. " + "Den kan kun tas av vent av saksbehandler ved å gjenoppta behandlingen", ) } @Transactional override fun gjenopptaSteg(behandlingId: UUID) { logger.info("Behandling $behandlingId gjenopptar på ${Behandlingssteg.VARSEL} steg") behandlingskontrollService.oppdaterBehandlingsstegStatus( behandlingId, Behandlingsstegsinfo( Behandlingssteg.VARSEL, Behandlingsstegstatus.UTFØRT, ), ) behandlingskontrollService.fortsettBehandling(behandlingId) } override fun getBehandlingssteg(): Behandlingssteg { return Behandlingssteg.VARSEL } }
21
null
16
26
1777aafb22c6fc7c1bc7db96c86b6ea70e38a36e
1,720
EMB
Apache License 2.0
project-system-gradle/testSrc/com/android/tools/idea/gradle/declarative/runsGradleVersionCatalogAndDeclarative/DeclarativeUnresolvedReferenceTest.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.declarative.runsGradleVersionCatalogAndDeclarative import com.android.SdkConstants.FN_BUILD_GRADLE_DECLARATIVE import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.gradle.dcl.ide.DeclarativeUnresolvedReferenceInspection import com.android.tools.idea.testing.AndroidGradleProjectRule import com.android.tools.idea.testing.TestProjectPaths import com.android.tools.idea.testing.onEdt import com.intellij.openapi.util.registry.Registry import com.intellij.testFramework.RunsInEdt import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test @RunsInEdt class DeclarativeUnresolvedReferenceTest { @get:Rule val projectRule = AndroidGradleProjectRule().onEdt() @Before fun setUp() { Registry.get("android.gradle.ide.gradle.declarative.ide.support").setValue(true) projectRule.fixture.enableInspections(DeclarativeUnresolvedReferenceInspection::class.java) } @After fun tearDown() { Registry.get("android.gradle.ide.gradle.declarative.ide.support").resetToDefault() } @Test fun testWrongReference() { projectRule.loadProject(TestProjectPaths.SIMPLE_APPLICATION_MULTI_VERSION_CATALOG) val file = projectRule.fixture.createFile(FN_BUILD_GRADLE_DECLARATIVE, """ dependencies { implementation(libs.<warning descr="Cannot resolve symbol 'libs.some-guava'">some.guava</warning>) } """.trimIndent()) projectRule.fixture.openFileInEditor(file) projectRule.fixture.checkHighlighting() } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
2,164
android
Apache License 2.0
fixture/src/test/kotlin/com/appmattus/kotlinfixture/resolver/CompositeResolverTest.kt
appmattus
208,850,028
false
{"Gradle Kotlin DSL": 12, "Markdown": 5, "Java Properties": 5, "YAML": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "AsciiDoc": 9, "XML": 14, "Kotlin": 203, "INI": 1, "Java": 3}
/* * Copyright 2019 Appmattus Limited * * 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.appmattus.kotlinfixture.resolver import com.appmattus.kotlinfixture.TestContext import com.appmattus.kotlinfixture.Unresolved import com.appmattus.kotlinfixture.config.Configuration import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class CompositeResolverTest { private val unresolvedResolver1 = mock<Resolver> { on { resolve(any(), any()) } doReturn Unresolved.Unhandled } private val unresolvedResolver2 = mock<Resolver> { on { resolve(any(), any()) } doReturn Unresolved.Unhandled } private val resolvedResolver1 = mock<Resolver> { on { resolve(any(), any()) } doAnswer { it.getArgument<Any>(1) } } @Test fun `Calls all resolvers when unresolved`() { val compositeResolver = CompositeResolver(unresolvedResolver1, unresolvedResolver2) val context = TestContext(Configuration(), compositeResolver) val result = context.resolve(Number::class) verify(unresolvedResolver1).resolve(any(), any()) verify(unresolvedResolver2).resolve(any(), any()) assertTrue(result is Unresolved) } @Test fun `Calls resolvers until resolvable`() { val compositeResolver = CompositeResolver(unresolvedResolver1, resolvedResolver1, unresolvedResolver2) val context = TestContext(Configuration(), compositeResolver) val result = context.resolve(Number::class) verify(unresolvedResolver1).resolve(any(), any()) verify(resolvedResolver1).resolve(any(), any()) verifyNoMoreInteractions(unresolvedResolver2) assertEquals(Number::class, result) } @Test fun `Iterates over resolvers in order`() { val compositeResolver = CompositeResolver(unresolvedResolver1, resolvedResolver1, unresolvedResolver2) assertEquals(listOf(unresolvedResolver1, resolvedResolver1, unresolvedResolver2), compositeResolver.toList()) } }
11
Kotlin
13
252
6d715e3c3a141cb32a5f3fbcd4fb0027ec6ba44c
2,817
kotlinfixture
Apache License 2.0
app/src/main/java/com/morpho/app/lexicons/app/bsky/graph/listitem.kt
morpho-app
752,463,268
false
{"Kotlin": 818890}
package app.bsky.graph import kotlinx.serialization.Serializable import morpho.app.api.AtUri import morpho.app.api.Did import morpho.app.api.model.Timestamp @Serializable public data class Listitem( public val subject: Did, public val list: AtUri, public val createdAt: Timestamp, )
21
Kotlin
0
4
b0a5a163fec50f3fc16e0caabb0036707ab09cb8
291
Morpho
Apache License 2.0
library/src/main/java/software/rsquared/materialcolors/MaterialColor.kt
rSquared-software
191,815,927
false
null
package software.rsquared.materialcolors import android.graphics.Color import android.support.annotation.FloatRange import kotlin.math.roundToInt class MaterialColor { companion object { @JvmField val red: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FFEBEE"), 100 to Color.parseColor("#FFCDD2"), 200 to Color.parseColor("#EF9A9A"), 300 to Color.parseColor("#E57373"), 400 to Color.parseColor("#EF5350"), 500 to Color.parseColor("#F44336"), 600 to Color.parseColor("#E53935"), 700 to Color.parseColor("#D32F2F"), 800 to Color.parseColor("#C62828"), 900 to Color.parseColor("#B71C1C") ) @JvmField val redAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#FF8A80"), 200 to Color.parseColor("#FF5252"), 400 to Color.parseColor("#FF1744"), 700 to Color.parseColor("#D50000") ) @JvmField val pink: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FCE4EC"), 100 to Color.parseColor("#F8BBD0"), 200 to Color.parseColor("#F48FB1"), 300 to Color.parseColor("#F06292"), 400 to Color.parseColor("#EC407A"), 500 to Color.parseColor("#E91E63"), 600 to Color.parseColor("#D81B60"), 700 to Color.parseColor("#C2185B"), 800 to Color.parseColor("#AD1457"), 900 to Color.parseColor("#880E4F") ) @JvmField val pinkAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#FF80AB"), 200 to Color.parseColor("#FF4081"), 400 to Color.parseColor("#F50057"), 700 to Color.parseColor("#C51162") ) @JvmField val purple: Map<Int, Int> = mapOf( 50 to Color.parseColor("#F3E5F5"), 100 to Color.parseColor("#E1BEE7"), 200 to Color.parseColor("#CE93D8"), 300 to Color.parseColor("#BA68C8"), 400 to Color.parseColor("#AB47BC"), 500 to Color.parseColor("#9C27B0"), 600 to Color.parseColor("#8E24AA"), 700 to Color.parseColor("#7B1FA2"), 800 to Color.parseColor("#6A1B9A"), 900 to Color.parseColor("#4A148C") ) @JvmField val purpleAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#EA80FC"), 200 to Color.parseColor("#E040FB"), 400 to Color.parseColor("#D500F9"), 700 to Color.parseColor("#AA00FF") ) @JvmField val deepPurple: Map<Int, Int> = mapOf( 50 to Color.parseColor("#EDE7F6"), 100 to Color.parseColor("#D1C4E9"), 200 to Color.parseColor("#B39DDB"), 300 to Color.parseColor("#9575CD"), 400 to Color.parseColor("#7E57C2"), 500 to Color.parseColor("#673AB7"), 600 to Color.parseColor("#5E35B1"), 700 to Color.parseColor("#512DA8"), 800 to Color.parseColor("#4527A0"), 900 to Color.parseColor("#311B92") ) @JvmField val deepPurpleAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#B388FF"), 200 to Color.parseColor("#7C4DFF"), 400 to Color.parseColor("#651FFF"), 700 to Color.parseColor("#6200EA") ) @JvmField val indigo: Map<Int, Int> = mapOf( 50 to Color.parseColor("#E8EAF6"), 100 to Color.parseColor("#C5CAE9"), 200 to Color.parseColor("#9FA8DA"), 300 to Color.parseColor("#7986CB"), 400 to Color.parseColor("#5C6BC0"), 500 to Color.parseColor("#3F51B5"), 600 to Color.parseColor("#3949AB"), 700 to Color.parseColor("#303F9F"), 800 to Color.parseColor("#283593"), 900 to Color.parseColor("#1A237E") ) @JvmField val indigoAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#8C9EFF"), 200 to Color.parseColor("#536DFE"), 400 to Color.parseColor("#3D5AFE"), 700 to Color.parseColor("#304FFE") ) @JvmField val blue: Map<Int, Int> = mapOf( 50 to Color.parseColor("#E3F2FD"), 100 to Color.parseColor("#BBDEFB"), 200 to Color.parseColor("#90CAF9"), 300 to Color.parseColor("#64B5F6"), 400 to Color.parseColor("#42A5F5"), 500 to Color.parseColor("#2196F3"), 600 to Color.parseColor("#1E88E5"), 700 to Color.parseColor("#1976D2"), 800 to Color.parseColor("#1565C0"), 900 to Color.parseColor("#0D47A1") ) @JvmField val blueAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#82B1FF"), 200 to Color.parseColor("#448AFF"), 400 to Color.parseColor("#2979FF"), 700 to Color.parseColor("#2962FF") ) @JvmField val lightBlue: Map<Int, Int> = mapOf( 50 to Color.parseColor("#E1F5FE"), 100 to Color.parseColor("#B3E5FC"), 200 to Color.parseColor("#81D4FA"), 300 to Color.parseColor("#4FC3F7"), 400 to Color.parseColor("#29B6F6"), 500 to Color.parseColor("#03A9F4"), 600 to Color.parseColor("#039BE5"), 700 to Color.parseColor("#0288D1"), 800 to Color.parseColor("#0277BD"), 900 to Color.parseColor("#01579B") ) @JvmField val lightBlueAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#80D8FF"), 200 to Color.parseColor("#40C4FF"), 400 to Color.parseColor("#00B0FF"), 700 to Color.parseColor("#0091EA") ) @JvmField val cyan: Map<Int, Int> = mapOf( 50 to Color.parseColor("#E0F7FA"), 100 to Color.parseColor("#B2EBF2"), 200 to Color.parseColor("#80DEEA"), 300 to Color.parseColor("#4DD0E1"), 400 to Color.parseColor("#26C6DA"), 500 to Color.parseColor("#00BCD4"), 600 to Color.parseColor("#00ACC1"), 700 to Color.parseColor("#0097A7"), 800 to Color.parseColor("#00838F"), 900 to Color.parseColor("#006064") ) @JvmField val cyanAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#84FFFF"), 200 to Color.parseColor("#18FFFF"), 400 to Color.parseColor("#00E5FF"), 700 to Color.parseColor("#00B8D4") ) @JvmField val teal: Map<Int, Int> = mapOf( 50 to Color.parseColor("#E0F2F1"), 100 to Color.parseColor("#B2DFDB"), 200 to Color.parseColor("#80CBC4"), 300 to Color.parseColor("#4DB6AC"), 400 to Color.parseColor("#26A69A"), 500 to Color.parseColor("#009688"), 600 to Color.parseColor("#00897B"), 700 to Color.parseColor("#00796B"), 800 to Color.parseColor("#00695C"), 900 to Color.parseColor("#004D40") ) @JvmField val tealAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#A7FFEB"), 200 to Color.parseColor("#64FFDA"), 400 to Color.parseColor("#1DE9B6"), 700 to Color.parseColor("#00BFA5") ) @JvmField val green: Map<Int, Int> = mapOf( 50 to Color.parseColor("#E8F5E9"), 100 to Color.parseColor("#C8E6C9"), 200 to Color.parseColor("#A5D6A7"), 300 to Color.parseColor("#81C784"), 400 to Color.parseColor("#66BB6A"), 500 to Color.parseColor("#4CAF50"), 600 to Color.parseColor("#43A047"), 700 to Color.parseColor("#388E3C"), 800 to Color.parseColor("#2E7D32"), 900 to Color.parseColor("#1B5E20") ) @JvmField val greenAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#B9F6CA"), 200 to Color.parseColor("#69F0AE"), 400 to Color.parseColor("#00E676"), 700 to Color.parseColor("#00C853") ) @JvmField val lightGreen: Map<Int, Int> = mapOf( 50 to Color.parseColor("#F1F8E9"), 100 to Color.parseColor("#DCEDC8"), 200 to Color.parseColor("#C5E1A5"), 300 to Color.parseColor("#AED581"), 400 to Color.parseColor("#9CCC65"), 500 to Color.parseColor("#8BC34A"), 600 to Color.parseColor("#7CB342"), 700 to Color.parseColor("#689F38"), 800 to Color.parseColor("#558B2F"), 900 to Color.parseColor("#33691E") ) @JvmField val lightGreenAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#CCFF90"), 200 to Color.parseColor("#B2FF59"), 400 to Color.parseColor("#76FF03"), 700 to Color.parseColor("#64DD17") ) @JvmField val lime: Map<Int, Int> = mapOf( 50 to Color.parseColor("#F9FBE7"), 100 to Color.parseColor("#F0F4C3"), 200 to Color.parseColor("#E6EE9C"), 300 to Color.parseColor("#DCE775"), 400 to Color.parseColor("#D4E157"), 500 to Color.parseColor("#CDDC39"), 600 to Color.parseColor("#C0CA33"), 700 to Color.parseColor("#AFB42B"), 800 to Color.parseColor("#9E9D24"), 900 to Color.parseColor("#827717") ) @JvmField val limeAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#F4FF81"), 200 to Color.parseColor("#EEFF41"), 400 to Color.parseColor("#C6FF00"), 700 to Color.parseColor("#AEEA00") ) @JvmField val yellow: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FFFDE7"), 100 to Color.parseColor("#FFF9C4"), 200 to Color.parseColor("#FFF59D"), 300 to Color.parseColor("#FFF176"), 400 to Color.parseColor("#FFEE58"), 500 to Color.parseColor("#FFEB3B"), 600 to Color.parseColor("#FDD835"), 700 to Color.parseColor("#FBC02D"), 800 to Color.parseColor("#F9A825"), 900 to Color.parseColor("#F57F17") ) @JvmField val yellowAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#FFFF8D"), 200 to Color.parseColor("#FFFF00"), 400 to Color.parseColor("#FFEA00"), 700 to Color.parseColor("#FFD600") ) @JvmField val amber: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FFF8E1"), 100 to Color.parseColor("#FFECB3"), 200 to Color.parseColor("#FFE082"), 300 to Color.parseColor("#FFD54F"), 400 to Color.parseColor("#FFCA28"), 500 to Color.parseColor("#FFC107"), 600 to Color.parseColor("#FFB300"), 700 to Color.parseColor("#FFA000"), 800 to Color.parseColor("#FF8F00"), 900 to Color.parseColor("#FF6F00") ) @JvmField val amberAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#FFE57F"), 200 to Color.parseColor("#FFD740"), 400 to Color.parseColor("#FFC400"), 700 to Color.parseColor("#FFAB00") ) @JvmField val orange: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FFF3E0"), 100 to Color.parseColor("#FFE0B2"), 200 to Color.parseColor("#FFCC80"), 300 to Color.parseColor("#FFB74D"), 400 to Color.parseColor("#FFA726"), 500 to Color.parseColor("#FF9800"), 600 to Color.parseColor("#FB8C00"), 700 to Color.parseColor("#F57C00"), 800 to Color.parseColor("#EF6C00"), 900 to Color.parseColor("#E65100") ) @JvmField val orangeAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#FFD180"), 200 to Color.parseColor("#FFAB40"), 400 to Color.parseColor("#FF9100"), 700 to Color.parseColor("#FF6D00") ) @JvmField val deepOrange: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FBE9E7"), 100 to Color.parseColor("#FFCCBC"), 200 to Color.parseColor("#FFAB91"), 300 to Color.parseColor("#FF8A65"), 400 to Color.parseColor("#FF7043"), 500 to Color.parseColor("#FF5722"), 600 to Color.parseColor("#F4511E"), 700 to Color.parseColor("#E64A19"), 800 to Color.parseColor("#D84315"), 900 to Color.parseColor("#BF360C") ) @JvmField val deepOrangeAccent: Map<Int, Int> = mapOf( 100 to Color.parseColor("#FF9E80"), 200 to Color.parseColor("#FF6E40"), 400 to Color.parseColor("#FF3D00"), 700 to Color.parseColor("#DD2C00") ) @JvmField val brown: Map<Int, Int> = mapOf( 50 to Color.parseColor("#EFEBE9"), 100 to Color.parseColor("#D7CCC8"), 200 to Color.parseColor("#BCAAA4"), 300 to Color.parseColor("#A1887F"), 400 to Color.parseColor("#8D6E63"), 500 to Color.parseColor("#795548"), 600 to Color.parseColor("#6D4C41"), 700 to Color.parseColor("#5D4037"), 800 to Color.parseColor("#4E342E"), 900 to Color.parseColor("#3E2723") ) @JvmField val grey: Map<Int, Int> = mapOf( 50 to Color.parseColor("#FAFAFA"), 100 to Color.parseColor("#F5F5F5"), 200 to Color.parseColor("#EEEEEE"), 300 to Color.parseColor("#E0E0E0"), 400 to Color.parseColor("#BDBDBD"), 500 to Color.parseColor("#9E9E9E"), 600 to Color.parseColor("#757575"), 700 to Color.parseColor("#616161"), 800 to Color.parseColor("#424242"), 900 to Color.parseColor("#212121") ) @JvmField val blueGrey: Map<Int, Int> = mapOf( 50 to Color.parseColor("#ECEFF1"), 100 to Color.parseColor("#CFD8DC"), 200 to Color.parseColor("#B0BEC5"), 300 to Color.parseColor("#90A4AE"), 400 to Color.parseColor("#78909C"), 500 to Color.parseColor("#607D8B"), 600 to Color.parseColor("#546E7A"), 700 to Color.parseColor("#455A64"), 800 to Color.parseColor("#37474F"), 900 to Color.parseColor("#263238"), 1000 to Color.parseColor("#101518") ) @JvmField val black = Color.parseColor("#000000") @JvmField val white = Color.parseColor("#FFFFFF") @JvmField val transparent = Color.parseColor("#00000000") @JvmField val textDark = Color.parseColor("#FFFFFFFF") @JvmField val secondaryTextDark = Color.parseColor("#B3FFFFFF") @JvmField val iconDark = Color.parseColor("#B3FFFFFF") @JvmField val disabledTextDark = Color.parseColor("#4DFFFFFF") @JvmField val hintTextDark = Color.parseColor("#4DFFFFFF") @JvmField val dividerDark = Color.parseColor("#1FFFFFFF") @JvmField val textLight = Color.parseColor("#DE000000") @JvmField val secondaryTextLight = Color.parseColor("#8A000000") @JvmField val iconLight = Color.parseColor("#8A000000") @JvmField val disabledTextLight = Color.parseColor("#61000000") @JvmField val hintTextLight = Color.parseColor("#61000000") @JvmField val dividerLight = Color.parseColor("#1F000000") @JvmStatic fun withAlpha(color: Int, @FloatRange(from = 0.0, to = 1.0) alpha: Float) = Color.argb((alpha * 255f).roundToInt(), Color.red(color), Color.green(color), Color.blue(color)) } }
0
Kotlin
0
0
52edea737ee731fbaa91a3b19724c11296caabc0
16,344
material-colors
Apache License 2.0
library/src/androidMain/kotlin/com/meowool/sweekt/dimension/FloatDps.kt
RinOrz
295,796,281
false
null
package com.meowool.sweekt.dimension import android.content.Context import android.content.res.Resources import android.util.DisplayMetrics import kotlin.math.roundToInt import kotlin.math.roundToLong /** * Converts this density-independent pixels to the int value stands device pixels. * * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ val Float.dpInt: Int get() = (this * Resources.getSystem().displayMetrics.density).roundToInt() /** * Converts this density-independent pixels to the int value stands device pixels by given [context]. * * @see Context.getResources * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ fun Float.dpInt(context: Context): Int = (this * context.resources.displayMetrics.density).roundToInt() /** * Converts this density-independent pixels to the long value stands device pixels. * * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ val Float.dpLong: Long get() = (this * Resources.getSystem().displayMetrics.density).roundToLong() /** * Converts this density-independent pixels to the long value stands device pixels by given [context]. * * @see Context.getResources * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ fun Float.dpLong(context: Context): Long = (this * context.resources.displayMetrics.density).roundToLong() /** * Converts this density-independent pixels to the float value stands device pixels. * * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ val Float.dpFloat: Float get() = this * Resources.getSystem().displayMetrics.density /** * Converts this density-independent pixels to the float value stands device pixels by given [context]. * * @see Context.getResources * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ fun Float.dpFloat(context: Context): Float = this * context.resources.displayMetrics.density /** * Converts this density-independent pixels to the double value stands device pixels. * * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ val Float.dpDouble: Double get() = (this * Resources.getSystem().displayMetrics.density).toDouble() /** * Converts this density-independent pixels to the double value stands device pixels by given [context]. * * @see Context.getResources * @see Resources.getDisplayMetrics * @see DisplayMetrics.density * @author 凛 (RinOrz) */ fun Float.dpDouble(context: Context): Double = (this * context.resources.displayMetrics.density).toDouble()
7
Kotlin
2
35
27d06268f21bebba295d04c0ec1b13019036bac3
2,669
sweekt
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Skull.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.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.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.Skull: ImageVector get() { if (_skull != null) { return _skull!! } _skull = Builder(name = "Skull", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 4.0f) curveToRelative(4.418f, 0.0f, 8.0f, 3.358f, 8.0f, 7.5f) curveToRelative(0.0f, 1.901f, -0.755f, 3.637f, -2.0f, 4.96f) lineToRelative(0.0f, 2.54f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f) horizontalLineToRelative(-10.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineToRelative(-2.54f) curveToRelative(-1.245f, -1.322f, -2.0f, -3.058f, -2.0f, -4.96f) curveToRelative(0.0f, -4.142f, 3.582f, -7.5f, 8.0f, -7.5f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.0f, 17.0f) verticalLineToRelative(3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 17.0f) verticalLineToRelative(3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 11.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 11.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) } } .build() return _skull!! } private var _skull: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,757
compose-icon-collections
MIT License
kotlinpoet-ktx/src/com/hendraanggrian/kotlinpoet/dsl/TypeAliasSpecHandler.kt
hendraanggrian
209,613,746
false
null
package com.hendraanggrian.kotlinpoet.collections import com.hendraanggrian.kotlinpoet.SpecMarker import com.hendraanggrian.kotlinpoet.TypeAliasSpecBuilder import com.hendraanggrian.kotlinpoet.buildTypeAliasSpec import com.hendraanggrian.kotlinpoet.typeAliasSpecOf import com.squareup.kotlinpoet.TypeAliasSpec import com.squareup.kotlinpoet.TypeName import java.lang.reflect.Type import kotlin.reflect.KClass /** An [TypeAliasSpecList] is responsible for managing a set of type alias instances. */ open class TypeAliasSpecList internal constructor(actualList: MutableList<TypeAliasSpec>) : MutableList<TypeAliasSpec> by actualList { /** Add type alias from [TypeName]. */ fun add(name: String, type: TypeName): Boolean = add(typeAliasSpecOf(name, type)) /** Add type alias from [TypeName] with custom initialization [configuration]. */ fun add( name: String, type: TypeName, configuration: TypeAliasSpecBuilder.() -> Unit ): Boolean = add(buildTypeAliasSpec(name, type, configuration)) /** Add type alias from [Type]. */ fun add(name: String, type: Type): Boolean = add(typeAliasSpecOf(name, type)) /** Add type alias from [Type] with custom initialization [configuration]. */ fun add( name: String, type: Type, configuration: TypeAliasSpecBuilder.() -> Unit ): Boolean = add(buildTypeAliasSpec(name, type, configuration)) /** Add type alias from [KClass]. */ fun add(name: String, type: KClass<*>): Boolean = add(typeAliasSpecOf(name, type)) /** Add type alias from [KClass] with custom initialization [configuration]. */ fun add( name: String, type: KClass<*>, configuration: TypeAliasSpecBuilder.() -> Unit ): Boolean = add(buildTypeAliasSpec(name, type, configuration)) /** Add type alias from [T]. */ inline fun <reified T> add(name: String): Boolean = add(typeAliasSpecOf<T>(name)) /** Add type alias from [T] with custom initialization [configuration]. */ inline fun <reified T> add(name: String, noinline configuration: TypeAliasSpecBuilder.() -> Unit): Boolean = add(buildTypeAliasSpec<T>(name, configuration)) /** Convenient method to add type alias with operator function. */ operator fun set(name: String, type: TypeName): Unit = plusAssign(typeAliasSpecOf(name, type)) /** Convenient method to add type alias with operator function. */ operator fun set(name: String, type: Type): Unit = plusAssign(typeAliasSpecOf(name, type)) /** Convenient method to add type alias with operator function. */ operator fun set(name: String, type: KClass<*>): Unit = plusAssign(typeAliasSpecOf(name, type)) } /** Receiver for the `typeAliases` block providing an extended set of operators for the configuration. */ @SpecMarker class TypeAliasSpecListScope internal constructor(actualList: MutableList<TypeAliasSpec>) : TypeAliasSpecList(actualList) { /** @see TypeAliasSpecList.add */ operator fun String.invoke(type: TypeName, configuration: TypeAliasSpecBuilder.() -> Unit): Boolean = add(this, type, configuration) /** @see TypeAliasSpecList.add */ operator fun String.invoke(type: Type, configuration: TypeAliasSpecBuilder.() -> Unit): Boolean = add(this, type, configuration) /** @see TypeAliasSpecList.add */ operator fun String.invoke(type: KClass<*>, configuration: TypeAliasSpecBuilder.() -> Unit): Boolean = add(this, type, configuration) /** @see TypeAliasSpecList.add */ inline operator fun <reified T> String.invoke(noinline configuration: TypeAliasSpecBuilder.() -> Unit): Boolean = add<T>(this, configuration) }
1
Kotlin
0
3
9c7ec6bf017caf34bd20ff4853eb851c791e87af
3,693
kotlinpoet-ktx
Apache License 2.0
experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt
corda
70,137,417
false
null
package net.corda.finance.contracts.universal import net.corda.finance.contracts.Frequency import net.corda.testing.DUMMY_NOTARY import net.corda.testing.transaction import org.junit.Test import java.time.Instant import kotlin.test.assertEquals class RollOutTests { val TEST_TX_TIME_1: Instant get() = Instant.parse("2017-09-02T12:00:00.00Z") val contract = arrange { rollOut("2016-09-01".ld, "2017-09-01".ld, Frequency.Monthly) { actions { (acmeCorp or highStreetBank) may { "transfer".givenThat(after(end)) { highStreetBank.owes(acmeCorp, 10.K, USD) next() } } } } } val contract2 = arrange { rollOut("2016-09-01".ld, "2017-09-01".ld, Frequency.Monthly) { actions { (acmeCorp or highStreetBank) may { "transfer".givenThat(after(end)) { highStreetBank.owes(acmeCorp, 10.K, USD) next() } } } } } val stateStart = UniversalContract.State(listOf(DUMMY_NOTARY), contract) val contractStep1a = arrange { rollOut("2016-10-03".ld, "2017-09-01".ld, Frequency.Monthly) { actions { (acmeCorp or highStreetBank) may { "transfer".givenThat(after(end)) { highStreetBank.owes(acmeCorp, 10.K, USD) next() } } } } } val contractStep1b = arrange { highStreetBank.owes(acmeCorp, 10.K, USD) } val stateStep1a = UniversalContract.State(listOf(DUMMY_NOTARY), contractStep1a) val stateStep1b = UniversalContract.State(listOf(DUMMY_NOTARY), contractStep1b) val contract_transfer1 = arrange { highStreetBank.owes(acmeCorp, 10.K, USD) } val contract_transfer2 = arrange { highStreetBank.owes(acmeCorp, 10.K, USD) } val contract_action1 = arrange { actions { highStreetBank may { "do it" anytime { highStreetBank.owes(acmeCorp, 10.K, USD) } } } } val contract_action2 = arrange { actions { highStreetBank may { "do it" anytime { highStreetBank.owes(acmeCorp, 10.K, USD) } } } } val contract_and1 = arrange { actions { highStreetBank may { "do it" anytime { highStreetBank.owes(acmeCorp, 10.K, USD) } } } actions { acmeCorp may { "do it" anytime { acmeCorp.owes(momAndPop, 10.K, USD) } } } next() } val contract_and2 = arrange { actions { highStreetBank may { "do it" anytime { highStreetBank.owes(acmeCorp, 10.K, USD) } } } actions { acmeCorp may { "do it" anytime { acmeCorp.owes(momAndPop, 10.K, USD) } } } next() } @Test fun `arrangement equality transfer`() { assertEquals(contract_transfer1, contract_transfer2) } @Test fun `arrangement equality action`() { assertEquals(contract_action1, contract_action2) } @Test fun `arrangement equality and`() { assertEquals(contract_and1, contract_and2) } @Test fun `arrangement equality complex`() { assertEquals(contract, contract2) } @Test fun issue() { transaction { output { stateStart } timeWindow(TEST_TX_TIME_1) tweak { command(acmeCorp.owningKey) { UniversalContract.Commands.Issue() } this `fails with` "the transaction is signed by all liable parties" } command(highStreetBank.owningKey) { UniversalContract.Commands.Issue() } this.verifies() } } @Test fun `execute`() { transaction { input { stateStart } output { stateStep1a } output { stateStep1b } timeWindow(TEST_TX_TIME_1) /* tweak { command(highStreetBank.owningKey) { UniversalContract.Commands.Action("some undefined name") } this `fails with` "action must be defined" }*/ command(highStreetBank.owningKey) { UniversalContract.Commands.Action("transfer") } this.verifies() } } }
62
null
1077
3,989
d27aa0e6850d3804d0982024054376d452e7073a
4,839
corda
Apache License 2.0
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/command/EduAppStarterBase.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.command import com.intellij.openapi.application.ModernApplicationStarter import com.intellij.openapi.diagnostic.logger import com.jetbrains.edu.learning.EduUtilsKt import com.jetbrains.edu.learning.courseFormat.Course import com.jetbrains.edu.learning.marketplace.api.MarketplaceConnector import org.apache.commons.cli.* import kotlin.system.exitProcess @Suppress("UnstableApiUsage") abstract class EduAppStarterBase : ModernApplicationStarter() { @Suppress("OVERRIDE_DEPRECATION") abstract override val commandName: String override suspend fun start(args: List<String>) { try { val parsedArgs = parseArgs(args) val course = loadCourse(parsedArgs) val result = doMain(course, parsedArgs) if (result is CommandResult.Error) { LOG.error(result.message, result.throwable) } saveAndExit(result.exitCode) } catch (e: Throwable) { LOG.error(e) exitProcess(1) } } protected abstract suspend fun doMain(course: Course, args: Args): CommandResult private fun parseArgs(args: List<String>): Args { val options = Options() val group = OptionGroup() group.isRequired = true group.addOption(Option(null, COURSE_ARCHIVE_PATH_OPTION, true, "Path to course archive file")) group.addOption( Option(null, MARKETPLACE_COURSE_LINK_OPTION, true, """Marketplace course link. Supported formats: - %course-id% - %course-id%-%plugin-name% - https://plugins.jetbrains.com/plugin/%course-id% - https://plugins.jetbrains.com/plugin/%course-id%-%plugin-name%. So, for https://plugins.jetbrains.com/plugin/16630-introduction-to-python course, you can pass: - 16630 - 16630-introduction-to-python - https://plugins.jetbrains.com/plugin/16630 - https://plugins.jetbrains.com/plugin/16630-introduction-to-python """.trimIndent()) ) options.addOptionGroup(group) addCustomArgs(options) val parser = DefaultParser() val cmd = try { parser.parse(options, args.drop(1).toTypedArray()) } catch (e: ParseException) { printHelp(options) LOG.error(e) exitProcess(1) } val positionalArgs = cmd.argList if (positionalArgs.isEmpty()) { printHelp(options) logErrorAndExit("Path to project is missing") } return Args(positionalArgs.first(), cmd) } protected open fun addCustomArgs(options: Options) {} private fun printHelp(options: Options) { val formatter = HelpFormatter() formatter.width = 140 @Suppress("DEPRECATION") formatter.printHelp("$commandName /path/to/project", options) } private fun loadCourse(args: Args): Course { val courseArchivePath = args.getOptionValue(COURSE_ARCHIVE_PATH_OPTION) val marketplaceCourseLink = args.getOptionValue(MARKETPLACE_COURSE_LINK_OPTION) return when { courseArchivePath != null -> { val course = EduUtilsKt.getLocalCourse(courseArchivePath) if (course == null) { logErrorAndExit("Failed to create course object from `$courseArchivePath` archive") } course } marketplaceCourseLink != null -> { val course = MarketplaceConnector.getInstance().getCourseInfoByLink(marketplaceCourseLink, searchPrivate = true) if (course == null) { logErrorAndExit("Failed to load Marketplace course `$marketplaceCourseLink`") } course } else -> error("unreachable") } } companion object { @JvmStatic protected val LOG = logger<EduCourseCreatorAppStarter>() private const val COURSE_ARCHIVE_PATH_OPTION = "archive" private const val MARKETPLACE_COURSE_LINK_OPTION = "marketplace" @JvmStatic fun logErrorAndExit(message: String): Nothing { LOG.error(message) exitProcess(1) } @JvmStatic protected fun Course.incompatibleCourseMessage(): String { return buildString { append("""Can't open `${course.name}` course (type="${course.itemType}", language="${course.languageId}", """) if (!course.languageVersion.isNullOrEmpty()) { append("""language version="${course.languageVersion}", """) } append("""environment="${course.environment}") with current IDE setup""") } } } } class Args( val projectPath: String, private val cmd: CommandLine ) { fun getOptionValue(option: String): String? = cmd.getOptionValue(option) }
5
null
48
131
19a2a4b48993f093dac88bdf4fb9fda3c054b24a
4,485
educational-plugin
Apache License 2.0
Aretech App/app/src/main/java/com/example/aretech/ui/compose/buttons/CloseButton.kt
s3bu7i
871,643,869
false
{"Kotlin": 317569, "TypeScript": 228210, "JavaScript": 16695, "Java": 6185, "CSS": 1738, "Python": 1259}
package com.example.aretech.ui.compose.buttons import androidx.compose.runtime.Composable import com.example.aretech.R import com.example.aretech.ui.activities.menu.task.views.common.ImageInRoundShapeCard @Composable fun CloseButton(onClick: () -> Unit) { ImageInRoundShapeCard( image = R.drawable.ic_close, description = "Close", ) { onClick() } }
0
Kotlin
0
1
a5c86328a4fced42e04380e448e53f9452be9b5b
374
Aretech
MIT License
vector/src/main/java/varta/cdac/app/features/settings/locale/LocalePickerViewModel.kt
crtn32002
395,765,587
false
null
/* * Copyright (c) 2020 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.settings.locale import androidx.lifecycle.viewModelScope import com.airbnb.mvrx.ActivityViewModelContext import com.airbnb.mvrx.FragmentViewModelContext import com.airbnb.mvrx.MvRxViewModelFactory import com.airbnb.mvrx.Success import com.airbnb.mvrx.ViewModelContext import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.AssistedInject import im.vector.app.core.extensions.exhaustive import im.vector.app.core.platform.VectorViewModel import im.vector.app.features.settings.VectorLocale import kotlinx.coroutines.launch class LocalePickerViewModel @AssistedInject constructor( @Assisted initialState: LocalePickerViewState ) : VectorViewModel<LocalePickerViewState, LocalePickerAction, LocalePickerViewEvents>(initialState) { @AssistedInject.Factory interface Factory { fun create(initialState: LocalePickerViewState): LocalePickerViewModel } init { viewModelScope.launch { val result = VectorLocale.getSupportedLocales() setState { copy( locales = Success(result) ) } } } companion object : MvRxViewModelFactory<LocalePickerViewModel, LocalePickerViewState> { @JvmStatic override fun create(viewModelContext: ViewModelContext, state: LocalePickerViewState): LocalePickerViewModel? { val factory = when (viewModelContext) { is FragmentViewModelContext -> viewModelContext.fragment as? Factory is ActivityViewModelContext -> viewModelContext.activity as? Factory } return factory?.create(state) ?: error("You should let your activity/fragment implements Factory interface") } } override fun handle(action: LocalePickerAction) { when (action) { is LocalePickerAction.SelectLocale -> handleSelectLocale(action) }.exhaustive } private fun handleSelectLocale(action: LocalePickerAction.SelectLocale) { VectorLocale.saveApplicationLocale(action.locale) _viewEvents.post(LocalePickerViewEvents.RestartActivity) } }
55
Kotlin
1
1
ef17804af2f134cfbeca5645579f2fbb4b685944
2,783
element-android
Apache License 2.0
split/src/main/java/com/android/split/MainActivity.kt
Charles-ljc
266,736,494
false
{"Kotlin": 16078, "Java": 879}
package com.android.split import android.app.Activity class MainActivity : Activity()
0
Kotlin
0
0
a96499a8757297d3b65805a20058415377cdbafe
88
AndroidStudio
Apache License 2.0
android/src/main/java/co/nimblehq/ic/kmm/suv/android/MainApplication.kt
suho
523,936,897
false
{"Kotlin": 232630, "Swift": 119332, "Ruby": 21329, "Shell": 81}
package co.nimblehq.ic.kmm.suv.android import android.app.Application import co.nimblehq.ic.kmm.suv.android.di.loginModule import co.nimblehq.ic.kmm.suv.android.di.mainModule import co.nimblehq.ic.kmm.suv.di.initKoin import org.koin.android.ext.koin.androidContext import timber.log.Timber class MainApplication : Application() { override fun onCreate() { super.onCreate() initKoin { androidContext(applicationContext) modules(loginModule + mainModule) } setupLogging() } private fun setupLogging() { if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } }
0
Kotlin
0
3
d34b39d4755770898c8236db0318535a5aa15dcf
669
kmm-ic
MIT License
SpeedyDemo/app/src/main/java/com/fullsail/smith/speedydemo/SealedState.kt
Smith508
98,380,663
false
null
package com.fullsail.smith.speedydemo sealed class SealedState() { object testing1 : SealedState() object testing2 : SealedState() object testing3 : SealedState() object testing4 : SealedState() object testing5 : SealedState() object testing6 : SealedState() object testing7 : SealedState() object testing8 : SealedState() object testing9 : SealedState() object testing10 : SealedState() object testing11 : SealedState() object testing12 : SealedState() object testing13 : SealedState() object testing14 : SealedState() object testing15 : SealedState() object testing16 : SealedState() object testing17 : SealedState() object testing18 : SealedState() object testing19 : SealedState() object testing20 : SealedState() object testing21 : SealedState() object testing22 : SealedState() object testing23 : SealedState() object testing24 : SealedState() object testing25 : SealedState() object testing26 : SealedState() object testing27 : SealedState() object testing28 : SealedState() object testing29 : SealedState() object testing30 : SealedState() object testing31 : SealedState() object testing32 : SealedState() object testing33 : SealedState() object testing34 : SealedState() object testing35 : SealedState() object testing36 : SealedState() object testing37 : SealedState() object testing38 : SealedState() object testing39 : SealedState() object testing40 : SealedState() object testing41 : SealedState() object testing42 : SealedState() object testing43 : SealedState() object testing44 : SealedState() object testing45 : SealedState() object testing46 : SealedState() object testing47 : SealedState() object testing48 : SealedState() object testing49 : SealedState() object testing50 : SealedState() object testing51 : SealedState() object testing52 : SealedState() object testing53 : SealedState() object testing54 : SealedState() object testing55 : SealedState() object testing56 : SealedState() object testing57 : SealedState() object testing58 : SealedState() object testing59 : SealedState() object testing60 : SealedState() object testing61 : SealedState() object testing62 : SealedState() object testing63 : SealedState() object testing64 : SealedState() object testing65 : SealedState() object testing66 : SealedState() object testing67 : SealedState() object testing68 : SealedState() object testing69 : SealedState() object testing70 : SealedState() object testing71 : SealedState() object testing72 : SealedState() object testing73 : SealedState() object testing74 : SealedState() object testing75 : SealedState() object testing76 : SealedState() object testing77 : SealedState() object testing78 : SealedState() object testing79 : SealedState() object testing80 : SealedState() object testing81 : SealedState() object testing82 : SealedState() object testing83 : SealedState() object testing84 : SealedState() object testing85 : SealedState() object testing86 : SealedState() object testing87 : SealedState() object testing88 : SealedState() object testing89 : SealedState() object testing90 : SealedState() object testing91 : SealedState() object testing92 : SealedState() object testing93 : SealedState() object testing94 : SealedState() object testing95 : SealedState() object testing96 : SealedState() object testing97 : SealedState() object testing98 : SealedState() object testing99 : SealedState() object testing100 : SealedState() companion object { fun toList() = listOf(testing1, testing2, testing3, testing4, testing5, testing6, testing7, testing8, testing9, testing10 , testing11, testing12, testing13, testing14, testing15, testing16, testing17, testing18, testing19, testing20 , testing21, testing22, testing23, testing24, testing25, testing26, testing27, testing28, testing29, testing30 , testing31, testing32, testing33, testing34, testing35, testing36, testing37, testing38, testing39, testing40 , testing41, testing42, testing43, testing44, testing45, testing46, testing47, testing48, testing49, testing50 , testing51, testing52, testing53, testing54, testing55, testing56, testing57, testing58, testing59, testing60 , testing61, testing62, testing63, testing64, testing65, testing66, testing67, testing68, testing69, testing70 , testing71, testing72, testing73, testing74, testing75, testing76, testing77, testing78, testing79, testing80 , testing81, testing82, testing83, testing84, testing85, testing86, testing87, testing88, testing89, testing90 , testing91, testing92, testing93, testing94, testing95, testing96, testing97, testing98, testing99, testing100) } }
1
Kotlin
1
1
af52c98f6959eeceda8d9d282c74db1b0db14515
5,075
Speedy
MIT License
vessel-runtime/src/main/java/com/textnow/android/vessel/VesselMigration.kt
textnow
294,513,050
false
null
/** * MIT License * * Copyright (c) 2020 TextNow, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.textnow.android.vessel import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase /** * Provide a migration from one version of [VesselDb] to another. * Forward migrations should be paired with reverse migrations to allow for production rollbacks. * * @param startVersion the starting version of the database * @param endVersion the ending version of the database after the migration has run * @param migration lambda function to run during the migration. Note that this can not access any generated dao methods and is already in a transaction. * @see Migration */ internal class VesselMigration( startVersion: Int, endVersion: Int, val migration: (Migration, SupportSQLiteDatabase)->Unit ) : Migration(startVersion, endVersion) { override fun migrate(database: SupportSQLiteDatabase) { migration.invoke(this, database) } }
2
Kotlin
5
6
fce15b991329631eaf9996654decf11bdc5b7c9b
2,041
vessel
MIT License
app/src/main/java/com/fwhyn/pocomon/domain/usecases/GetAllPokemonNamesUseCase.kt
fwhyn
532,494,747
false
{"Kotlin": 87628}
package com.fwhyn.pocomon.domain.usecases import com.fwhyn.pocomon.domain.model.PokemonResults import com.fwhyn.pocomon.domain.api.RepositoryDataInterface class GetAllPokemonNamesUseCase(private val repository: RepositoryDataInterface) { suspend fun getAllPokemonNames(limit: Int): PokemonResults = repository.getPokemonList(limit) }
5
Kotlin
0
0
7c1d57e31d46c443b78762fd96c2414364de2503
339
Pocomon_Android
Apache License 2.0
src/main/kotlin/com/cognifide/gradle/sling/common/CommonOptions.kt
Cognifide
138,027,523
false
null
package com.cognifide.gradle.sling.common import com.cognifide.gradle.sling.SlingExtension import com.cognifide.gradle.sling.common.utils.LineSeparator import org.gradle.internal.os.OperatingSystem open class CommonOptions(private val sling: SlingExtension) { private val project = sling.project /** * Base name used as default for Vault packages being created by compose or collect task * and also for OSGi bundle JARs. */ val baseName = sling.obj.string { convention(sling.obj.provider { (if (project == project.rootProject) { project.rootProject.name } else { "${project.rootProject.name}-${project.name}" }) }) } /** * Allows to disable features that are using running Sling instances. * * It is more soft offline mode than Gradle's one which does much more. * It will not use any Maven repository so that CI build will fail which is not expected in e.g integration tests. */ val offline = sling.obj.boolean { convention(sling.prop.flag("offline")) } /** * Determines current environment name to be used in e.g package deployment. */ val env = sling.obj.string { convention(System.getenv("ENV") ?: "local") sling.prop.string("env")?.let { set(it) } } /** * Specify characters to be used as line endings when cleaning up checked out JCR content. */ val lineSeparator = sling.obj.typed<LineSeparator> { convention(LineSeparator.LF) sling.prop.string("lineSeparator")?.let { set(LineSeparator.of(it)) } } val archiveExtension = sling.obj.string { convention(sling.project.provider { if (OperatingSystem.current().isUnix) "tar.gz" else "zip" }) sling.prop.string("archiveExtension")?.let { set(it) } } val executableExtension = sling.obj.string { convention(sling.project.provider { if (OperatingSystem.current().isWindows) ".bat" else "" }) sling.prop.string("executableExtension")?.let { set(it) } } }
0
Kotlin
2
15
b3e7244f887b24dece21571a5a63ae79ef0c7597
2,085
gradle-sling-plugin
Apache License 2.0
app/src/main/java/com/mooveit/kotlin/kotlintemplateproject/data/repository/PetDataRepository.kt
Transmigrado
127,310,342
true
{"Kotlin": 48790}
package com.mooveit.kotlin.kotlintemplateproject.data.repository import com.mooveit.kotlin.kotlintemplateproject.data.entity.Pet import com.mooveit.kotlin.kotlintemplateproject.data.repository.datasource.PetDataStoreFactory import com.mooveit.kotlin.kotlintemplateproject.domain.repository.PetRepository import io.reactivex.Observable import retrofit2.Response class PetDataRepository(private val petDataStoreFactory: PetDataStoreFactory) : PetRepository { override fun getPet(petId: Long): Observable<Pet> { return petDataStoreFactory.forPet(petId).getPet(petId) } override fun getPets(): Observable<List<Pet>> { return petDataStoreFactory.forPetList().getPetList() } override fun deletePet(petId: Long): Observable<Response<Void>> { return petDataStoreFactory.forDelete().deletePet(petId) } }
0
Kotlin
0
0
cab69aa1be73e0bf2d0a9e0a35624dc5f41f41c5
847
android-kotlin-architecture
MIT License
app/src/main/java/com/skydoves/themovies/models/Status.kt
skydoves
143,843,903
false
null
/* * The MIT License (MIT) * * Designed and developed by 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.zeynelerdi.themovies.models /** * Status of a resource that is provided to the UI. * * * These are usually created by the Repository classes where they return * `LiveData<Resource<T>>` to pass back the latest data to the UI with its fetch status. */ enum class Status { SUCCESS, ERROR, LOADING }
5
null
47
470
a286f35e5295fa2da0ef2d64d4bda88d65c182cf
1,473
TheMovies
MIT License
cli/src/main/kotlin/com/malinskiy/marathon/cli/args/FileConfiguration.kt
cdsap
134,924,816
true
{"Kotlin": 300576, "JavaScript": 33573, "CSS": 29044, "HTML": 2224, "Shell": 964}
package com.malinskiy.marathon.cli.args import com.malinskiy.marathon.execution.AnalyticsConfiguration import com.malinskiy.marathon.execution.FilteringConfiguration import com.malinskiy.marathon.execution.strategy.BatchingStrategy import com.malinskiy.marathon.execution.strategy.FlakinessStrategy import com.malinskiy.marathon.execution.strategy.PoolingStrategy import com.malinskiy.marathon.execution.strategy.RetryStrategy import com.malinskiy.marathon.execution.strategy.ShardingStrategy import com.malinskiy.marathon.execution.strategy.SortingStrategy import java.io.File data class FileConfiguration( var name: String, var outputDir: File, var applicationOutput: File, var testApplicationOutput: File, var analyticsConfiguration: AnalyticsConfiguration?, var poolingStrategy: PoolingStrategy?, var shardingStrategy: ShardingStrategy?, var sortingStrategy: SortingStrategy?, var batchingStrategy: BatchingStrategy?, var flakinessStrategy: FlakinessStrategy?, var retryStrategy: RetryStrategy?, var filteringConfiguration: FilteringConfiguration?, var ignoreFailures: Boolean?, var isCodeCoverageEnabled: Boolean?, var fallbackToScreenshots: Boolean?, var testClassRegexes: Collection<Regex>?, var includeSerialRegexes: Collection<Regex>?, var excludeSerialRegexes: Collection<Regex>?, var testOutputTimeoutMillis: Int?, var debug: Boolean?, var autoGrantPermission: Boolean? )
1
Kotlin
0
1
ce6648774cd47c87f074ebdfdacbbcf781bdfdd4
1,558
marathon
Apache License 2.0
lego/lego_plugins/src/main/java/com/lego/plugins/context/task/component/ContextComponentTasks.kt
ruichard
775,792,965
false
{"Kotlin": 369040, "Java": 13237}
package com.lego.plugins.context.task.component import com.android.build.gradle.api.BaseVariant import com.ktnail.x.toCamel import com.ktnail.x.uriToPascal import com.lego.plugins.context.ContextPlugin import com.lego.plugins.extension.context.ContextExtension import com.lego.plugins.basic.publish.maven.PublicationType import com.lego.plugins.basic.utility.isTaskTarget import com.lego.plugins.basic.utility.legoComponentDevTask import com.lego.plugins.basic.utility.legoComponentTask import org.gradle.api.Project class ContextComponentTasks( project: Project, val context: ContextExtension, val variant: BaseVariant ) { companion object { fun create( project: Project, context: ContextExtension, variant: BaseVariant ): ContextComponentTasks? = if (context.enablePublishComponent) ContextComponentTasks(project, context, variant) else null } val publishTask = if(context.enablePublish) project.legoComponentTask(toCamel(ContextPlugin.PUBLISH_TASK_NAME_PREFIX, context.publishArtifactName.uriToPascal(), variant.name, ContextPlugin.PUBLISH_COMPONENT_TASK_NAME_SUFFIX)) else null val publishDevTask = if(context.enablePublishDev) project.legoComponentDevTask(toCamel(ContextPlugin.PUBLISH_DEV_TASK_NAME_PREFIX, context.publishArtifactName.uriToPascal(), variant.name, ContextPlugin.PUBLISH_COMPONENT_TASK_NAME_SUFFIX)) else null fun configuringPublicationType(project: Project): PublicationType? { return when { publishTask?.name?.let { name -> project.isTaskTarget(name) } == true -> PublicationType.FORMAL publishDevTask?.name?.let { name -> project.isTaskTarget(name) } == true -> PublicationType.DEV else -> null } } }
0
Kotlin
0
1
0a581d294e3e76050b9bc7478fbc200a43b4b919
1,825
Lego
Apache License 2.0
bitkointlin/src/test/kotlin/se/simbio/bitkointlin/Fixture.kt
ademar111190
51,411,720
false
null
package se.simbio.bitkointlin import com.google.gson.JsonElement import se.simbio.bitkointlin.http.HttpClient // Bitkointlin val USER = "User" val PASSWORD = "<PASSWORD>" val HTTP_ADDRESS = "http://127.0.0.1:8332/" val HTTP_CLIENT = object : HttpClient { override fun post(bitkointlin: Bitkointlin, method: String, success: (JsonElement) -> Unit, error: (String) -> Unit) { } } // Balance val BALANCE_RESULT = 0.0 val BALANCE_GET_BALANCE_METHOD_NAME = "getbalance" val BALANCE_GET_BALANCE_ERROR_RETURN_EXAMPLE = "Balance Error" val BALANCE_GET_BALANCE_SUCCESS_RETURN_EXAMPLE = """ {"result": $BALANCE_RESULT, "error":null, "id":"sentId"} """ // Best Block Hash val BEST_BLOCK_HASH_RESULT = "000000000000000002e7469aa3f6f2a2c5d99f986cb56804b745b21e86567a0e" val BEST_BLOCK_HASH_GET_BEST_BLOCK_HASH_METHOD_NAME = "getbestblockhash" val BEST_BLOCK_HASH_GET_BEST_BLOCK_HASH_ERROR_RETURN_EXAMPLE = "Best Block Error" val BEST_BLOCK_HASH_GET_BEST_BLOCK_HASH_SUCCESS_RETURN_EXAMPLE = """ {"result": "$BEST_BLOCK_HASH_RESULT", "error":null, "id":"sentId"} """ // Difficulty val DIFFICULTY_RESULT = 163491654908.95925903 val DIFFICULTY_GET_DIFFICULTY_METHOD_NAME = "getdifficulty" val DIFFICULTY_GET_DIFFICULTY_ERROR_RETURN_EXAMPLE = "Difficulty Error" val DIFFICULTY_GET_DIFFICULTY_SUCCESS_RETURN_EXAMPLE = """ {"result": $DIFFICULTY_RESULT, "error":null, "id":"sentId"} """ // Info val INFO_BALANCE = 4.5 val INFO_BLOCKS = 6L val INFO_CONNECTIONS = 8L val INFO_DIFFICULTY = 9.10 val INFO_ERRORS = "" val INFO_KEY_POOL_OLDEST = 11L val INFO_KEY_POOL_SIZE = 12L val INFO_PAY_TX_FEE = 13.14 val INFO_PROTOCOL_VERSION = 2L val INFO_PROXY = "Some Proxy" val INFO_RELAY_FEE = 15.16 val INFO_TEST_NET = false val INFO_TIME_OFFSET = 7L val INFO_VERSION = 1L val INFO_WALLET_VERSION = 3L val INFO_GET_INFO_METHOD_NAME = "getinfo" val INFO_GET_INFO_ERROR_RETURN_EXAMPLE = "Info Error" val INFO_GET_INFO_SUCCESS_RESULT_EXAMPLE = """ {"result":{ "version": $INFO_VERSION, "protocolversion": $INFO_PROTOCOL_VERSION, "walletversion": $INFO_WALLET_VERSION, "balance": $INFO_BALANCE, "blocks": $INFO_BLOCKS, "timeoffset": $INFO_TIME_OFFSET, "connections": $INFO_CONNECTIONS, "proxy": "$INFO_PROXY", "difficulty": $INFO_DIFFICULTY, "testnet": $INFO_TEST_NET, "keypoololdest": $INFO_KEY_POOL_OLDEST, "keypoolsize": $INFO_KEY_POOL_SIZE, "paytxfee": $INFO_PAY_TX_FEE, "relayfee": $INFO_RELAY_FEE, "errors": "$INFO_ERRORS"}, "error":null, "id":"sentId"} """
1
null
1
2
cd73e8aab7f62cf00b1043c7f5ed62cb1094fae2
2,611
bitkointlin
MIT License
app/src/main/java/com/skyinu/jvmti/wrapper/SecondActivity.kt
skyinu
225,858,817
false
null
package com.skyinu.jvmti.wrapper import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class SecondActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) } }
0
null
0
1
2eea82b087f9193e71ad50d89aacb088241d69ff
308
MixVegetable
MIT License
features/tournaments/domain/src/main/java/com/mctech/pokergrinder/tournament/domain/usecase/LoadTournamentUseCase.kt
MayconCardoso
539,349,342
false
{"Kotlin": 630714}
package com.mctech.pokergrinder.tournament.domain.usecase import com.mctech.pokergrinder.tournament.domain.TournamentRepository import com.mctech.pokergrinder.tournament.domain.entities.Tournament import javax.inject.Inject /** * Load a tournament by its title [Tournament]. * * @property repository tournament data repository. */ class LoadTournamentUseCase @Inject constructor( private val repository: TournamentRepository, ){ suspend operator fun invoke(title: String): Tournament? { return repository.load(title.trim()) } }
7
Kotlin
1
7
ecb4278d82b5e055b3dd1d08080ebbf8a17d2915
543
poker-grinder
Apache License 2.0
feature/settings/import/src/main/kotlin/app/k9mail/feature/settings/import/ui/SettingsImportScreen.kt
thunderbird
1,326,671
false
null
package app.k9mail.feature.settings.import.ui import android.os.Bundle import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.fragment.app.FragmentActivity import app.k9mail.core.ui.compose.common.activity.LocalActivity import app.k9mail.core.ui.compose.common.fragment.FragmentView import app.k9mail.core.ui.compose.designsystem.atom.button.ButtonIcon import app.k9mail.core.ui.compose.designsystem.organism.TopAppBar import app.k9mail.core.ui.compose.designsystem.template.Scaffold import app.k9mail.core.ui.compose.theme.Icons import app.k9mail.feature.settings.importing.R @Composable fun SettingsImportScreen( onImportSuccess: () -> Unit, onBack: () -> Unit, modifier: Modifier = Modifier, ) { Scaffold( topBar = { TopAppBar( title = stringResource(R.string.settings_import_title), navigationIcon = { ButtonIcon( onClick = onBack, imageVector = Icons.Outlined.arrowBack, ) }, ) }, modifier = modifier, ) { innerPadding -> SettingsImportContent(onImportSuccess, onBack, innerPadding) } } @Composable private fun SettingsImportContent( onImportSuccess: () -> Unit, onBack: () -> Unit, paddingValues: PaddingValues, ) { val activity = LocalActivity.current as FragmentActivity activity.supportFragmentManager.setFragmentResultListener( SettingsImportFragment.FRAGMENT_RESULT_KEY, LocalLifecycleOwner.current, ) { _, result: Bundle -> if (result.getBoolean(SettingsImportFragment.FRAGMENT_RESULT_ACCOUNT_IMPORTED, false)) { onImportSuccess() } else { onBack() } } FragmentView( fragmentFactory = { SettingsImportFragment() }, modifier = Modifier .fillMaxSize() .padding(paddingValues), ) }
886
null
2492
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
2,254
thunderbird-android
Apache License 2.0
core/src/io/github/advancerman/todd/json/ManualJsonConstructor.kt
AdvancerMan
278,029,588
false
null
package io.github.advancerman.todd.json @Target(AnnotationTarget.FUNCTION) annotation class ManualJsonConstructor(val constructorName: String = "") object JsonDefaults { fun setDefault(key: String, value: Any?, map: MutableMap<String, Pair<Any?, Boolean>>): Any? { map.getOrPut(key) { value to true }.let { val (previousValue, valuePresent) = it return if (!valuePresent) { map[key] = value to true value } else { previousValue } } } }
1
Kotlin
0
2
efeb10c60c607d393a26963dc9aa9109dd00bd1c
558
todd-kt
MIT License
library/src/main/java/com/lisb/android/mediashrink/AudioShrink.kt
lisb
41,290,110
false
null
package com.lisb.android.mediashrink import android.annotation.SuppressLint import android.media.* import timber.log.Timber import java.io.IOException import java.nio.ByteBuffer import java.util.concurrent.atomic.AtomicReference class AudioShrink(private val extractor: MediaExtractor, private val muxer: MediaMuxer, private val errorCallback: UnrecoverableErrorCallback) { var bitRate = 0 var onProgressListener: OnProgressListener? = null /** * エンコーダの設定に使うフォーマットを作成する。 <br></br> * [MediaMuxer.addTrack] には利用できない。 */ private fun createEncoderConfigurationFormat(decoderOutputFormat: MediaFormat): MediaFormat { val channelCount = decoderOutputFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT) val sampleRate = decoderOutputFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE) val format = MediaFormat.createAudioFormat(ENCODE_MIMETYPE, sampleRate, channelCount) format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate) format.setInteger(MediaFormat.KEY_AAC_PROFILE, AAC_PROFILE) Timber.tag(TAG).d("create audio encoder configuration format:%s, decoderOutputFormat:%s", Utils.toString(format), Utils.toString(decoderOutputFormat)) return format } @Throws(DecodeException::class) private fun reencode(trackIndex: Int, newTrackIndex: Int?, listener: ReencodeListener?) { Timber.tag(TAG).d("reencode. trackIndex:%d, newTrackIndex:%d, isNull(listener):%b", trackIndex, newTrackIndex, listener == null) // TODO 既存の音声のビットレートが指定された bitRate よりも低い場合、圧縮せずにそのまま利用する val originalFormat = extractor.getTrackFormat(trackIndex) var encoder: MediaCodec? = null var decoder: MediaCodec? = null // 進捗取得に利用 val durationUs = originalFormat.getLong(MediaFormat.KEY_DURATION).toFloat() val startTimeNs = System.nanoTime() var deliverProgressCount: Long = 0 try { val encoderOutputBufferInfo = MediaCodec.BufferInfo() // create decorder decoder = createDecoder(originalFormat) if (decoder == null) { Timber.tag(TAG).e("audio decoder not found.") throw DecodeException("audio decoder not found.") } decoder.start() val decoderOutputBufferInfo = MediaCodec.BufferInfo() extractor.selectTrack(trackIndex) var extractorDone = false var decoderDone = false var decoderOutputBuffer: ByteBuffer? = null // エンコーダに入力されていないデータが残っているデコーダの出力 var decoderOutputBufferIndex: Int = -1 var lastExtractorOutputPts: Long = -1 var lastDecoderOutputPts: Long = -1 var lastEncoderOutputPts: Long = -1 var sampleCount = 0 while (true) { // read from extractor, write to decoder while (!extractorDone) { val decoderInputBufferIndex = decoder.dequeueInputBuffer(TIMEOUT_USEC) if (decoderInputBufferIndex < 0) { break } val decoderInputBuffer = requireNotNull(decoder.getInputBuffer(decoderInputBufferIndex)) val size = extractor.readSampleData(decoderInputBuffer, 0) // extractor.advance() より先に行うこと val pts = extractor.sampleTime var sampleFlags = extractor.sampleFlags Timber.tag(TAG).v("audio extractor output. buffer.pos:%d, buffer.limit:%d, size:%d, sample time:%d, sample flags:%d", decoderInputBuffer.position(), decoderInputBuffer.limit(), size, pts, sampleFlags) extractorDone = !extractor.advance() if (extractorDone) { Timber.tag(TAG).d("audio extractor: EOS, size:%d, sampleCount:%d", size, sampleCount) sampleFlags = sampleFlags or MediaCodec.BUFFER_FLAG_END_OF_STREAM if (sampleCount == 0) { Timber.tag(TAG).e("no audio sample found.") throw DecodeException("no audio sample found.") } } if (size >= 0) { if (lastExtractorOutputPts >= pts) { Timber.tag(TAG).w("extractor output pts(%d) is smaller than last pts(%d)", pts, lastExtractorOutputPts) } else { lastExtractorOutputPts = pts } decoder.queueInputBuffer(decoderInputBufferIndex, 0, size, pts, sampleFlags) } else if (extractorDone) { decoder.queueInputBuffer(decoderInputBufferIndex, 0, 0, 0, sampleFlags) } break } // read from decoder while (!decoderDone && decoderOutputBuffer == null) { @SuppressLint("WrongConstant") decoderOutputBufferIndex = decoder.dequeueOutputBuffer( decoderOutputBufferInfo, TIMEOUT_USEC) Timber.tag(TAG).v("audio decoder output. bufferIndex:%d, time:%d, offset:%d, size:%d, flags:%d", decoderOutputBufferIndex, decoderOutputBufferInfo.presentationTimeUs, decoderOutputBufferInfo.offset, decoderOutputBufferInfo.size, decoderOutputBufferInfo.flags) if (decoderOutputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { Timber.tag(TAG).d("audio decoder: output format changed. %s", Utils.toString(decoder.outputFormat)) break } if (decoderOutputBufferIndex < 0) break // NOTE: flags が MediaCodec.BUFFER_FLAG_CODEC_CONFIG かつ BUFFER_FLAG_END_OF_STREAM // のときがあるので注意。 if (decoderOutputBufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) { decoder.releaseOutputBuffer(decoderOutputBufferIndex, false) break } decoderOutputBuffer = requireNotNull(decoder.getOutputBuffer(decoderOutputBufferIndex)) if (lastDecoderOutputPts >= decoderOutputBufferInfo.presentationTimeUs) { Timber.tag(TAG).w("decoder output pts(%d) is smaller than last pts(%d)", decoderOutputBufferInfo.presentationTimeUs, lastDecoderOutputPts) } else { lastDecoderOutputPts = decoderOutputBufferInfo.presentationTimeUs } break } // write to encoder while (decoderOutputBuffer != null) { if (encoder == null) { // デコーダの制限などでデコード前とデコード後でサンプリングレートやチャネル数が違うことがあるので // Encoder の作成を遅延する。 val encoderConfigurationFormat = createEncoderConfigurationFormat( decoder.outputFormat) encoder = createEncoder(encoderConfigurationFormat) encoder.start() } // TODO // デコード後、デコード前と比べてチャネル数やサンプリングレートが上がってしまっていた場合でも // チャネル数やサンプリングレートをデコード前の値に落として圧縮できるようにする val encoderInputBufferIndex = encoder.dequeueInputBuffer(TIMEOUT_USEC) if (encoderInputBufferIndex < 0) { break } val encoderInputBuffer = requireNotNull(encoder.getInputBuffer(encoderInputBufferIndex)) encoderInputBuffer.clear() if (encoderInputBuffer.remaining() >= decoderOutputBufferInfo.size) { Timber.tag(TAG).v("audio encoder input. bufferIndex:%d, time:%d, offset:%d, size:%d, flags:%d", encoderInputBufferIndex, decoderOutputBufferInfo.presentationTimeUs, decoderOutputBufferInfo.offset, decoderOutputBufferInfo.size, decoderOutputBufferInfo.flags) decoderOutputBuffer.position(decoderOutputBufferInfo.offset) decoderOutputBuffer.limit(decoderOutputBufferInfo.offset + decoderOutputBufferInfo.size) encoderInputBuffer.put(decoderOutputBuffer) encoder.queueInputBuffer(encoderInputBufferIndex, 0, decoderOutputBufferInfo.size, decoderOutputBufferInfo.presentationTimeUs, decoderOutputBufferInfo.flags) decoder.releaseOutputBuffer(decoderOutputBufferIndex, false) if (decoderOutputBufferInfo.size != 0) { sampleCount++ } decoderOutputBuffer = null if (decoderOutputBufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { Timber.tag(TAG).d("audio decoder: EOS") decoderDone = true } } else { // エンコーダの入力バッファがデコーダの出力より小さい val inputBufferRemaining = encoderInputBuffer.remaining() val pts = decoderOutputBufferInfo.presentationTimeUs val flags = decoderOutputBufferInfo.flags.and(MediaCodec.BUFFER_FLAG_END_OF_STREAM.inv()) Timber.tag(TAG).v("multi-phase audio encoder input. bufferIndex:%d, time:%d, offset:%d, size:%d, flags:%d", encoderInputBufferIndex, pts, decoderOutputBufferInfo.offset, inputBufferRemaining, flags) decoderOutputBuffer.position(decoderOutputBufferInfo.offset) decoderOutputBuffer.limit(decoderOutputBufferInfo.offset + inputBufferRemaining) encoderInputBuffer.put(decoderOutputBuffer) encoder.queueInputBuffer(encoderInputBufferIndex, 0, inputBufferRemaining, pts, flags) sampleCount++ decoderOutputBufferInfo.offset += inputBufferRemaining decoderOutputBufferInfo.size -= inputBufferRemaining val outputSamplingRate = decoder.outputFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE) val outputChannelCount = decoder.outputFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT) val duration = (inputBufferRemaining / 2 / outputChannelCount) * 1000L * 1000L / outputSamplingRate decoderOutputBufferInfo.presentationTimeUs += duration } break } // write to muxer while (encoder != null) { val encoderOutputBufferIndex = encoder.dequeueOutputBuffer( encoderOutputBufferInfo, TIMEOUT_USEC) Timber.tag(TAG).v("audio encoder output. bufferIndex:%d, time:%d, offset:%d, size:%d, flags:%d", encoderOutputBufferIndex, encoderOutputBufferInfo.presentationTimeUs, encoderOutputBufferInfo.offset, encoderOutputBufferInfo.size, encoderOutputBufferInfo.flags) if (encoderOutputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // エンコーダに何か入力しないと、ここに来ないエンコーダがあるので注意。 if (listener?.onEncoderFormatChanged(encoder) == true) return break } if (encoderOutputBufferIndex < 0) break val encoderOutputBuffer = requireNotNull(encoder.getOutputBuffer(encoderOutputBufferIndex)) // NOTE: flags が MediaCodec.BUFFER_FLAG_CODEC_CONFIG かつ BUFFER_FLAG_END_OF_STREAM // のときがあるので注意。 if (encoderOutputBufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0 && encoderOutputBufferInfo.size != 0) { if (lastEncoderOutputPts >= encoderOutputBufferInfo.presentationTimeUs) { Timber.tag(TAG).w("encoder output pts(%d) is smaller than last pts(%d)", encoderOutputBufferInfo.presentationTimeUs, lastEncoderOutputPts) } else { if (newTrackIndex != null) { muxer.writeSampleData(newTrackIndex, encoderOutputBuffer, encoderOutputBufferInfo) lastEncoderOutputPts = encoderOutputBufferInfo.presentationTimeUs // 進捗更新 if ((System.nanoTime() - startTimeNs) / 1000 / 1000 > UPDATE_PROGRESS_INTERVAL_MS * (deliverProgressCount + 1)) { deliverProgressCount++ onProgressListener?.onProgress((encoderOutputBufferInfo.presentationTimeUs * 100 / durationUs).toInt()) } } } } encoder.releaseOutputBuffer(encoderOutputBufferIndex, false) if (encoderOutputBufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { Timber.tag(TAG).d("audio encoder: EOS") return } break } } } catch (e: DecodeException) { // recoverable error Timber.tag(TAG).e(e, "Recoverable error occurred on audio shrink.") throw e } catch (e: Throwable) { Timber.tag(TAG).e(e, "Unrecoverable error occurred on audio shrink.") errorCallback.onUnrecoverableError(e) } finally { if (encoder != null) { encoder.stopWithTimeout() encoder.release() } if (decoder != null) { decoder.stopWithTimeout() decoder.release() } extractor.unselectTrack(trackIndex) } } @Throws(DecodeException::class) fun createOutputFormat(trackIndex: Int): MediaFormat { val formatRef = AtomicReference<MediaFormat>() reencode(trackIndex, null, object : ReencodeListener { override fun onEncoderFormatChanged(encoder: MediaCodec): Boolean { Timber.tag(TAG).d("audio encoder: output format changed. %s", Utils.toString(encoder.outputFormat)) formatRef.set(encoder.outputFormat) return true } }) return formatRef.get() } @Throws(DecodeException::class) fun shrink(trackIndex: Int, newTrackIndex: Int) { reencode(trackIndex, newTrackIndex, null) } @Throws(DecoderCreationException::class) private fun createDecoder(format: MediaFormat): MediaCodec? { val mimeType = format.getString(MediaFormat.KEY_MIME) val codec = Utils.selectCodec(mimeType, false) if (codec == null) { val detailMessage = "audio decoder codec is not found. mime-type:$mimeType" Timber.tag(TAG).e(detailMessage) throw DecoderCreationException(detailMessage) } val codecName = codec.name return try { // 古いAndroidではNullableだったのでそのまま残している @Suppress("RedundantNullableReturnType") val decoder: MediaCodec? = MediaCodec.createByCodecName(codecName) if (decoder != null) { decoder.configure(format, null, null, 0) Timber.tag(TAG).d("audio decoder:%s", decoder.name) } decoder } catch (e: IOException) { // later Lollipop. val detailMessage = "audio decoder cannot be created. codec-name:$codecName" Timber.tag(TAG).e(e, detailMessage) throw DecoderCreationException(detailMessage, e) } catch (e: IllegalStateException) { val detailMessage = "audio decoder cannot be created. codec-name:$codecName" Timber.tag(TAG).e(e, detailMessage) throw DecoderCreationException(detailMessage, e) } } @Throws(EncoderCreationException::class) private fun createEncoder(format: MediaFormat): MediaCodec { val codec = Utils.selectCodec(ENCODE_MIMETYPE, true) if (codec == null) { val detailMessage = "audio encoder codec is not found. media-type:$ENCODE_MIMETYPE" Timber.tag(TAG).e(detailMessage) throw EncoderCreationException(detailMessage) } val codecName = codec.name return try { val encoder = MediaCodec.createByCodecName(codecName) encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) Timber.tag(TAG).d("audio encoder:%s", encoder.name) encoder } catch (e: IOException) { // later Lollipop. val detailMessage = "audio encoder cannot be created. codec-name:$codecName" Timber.tag(TAG).e(e, detailMessage) throw EncoderCreationException(detailMessage, e) } catch (e: IllegalStateException) { // TODO Change Detail Message If minSDKVersion > 21 val detailMessage = "audio encoder cannot be created. codec-name:$codecName" Timber.tag(TAG).e(e, detailMessage) throw EncoderCreationException(detailMessage, e) } } private interface ReencodeListener { /** * @return if stop or not */ fun onEncoderFormatChanged(encoder: MediaCodec): Boolean } companion object { private const val TAG = "AudioShrink" private const val TIMEOUT_USEC: Long = 250 private const val ENCODE_MIMETYPE = "audio/mp4a-latm" // Because AACObjectHE of some encoder(ex. OMX.google.aac.encoder) is buggy, // Don't use AACObjectHE. // // bug example: // - specify mono sound but output stereo sound. // - output wrong time_base_codec. private const val AAC_PROFILE = MediaCodecInfo.CodecProfileLevel.AACObjectLC private const val UPDATE_PROGRESS_INTERVAL_MS = 3 * 1000.toLong() } }
0
Kotlin
0
0
03c434cd17009228b1b99604b6bf0763d1a8a7e4
19,408
android-mediashrink
Apache License 2.0
src/main/kotlin/com/flowkode/mailvalidator/InvalidArgumentException.kt
nelsongraca
160,852,560
false
null
package com.flowkode.mailvalidator class InvalidArgumentException(message: Messages) : Exception() { val errorMessage = message.errorMessage enum class Messages(val errorMessage: String) { NO_MX("do me") } }
0
Kotlin
0
1
5bd410c0699051c00724be195436c4d864a6ee8a
230
mailvalidator
Apache License 2.0
message_holder/MessageSwipeController.kt
nitish098123
481,869,940
false
null
package com.example.database_part_3.message_holder import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.Drawable import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.View import androidx.core.content.ContextCompat import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.example.database_part_3.R import com.example.database_part_3.utils.AndroidUtils class MessageSwipeController(private val context: Context, private val swipeControllerActions : SwipeControllerActions ) : ItemTouchHelper.Callback(){ private lateinit var imageDrawable: Drawable private lateinit var shareRound: Drawable private var currentItemViewHolder: RecyclerView.ViewHolder? = null private lateinit var mView: View private var dX = 0f private var replyButtonProgress: Float = 0.toFloat() private var lastReplyButtonAnimationTime: Long = 0 private var swipeBack = false private var isVibrate = false private var startTracking = false override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { mView = viewHolder.itemView imageDrawable = context.getDrawable(R.drawable.swipe_replay)!! shareRound = context.getDrawable(R.drawable.ic_round_circle)!! return ItemTouchHelper.Callback.makeMovementFlags(ItemTouchHelper.ACTION_STATE_IDLE,ItemTouchHelper.RIGHT) } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} override fun convertToAbsoluteDirection(flags: Int, layoutDirection: Int): Int { if(swipeBack){ swipeBack=false return 0 } return super.convertToAbsoluteDirection(flags,layoutDirection) } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ){ if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){ setTouchListener(recyclerView,viewHolder) } if(mView.translationX < convertTodp(130) || dX < this.dX){ super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) this.dX = dX startTracking = true } currentItemViewHolder = viewHolder drawReplayButton(c) } @SuppressLint("ClickableViewAccessibility") private fun setTouchListener(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder){ recyclerView.setOnTouchListener{ _,event-> swipeBack = event.action == MotionEvent.ACTION_CANCEL || event.action == MotionEvent.ACTION_UP if(swipeBack){ if (Math.abs(mView.translationX) >= [email protected](100)) { swipeControllerActions.showReplyUI(viewHolder.adapterPosition) } } false } } private fun drawReplayButton(canvas: Canvas){ if(currentItemViewHolder == null){ return } val translationX = mView.translationX val newTime = System.currentTimeMillis() val dt = Math.min(17, newTime - lastReplyButtonAnimationTime) lastReplyButtonAnimationTime = newTime val showing = translationX >= convertTodp(30) if (showing) { if (replyButtonProgress < 1.0f) { replyButtonProgress += dt / 180.0f if (replyButtonProgress > 1.0f) { replyButtonProgress = 1.0f } else { mView.invalidate() } } } else if (translationX <= 0.0f) { replyButtonProgress = 0f startTracking = false isVibrate = false } else { if (replyButtonProgress > 0.0f) { replyButtonProgress -= dt / 180.0f if (replyButtonProgress < 0.1f) { replyButtonProgress = 0f } else { mView.invalidate() } } } val alpha: Int val scale: Float if (showing) { scale = if (replyButtonProgress <= 0.8f) { 1.2f * (replyButtonProgress / 0.8f) } else { 1.2f - 0.2f * ((replyButtonProgress - 0.8f) / 0.2f) } alpha = Math.min(255f, 255 * (replyButtonProgress / 0.8f)).toInt() } else { scale = replyButtonProgress alpha = Math.min(255f, 255 * replyButtonProgress).toInt() } shareRound.alpha = alpha imageDrawable.alpha = alpha if (startTracking) { if (!isVibrate && mView.translationX >= convertTodp(100)) { mView.performHapticFeedback( HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING ) isVibrate = true } } val x: Int = if (mView.translationX > convertTodp(130)) { convertTodp(130) / 2 } else { (mView.translationX / 2).toInt() } val y = (mView.top + mView.measuredHeight / 2).toFloat() shareRound.colorFilter = PorterDuffColorFilter(ContextCompat.getColor(context, R.color.gray), PorterDuff.Mode.MULTIPLY) shareRound.setBounds( (x - convertTodp(18) * scale).toInt(), (y - convertTodp(18) * scale).toInt(), (x + convertTodp(18) * scale).toInt(), (y + convertTodp(18) * scale).toInt() ) shareRound.draw(canvas) imageDrawable.setBounds( (x - convertTodp(12) * scale).toInt(), (y - convertTodp(11) * scale).toInt(), (x + convertTodp(12) * scale).toInt(), (y + convertTodp(10) * scale).toInt() ) imageDrawable.draw(canvas) shareRound.alpha = 255 imageDrawable.alpha = 255 } private fun convertTodp(pixel: Int): Int { return AndroidUtils.dp(pixel.toFloat(), context) } }
1
Kotlin
0
1
61ef3ffb99db93ece011f701a55804cb8fedf211
6,643
Sofessist-a-messaging-specialist
Apache License 2.0
library/src/androidTest/java/com/github/pelmenstar1/rangecalendar/LocaleUtilsTests.kt
pelmenstar1
454,918,220
false
{"Kotlin": 666647}
package com.github.pelmenstar1.rangecalendar import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.pelmenstar1.rangecalendar.utils.getFirstDayOfWeek import org.junit.Test import org.junit.runner.RunWith import java.util.Locale import kotlin.test.assertEquals @RunWith(AndroidJUnit4::class) class LocaleUtilsTests { @Test fun getFirstDayOfWeekTest() { fun testHelper(locale: Locale, expectedFirstDow: CompatDayOfWeek) { val actualFirstDow = locale.getFirstDayOfWeek() assertEquals(expectedFirstDow, actualFirstDow, "locale: ${locale.toLanguageTag()}") } testHelper(Locale.FRANCE, CompatDayOfWeek.Monday) testHelper(Locale.CANADA, CompatDayOfWeek.Sunday) testHelper(Locale.US, CompatDayOfWeek.Sunday) testHelper(Locale.forLanguageTag("ar"), CompatDayOfWeek.Saturday) } }
2
Kotlin
0
13
c5eb42e2e269aeac9b108990bb9c928043ad8ca2
873
RangeCalendar
MIT License
zowe-imperative/src/jsMain/kotlin/zowe/imperative/imperative/profiles/handlers/CreateProfilesHandler.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
@file:JsModule("@zowe/imperative") package zowe.imperative.imperative.profiles.handlers import js.promise.Promise import zowe.imperative.cmd.doc.handler.ICommandHandler import zowe.imperative.cmd.doc.handler.IHandlerParameters /** * Handler that allows creation of a profile from command line arguments. Intended for usage with * the automatically generated profile create commands, but can be used otherwise. */ external class CreateProfilesHandler : ICommandHandler { /** * Create a profile from command line arguments. * * @param commandParameters Standard Imperative command handler parameters - see the interface for full details */ override fun process(commandParameters: IHandlerParameters): Promise<Unit> }
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
737
kotlin-externals
MIT License
app/nico2vocadb-songlist-exporter/src/main/kotlin/mikufan/cx/vtool/app/n2vex/config/CoreComponentSetup.kt
CXwudi
748,516,931
false
{"Kotlin": 57945}
package mikufan.cx.vtool.app.n2vex.config import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.asCoroutineDispatcher import mikufan.cx.vtool.component.httpser.api.NicoListFetcher import mikufan.cx.vtool.component.httpser.api.PvMapper import mikufan.cx.vtool.component.httpser.impl.NicoListFetcherImpl import mikufan.cx.vtool.component.httpser.impl.VocaDbPvMapper import mikufan.cx.vtool.component.httpser.impl.api.NicoListApi import mikufan.cx.vtool.component.httpser.impl.api.VocaDbSongByPvApi import mikufan.cx.vtool.component.io.api.ItemRecorder import mikufan.cx.vtool.component.io.impl.ToCsvItemRecorder import mikufan.cx.vtool.component.io.impl.VocaDbCompatibleSongListCsvProducer import mikufan.cx.vtool.core.n2vex.MainExporter import mikufan.cx.vtool.core.n2vex.MainExporterWithLocalWrite import mikufan.cx.vtool.core.n2vex.config.IOConfig import mikufan.cx.vtool.core.n2vex.config.Preference import mikufan.cx.vtool.shared.model.niconico.NicoListItem import mikufan.cx.vtool.shared.model.vocadb.VocaDBSongListItem import mikufan.cx.vtool.shared.model.vocadb.VocaDbCacheKeys import org.springframework.beans.factory.annotation.Qualifier import org.springframework.cache.CacheManager import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.util.concurrent.Executors @Configuration(proxyBeanMethods = false) class CoreComponentSetup { @Bean fun loomDispatcher(): CoroutineDispatcher = Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher() @Bean fun nicoListFetcher( nicoListApi: NicoListApi, preference: Preference, ): NicoListFetcher = NicoListFetcherImpl(nicoListApi, preference.usePrivateApi) @Bean fun vocadbPvMapper( vocaDbSongByPvApi: VocaDbSongByPvApi, cacheManager: CacheManager, ) : PvMapper { val cache = cacheManager.getCache(VocaDbCacheKeys.SONG_BY_PV) ?: throw IllegalStateException("Cache ${VocaDbCacheKeys.SONG_BY_PV} not found") return VocaDbPvMapper(vocaDbSongByPvApi, cache) } @Bean fun notFoundCsvRecorder( ioConfig: IOConfig, ) = ToCsvItemRecorder<NicoListItem>(ioConfig.notFoundCsv) @Bean fun outputCsvRecorder( ioConfig: IOConfig, preference: Preference, ) = if (preference.useVocadbCsvFormat) { VocaDbCompatibleSongListCsvProducer(ioConfig.outputCsv) } else { ToCsvItemRecorder<VocaDBSongListItem>(ioConfig.outputCsv) } @Bean fun mainExporter( nicoListFetcher: NicoListFetcher, vocadbPvMapper: PvMapper, loomDispatcher: CoroutineDispatcher, ) = MainExporter(nicoListFetcher, vocadbPvMapper, loomDispatcher) @Bean fun mainExporterWithLocalWrite( ioConfig: IOConfig, preference: Preference, mainExporter: MainExporter, @Qualifier("notFoundCsvRecorder") notFoundCsvRecorder: ItemRecorder<NicoListItem>, @Qualifier("outputCsvRecorder") outputCsvRecorder: ItemRecorder<VocaDBSongListItem>, ) = MainExporterWithLocalWrite( ioConfig, preference, mainExporter, notFoundCsvRecorder, outputCsvRecorder, ) }
2
Kotlin
0
0
7b260c3e08e654b588552182447f37965f5c0534
3,086
vsonglist-toolkit
MIT License
core/usecases/src/main/kotlin/net/onefivefour/sessiontimer/core/usecases/taskgroup/UpdateTaskGroupUseCase.kt
OneFiveFour
715,295,614
false
{"Kotlin": 141988}
package net.onefivefour.sessiontimer.core.usecases.taskgroup import dagger.hilt.android.scopes.ViewModelScoped import net.onefivefour.sessiontimer.core.common.domain.model.PlayMode import net.onefivefour.sessiontimer.core.database.domain.TaskGroupRepository import javax.inject.Inject @ViewModelScoped class UpdateTaskGroupUseCase @Inject constructor( private val taskGroupRepository: TaskGroupRepository ) { suspend fun execute( id: Long, title: String, color: Int, playMode: PlayMode, numberOfRandomTasks: Int ) { taskGroupRepository.update( id, title, color, playMode, numberOfRandomTasks ) } }
0
Kotlin
0
0
c40907f9c2a4cd38a0d81ea385b23f6084e54250
732
session-timer
Apache License 2.0
app/src/main/java/io/horizontalsystems/dynamitewallet/modules/receive/ReceivePresenter.kt
allmaechtig
283,654,113
true
{"Kotlin": 817536, "Ruby": 4839}
package io.horizontalsystems.bankwallet.modules.receive import io.horizontalsystems.bankwallet.R import io.horizontalsystems.bankwallet.modules.receive.viewitems.AddressItem class ReceivePresenter( private val interactor: ReceiveModule.IInteractor, private val router: ReceiveModule.IRouter) : ReceiveModule.IViewDelegate, ReceiveModule.IInteractorDelegate { var view: ReceiveModule.IView? = null private var receiveAddress: AddressItem? = null override fun viewDidLoad() { interactor.getReceiveAddress() } override fun didReceiveAddress(address: AddressItem) { this.receiveAddress = address view?.showAddress(address) } override fun didFailToReceiveAddress(exception: Exception) { view?.showError(R.string.Error) } override fun onShareClick() { receiveAddress?.address?.let { router.shareAddress(it) } } override fun onAddressClick() { receiveAddress?.address?.let { interactor.copyToClipboard(it) } } override fun didCopyToClipboard() { view?.showCopied() } }
0
Kotlin
0
0
7ace078fc242c65950d30f803c1903c09687ba3b
1,100
unstoppable-wallet-android
MIT License
src/main/kotlin/model/applicationfunctions/PngFileFilter.kt
MaxBuster380
622,688,076
false
null
package model.applicationfunctions import java.io.File import java.io.FilenameFilter internal class PngFileFilter : FilenameFilter { override fun accept(dir: File, name:String): Boolean { return false//name.matches(Regex("^.*\\.png$")) } }
0
Kotlin
0
3
c77168a15f7da11c44a7ebaec8fb9a1cd826b1b7
246
OneShot-Color-Filter
MIT License
napster/src/main/kotlin/io/anaxo/alexa/napster/handlers/audioplayer/PlaybackStarted.kt
hmedkouri
161,028,677
false
null
package io.anaxo.alexa.napster.handlers.audioplayer import com.amazon.ask.dispatcher.request.handler.HandlerInput import com.amazon.ask.dispatcher.request.handler.RequestHandler import com.amazon.ask.model.Response import com.amazon.ask.model.interfaces.audioplayer.PlaybackStartedRequest import com.amazon.ask.request.Predicates import java.util.* import javax.inject.Singleton @Singleton class PlaybackStarted : RequestHandler { override fun canHandle(input: HandlerInput): Boolean { return input.matches(Predicates.requestType(PlaybackStartedRequest::class.java)) } override fun handle(input: HandlerInput): Optional<Response> { return Optional.empty() } }
0
Kotlin
0
0
1d153d337de7e173f3d741836e57fffaf001361f
696
alexa-skills
MIT License
src/kotlin/ru/ifmo/antll1/generator/math/Token.kt
niki999922
283,890,943
false
null
package ru.ifmo.antll1.generator.math enum class Token(val title: String) { WS("[ \t\n\r]+"), NUMBER("[0-9]+"), PLUS("[+]"), MINUS("[-]"), POW("[*]{2}"), MUL("[*]"), L_SHIFT("<<"), R_SHIFT(">>"), OP_B("[(]"), CL_B("[)]"), END("end") }
0
Kotlin
0
0
3b980c6c7348dbdcbc7eaf69b28db0083540efc0
280
parser-generator
MIT License
EvoMaster/resource-rest-experiments/api-generator/src/main/kotlin/org/evomaster/resource/rest/generator/implementation/java/SwaggerAnnotation.kt
mitchellolsthoorn
364,836,402
false
{"Java": 3999651, "JavaScript": 2621912, "Kotlin": 2157071, "TypeScript": 137702, "CSS": 94780, "HTML": 35418, "Less": 29035, "Python": 25019, "R": 20339, "ANTLR": 12520, "XSLT": 6892, "Shell": 5833, "TeX": 4838, "Dockerfile": 493}
package org.evomaster.resource.rest.generator.implementation.java import org.evomaster.resource.rest.generator.template.Tag /** * created by manzh on 2019-08-15 */ object SwaggerAnnotation { /** * Provides additional information about Swagger models. */ val API_MODEL = Tag("ApiModel") /** * Adds and manipulates data of a model property. */ val API_MODEL_PROPERTY = object : Tag("ApiModelProperty"){ /** * valid params: * readOnly : boolean -- Allows a model property to be designated as read only. * required : boolean -- Specifies if the parameter is required or not. * value : String -- A brief description of this property. * hide : boolean -- Allows a model property to be hidden in the Swagger model definition. * example : String -- A sample value for the property. * dataType : String -- The data type of the parameter. */ private val params = mapOf("readOnly" to true, "required" to true, "value" to false, "hide" to true, "example" to false, "dataType" to false) override fun validateParams(param: String): Boolean = params.containsKey(param) override fun withoutQuotation(param: String): Boolean = params.getValue(param) } val ENABLE_SWAGGER_2 = Tag("EnableSwagger2") fun requiredPackages() : Array<String> = arrayOf( "io.swagger.annotations.ApiModel", "io.swagger.annotations.ApiModelProperty" ) }
1
null
1
1
50e9fb327fe918cc64c6b5e30d0daa2d9d5d923f
1,501
ASE-Technical-2021-api-linkage-replication
MIT License
src/test/kotlin/io/wusa/SemverGitPluginGroovyFunctionalTest.kt
jgindin
261,288,196
true
{"Kotlin": 93004}
package io.wusa import org.gradle.internal.impldep.org.eclipse.jgit.api.Git import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.UnexpectedBuildFailure import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.assertTrue import java.io.File @TestInstance(TestInstance.Lifecycle.PER_CLASS) class SemverGitPluginGroovyFunctionalTest : FunctionalBaseTest() { private lateinit var gradleRunner: GradleRunner @BeforeAll fun setUp() { gradleRunner = GradleRunner.create() } @AfterAll fun tearDown() { gradleRunner.projectDir.deleteRecursively() } @Test fun `defaults`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } """) initializeGitWithoutBranch(testProjectDirectory) val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0")) } @Test fun `version formatter for all branches`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}" } } } } """) initializeGitWithoutBranch(testProjectDirectory) val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0")) } @Test fun `version formatter for feature branches use specific`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = "feature/.*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+branch.${'$'}{it.branch.id}" } } branch { regex = ".+" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}" } } } } """) val git = initializeGitWithBranch(testProjectDirectory, "0.0.1", "feature/test") git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0+branch.feature-test-SNAPSHOT")) } @Test fun `no existing tag`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } """) val git = Git.init().setDirectory(testProjectDirectory).call() git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("-SNAPSHOT")) assertTrue(result.output.contains("Version: 0.1.0")) } @Test fun `no existing tag with custom initial version`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { initialVersion = '1.0.0' } """) val git = Git.init().setDirectory(testProjectDirectory).call() git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("-SNAPSHOT")) assertTrue(result.output.contains("Version: 1.0.0")) } @Test fun `no existing tag with configuration without commits`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { snapshotSuffix = 'SNAPSHOT' } """) Git.init().setDirectory(testProjectDirectory).call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue("""Version: 0\.1\.0\-SNAPSHOT""".toRegex().containsMatchIn(result.output)) } @Test fun `no existing tag with configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { snapshotSuffix = 'TEST' } """) val git = Git.init().setDirectory(testProjectDirectory).call() git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("-TEST")) assertTrue(result.output.contains("Version: 0.1.0")) } @Test fun `patch release with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "0.0.1") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.0.1")) } @Test fun `minor release with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory) val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0")) } @Test fun `major release with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { snapshotSuffix = 'SNAPSHOT' branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "1.0.0") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 1.0.0")) } @Test fun `release alpha with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "0.1.0-alpha") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0-alpha")) } @Test fun `release alpha beta with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "0.1.0-alpha.beta") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0-alpha.beta")) } @Test fun `release alpha 1 with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "0.1.0-alpha.1") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0-alpha.1")) } @Test fun `release beta with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "0.1.0-beta") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0-beta")) } @Test fun `release rc with custom configuration`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) initializeGitWithoutBranch(testProjectDirectory, "0.1.0-rc") val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0-rc")) } @Test fun `bump patch version`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "PATCH_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) val git = initializeGitWithoutBranch(testProjectDirectory) git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.1")) } @Test fun `bump minor version`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MINOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) val git = initializeGitWithoutBranch(testProjectDirectory) git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.2.0")) } @Test fun `bump major version`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "MAJOR_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) val git = initializeGitWithoutBranch(testProjectDirectory) git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("-SNAPSHOT")) assertTrue(result.output.contains("Version: 1.0.0")) } @Test fun `don't bump version`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } semver { branches { branch { regex = ".*" incrementer = "NO_VERSION_INCREMENTER" formatter = { "${'$'}{it.version.major}.${'$'}{it.version.minor}.${'$'}{it.version.patch}+build.${'$'}{it.count}.sha.${'$'}{it.shortCommit}" } } } } """) val git = initializeGitWithoutBranch(testProjectDirectory) git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Version: 0.1.0")) } @Test fun `non-semver tag`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } """) val git = initializeGitWithoutBranch(testProjectDirectory) val commit = git.commit().setMessage("").call() git.tag().setName("test-tag").setObjectId(commit).call() Assertions.assertThrows(UnexpectedBuildFailure::class.java) { gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showVersion") .withPluginClasspath() .build() } } @Test fun `full info of master branch with one commit after the tag`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } """) val git = initializeGitWithoutBranch(testProjectDirectory) val commit = git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showInfo") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Branch name: master")) assertTrue(result.output.contains("Branch group: master")) assertTrue(result.output.contains("Branch id: master")) assertTrue(result.output.contains("Commit: " + commit.id.name())) assertTrue(result.output.contains("Short commit: " + commit.id.abbreviate( 7 ).name())) assertTrue(result.output.contains("Tag: none")) assertTrue(result.output.contains("Last tag: 0.1.0")) assertTrue(result.output.contains("Dirty: false")) assertTrue(result.output.contains("Version major: 0")) assertTrue(result.output.contains("Version minor: 2")) assertTrue(result.output.contains("Version patch: 0")) assertTrue(result.output.contains("Version pre release: none")) assertTrue(result.output.contains("Version build: none")) } @Test fun `full info of feature-test branch with one commit after the tag`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } """) val git = initializeGitWithBranch(testProjectDirectory, "0.0.1", "feature/test") val commit = git.commit().setMessage("").call() val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showInfo") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Branch name: feature/test")) assertTrue(result.output.contains("Branch group: feature")) assertTrue(result.output.contains("Branch id: feature-test")) assertTrue(result.output.contains("Commit: " + commit.id.name())) assertTrue(result.output.contains("Short commit: " + commit.id.abbreviate( 7 ).name())) assertTrue(result.output.contains("Tag: none")) assertTrue(result.output.contains("Last tag: 0.0.1")) assertTrue(result.output.contains("Dirty: false")) assertTrue(result.output.contains("Version major: 0")) assertTrue(result.output.contains("Version minor: 1")) assertTrue(result.output.contains("Version patch: 0")) assertTrue(result.output.contains("Version pre release: none")) assertTrue(result.output.contains("Version build: none")) } @Test fun `full info of feature-test branch with no commit after the tag`() { val testProjectDirectory = createTempDir() val buildFile = File(testProjectDirectory, "build.gradle") buildFile.writeText(""" plugins { id 'io.wusa.semver-git-plugin' } """) val git = initializeGitWithBranch(testProjectDirectory, "0.0.1", "feature/test") val head = git.repository.allRefs["HEAD"] val result = gradleRunner .withProjectDir(testProjectDirectory) .withArguments("showInfo") .withPluginClasspath() .build() println(result.output) assertTrue(result.output.contains("Branch name: feature/test")) assertTrue(result.output.contains("Branch group: feature")) assertTrue(result.output.contains("Branch id: feature-test")) assertTrue(result.output.contains("Commit: " + head?.objectId?.name)) assertTrue(result.output.contains("Tag: 0.0.1")) assertTrue(result.output.contains("Last tag: 0.0.1")) assertTrue(result.output.contains("Dirty: false")) assertTrue(result.output.contains("Version major: 0")) assertTrue(result.output.contains("Version minor: 0")) assertTrue(result.output.contains("Version patch: 1")) assertTrue(result.output.contains("Version pre release: none")) assertTrue(result.output.contains("Version build: none")) } }
0
null
0
0
56154065cf4490f2792eb7cea33089ccaa25f894
25,408
semver-git-plugin
MIT License
UserCenter/src/main/java/com/kotlin/user/presenter/view/RegisterView.kt
heisexyyoumo
145,665,152
false
{"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Proguard": 8, "Kotlin": 218, "XML": 116, "Java": 14}
package com.kotlin.user.presenter.view import com.kotlin.base.presenter.view.BaseView open interface RegisterView : BaseView { fun onRegisterResult(result : String) }
0
Kotlin
1
2
27fea0090cea5fb636f8db5025379d274693b1b4
173
KotlinMall
Apache License 2.0
compiler/testData/compileKotlinAgainstKotlin/typeAliasesKt13181.kt
JakeWharton
99,388,807
true
null
// MODULE: lib // FILE: A.kt typealias Bar<T> = (T) -> String class Foo<out T>(val t: T) { fun baz(b: Bar<T>) = b(t) } // MODULE: main(lib) // FILE: B.kt class FooTest { fun baz(): String { val b: Bar<String> = { "OK" } return Foo("").baz(b) } } fun box(): String = FooTest().baz()
181
Kotlin
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
321
kotlin
Apache License 2.0
fxgl/src/test/kotlin/com/almasb/fxgl/io/serialization/BundleTest.kt
nagyist
170,678,757
true
{"Java": 2201675, "Kotlin": 870282, "CSS": 24668, "Ragel": 10660, "JavaScript": 4913, "Shell": 405}
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB (<EMAIL>). * See LICENSE for details. */ package com.almasb.fxgl.core.serialization import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test /** * * * @author <NAME> (<EMAIL>) */ class BundleTest { @Test fun `Test access`() { val bundle = Bundle("Test") val s: String? = bundle.get<String>("None") assertTrue(s == null) } @Test fun `exists`() { val bundle = Bundle("Test") assertFalse(bundle.exists("key")) bundle.put("key", "someValue") assertTrue(bundle.exists("key")) } }
0
Java
0
0
aaafc756e070585cc003704392978230174797c2
731
FXGL
MIT License
src/main/kotlin/net/sportsday/routes/v1/TagRouter.kt
Sports-day
589,245,462
false
{"Kotlin": 218532, "Dockerfile": 330}
package net.sportsday.routes.v1 import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import net.sportsday.models.OmittedTag import net.sportsday.plugins.Role import net.sportsday.plugins.withRole import net.sportsday.services.TagService import net.sportsday.utils.DataMessageResponse import net.sportsday.utils.DataResponse import net.sportsday.utils.respondOrInternalError /** * Created by testusuke on 2023/10/02 * @author testusuke */ fun Route.tagRouter() { route("/tags") { withRole(Role.USER) { /** * Get all tags */ get { val tags = TagService.getAll() call.respond(HttpStatusCode.OK, DataResponse(tags.getOrDefault(listOf()))) } withRole(Role.ADMIN) { /** * Create new tag */ post { val requestBody = call.receive<OmittedTag>() TagService .create(requestBody) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataMessageResponse( "created tag", it, ), ) } } } route("/{id?}") { /** * Get tag by id */ get { val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter") TagService .getById(id) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataResponse(it), ) } } withRole(Role.ADMIN) { /** * Update tag */ put { val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter") val requestBody = call.receive<OmittedTag>() TagService .update(id, requestBody) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataMessageResponse( "update tag", it, ), ) } } /** * Delete tag */ delete { val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter") TagService .deleteById(id) .respondOrInternalError { call.respond( HttpStatusCode.OK, DataMessageResponse( "deleted tag", it, ), ) } } } } } } }
8
Kotlin
1
1
c28a83cdbb8a893372b26f0a7ec3bef617a4acad
3,871
SportsDayAPI
Apache License 2.0
app/src/main/java/com/steve_md/socialsapp/di/AppModule.kt
MuindiStephen
622,247,213
false
null
package com.steve_md.socialsapp.di import com.google.gson.Gson import com.google.gson.GsonBuilder import com.steve_md.socialsapp.data.api.SocialsApiService import com.steve_md.socialsapp.screens.commons.Constants.BASE_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun providesBaseUrl() : String{ return BASE_URL } private val httpLoggingInterceptor = HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY) val okHttpClient = OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .build() @Provides @Singleton fun providesGson() : Gson = GsonBuilder().setLenient().create() @Provides @Singleton fun providesRetrofit( okHttpClient: OkHttpClient, gson: Gson ) : Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() } @Provides @Singleton fun providesSocialsApiService(retrofit: Retrofit) : SocialsApiService { return retrofit.create(SocialsApiService::class.java) } }
0
Kotlin
0
0
9521c69a104653fe1376ded00008d2ba897969bd
1,518
Jenkins
MIT License
minchat-common/src/main/kotlin/io/minchat/common/event/MessageEvents.kt
MinChat-official
604,238,971
false
{"Kotlin": 394469}
package io.minchat.common.event import io.minchat.common.entity.Message import kotlinx.serialization.* @Serializable @SerialName("MessageCreate") data class MessageCreateEvent( val message: Message ) : Event() { override fun toString() = "MessageCreateEvent(author=${message.author.loggable()}, message=${message.loggable()})" } @Serializable @SerialName("MessageModify") data class MessageModifyEvent( val message: Message ) : Event() { override fun toString() = "MessageModifyEvent(author=${message.author.loggable()}, message=${message.loggable()})" } @Serializable @SerialName("MessageDelete") data class MessageDeleteEvent( val messageId: Long, val channelId: Long, val authorId: Long, val byAuthor: Boolean ) : Event()
0
Kotlin
0
3
8f70585146311efe9fc49e4e3b93eb8becb92cba
741
MinChat
Apache License 2.0
tinyK-ast/src/main/kotlin/tinyK/ast/visitor/Visitor.kt
pocmo
289,081,739
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tinyK.ast.visitor import tinyK.ast.BinaryOperation import tinyK.ast.ConjunctionNode import tinyK.ast.DisjunctionNode import tinyK.ast.EqualityNode import tinyK.ast.FunctionCallNode import tinyK.ast.IdentifierNode import tinyK.ast.LiteralNode import tinyK.ast.MemberAccessNode import tinyK.ast.PropertyDeclarationNode interface Visitor { fun visitBinaryOperation(node: BinaryOperation) fun visitLiteralNode(node: LiteralNode) fun visitConjunctionNode(node: ConjunctionNode) fun visitDisjunctionNode(node: DisjunctionNode) fun visitEqualityNode(node: EqualityNode) fun visitIdentifierNode(node: IdentifierNode) fun visitPropertyDeclarationNode(node: PropertyDeclarationNode) fun visitFunctionCallNode(node: FunctionCallNode) fun visitMemberAccessNode(node: MemberAccessNode) }
9
Kotlin
0
0
1e57fb51c659e6e4dc713087d09a76be935bf2c5
1,408
tinyK
Apache License 2.0
core/src/commonMain/kotlin/pro/respawn/flowmvi/plugins/UndoRedoPlugin.kt
respawn-app
477,143,989
false
null
package pro.respawn.flowmvi.plugins import kotlinx.atomicfu.atomic import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import pro.respawn.flowmvi.api.FlowMVIDSL import pro.respawn.flowmvi.api.IntentReceiver import pro.respawn.flowmvi.api.MVIAction import pro.respawn.flowmvi.api.MVIIntent import pro.respawn.flowmvi.api.MVIState import pro.respawn.flowmvi.api.StorePlugin import pro.respawn.flowmvi.dsl.StoreBuilder import pro.respawn.flowmvi.dsl.plugin import pro.respawn.flowmvi.util.CappedMutableList /** * An object that allows to undo and redo any actions happening in the [pro.respawn.flowmvi.api.Store]. * Keep a reference to the object instance to call [undo], [redo], and [invoke]. * Don't forget to install the corresponding plugin with [undoRedoPlugin]. */ public class UndoRedo( private val maxQueueSize: Int, ) { init { require(maxQueueSize > 0) { "Queue size less than 1 is not allowed, you provided: $maxQueueSize" } } private val _queue by atomic<CappedMutableList<Event>>(CappedMutableList(maxQueueSize)) private val _index = MutableStateFlow(-1) private val lock = Mutex() /** * Current index of the queue. * * Larger value means newer, but not larger than [maxQueueSize]. * When the index is equal to -1, the undo queue is empty. * An index of 0 means that there is one event to undo. */ public val index: StateFlow<Int> = _index.asStateFlow() /** * Current state of the [Queue]. * For synchronous / initial queue value access, see [canUndo], [canRedo], [queueSize] */ public val queue: Flow<Queue> = _index.asStateFlow().map { i -> Queue(i, canUndo, canRedo) } /** * Whether the event queue is empty. Does not take [Queue.index] into account */ public val isQueueEmpty: Boolean get() = _queue.isEmpty() /** * The current queue size of the plugin. * This queue size does **not** consider current index and allows to get the total amount of events stored */ public val queueSize: Int get() = _queue.size /** * Whether the plugin can [undo] at this moment. */ public val canUndo: Boolean get() = !isQueueEmpty && _index.value >= 0 /** * Whether the plugin can [redo] at this moment. */ public val canRedo: Boolean get() = !isQueueEmpty && _index.value < _queue.lastIndex /** * Add a given [undo] and [redo] to the queue. * If [doImmediately] is true, then [redo] will be executed **before** the queue is modified! * **You cannot call [UndoRedo.undo] or [UndoRedo.redo] in [redo] or [undo]!** */ public suspend operator fun invoke( doImmediately: Boolean = true, redo: suspend () -> Unit, undo: suspend () -> Unit, ): Int = lock.withLock { with(_queue) { if (doImmediately) redo() val range = _index.value.coerceAtLeast(0) + 1..lastIndex if (!range.isEmpty()) removeAll(slice(range).toSet()) add(Event(redo, undo)) lastIndex.also { _index.value = it } } } /** * Add the [intent] to the queue with specified [undo] and **immediately** execute the [intent]. * **You cannot call [UndoRedo.undo] or [UndoRedo.redo] in [intent] or [undo]!** */ public suspend operator fun <I : MVIIntent> IntentReceiver<I>.invoke( intent: I, undo: suspend () -> Unit, ): Int = invoke(redo = { intent(intent) }, undo = undo, doImmediately = true) /** * Undo the event at current [_index]. * **You cannot undo and redo while another undo/redo is running!** */ public suspend fun undo(require: Boolean = false): Int = lock.withLock { if (!canUndo) { require(!require) { "Tried to undo action #${_index.value} but nothing was in the queue" } -1 } else { val i = _index.value.coerceIn(_queue.indices) _queue[i].undo() (i - 1).also { _index.value = it } } } /** * Redo the event at current [_index]. * **You cannot undo and redo while another undo/redo is running!** */ public suspend fun redo(require: Boolean = false): Int = lock.withLock { if (!canRedo) { require(!require) { "Tried to redo but queue already at the last index of ${_queue.lastIndex}" } _queue.lastIndex } else { val i = _index.value.coerceIn(_queue.indices) _queue[i].redo() (i + 1).also { _index.value = it } } } /** * Clear the queue of events and reset [_index] to -1 */ public fun reset(): Unit = _index.update { _queue.clear() -1 } internal fun <S : MVIState, I : MVIIntent, A : MVIAction> asPlugin( name: String?, resetOnException: Boolean, ): StorePlugin<S, I, A> = plugin { this.name = name // reset because pipeline context captured in Events is no longer running onStop { reset() } if (resetOnException) onException { it.also { reset() } } } /** * An event happened in the [UndoRedo]. */ internal data class Event internal constructor( internal val redo: suspend () -> Unit, internal val undo: suspend () -> Unit, ) { override fun toString(): String = "UndoRedoPlugin.Event" } /** * Undo/redo queue representation * * @param index Current index of the queue. * Larger value means newer, but not larger than [maxQueueSize]. * When the index is equal to -1, the undo queue is empty. * An index of 0 means that there is one event to undo. * @param canUndo whether there are actions to undo * @param canRedo whether there are actions to redo * @see _queue */ public data class Queue( val index: Int, val canUndo: Boolean, val canRedo: Boolean, ) } /** * Returns a plugin that manages the [undoRedo] provided. */ @FlowMVIDSL public fun <S : MVIState, I : MVIIntent, A : MVIAction> undoRedoPlugin( undoRedo: UndoRedo, name: String? = null, resetOnException: Boolean = true, ): StorePlugin<S, I, A> = undoRedo.asPlugin(name, resetOnException) /** * Creates, installs and returns a new [UndoRedo] instance * @return an instance that was created. Use the returned instance to execute undo and redo operations. * @see UndoRedo * @see undoRedoPlugin */ @FlowMVIDSL public fun <S : MVIState, I : MVIIntent, A : MVIAction> StoreBuilder<S, I, A>.undoRedo( maxQueueSize: Int, name: String? = null, resetOnException: Boolean = true, ): UndoRedo = UndoRedo(maxQueueSize).also { install(it.asPlugin(name, resetOnException)) }
8
null
7
305
80ea0a5eedc948fe50d3f23ddce041d8144f0f23
7,003
FlowMVI
Apache License 2.0
app/src/main/java/com/sunnyseather/android/TestAmap.kt
catcatpro
615,196,841
false
null
package com.sunnyseather.android import android.content.Context import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.amap.api.services.core.AMapException import com.amap.api.services.core.PoiItemV2 import com.amap.api.services.core.ServiceSettings import com.amap.api.services.geocoder.GeocodeResult import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener import com.amap.api.services.geocoder.RegeocodeResult import com.amap.api.services.poisearch.PoiResult import com.amap.api.services.poisearch.PoiResultV2 import com.amap.api.services.poisearch.PoiSearchV2 import com.amap.api.services.poisearch.PoiSearchV2.OnPoiSearchListener import com.sunnyseather.android.databinding.ActivityTestAampBinding class TestAmap : AppCompatActivity(), OnGeocodeSearchListener , OnPoiSearchListener{ lateinit var viewBinding:ActivityTestAampBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivityTestAampBinding.inflate(layoutInflater) setContentView(viewBinding.root) ServiceSettings.updatePrivacyAgree(this, true) ServiceSettings.updatePrivacyShow(this, true, true) // var geocoderSearch:GeocodeSearch viewBinding.queryBtn.setOnClickListener { try { val city = viewBinding.editAddress.text.toString() // geocoderSearch = GeocodeSearch(this) // geocoderSearch.setOnGeocodeSearchListener(this) // Log.d("city", city) // val query = GeocodeQuery(city, "0766") // geocoderSearch.getFromLocationNameAsyn(query) val query = PoiSearchV2.Query(city, "","") query.setPageSize(10);// 设置每页最多返回多少条poiitem query.setPageNum(1);//设置查询页码 val poiSearch = PoiSearchV2(this, query) poiSearch.setOnPoiSearchListener(this) poiSearch.searchPOIAsyn() }catch (e: AMapException){ // } } } override fun onRegeocodeSearched(p0: RegeocodeResult?, p1: Int) { TODO("Not yet implemented") } override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) { p0?.geocodeQuery?.let { Log.d("SeachRes", it.locationName) } } override fun onPoiSearched(p0: PoiResultV2?, p1: Int) { p0?.pois?.let { // for (item in it){ // Log.d("SearchRes.", item.adCode) // } viewBinding.coordinator.text = "城市编号:" + it[0].adCode } // p0?.pois?.let { // Log.d("SearchRes.", it[0].adCode) // viewBinding.coordinator.text = it[0].adCode // } } override fun onPoiItemSearched(p0: PoiItemV2?, p1: Int) { p0?.let { Log.d("SearchRes",it.adCode) } } companion object{ @JvmStatic open fun updatePrivacyShow(context: Context, isContains: Boolean, isShow: Boolean){ } @JvmStatic open fun updatePrivacyAgree(context: Context?, isAgree: Boolean){ } } }
0
Kotlin
0
0
e5a2522c136a59dabc9be44dac501a8a39658847
3,165
SunnyWeather
Apache License 2.0
sdk-lib/src/main/java/cash/z/ecc/android/sdk/internal/db/PendingTransactionDb.kt
zcash
151,763,639
false
null
package cash.z.ecc.android.sdk.db import androidx.room.* import cash.z.ecc.android.sdk.db.entity.PendingTransactionEntity import kotlinx.coroutines.flow.Flow // // Database // /** * Database for pending transaction information. Unlike with the "Data DB," the wallet is free to * write to this database. In a way, this almost serves as a local mempool for all transactions * initiated by this wallet. Currently, the data necessary to support expired transactions is there * but it is not being leveraged. */ @Database( entities = [ PendingTransactionEntity::class ], version = 1, exportSchema = true ) abstract class PendingTransactionDb : RoomDatabase() { abstract fun pendingTransactionDao(): PendingTransactionDao } // // Data Access Objects // /** * Data access object providing crud for pending transactions. */ @Dao interface PendingTransactionDao { @Insert(onConflict = OnConflictStrategy.ABORT) suspend fun create(transaction: PendingTransactionEntity): Long @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun update(transaction: PendingTransactionEntity) @Delete suspend fun delete(transaction: PendingTransactionEntity): Int @Query("UPDATE pending_transactions SET cancelled = 1 WHERE id = :id") suspend fun cancel(id: Long) @Query("SELECT * FROM pending_transactions WHERE id = :id") suspend fun findById(id: Long): PendingTransactionEntity? @Query("SELECT * FROM pending_transactions ORDER BY createTime") fun getAll(): Flow<List<PendingTransactionEntity>> @Query("SELECT * FROM pending_transactions WHERE id = :id") fun monitorById(id: Long): Flow<PendingTransactionEntity> // // Update helper functions // @Query("UPDATE pending_transactions SET rawTransactionId = null WHERE id = :id") suspend fun removeRawTransactionId(id: Long) @Query("UPDATE pending_transactions SET minedHeight = :minedHeight WHERE id = :id") suspend fun updateMinedHeight(id: Long, minedHeight: Int) @Query("UPDATE pending_transactions SET raw = :raw, rawTransactionId = :rawTransactionId, expiryHeight = :expiryHeight WHERE id = :id") suspend fun updateEncoding(id: Long, raw: ByteArray, rawTransactionId: ByteArray, expiryHeight: Int?) @Query("UPDATE pending_transactions SET errorMessage = :errorMessage, errorCode = :errorCode WHERE id = :id") suspend fun updateError(id: Long, errorMessage: String?, errorCode: Int?) @Query("UPDATE pending_transactions SET encodeAttempts = :attempts WHERE id = :id") suspend fun updateEncodeAttempts(id: Long, attempts: Int) @Query("UPDATE pending_transactions SET submitAttempts = :attempts WHERE id = :id") suspend fun updateSubmitAttempts(id: Long, attempts: Int) }
70
null
38
45
3a0ded71138d0b35d238cfeae523abde6e7e2a01
2,779
zcash-android-wallet-sdk
MIT License
tools/string_converter/src/main/java/com/wa2c/android/cifsdocumentsprovider/tools/string_converter/model/CsvRow.kt
wa2c
309,159,444
false
null
package com.wa2c.android.medolylibrary.tools.string_converter.model /** * CSV Row */ data class CsvRow( /** Title */ val title: String, /** String resource ID */ val resourceId: String, /** Language text map (key: lang code, value: text) */ val langText: Map<String, String>, )
36
null
24
247
1145bebed366f707c1c07bc9e2102322e59f9b61
305
cifs-documents-provider
MIT License
testing/cpbs/packaging-verification-contract-v1/src/main/kotlin/com/r3/corda/testing/packagingverification/contract/SimpleTokenStateObserver.kt
corda
346,070,752
false
null
package net.cordapp.testing.packagingverification.contract import net.corda.v5.application.crypto.DigestService import net.corda.v5.ledger.utxo.observer.UtxoLedgerTokenStateObserver import net.corda.v5.ledger.utxo.observer.UtxoToken import net.corda.v5.ledger.utxo.observer.UtxoTokenFilterFields import net.corda.v5.ledger.utxo.observer.UtxoTokenPoolKey class SimpleTokenStateObserver : UtxoLedgerTokenStateObserver<SimpleState> { override fun getStateType() = SimpleState::class.java override fun onCommit(state: SimpleState, digestService: DigestService) = UtxoToken( UtxoTokenPoolKey(STATE_NAME, state.issuer.toSecureHash(digestService), STATE_SYMBOL), state.value.toBigDecimal(), UtxoTokenFilterFields() ) }
71
Kotlin
9
39
9790d4f101f2fd8aecc9d083f8a61c21efe089e7
751
corda-runtime-os
Apache License 2.0
web/core/src/jsTest/kotlin/MediaQueryTests.kt
JetBrains
293,498,508
false
null
/* * Copyright 2020-2021 JetBrains s.r.o. and respective authors and developers. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.compose.web.core.tests import org.jetbrains.compose.web.css.CSSMediaRuleDeclaration import org.jetbrains.compose.web.css.StyleSheet import org.jetbrains.compose.web.css.and import org.jetbrains.compose.web.css.mediaMaxHeight import org.jetbrains.compose.web.css.mediaMaxWidth import org.jetbrains.compose.web.css.media import org.jetbrains.compose.web.css.mediaMinHeight import org.jetbrains.compose.web.css.mediaMinWidth import org.jetbrains.compose.web.css.px import kotlin.test.Test import kotlin.test.assertEquals class MediaQueryTests { private object CombinedMediaQueries : StyleSheet() { val combine by style { media(mediaMinWidth(200.px).and(mediaMaxWidth(400.px))) { } media(mediaMinWidth(300.px), mediaMaxWidth(500.px)) { } } } private object MediaFeatures : StyleSheet() { val features by style { media(mediaMinWidth(200.px)) {} media(mediaMinHeight(300.px)) {} media(mediaMaxWidth(500.px)) {} media(mediaMaxHeight(600.px)) {} } } @Test fun mediaFeatures() { assertEquals( "@media (min-width: 200px)", (MediaFeatures.cssRules[1] as CSSMediaRuleDeclaration).header ) assertEquals( "@media (min-height: 300px)", (MediaFeatures.cssRules[2] as CSSMediaRuleDeclaration).header ) assertEquals( "@media (max-width: 500px)", (MediaFeatures.cssRules[3] as CSSMediaRuleDeclaration).header ) assertEquals( "@media (max-height: 600px)", (MediaFeatures.cssRules[4] as CSSMediaRuleDeclaration).header ) } @Test fun combineMediaQueries() { assertEquals( "@media (min-width: 200px) and (max-width: 400px)", (CombinedMediaQueries.cssRules[1] as CSSMediaRuleDeclaration).header ) assertEquals( "@media (min-width: 300px), (max-width: 500px)", (CombinedMediaQueries.cssRules[2] as CSSMediaRuleDeclaration).header ) } }
668
null
645
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
2,348
compose-jb
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppslaunchpadauth/service/SsoRequestService.kt
ministryofjustice
650,525,398
false
{"Kotlin": 226753, "HTML": 2361, "Dockerfile": 1146}
package uk.gov.justice.digital.hmpps.hmppslaunchpadauth.service import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.constant.AuthServiceConstant.Companion.INTERNAL_SERVER_ERROR_MSG import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.exception.ApiErrorTypes import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.exception.SsoException import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.model.Scope import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.model.SsoClient import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.model.SsoRequest import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.repository.SsoRequestRepository import java.time.LocalDateTime import java.time.ZoneOffset import java.util.* @Service class SsoRequestService( private var ssoRequestRepository: SsoRequestRepository, ) { companion object { private val logger = LoggerFactory.getLogger(SsoRequestService::class.java) } fun createSsoRequest(ssoRequest: SsoRequest): SsoRequest { val ssoRequestCreated = ssoRequestRepository.save(ssoRequest) logger.info("Sso request created for user of client: {}", ssoRequestCreated.client.id) return ssoRequestCreated } fun updateSsoRequest(ssoRequest: SsoRequest): SsoRequest { val updatedSsoRequest = ssoRequestRepository.save(ssoRequest) logger.info("Sso request updated for user of client: {}", ssoRequest.client.id) return updatedSsoRequest } fun getSsoRequestById(id: UUID): Optional<SsoRequest> { logger.debug("Sso request retrieved for id: {}", id) return ssoRequestRepository.findById(id) } fun deleteSsoRequestById(id: UUID) { logger.debug("Sso request deleted for id: {}", id) ssoRequestRepository.deleteById(id) } fun generateSsoRequest( scopes: Set<Scope>, state: String?, nonce: String?, redirectUri: String, clientId: UUID, ): SsoRequest { var authorizationCode: UUID = UUID.randomUUID() var ssoRequestRecord = ssoRequestRepository.findSsoRequestByAuthorizationCode(authorizationCode) var count = 0 while (ssoRequestRecord.isPresent) { count += 1 if (count > 3) { val message = "Duplicate uuid created multiple time for auth code" throw SsoException( message, HttpStatus.INTERNAL_SERVER_ERROR, ApiErrorTypes.SERVER_ERROR.toString(), INTERNAL_SERVER_ERROR_MSG, redirectUri, state, ) } logger.debug("Authorization code exist in sso request db record so creating new") authorizationCode = UUID.randomUUID() ssoRequestRecord = ssoRequestRepository.findSsoRequestByAuthorizationCode(authorizationCode) } val ssoRequest = SsoRequest( UUID.randomUUID(), UUID.randomUUID(), LocalDateTime.now(ZoneOffset.UTC), UUID.randomUUID(), SsoClient( clientId, state, nonce, scopes, redirectUri, ), null, ) return createSsoRequest(ssoRequest) } fun getSsoRequestByAuthorizationCode(code: UUID): Optional<SsoRequest> { return ssoRequestRepository.findSsoRequestByAuthorizationCode(code) } }
3
Kotlin
0
0
e87ab79e7804e189e7875b05a8f657bc82c4d016
3,272
hmpps-launchpad-auth
MIT License
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/api/ArgumentMapping.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.api import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType interface ArgumentMapping<out P : CallParameter> { val arguments: Arguments val varargParameter: P? get() = null fun targetParameter(argument: Argument): P? fun expectedType(argument: Argument): PsiType? val expectedTypes: Iterable<Pair<PsiType, Argument>> fun applicability(): Applicability fun highlightingApplicabilities(substitutor: PsiSubstitutor): ApplicabilityResult }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
665
intellij-community
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/analyzer/AbstractResolverForProject.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2019 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.analyzer import com.intellij.openapi.util.ModificationTracker import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentProvider import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.RESOLUTION_ANCHOR_PROVIDER_CAPABILITY import org.jetbrains.kotlin.resolve.ResolutionAnchorProvider import org.jetbrains.kotlin.utils.checkWithAttachment abstract class AbstractResolverForProject<M : ModuleInfo>( private val debugName: String, protected val projectContext: ProjectContext, modules: Collection<M>, protected val fallbackModificationTracker: ModificationTracker? = null, private val delegateResolver: ResolverForProject<M> = EmptyResolverForProject(), private val packageOracleFactory: PackageOracleFactory = PackageOracleFactory.OptimisticFactory, protected val resolutionAnchorProvider: ResolutionAnchorProvider = ResolutionAnchorProvider.Default, ) : ResolverForProject<M>() { protected class ModuleData( val moduleDescriptor: ModuleDescriptorImpl, val modificationTracker: ModificationTracker? ) { val modificationCount: Long = modificationTracker?.modificationCount ?: Long.MIN_VALUE fun isOutOfDate(): Boolean { val currentModCount = modificationTracker?.modificationCount return currentModCount != null && currentModCount > modificationCount } } // Protected by ("projectContext.storageManager.lock") protected val descriptorByModule = mutableMapOf<M, ModuleData>() // Protected by ("projectContext.storageManager.lock") private val moduleInfoByDescriptor = mutableMapOf<ModuleDescriptorImpl, M>() @Suppress("UNCHECKED_CAST") private val moduleInfoToResolvableInfo: Map<M, M> = modules.flatMap { module -> module.flatten().map { modulePart -> modulePart to module } }.toMap() as Map<M, M> init { assert(moduleInfoToResolvableInfo.values.toSet() == modules.toSet()) } abstract fun sdkDependency(module: M): M? abstract fun modulesContent(module: M): ModuleContent<M> abstract fun builtInsForModule(module: M): KotlinBuiltIns abstract fun createResolverForModule(descriptor: ModuleDescriptor, moduleInfo: M): ResolverForModule override fun tryGetResolverForModule(moduleInfo: M): ResolverForModule? { if (!isCorrectModuleInfo(moduleInfo)) { return null } return resolverForModuleDescriptor(doGetDescriptorForModule(moduleInfo)) } private fun setupModuleDescriptor(module: M, moduleDescriptor: ModuleDescriptorImpl) { moduleDescriptor.setDependencies( LazyModuleDependencies( projectContext.storageManager, module, sdkDependency(module), this ) ) val content = modulesContent(module) moduleDescriptor.initialize( DelegatingPackageFragmentProvider( this, moduleDescriptor, content, packageOracleFactory.createOracle(module) ) ) } // Protected by ("projectContext.storageManager.lock") private val resolverByModuleDescriptor = mutableMapOf<ModuleDescriptor, ResolverForModule>() override val allModules: Collection<M> by lazy { this.moduleInfoToResolvableInfo.keys + delegateResolver.allModules } override val name: String get() = "Resolver for '$debugName'" private fun isCorrectModuleInfo(moduleInfo: M) = moduleInfo in allModules final override fun resolverForModuleDescriptor(descriptor: ModuleDescriptor): ResolverForModule { val moduleResolver = resolverForModuleDescriptorImpl(descriptor) // Please, attach exceptions from here to EA-214260 (see `resolverForModuleDescriptorImpl` comment) checkWithAttachment( moduleResolver != null, lazyMessage = { "$descriptor is not contained in resolver $name" }, attachments = { it.withAttachment( "resolverContents.txt", "Expected module descriptor: $descriptor\n\n${renderResolversChainContents()}" ) } ) return moduleResolver } /** * We have a problem investigating EA-214260 (KT-40301), that is why we separated searching the * [ResolverForModule] and reporting the problem in [resolverForModuleDescriptor] (so we can tweak the reported information more * accurately). * * We use the fact that [ResolverForProject] have only two inheritors: [EmptyResolverForProject] and [AbstractResolverForProject]. * So if the [delegateResolver] is not an [EmptyResolverForProject], it has to be [AbstractResolverForProject]. * * Knowing that, we can safely use [resolverForModuleDescriptorImpl] recursively, and get the same result * as with [resolverForModuleDescriptor]. */ private fun resolverForModuleDescriptorImpl(descriptor: ModuleDescriptor): ResolverForModule? { return projectContext.storageManager.compute { val module = moduleInfoByDescriptor[descriptor] if (module == null) { if (delegateResolver is EmptyResolverForProject<*>) { return@compute null } return@compute (delegateResolver as AbstractResolverForProject<M>).resolverForModuleDescriptorImpl(descriptor) } resolverByModuleDescriptor.getOrPut(descriptor) { checkModuleIsCorrect(module) ResolverForModuleComputationTracker.getInstance(projectContext.project)?.onResolverComputed(module) createResolverForModule(descriptor, module) } } } internal fun isResolverForModuleDescriptorComputed(descriptor: ModuleDescriptor) = projectContext.storageManager.compute { descriptor in resolverByModuleDescriptor } override fun descriptorForModule(moduleInfo: M): ModuleDescriptorImpl { checkModuleIsCorrect(moduleInfo) return doGetDescriptorForModule(moduleInfo) } override fun moduleInfoForModuleDescriptor(moduleDescriptor: ModuleDescriptor): M { return moduleInfoByDescriptor[moduleDescriptor] ?: delegateResolver.moduleInfoForModuleDescriptor(moduleDescriptor) } override fun diagnoseUnknownModuleInfo(infos: List<ModuleInfo>): Nothing { DiagnoseUnknownModuleInfoReporter.report(name, infos, allModules) } private fun checkModuleIsCorrect(moduleInfo: M) { if (!isCorrectModuleInfo(moduleInfo)) { diagnoseUnknownModuleInfo(listOf(moduleInfo)) } } private fun doGetDescriptorForModule(module: M): ModuleDescriptorImpl { val moduleFromThisResolver = moduleInfoToResolvableInfo[module] ?: return delegateResolver.descriptorForModule(module) as ModuleDescriptorImpl return projectContext.storageManager.compute { var moduleData = descriptorByModule.getOrPut(moduleFromThisResolver) { createModuleDescriptor(moduleFromThisResolver) } if (moduleData.isOutOfDate()) { moduleData = recreateModuleDescriptor(moduleFromThisResolver) } moduleData.moduleDescriptor } } private fun recreateModuleDescriptor(module: M): ModuleData { val oldDescriptor = descriptorByModule[module]?.moduleDescriptor if (oldDescriptor != null) { oldDescriptor.isValid = false moduleInfoByDescriptor.remove(oldDescriptor) resolverByModuleDescriptor.remove(oldDescriptor) projectContext.project.messageBus.syncPublisher(ModuleDescriptorListener.TOPIC).moduleDescriptorInvalidated(oldDescriptor) } val moduleData = createModuleDescriptor(module) descriptorByModule[module] = moduleData return moduleData } private fun createModuleDescriptor(module: M): ModuleData { val moduleDescriptor = ModuleDescriptorImpl( module.name, projectContext.storageManager, builtInsForModule(module), module.platform, module.capabilities + listOf(RESOLUTION_ANCHOR_PROVIDER_CAPABILITY to resolutionAnchorProvider), module.stableName, ) moduleInfoByDescriptor[moduleDescriptor] = module setupModuleDescriptor(module, moduleDescriptor) val modificationTracker = (module as? TrackableModuleInfo)?.createModificationTracker() ?: fallbackModificationTracker return ModuleData(moduleDescriptor, modificationTracker) } private fun renderResolversChainContents(): String { val resolversChain = generateSequence(this) { it.delegateResolver as? AbstractResolverForProject<M> } return resolversChain.joinToString("\n\n") { resolver -> "Resolver: ${resolver.name}\n'moduleInfoByDescriptor' content:\n[${resolver.renderResolverModuleInfos()}]" } } private fun renderResolverModuleInfos(): String = projectContext.storageManager.compute { moduleInfoByDescriptor.entries.joinToString(",\n") { (descriptor, moduleInfo) -> """ { moduleDescriptor: $descriptor moduleInfo: $moduleInfo } """.trimIndent() } } } private class DelegatingPackageFragmentProvider<M : ModuleInfo>( private val resolverForProject: AbstractResolverForProject<M>, private val module: ModuleDescriptor, moduleContent: ModuleContent<M>, private val packageOracle: PackageOracle ) : PackageFragmentProvider { private val syntheticFilePackages = moduleContent.syntheticFiles.map { it.packageFqName }.toSet() override fun getPackageFragments(fqName: FqName): List<PackageFragmentDescriptor> { if (certainlyDoesNotExist(fqName)) return emptyList() return resolverForProject.resolverForModuleDescriptor(module).packageFragmentProvider.getPackageFragments(fqName) } override fun collectPackageFragments(fqName: FqName, packageFragments: MutableCollection<PackageFragmentDescriptor>) { if (certainlyDoesNotExist(fqName)) return resolverForProject.resolverForModuleDescriptor(module).packageFragmentProvider.collectPackageFragments(fqName, packageFragments) } override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection<FqName> { if (certainlyDoesNotExist(fqName)) return emptyList() return resolverForProject.resolverForModuleDescriptor(module).packageFragmentProvider.getSubPackagesOf(fqName, nameFilter) } private fun certainlyDoesNotExist(fqName: FqName): Boolean { if (resolverForProject.isResolverForModuleDescriptorComputed(module)) return false // let this request get cached inside delegate return !packageOracle.packageExists(fqName) && fqName !in syntheticFilePackages } } private object DiagnoseUnknownModuleInfoReporter { fun report(name: String, infos: List<ModuleInfo>, allModules: Collection<ModuleInfo>): Nothing { val message = "$name does not know how to resolve $infos, allModules: $allModules" when { name.contains(ResolverForProject.resolverForSdkName) -> errorInSdkResolver(message) name.contains(ResolverForProject.resolverForLibrariesName) -> errorInLibrariesResolver(message) name.contains(ResolverForProject.resolverForModulesName) -> { when { infos.isEmpty() -> errorInModulesResolverWithEmptyInfos(message) infos.size == 1 -> { val infoAsString = infos.single().toString() when { infoAsString.contains("ScriptDependencies") -> errorInModulesResolverWithScriptDependencies(message) infoAsString.contains("Library") -> errorInModulesResolverWithLibraryInfo(message) else -> errorInModulesResolver(message) } } else -> throw errorInModulesResolver(message) } } name.contains(ResolverForProject.resolverForScriptDependenciesName) -> errorInScriptDependenciesInfoResolver(message) name.contains(ResolverForProject.resolverForSpecialInfoName) -> { when { name.contains("ScriptModuleInfo") -> errorInScriptModuleInfoResolver(message) else -> errorInSpecialModuleInfoResolver(message) } } else -> otherError(message) } } // Do not inline 'error*'-methods, they are needed to avoid Exception Analyzer merging those AssertionErrors private fun errorInSdkResolver(message: String): Nothing = throw AssertionError(message) private fun errorInLibrariesResolver(message: String): Nothing = throw AssertionError(message) private fun errorInModulesResolver(message: String): Nothing = throw AssertionError(message) private fun errorInModulesResolverWithEmptyInfos(message: String): Nothing = throw AssertionError(message) private fun errorInModulesResolverWithScriptDependencies(message: String): Nothing = throw AssertionError(message) private fun errorInModulesResolverWithLibraryInfo(message: String): Nothing = throw AssertionError(message) private fun errorInScriptDependenciesInfoResolver(message: String): Nothing = throw AssertionError(message) private fun errorInScriptModuleInfoResolver(message: String): Nothing = throw AssertionError(message) private fun errorInSpecialModuleInfoResolver(message: String): Nothing = throw AssertionError(message) private fun otherError(message: String): Nothing = throw AssertionError(message) }
5
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
14,443
kotlin
Apache License 2.0
liveview-android/src/main/java/org/phoenixframework/liveview/data/dto/NavigationBarItemDTO.kt
liveview-native
459,214,950
false
{"Kotlin": 1516711, "Elixir": 68940}
package org.phoenixframework.liveview.data.dto import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.RowScope import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationBarItemColors import androidx.compose.material3.NavigationBarItemDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.toImmutableMap import org.phoenixframework.liveview.data.constants.Attrs.alwaysShowLabel import org.phoenixframework.liveview.data.constants.Attrs.attrColors import org.phoenixframework.liveview.data.constants.Attrs.attrEnabled import org.phoenixframework.liveview.data.constants.Attrs.attrPhxClick import org.phoenixframework.liveview.data.constants.Attrs.attrSelected import org.phoenixframework.liveview.data.constants.ColorAttrs import org.phoenixframework.liveview.data.constants.Templates import org.phoenixframework.liveview.data.core.CoreAttribute import org.phoenixframework.liveview.domain.base.ComposableBuilder import org.phoenixframework.liveview.domain.base.ComposableView import org.phoenixframework.liveview.domain.base.ComposableViewFactory import org.phoenixframework.liveview.domain.base.PushEvent import org.phoenixframework.liveview.domain.extensions.toColor import org.phoenixframework.liveview.domain.factory.ComposableTreeNode import org.phoenixframework.liveview.ui.phx_components.PhxLiveView /** * Material Design navigation bar item. * Navigation bars offer a persistent and convenient way to switch between primary destinations in * an app. * This component can has two children templates: * - `label` for the item text. * - `icon` for the item icon. * ``` * <NavigationBarItem selected="true" phx-click="selectTab1"> * <Icon image-vector="filled:HorizontalDistribute" template="icon"/> * <Text template="label">Tab 1</Text> * </NavigationBarItem> * ``` */ internal class NavigationBarItemDTO private constructor(builder: Builder) : ComposableView(modifier = builder.modifier) { private val rowScope = builder.rowScope private val alwaysShowLabel = builder.alwaysShowLabel private val colors = builder.colors?.toImmutableMap() private val enabled = builder.enabled private val onClick = builder.onClick private val selected = builder.selected private val value = builder.value @Composable override fun Compose( composableNode: ComposableTreeNode?, paddingValues: PaddingValues?, pushEvent: PushEvent ) { val icon = remember(composableNode?.children) { composableNode?.children?.find { it.node?.template == Templates.templateIcon } } val label = remember(composableNode?.children) { composableNode?.children?.find { it.node?.template == Templates.templateLabel } } rowScope.NavigationBarItem( selected = selected, onClick = onClick?.let { onClickFromString(pushEvent, it, value.toString()) } ?: {}, icon = { icon?.let { PhxLiveView(it, pushEvent, composableNode, null) } }, modifier = modifier, enabled = enabled, label = label?.let { { PhxLiveView(it, pushEvent, composableNode, null) } }, alwaysShowLabel = alwaysShowLabel, colors = getNavigationBarColors(colors), ) } @Composable private fun getNavigationBarColors(colors: ImmutableMap<String, String>?): NavigationBarItemColors { val defaultColors = NavigationBarItemDefaults.colors() return if (colors == null) { defaultColors } else { return NavigationBarItemDefaults.colors( selectedIconColor = colors[ColorAttrs.colorAttrSelectedIconColor]?.toColor() ?: MaterialTheme.colorScheme.onSecondaryContainer, selectedTextColor = colors[ColorAttrs.colorAttrSelectedTextColor]?.toColor() ?: MaterialTheme.colorScheme.onSurface, indicatorColor = colors[ColorAttrs.colorAttrIndicatorColor]?.toColor() ?: MaterialTheme.colorScheme.secondaryContainer, unselectedIconColor = colors[ColorAttrs.colorAttrUnselectedIconColor]?.toColor() ?: MaterialTheme.colorScheme.onSurfaceVariant, unselectedTextColor = colors[ColorAttrs.colorAttrUnselectedTextColor]?.toColor() ?: MaterialTheme.colorScheme.onSurfaceVariant, disabledIconColor = colors[ColorAttrs.colorAttrDisabledIconColor]?.toColor() ?: ( colors[ColorAttrs.colorAttrUnselectedIconColor]?.toColor() ?: MaterialTheme.colorScheme.onSurfaceVariant ).copy(alpha = 0.38f), disabledTextColor = colors[ColorAttrs.colorAttrDisabledTextColor]?.toColor() ?: (colors[ColorAttrs.colorAttrUnselectedTextColor]?.toColor() ?: MaterialTheme.colorScheme.onSurfaceVariant).copy(alpha = 0.38f), ) } } internal class Builder(val rowScope: RowScope) : ComposableBuilder() { var alwaysShowLabel: Boolean = false private set var colors: Map<String, String>? = null private set var enabled: Boolean = true private set var onClick: String? = null private set var selected: Boolean = false private set /** * Whether to always show the label for this item. If false, the label will only be shown * when this item is selected. * ``` * <NavigationBarItem always-show-label="true">...</NavigationDrawerItem> * ``` * @param alwaysShowLabel true if the label is always visible, false if it's only visible * when is selected. */ fun alwaysShowLabel(alwaysShowLabel: String) = apply { this.alwaysShowLabel = alwaysShowLabel.toBoolean() } /** * Set Button colors. * ``` * <NavigationBarItem * colors="{'containerColor': '#FFFF0000', 'contentColor': '#FF00FF00'}"> * ... * </NavigationBarItem> * ``` * @param colors an JSON formatted string, containing the navigation bar item colors. The * color keys supported are: `selectedIconColor`, `selectedTextColor`, `indicatorColor`, * `unselectedIconColor`, `unselectedTextColor`, `disabledIconColor`, and * `disabledTextColor`. */ fun colors(colors: String) = apply { if (colors.isNotEmpty()) { this.colors = colorsFromString(colors) } } /** * A boolean value indicating if the component is enabled or not. * * ``` * <NavigationBarItem enabled="true">...</NavigationBarItem> * ``` * @param enabled true if the component is enabled, false otherwise. */ fun enabled(enabled: String) = apply { this.enabled = enabled.toBoolean() } /** * Sets the event name to be triggered on the server when the item is clicked. * * ``` * <NavigationBarItem phx-click="yourServerEventHandler">...</NavigationBarItem> * ``` * @param event event name defined on the server to handle the button's click. */ fun onClick(event: String) = apply { this.onClick = event } /** * Whether this item is selected or not. * ``` * <NavigationBarItem selected="true">...</NavigationDrawerItem> * ``` * @param selected true if the item is selected, false otherwise. */ fun selected(selected: String) = apply { this.selected = selected.toBoolean() } fun build() = NavigationBarItemDTO(this) } } internal object NavigationBarItemDtoFactory : ComposableViewFactory<NavigationBarItemDTO, NavigationBarItemDTO.Builder>() { override fun buildComposableView( attributes: Array<CoreAttribute>, pushEvent: PushEvent?, scope: Any? ): NavigationBarItemDTO = attributes.fold(NavigationBarItemDTO.Builder(scope as RowScope)) { builder, attribute -> when (attribute.name) { alwaysShowLabel -> builder.alwaysShowLabel(attribute.value) attrColors -> builder.colors(attribute.value) attrEnabled -> builder.enabled(attribute.value) attrPhxClick -> builder.onClick(attribute.value) attrSelected -> builder.selected(attribute.value) else -> builder.handleCommonAttributes(attribute, pushEvent, scope) } as NavigationBarItemDTO.Builder }.build() }
64
Kotlin
3
71
7f84ecbc9bbacee570c9ce5e759e0285a5f7b8e1
9,165
liveview-client-jetpack
MIT License
composeApp/src/desktopMain/kotlin/meetnote/RecorderController.kt
tokuhirom
721,923,549
false
{"Kotlin": 53506}
package meetnote interface RecorderController { fun start() }
1
Kotlin
0
0
ec8e85db42107ad61dc826327a6387541dcbc4a8
67
MeetNote
The Unlicense
compass-conformance-server/src/main/kotlin/science/numcompass/conformance/compass/rest/GeccoConformanceRestResource.kt
NUMde
391,039,823
false
null
package science.numcompass.conformance.compass.rest import ca.uhn.fhir.context.FhirContext import org.hl7.fhir.r4.model.Bundle import org.hl7.fhir.r4.model.CapabilityStatement import org.hl7.fhir.r4.model.OperationOutcome import org.springframework.http.MediaType.APPLICATION_JSON_VALUE import org.springframework.http.MediaType.APPLICATION_PDF import org.springframework.http.MediaType.APPLICATION_PDF_VALUE import org.springframework.http.MediaType.APPLICATION_XML_VALUE import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity.notFound import org.springframework.http.ResponseEntity.ok import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestAttribute import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import science.numcompass.conformance.compass.engine.isSuccessful import science.numcompass.conformance.compass.report.CodeSystemReportGenerator import science.numcompass.conformance.compass.service.GeccoConformanceService import science.numcompass.conformance.fhir.rest.APPLICATION_FHIR_JSON_VALUE import science.numcompass.conformance.fhir.rest.APPLICATION_FHIR_XML_VALUE import java.util.* @RestController @RequestMapping( path = ["/\${fhir.rest.base-path:fhir}"], produces = [ APPLICATION_JSON_VALUE, APPLICATION_FHIR_JSON_VALUE, APPLICATION_XML_VALUE, APPLICATION_FHIR_XML_VALUE, APPLICATION_PDF_VALUE ] ) class GeccoConformanceRestResource( fhirContext: FhirContext, private val conformanceService: GeccoConformanceService, private val codeSystemReportGenerator: CodeSystemReportGenerator ) { private val capabilityStatement = javaClass.getResourceAsStream("/fhir/CapabilityStatement-conformanceServerCapabilities.json") .use { fhirContext.newJsonParser().parseResource(it) as CapabilityStatement } /** * FHIR capability interaction returning the CapabilityStatement resource for the server. */ @GetMapping("/metadata") fun metadata() = capabilityStatement /** * Endpoint for retrieving the code system report PDF. */ @GetMapping(path = ["/codesystems"], produces = [APPLICATION_PDF_VALUE]) fun codeSystems() = createPdfResponse(codeSystemReportGenerator.getReport(), "codesystems") /** * Check a complete GECCO conformance bundle. The return value is a PDF stream in case of success or an * [OperationOutcome] in case of errors. */ @PostMapping( path = ["/\$check-gecco-conformance"], consumes = [ APPLICATION_JSON_VALUE, APPLICATION_FHIR_JSON_VALUE, APPLICATION_XML_VALUE, APPLICATION_FHIR_XML_VALUE ] ) fun checkGeccoConformance(@RequestBody bundle: Bundle, @RequestAttribute md5: String): ResponseEntity<*> = conformanceService.checkConformance(bundle).let { if (it.isSuccessful()) { createPdfResponse(conformanceService.generatePdfResponse(bundle), "certificate") } else { ok(it) } } /** * Check a complete GECCO conformance bundle asynchronously by setting the prefer header to * "respond-async" - the return value is an ID that can be used to retrieve the results under * /$vcheck-gecco-conformance/{id}. */ @PostMapping( path = ["/\$check-gecco-conformance"], headers = ["prefer=respond-async"], consumes = [ APPLICATION_JSON_VALUE, APPLICATION_FHIR_JSON_VALUE, APPLICATION_XML_VALUE, APPLICATION_FHIR_XML_VALUE ], produces = [APPLICATION_JSON_VALUE, APPLICATION_FHIR_JSON_VALUE] ) fun checkGeccoConformanceAsync( @RequestBody bundle: Bundle, @RequestAttribute md5: String ) = conformanceService.checkConformanceAsync(bundle, md5) /** * Retrieve the result of a FHIR validation triggered via the $check-gecco-conformance endpoint. */ @GetMapping("/\$check-gecco-conformance/{id}") fun conformanceResult(@PathVariable id: String): ResponseEntity<*> = when (val result = conformanceService.getResult(UUID.fromString(id))) { is OperationOutcome -> ok(result) is ByteArray -> createPdfResponse(result, "certificate") null -> notFound().build<Any>() else -> throw IllegalArgumentException("Unsupported result ${result.javaClass}") } private fun createPdfResponse(rawData: ByteArray, fileName: String) = ok() .header("Content-Disposition", "attachment; filename=$fileName.pdf") .contentType(APPLICATION_PDF) .body(rawData) }
1
Kotlin
2
0
037367c0bace7dc498284cd9b974462227494bb4
4,969
compass-num-conformance-checker
MIT License
furniture-k-shop/src/main/kotlin/org/jesperancinha/smtd/furniture/client/ExternalClient.kt
jesperancinha
369,597,921
false
{"Java": 98494, "Kotlin": 86678, "Makefile": 668, "Shell": 192, "Dockerfile": 184}
package org.jesperancinha.smtd.furniture.client import org.jesperancinha.smtd.furniture.model.Chair import org.springframework.stereotype.Service import org.springframework.web.client.RestTemplate @Service class ExternalClient( private val restTemplate: RestTemplate ) { fun externalChairs(): List<Chair> = restTemplate.getForObject("http://localhost:9001", Array<Chair>::class.java) ?.toList() ?: emptyList() }
1
Kotlin
0
3
e4043f03dfcc2b5801c1b6a4f9050523f9ed0665
443
jeorg-spring-master-test-drives
Apache License 2.0
src/commonMain/kotlin/com/ashampoo/kim/format/tiff/taginfos/TagInfoAsciiOrRational.kt
Ashampoo
647,186,626
false
null
/* * Copyright 2024 Ashampoo GmbH & Co. KG * Copyright 2007-2023 The Apache Software Foundation * * 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.ashampoo.kim.format.tiff.taginfo import com.ashampoo.kim.format.tiff.constant.TiffDirectoryType import com.ashampoo.kim.format.tiff.fieldtype.FieldTypeUndefined class TagInfoUndefineds( tag: Int, name: String, length: Int, directoryType: TiffDirectoryType? ) : TagInfoBytes(tag, name, FieldTypeUndefined, length, directoryType)
8
null
8
98
b3dac7e88bb03636b68099ed065a81bd0e5e3d08
1,018
kim
Apache License 2.0
shared/src/commonMain/kotlin/com/ramitsuri/podcasts/network/model/EpisodeDto.kt
ramitsuri
760,212,962
false
{"Kotlin": 558852, "Shell": 9622, "Swift": 296}
package com.ramitsuri.podcasts.network.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class EpisodeDto( @SerialName("guid") val id: String, @SerialName("feedId") val podcastId: Long, @SerialName("title") val title: String, @SerialName("description") val description: String, @SerialName("link") val link: String, @SerialName("enclosureUrl") val enclosureUrl: String, @SerialName("datePublished") val datePublished: Long, @SerialName("duration") val duration: Int?, @SerialName("explicit") val explicit: Int, @SerialName("episode") val episode: Int?, @SerialName("season") val season: Int?, )
2
Kotlin
0
1
b43522bae0113efa5eceb5505c19c8b57cfb27d9
751
podcasts
MIT License
app/src/main/java/com/cornellappdev/uplift/ui/components/home/SportButton.kt
cuappdev
596,747,757
false
null
package com.cornellappdev.uplift.ui.components.home import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.ripple.rememberRipple import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.cornellappdev.uplift.util.PRIMARY_BLACK import com.cornellappdev.uplift.util.montserratFamily /** * Makes a component that displays a sport whose icon is [painter], name is [text]. * Does [onClick] when this button is clicked. */ @Composable fun SportButton(text: String, painter: Painter, onClick: () -> Unit) { val interactionSource = remember { MutableInteractionSource() } Column(horizontalAlignment = Alignment.CenterHorizontally) { Surface( shape = CircleShape, color = Color.White, elevation = 4.dp, modifier = Modifier .size(64.dp) .clickable( interactionSource = interactionSource, indication = ripple(radius = 32.dp), onClick = onClick ) ) { Box(modifier = Modifier.fillMaxSize()) { Icon( painter = painter, contentDescription = null, modifier = Modifier .size(40.dp) .align(Alignment.Center), tint = PRIMARY_BLACK ) } } Text( text = text, fontFamily = montserratFamily, fontSize = 12.sp, fontWeight = FontWeight(500), lineHeight = 17.07.sp, textAlign = TextAlign.Center, color = PRIMARY_BLACK, modifier = Modifier.padding(top = 6.dp) ) } }
2
Kotlin
0
1
c3f70c126efe38f1bb6376f6cc810e5e0c0cbb70
2,655
uplift-android
MIT License