path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/kylecorry/trail_sense/tools/maps/domain/sort/mappers/MapNameMapper.kt | kylecorry31 | 215,154,276 | false | {"Kotlin": 2589968, "Python": 22919, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3814, "Batchfile": 2553} | package com.kylecorry.trail_sense.tools.maps.domain.sort.mappers
import com.kylecorry.trail_sense.shared.grouping.mapping.ISuspendMapper
import com.kylecorry.trail_sense.tools.maps.domain.IMap
class MapNameMapper : ISuspendMapper<IMap, String> {
override suspend fun map(item: IMap): String {
return item.name
}
} | 456 | Kotlin | 66 | 989 | 41176d17b498b2dcecbbe808fbe2ac638e90d104 | 331 | Trail-Sense | MIT License |
app/src/main/java/com/kylecorry/trail_sense/tools/maps/domain/sort/mappers/MapNameMapper.kt | kylecorry31 | 215,154,276 | false | {"Kotlin": 2589968, "Python": 22919, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3814, "Batchfile": 2553} | package com.kylecorry.trail_sense.tools.maps.domain.sort.mappers
import com.kylecorry.trail_sense.shared.grouping.mapping.ISuspendMapper
import com.kylecorry.trail_sense.tools.maps.domain.IMap
class MapNameMapper : ISuspendMapper<IMap, String> {
override suspend fun map(item: IMap): String {
return item.name
}
} | 456 | Kotlin | 66 | 989 | 41176d17b498b2dcecbbe808fbe2ac638e90d104 | 331 | Trail-Sense | MIT License |
app/src/main/java/io/wookey/wallet/feature/setting/NodeListActivity.kt | WooKeyWallet | 176,637,569 | false | null | package io.wookey.wallet.feature.setting
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.wookey.wallet.R
import io.wookey.wallet.base.BaseTitleSecondActivity
import io.wookey.wallet.data.AppDatabase
import io.wookey.wallet.data.entity.Node
import io.wookey.wallet.dialog.NodeEditDialog
import io.wookey.wallet.support.extensions.dp2px
import io.wookey.wallet.support.extensions.openBrowser
import io.wookey.wallet.support.extensions.toast
import io.wookey.wallet.widget.DividerItemDecoration
import io.wookey.wallet.widget.IOSDialog
import kotlinx.android.synthetic.main.activity_node_list.*
import kotlinx.android.synthetic.main.item_node.view.*
class NodeListActivity : BaseTitleSecondActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_node_list)
val viewModel = ViewModelProviders.of(this).get(NodeListViewModel::class.java)
val symbol = "TXX"
val canDelete = intent.getBooleanExtra("canDelete", true)
viewModel.setCanDelete(canDelete)
setCenterTitle("$symbol ${getString(R.string.node_setting)}")
setRightIcon(R.drawable.icon_add)
setRightIconClick(View.OnClickListener { _ ->
NodeEditDialog.display(supportFragmentManager, symbol) { value ->
value?.let {
viewModel.insertNode(it)
}
}
})
recyclerView.layoutManager = LinearLayoutManager(this)
val list = mutableListOf<Node>()
val adapter = NodeAdapter(list, viewModel)
recyclerView.adapter = adapter
recyclerView.addItemDecoration(DividerItemDecoration().apply {
setOrientation(DividerItemDecoration.VERTICAL)
setMarginStart(dp2px(25))
})
recyclerView.isNestedScrollingEnabled = false
AppDatabase.getInstance().nodeDao().loadSymbolNodes(symbol).observe(this, Observer { value ->
value?.let {
list.clear()
list.addAll(it)
adapter.notifyDataSetChanged()
viewModel.testRpcService(list)
}
})
viewModel.toastRes.observe(this, Observer { toast(it) })
viewModel.showConfirmDialog.observe(this, Observer { value ->
value?.let {
IOSDialog(this)
.radius(dp2px(5))
.titleText(getString(R.string.confirm_delete))
.contentText(getString(R.string.confirm_delete_content, it))
.leftText(getString(R.string.cancel))
.rightText(getString(R.string.confirm))
.setIOSDialogLeftListener { viewModel.cancelDelete() }
.setIOSDialogRightListener { viewModel.confirmDelete(symbol) }
.cancelAble(true)
.layout()
.show()
}
})
viewModel.showLoading.observe(this, Observer { showLoading() })
viewModel.hideLoading.observe(this, Observer { hideLoading() })
viewModel.toast.observe(this, Observer { toast(it) })
viewModel.dataChanged.observe(this, Observer { adapter.notifyDataSetChanged() })
more.setOnClickListener {
openBrowser("https://node.txchange.online/txchangecoin-nodes/app.html")
}
viewModel.finish.observe(this, Observer {
setResult(Activity.RESULT_OK, Intent().apply { putExtra("node", it) })
finish()
})
}
class NodeAdapter(val data: List<Node>, val viewModel: NodeListViewModel) : RecyclerView.Adapter<NodeAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_node, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val node = data[position]
with(holder.itemView) {
title.text = node.url
if (node.isSelected) {
selected.setImageResource(R.drawable.icon_selected)
} else {
selected.setImageResource(R.drawable.icon_unselected)
}
if (node.responseTime != Long.MAX_VALUE && node.responseTime >= 0) {
subTitle.text = "${node.responseTime} ms"
} else {
subTitle.text = ""
}
if (node.responseTime < 1000) {
subTitle.setTextColor(ContextCompat.getColor(subTitle.context, R.color.color_26B479))
} else {
subTitle.setTextColor(ContextCompat.getColor(subTitle.context, R.color.color_FF3A5C))
}
setOnClickListener {
viewModel.updateNode(data, node)
}
setOnLongClickListener {
viewModel.onLongClick(node)
true
}
}
}
class ViewHolder(item: View) : RecyclerView.ViewHolder(item)
}
}
| 6 | null | 20 | 23 | 93d0d6a4743e95ab2455bb6ae24b2cc6b616bd90 | 5,693 | monero-wallet-android-app | MIT License |
src/main/kotlin/br/com/alura/bytebank/modelo/Funcionario.kt | vitor-sb | 673,529,542 | false | {"Kotlin": 8845} | abstract class Funcionario(
val nome: String,
val cpf: String,
val salario: Double
) {
abstract val bonificacao: Double
} | 0 | Kotlin | 0 | 0 | da9fedd0a9dd435bcd748cfd62f361e3293c15dd | 137 | kotlin-paradigma-funcional | MIT License |
compiler/fir/analysis-tests/testData/resolve/overrides/simple.kt | android | 263,405,600 | false | null |
open class A {
open fun foo(): A = this
open fun bar(): A = this
open fun buz(p: A): A = this
}
class B : A() {
override fun foo(): B = this
fun bar(): B = this // Ambiguity, no override here (really it's just "missing override" and no ambiguity)
override fun buz(p: B): B = this //No override as B <!:> A
fun test() {
foo()
bar()
<!NONE_APPLICABLE!>buz<!>()
}
}
| 1 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 424 | kotlin | Apache License 2.0 |
lib/schedule/src/commonMain/kotlin/zakadabar/lib/schedule/data/PushJob.kt | spxbhuhb | 290,390,793 | false | null | /*
* Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.lib.schedule.data
import kotlinx.serialization.Serializable
import zakadabar.core.data.ActionBo
import zakadabar.core.data.ActionBoCompanion
import zakadabar.core.data.ActionStatus
import zakadabar.core.data.EntityId
import zakadabar.core.schema.BoSchema
/**
* Used by the dispatcher to push a job to a worker. If the worker accepts the job
* it should return with a successful action status. If it cannot accept the job
* for any reasons it may return with an unsuccessful action status.
*/
@Serializable
class PushJob(
var jobId: EntityId<Job>,
var actionNamespace: String,
var actionType: String,
var actionData: String
) : ActionBo<ActionStatus> {
companion object : ActionBoCompanion(Job.boNamespace)
override suspend fun execute() = comm.action(this, serializer(), ActionStatus.serializer())
suspend fun execute(baseUrl : String) = comm.action(this, serializer(), ActionStatus.serializer(), baseUrl)
override fun schema() = BoSchema {
+ ::jobId
+ ::actionNamespace
+ ::actionType
+ ::actionData
}
} | 6 | null | 3 | 24 | 61ac92ff04eb53bff5b9a9b2649bd4866f469942 | 1,237 | zakadabar-stack | Apache License 2.0 |
android/fedmlsdk/src/main/java/ai/fedml/edge/utils/CpuUtils.kt | FedML-AI | 281,519,510 | false | null | package ai.fedml.edge.utils
import android.os.Build
import android.text.TextUtils
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.RandomAccessFile
object CpuUtil {
private var mProcStatFile: RandomAccessFile? = null
private var mAppStatFile: RandomAccessFile? = null
private var mLastCpuTime: Long? = null
private var mLastAppCpuTime: Long? = null
/**
* get Cpu Usage
*/
fun getCpuUsage(): Float {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getCpuUsageForHigherVersion()
} else {
getCpuUsageForLowerVersion()
}
}
private fun getCpuUsageForHigherVersion(): Float {
var process: Process? = null
try {
process = Runtime.getRuntime().exec("top -n 1")
val reader = BufferedReader(InputStreamReader(process.inputStream))
var line: String
var cpuIndex = -1
while (reader.readLine().also {
line = it
} != null) {
line = line.trim {
it <= ' '
}
if (TextUtils.isEmpty(line)) {
continue
}
val tempIndex = getCPUIndex(line)
if (tempIndex != -1) {
cpuIndex = tempIndex
continue
}
if (line.startsWith(android.os.Process.myPid().toString())) {
if (cpuIndex == -1) {
continue
}
val param = line.split("\\s+".toRegex()).toTypedArray()
if (param.size <= cpuIndex) {
continue
}
var cpu = param[cpuIndex]
if (cpu.endsWith("%")) {
cpu = cpu.substring(0, cpu.lastIndexOf("%"))
}
return cpu.toFloat() / Runtime.getRuntime().availableProcessors()
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
process?.destroy()
}
return 0F
}
private fun getCpuUsageForLowerVersion(): Float {
val cpuTime: Long
val appTime: Long
var value = 0.0f
try {
if (mProcStatFile == null || mAppStatFile == null) {
mProcStatFile = RandomAccessFile("/proc/stat", "r")
mAppStatFile = RandomAccessFile("/proc/" + android.os.Process.myPid() + "/stat", "r")
} else {
mProcStatFile!!.seek(0L)
mAppStatFile!!.seek(0L)
}
val procStatString = mProcStatFile!!.readLine()
val appStatString = mAppStatFile!!.readLine()
val procStats = procStatString.split(" ".toRegex()).toTypedArray()
val appStats = appStatString.split(" ".toRegex()).toTypedArray()
cpuTime = procStats[2].toLong() + procStats[3].toLong() + procStats[4].toLong() + procStats[5].toLong() + procStats[6].toLong() + procStats[7].toLong() + procStats[8].toLong()
appTime = appStats[13].toLong() + appStats[14].toLong()
if (mLastCpuTime == null && mLastAppCpuTime == null) {
mLastCpuTime = cpuTime
mLastAppCpuTime = appTime
return value
}
value = (appTime - mLastAppCpuTime!!).toFloat() / (cpuTime - mLastCpuTime!!).toFloat() * 100f
mLastCpuTime = cpuTime
mLastAppCpuTime = appTime
} catch (e: Exception) {
e.printStackTrace()
}
return value
}
private fun getCPUIndex(line: String): Int {
if (line.contains("CPU")) {
val titles = line.split("\\s+".toRegex()).toTypedArray()
for (i in titles.indices) {
if (titles[i].contains("CPU")) {
return i
}
}
}
return -1
}
} | 118 | Python | 601 | 2,523 | 1b18774ca80f904b6a2b89c729e31c6ec1a3688f | 4,107 | FedML | Apache License 2.0 |
src/main/kotlin/no/nav/sosialhjelp/innsyn/app/tokendings/TokendingsClientConfig.kt | navikt | 184,267,271 | false | {"Kotlin": 773484, "Dockerfile": 427} | package no.nav.sosialhjelp.innsyn.app.tokendings
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.slf4j.MDCContext
import no.nav.sosialhjelp.innsyn.app.ClientProperties
import no.nav.sosialhjelp.innsyn.utils.logger
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.function.client.WebClient
class TokendingsWebClient(
val webClient: WebClient,
val wellKnown: WellKnown,
)
@Configuration
class TokendingsClientConfig(
private val clientProperties: ClientProperties,
) {
@Bean
fun tokendingsWebClient(webClientBuilder: WebClient.Builder): TokendingsWebClient =
runBlocking(MDCContext()) {
val wellKnown = downloadWellKnown(clientProperties.tokendingsUrl)
log.info(
"TokendingsClient: Lastet ned well known fra: ${clientProperties.tokendingsUrl}." +
" bruker token endpoint: ${wellKnown.tokenEndpoint}",
)
TokendingsWebClient(
buildWebClient(webClientBuilder, wellKnown.tokenEndpoint, applicationFormUrlencodedHeaders()),
wellKnown,
)
}
companion object {
private val log by logger()
}
}
| 6 | Kotlin | 0 | 0 | 55867535dc0778572255c942102eb0a215302b0b | 1,285 | sosialhjelp-innsyn-api | MIT License |
src/main/kotlin/org/wfanet/measurement/loadtest/dataprovider/EdpSimulator.kt | world-federation-of-advertisers | 349,561,061 | false | null | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.loadtest.dataprovider
import com.google.protobuf.ByteString
import com.google.protobuf.Descriptors
import com.google.protobuf.Message
import com.google.protobuf.duration
import com.google.protobuf.kotlin.unpack
import com.google.protobuf.timestamp
import com.google.type.interval
import io.grpc.Status
import io.grpc.StatusException
import java.security.SignatureException
import java.security.cert.CertPathValidatorException
import java.security.cert.X509Certificate
import java.time.Instant
import java.util.logging.Level
import java.util.logging.Logger
import kotlin.math.log2
import kotlin.math.max
import kotlin.math.roundToInt
import kotlin.random.Random
import kotlin.random.asJavaRandom
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import org.apache.commons.math3.distribution.ConstantRealDistribution
import org.wfanet.anysketch.Sketch
import org.wfanet.anysketch.SketchConfig
import org.wfanet.anysketch.crypto.ElGamalPublicKey as AnySketchElGamalPublicKey
import org.wfanet.anysketch.crypto.elGamalPublicKey as anySketchElGamalPublicKey
import org.wfanet.frequencycount.FrequencyVector
import org.wfanet.frequencycount.SecretShare
import org.wfanet.frequencycount.SecretShareGeneratorAdapter
import org.wfanet.frequencycount.frequencyVector
import org.wfanet.frequencycount.secretShareGeneratorRequest
import org.wfanet.measurement.api.v2alpha.Certificate
import org.wfanet.measurement.api.v2alpha.CertificatesGrpcKt.CertificatesCoroutineStub
import org.wfanet.measurement.api.v2alpha.CustomDirectMethodologyKt.variance
import org.wfanet.measurement.api.v2alpha.DataProviderKey
import org.wfanet.measurement.api.v2alpha.DataProviderKt
import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt.DataProvidersCoroutineStub
import org.wfanet.measurement.api.v2alpha.DeterministicCount
import org.wfanet.measurement.api.v2alpha.DeterministicCountDistinct
import org.wfanet.measurement.api.v2alpha.DeterministicDistribution
import org.wfanet.measurement.api.v2alpha.DifferentialPrivacyParams
import org.wfanet.measurement.api.v2alpha.ElGamalPublicKey
import org.wfanet.measurement.api.v2alpha.EncryptedMessage
import org.wfanet.measurement.api.v2alpha.EncryptionPublicKey
import org.wfanet.measurement.api.v2alpha.EventAnnotationsProto
import org.wfanet.measurement.api.v2alpha.EventGroup
import org.wfanet.measurement.api.v2alpha.EventGroupKey
import org.wfanet.measurement.api.v2alpha.EventGroupKt
import org.wfanet.measurement.api.v2alpha.EventGroupKt.metadata
import org.wfanet.measurement.api.v2alpha.EventGroupMetadataDescriptor
import org.wfanet.measurement.api.v2alpha.EventGroupMetadataDescriptorsGrpcKt.EventGroupMetadataDescriptorsCoroutineStub
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineStub
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequest
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequestKt.HeaderKt.honestMajorityShareShuffle
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequestKt.bodyChunk
import org.wfanet.measurement.api.v2alpha.FulfillRequisitionRequestKt.header
import org.wfanet.measurement.api.v2alpha.ListEventGroupsRequestKt
import org.wfanet.measurement.api.v2alpha.Measurement
import org.wfanet.measurement.api.v2alpha.MeasurementConsumer
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub
import org.wfanet.measurement.api.v2alpha.MeasurementKey
import org.wfanet.measurement.api.v2alpha.MeasurementKt
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.frequency
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.impression
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.reach
import org.wfanet.measurement.api.v2alpha.MeasurementKt.ResultKt.watchDuration
import org.wfanet.measurement.api.v2alpha.MeasurementSpec
import org.wfanet.measurement.api.v2alpha.ProtocolConfig
import org.wfanet.measurement.api.v2alpha.ProtocolConfig.NoiseMechanism
import org.wfanet.measurement.api.v2alpha.Requisition
import org.wfanet.measurement.api.v2alpha.Requisition.DuchyEntry
import org.wfanet.measurement.api.v2alpha.RequisitionFulfillmentGrpcKt.RequisitionFulfillmentCoroutineStub
import org.wfanet.measurement.api.v2alpha.RequisitionSpec
import org.wfanet.measurement.api.v2alpha.RequisitionsGrpcKt.RequisitionsCoroutineStub
import org.wfanet.measurement.api.v2alpha.SignedMessage
import org.wfanet.measurement.api.v2alpha.copy
import org.wfanet.measurement.api.v2alpha.createEventGroupMetadataDescriptorRequest
import org.wfanet.measurement.api.v2alpha.createEventGroupRequest
import org.wfanet.measurement.api.v2alpha.customDirectMethodology
import org.wfanet.measurement.api.v2alpha.eventGroup
import org.wfanet.measurement.api.v2alpha.eventGroupMetadataDescriptor
import org.wfanet.measurement.api.v2alpha.fulfillRequisitionRequest
import org.wfanet.measurement.api.v2alpha.getEventGroupRequest
import org.wfanet.measurement.api.v2alpha.getMeasurementConsumerRequest
import org.wfanet.measurement.api.v2alpha.listEventGroupsRequest
import org.wfanet.measurement.api.v2alpha.randomSeed
import org.wfanet.measurement.api.v2alpha.replaceDataAvailabilityIntervalRequest
import org.wfanet.measurement.api.v2alpha.replaceDataProviderCapabilitiesRequest
import org.wfanet.measurement.api.v2alpha.unpack
import org.wfanet.measurement.api.v2alpha.updateEventGroupMetadataDescriptorRequest
import org.wfanet.measurement.api.v2alpha.updateEventGroupRequest
import org.wfanet.measurement.common.ProtoReflection
import org.wfanet.measurement.common.asBufferedFlow
import org.wfanet.measurement.common.crypto.authorityKeyIdentifier
import org.wfanet.measurement.common.crypto.readCertificate
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.pack
import org.wfanet.measurement.common.throttler.Throttler
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.consent.client.dataprovider.computeRequisitionFingerprint
import org.wfanet.measurement.consent.client.dataprovider.encryptMetadata
import org.wfanet.measurement.consent.client.dataprovider.encryptRandomSeed
import org.wfanet.measurement.consent.client.dataprovider.signRandomSeed
import org.wfanet.measurement.consent.client.dataprovider.verifyElGamalPublicKey
import org.wfanet.measurement.consent.client.measurementconsumer.verifyEncryptionPublicKey
import org.wfanet.measurement.dataprovider.DataProviderData
import org.wfanet.measurement.dataprovider.RequisitionFulfiller
import org.wfanet.measurement.eventdataprovider.eventfiltration.validation.EventFilterValidationException
import org.wfanet.measurement.eventdataprovider.noiser.AbstractNoiser
import org.wfanet.measurement.eventdataprovider.noiser.DirectNoiseMechanism
import org.wfanet.measurement.eventdataprovider.noiser.DpParams
import org.wfanet.measurement.eventdataprovider.noiser.GaussianNoiser
import org.wfanet.measurement.eventdataprovider.noiser.LaplaceNoiser
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.PrivacyBudgetManager
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.PrivacyBudgetManagerException
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.PrivacyBudgetManagerExceptionType
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.Reference
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.api.v2alpha.PrivacyQueryMapper.getDirectAcdpQuery
import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.api.v2alpha.PrivacyQueryMapper.getMpcAcdpQuery
import org.wfanet.measurement.loadtest.common.sampleVids
import org.wfanet.measurement.loadtest.config.TestIdentifiers.SIMULATOR_EVENT_GROUP_REFERENCE_ID_PREFIX
import org.wfanet.measurement.loadtest.dataprovider.MeasurementResults.computeImpression
/** A simulator handling EDP businesses. */
class EdpSimulator(
private val edpData: DataProviderData,
measurementConsumerName: String,
private val measurementConsumersStub: MeasurementConsumersCoroutineStub,
certificatesStub: CertificatesCoroutineStub,
private val dataProvidersStub: DataProvidersCoroutineStub,
private val eventGroupsStub: EventGroupsCoroutineStub,
private val eventGroupMetadataDescriptorsStub: EventGroupMetadataDescriptorsCoroutineStub,
requisitionsStub: RequisitionsCoroutineStub,
private val requisitionFulfillmentStubsByDuchyId:
Map<String, RequisitionFulfillmentCoroutineStub>,
private val eventQuery: EventQuery<Message>,
throttler: Throttler,
private val privacyBudgetManager: PrivacyBudgetManager,
private val trustedCertificates: Map<ByteString, X509Certificate>,
/**
* EDP uses the vidToIndexMap to fulfill the requisitions for the honest majority share shuffle
* protocol.
*
* When the vidToIndexMap is empty, the honest majority share shuffle protocol is not supported.
*/
private val vidToIndexMap: Map<Long, IndexedValue> = emptyMap(),
/**
* Known protobuf types for [EventGroupMetadataDescriptor]s.
*
* This is in addition to the standard
* [protobuf well-known types][ProtoReflection.WELL_KNOWN_TYPES].
*/
private val knownEventGroupMetadataTypes: Iterable<Descriptors.FileDescriptor> = emptyList(),
private val sketchEncrypter: SketchEncrypter = SketchEncrypter.Default,
private val random: Random = Random,
private val logSketchDetails: Boolean = false,
) :
RequisitionFulfiller(
edpData,
certificatesStub,
requisitionsStub,
throttler,
trustedCertificates,
measurementConsumerName,
) {
val eventGroupReferenceIdPrefix = getEventGroupReferenceIdPrefix(edpData.displayName)
val supportedProtocols = buildSet {
add(ProtocolConfig.Protocol.ProtocolCase.LIQUID_LEGIONS_V2)
add(ProtocolConfig.Protocol.ProtocolCase.REACH_ONLY_LIQUID_LEGIONS_V2)
if (vidToIndexMap.isNotEmpty()) {
add(ProtocolConfig.Protocol.ProtocolCase.HONEST_MAJORITY_SHARE_SHUFFLE)
}
}
/** A sequence of operations done in the simulator. */
override suspend fun run() {
dataProvidersStub.replaceDataAvailabilityInterval(
replaceDataAvailabilityIntervalRequest {
name = dataProviderData.name
dataAvailabilityInterval = interval {
startTime = timestamp {
seconds = 1577865600 // January 1, 2020 12:00:00 AM, America/Los_Angeles
}
endTime = Instant.now().toProtoTime()
}
}
)
dataProvidersStub.replaceDataProviderCapabilities(
replaceDataProviderCapabilitiesRequest {
name = edpData.name
capabilities =
DataProviderKt.capabilities {
honestMajorityShareShuffleSupported = vidToIndexMap.isNotEmpty()
}
}
)
throttler.loopOnReady { executeRequisitionFulfillingWorkflow() }
}
/**
* Ensures that an appropriate [EventGroup] with appropriate [EventGroupMetadataDescriptor] exists
* for the [MeasurementConsumer].
*/
suspend fun ensureEventGroup(
eventTemplates: Iterable<EventGroup.EventTemplate>,
eventGroupMetadata: Message,
): EventGroup {
return ensureEventGroups(eventTemplates, mapOf("" to eventGroupMetadata)).single()
}
/**
* Ensures that appropriate [EventGroup]s with appropriate [EventGroupMetadataDescriptor] exists
* for the [MeasurementConsumer].
*/
suspend fun ensureEventGroups(
eventTemplates: Iterable<EventGroup.EventTemplate>,
metadataByReferenceIdSuffix: Map<String, Message>,
): List<EventGroup> {
require(metadataByReferenceIdSuffix.isNotEmpty())
val metadataDescriptor: Descriptors.Descriptor =
metadataByReferenceIdSuffix.values.first().descriptorForType
require(metadataByReferenceIdSuffix.values.all { it.descriptorForType == metadataDescriptor }) {
"All metadata messages must have the same type"
}
val measurementConsumer: MeasurementConsumer =
try {
measurementConsumersStub.getMeasurementConsumer(
getMeasurementConsumerRequest { name = measurementConsumerName }
)
} catch (e: StatusException) {
throw Exception("Error getting MeasurementConsumer $measurementConsumerName", e)
}
verifyEncryptionPublicKey(
measurementConsumer.publicKey,
getCertificate(measurementConsumer.certificate),
)
val descriptorResource: EventGroupMetadataDescriptor =
ensureMetadataDescriptor(metadataDescriptor)
return metadataByReferenceIdSuffix.map { (suffix, metadata) ->
val eventGroupReferenceId = eventGroupReferenceIdPrefix + suffix
ensureEventGroup(
measurementConsumer,
eventGroupReferenceId,
eventTemplates,
metadata,
descriptorResource,
)
}
}
/**
* Ensures that an [EventGroup] exists for [measurementConsumer] with the specified
* [eventGroupReferenceId] and [descriptorResource].
*/
private suspend fun ensureEventGroup(
measurementConsumer: MeasurementConsumer,
eventGroupReferenceId: String,
eventTemplates: Iterable<EventGroup.EventTemplate>,
eventGroupMetadata: Message,
descriptorResource: EventGroupMetadataDescriptor,
): EventGroup {
val existingEventGroup: EventGroup? = getEventGroupByReferenceId(eventGroupReferenceId)
val encryptedMetadata: EncryptedMessage =
encryptMetadata(
metadata {
eventGroupMetadataDescriptor = descriptorResource.name
metadata = eventGroupMetadata.pack()
},
measurementConsumer.publicKey.message.unpack(),
)
if (existingEventGroup == null) {
val request = createEventGroupRequest {
parent = edpData.name
eventGroup = eventGroup {
this.measurementConsumer = measurementConsumerName
this.eventGroupReferenceId = eventGroupReferenceId
this.eventTemplates += eventTemplates
measurementConsumerPublicKey = measurementConsumer.publicKey.message
this.encryptedMetadata = encryptedMetadata
}
}
return try {
eventGroupsStub.createEventGroup(request).also {
logger.info { "Successfully created ${it.name}..." }
}
} catch (e: StatusException) {
throw Exception("Error creating event group", e)
}
}
val request = updateEventGroupRequest {
eventGroup =
existingEventGroup.copy {
this.eventTemplates.clear()
this.eventTemplates += eventTemplates
measurementConsumerPublicKey = measurementConsumer.publicKey.message
this.encryptedMetadata = encryptedMetadata
}
}
return try {
eventGroupsStub.updateEventGroup(request).also {
logger.info { "Successfully updated ${it.name}..." }
}
} catch (e: StatusException) {
throw Exception("Error updating event group", e)
}
}
/**
* Returns the first [EventGroup] for this `DataProvider` and [MeasurementConsumer] with
* [eventGroupReferenceId], or `null` if not found.
*/
private suspend fun getEventGroupByReferenceId(eventGroupReferenceId: String): EventGroup? {
val response =
try {
eventGroupsStub.listEventGroups(
listEventGroupsRequest {
parent = edpData.name
filter =
ListEventGroupsRequestKt.filter { measurementConsumers += measurementConsumerName }
pageSize = Int.MAX_VALUE
}
)
} catch (e: StatusException) {
throw Exception("Error listing EventGroups", e)
}
// TODO(@SanjayVas): Support filtering by reference ID so we don't need to handle multiple pages
// of EventGroups.
check(response.nextPageToken.isEmpty()) {
"Too many EventGroups for ${edpData.name} and $measurementConsumerName"
}
return response.eventGroupsList.find { it.eventGroupReferenceId == eventGroupReferenceId }
}
private suspend fun ensureMetadataDescriptor(
metadataDescriptor: Descriptors.Descriptor
): EventGroupMetadataDescriptor {
val descriptorSet =
ProtoReflection.buildFileDescriptorSet(
metadataDescriptor,
ProtoReflection.WELL_KNOWN_TYPES + knownEventGroupMetadataTypes,
)
val descriptorResource =
try {
eventGroupMetadataDescriptorsStub.createEventGroupMetadataDescriptor(
createEventGroupMetadataDescriptorRequest {
parent = edpData.name
eventGroupMetadataDescriptor = eventGroupMetadataDescriptor {
this.descriptorSet = descriptorSet
}
requestId = "type.googleapis.com/${metadataDescriptor.fullName}"
}
)
} catch (e: StatusException) {
throw Exception("Error creating EventGroupMetadataDescriptor", e)
}
if (descriptorResource.descriptorSet == descriptorSet) {
return descriptorResource
}
return try {
eventGroupMetadataDescriptorsStub.updateEventGroupMetadataDescriptor(
updateEventGroupMetadataDescriptorRequest {
eventGroupMetadataDescriptor =
descriptorResource.copy { this.descriptorSet = descriptorSet }
}
)
} catch (e: StatusException) {
throw Exception("Error updating EventGroupMetadataDescriptor", e)
}
}
private fun verifyProtocolConfig(
requsitionName: String,
protocol: ProtocolConfig.Protocol.ProtocolCase,
) {
if (protocol !in supportedProtocols) {
logger.log(Level.WARNING, "Skipping $requsitionName: Protocol not supported.")
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Protocol not supported.",
)
}
}
private fun verifyDuchyEntry(
duchyEntry: DuchyEntry,
duchyCertificate: Certificate,
protocol: ProtocolConfig.Protocol.ProtocolCase,
) {
val duchyX509Certificate: X509Certificate = readCertificate(duchyCertificate.x509Der)
// Look up the trusted issuer certificate for this Duchy certificate. Note that this doesn't
// confirm that this is the trusted issuer for the right Duchy. In a production environment,
// consider having a mapping of Duchy to issuer certificate.
val trustedIssuer =
trustedCertificates[checkNotNull(duchyX509Certificate.authorityKeyIdentifier)]
?: throw InvalidConsentSignalException("Issuer of ${duchyCertificate.name} is not trusted")
try {
when (protocol) {
ProtocolConfig.Protocol.ProtocolCase.LIQUID_LEGIONS_V2 ->
verifyElGamalPublicKey(
duchyEntry.value.liquidLegionsV2.elGamalPublicKey,
duchyX509Certificate,
trustedIssuer,
)
ProtocolConfig.Protocol.ProtocolCase.REACH_ONLY_LIQUID_LEGIONS_V2 ->
verifyElGamalPublicKey(
duchyEntry.value.reachOnlyLiquidLegionsV2.elGamalPublicKey,
duchyX509Certificate,
trustedIssuer,
)
ProtocolConfig.Protocol.ProtocolCase.HONEST_MAJORITY_SHARE_SHUFFLE ->
if (duchyEntry.value.honestMajorityShareShuffle.hasPublicKey()) {
verifyEncryptionPublicKey(
duchyEntry.value.honestMajorityShareShuffle.publicKey,
duchyX509Certificate,
trustedIssuer,
)
}
else -> throw InvalidSpecException("Unsupported protocol $protocol")
}
} catch (e: CertPathValidatorException) {
throw InvalidConsentSignalException(
"Certificate path for ${duchyCertificate.name} is invalid",
e,
)
} catch (e: SignatureException) {
throw InvalidConsentSignalException(
"ElGamal public key signature is invalid for Duchy ${duchyEntry.key}",
e,
)
}
}
/**
* Verify duchy entries.
*
* For each duchy entry, verifies its certificate. If the protocol is honest majority share
* shuffle, also verify that there are exactly two duchy entires, and only one of them has the
* encryption public key. Throws a RequisitionRefusalException if the verification fails.
*/
private suspend fun verifyDuchyEntries(
requisition: Requisition,
protocol: ProtocolConfig.Protocol.ProtocolCase,
) {
try {
for (duchyEntry in requisition.duchiesList) {
val duchyCertificate: Certificate = getCertificate(duchyEntry.value.duchyCertificate)
verifyDuchyEntry(duchyEntry, duchyCertificate, protocol)
}
} catch (e: InvalidConsentSignalException) {
logger.log(Level.WARNING, e) {
"Consent signaling verification failed for ${requisition.name}"
}
throw RequisitionRefusalException(
Requisition.Refusal.Justification.CONSENT_SIGNAL_INVALID,
e.message.orEmpty(),
)
}
if (protocol == ProtocolConfig.Protocol.ProtocolCase.HONEST_MAJORITY_SHARE_SHUFFLE) {
if (requisition.duchiesList.size != 2) {
logger.log(
Level.WARNING,
"Two duchy entries are expected, but there are ${requisition.duchiesList.size}.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Two duchy entries are expected, but there are ${requisition.duchiesList.size}.",
)
}
val publicKeyList =
requisition.duchiesList
.filter { it.value.honestMajorityShareShuffle.hasPublicKey() }
.map { it.value.honestMajorityShareShuffle.publicKey }
if (publicKeyList.size != 1) {
logger.log(
Level.WARNING,
"Exactly one duchy entry is expected to have the encryption public key, but ${publicKeyList.size} duchy entries do.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Exactly one duchy entry is expected to have the encryption public key, but ${publicKeyList.size} duchy entries do.",
)
}
}
}
private fun verifyEncryptionPublicKey(
signedEncryptionPublicKey: SignedMessage,
measurementConsumerCertificate: Certificate,
) {
val x509Certificate = readCertificate(measurementConsumerCertificate.x509Der)
// Look up the trusted issuer certificate for this MC certificate. Note that this doesn't
// confirm that this is the trusted issuer for the right MC. In a production environment,
// consider having a mapping of MC to root/CA cert.
val trustedIssuer =
trustedCertificates[checkNotNull(x509Certificate.authorityKeyIdentifier)]
?: throw InvalidConsentSignalException(
"Issuer of ${measurementConsumerCertificate.name} is not trusted"
)
// TODO(world-federation-of-advertisers/consent-signaling-client#41): Use method from
// DataProviders client instead of MeasurementConsumers client.
try {
verifyEncryptionPublicKey(signedEncryptionPublicKey, x509Certificate, trustedIssuer)
} catch (e: CertPathValidatorException) {
throw InvalidConsentSignalException(
"Certificate path for ${measurementConsumerCertificate.name} is invalid",
e,
)
} catch (e: SignatureException) {
throw InvalidConsentSignalException("EncryptionPublicKey signature is invalid", e)
}
}
/** Executes the requisition fulfillment workflow. */
override suspend fun executeRequisitionFulfillingWorkflow() {
logger.info("Executing requisitionFulfillingWorkflow...")
val requisitions =
getRequisitions().filter {
checkNotNull(MeasurementKey.fromName(it.measurement)).measurementConsumerId ==
checkNotNull(MeasurementConsumerKey.fromName(measurementConsumerName))
.measurementConsumerId
}
if (requisitions.isEmpty()) {
logger.fine("No unfulfilled requisition. Polling again later...")
return
}
for (requisition in requisitions) {
try {
logger.info("Processing requisition ${requisition.name}...")
// TODO(@SanjayVas): Verify that DataProvider public key in Requisition matches private key
// in edpData. A real EDP would look up the matching private key.
val measurementConsumerCertificate: Certificate =
getCertificate(requisition.measurementConsumerCertificate)
val (measurementSpec, requisitionSpec) =
try {
verifySpecifications(requisition, measurementConsumerCertificate)
} catch (e: InvalidConsentSignalException) {
logger.log(Level.WARNING, e) {
"Consent signaling verification failed for ${requisition.name}"
}
throw RequisitionRefusalException(
Requisition.Refusal.Justification.CONSENT_SIGNAL_INVALID,
e.message.orEmpty(),
)
}
logger.log(Level.INFO, "MeasurementSpec:\n$measurementSpec")
logger.log(Level.INFO, "RequisitionSpec:\n$requisitionSpec")
for (eventGroupEntry in requisitionSpec.events.eventGroupsList) {
val eventGroupId = EventGroupKey.fromName(eventGroupEntry.key)!!.eventGroupId
if (eventGroupId == CONSENT_SIGNAL_INVALID_EVENT_GROUP_ID) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.CONSENT_SIGNAL_INVALID,
"consent signal invalid",
)
}
if (eventGroupId == SPEC_INVALID_EVENT_GROUP_ID) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"spec invalid",
)
}
if (eventGroupId == INSUFFICIENT_PRIVACY_BUDGET_EVENT_GROUP_ID) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.INSUFFICIENT_PRIVACY_BUDGET,
"insufficient privacy budget",
)
}
if (eventGroupId == UNFULFILLABLE_EVENT_GROUP_ID) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.UNFULFILLABLE,
"unfulfillable",
)
}
if (eventGroupId == DECLINED_EVENT_GROUP_ID) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.DECLINED,
"declined",
)
}
}
val eventGroupSpecs: List<EventQuery.EventGroupSpec> =
try {
buildEventGroupSpecs(requisitionSpec)
} catch (e: InvalidSpecException) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
e.message.orEmpty(),
)
}
val requisitionFingerprint = computeRequisitionFingerprint(requisition)
val protocols: List<ProtocolConfig.Protocol> = requisition.protocolConfig.protocolsList
if (protocols.any { it.hasDirect() }) {
val directProtocolConfig =
requisition.protocolConfig.protocolsList.first { it.hasDirect() }.direct
val directNoiseMechanismOptions =
directProtocolConfig.noiseMechanismsList
.mapNotNull { protocolConfigNoiseMechanism ->
protocolConfigNoiseMechanism.toDirectNoiseMechanism()
}
.toSet()
if (measurementSpec.hasReach() || measurementSpec.hasReachAndFrequency()) {
val directProtocol =
DirectProtocol(
directProtocolConfig,
selectReachAndFrequencyNoiseMechanism(directNoiseMechanismOptions),
)
fulfillDirectReachAndFrequencyMeasurement(
requisition,
measurementSpec,
requisitionSpec.nonce,
eventGroupSpecs,
directProtocol,
)
} else if (measurementSpec.hasDuration()) {
val directProtocol =
DirectProtocol(
directProtocolConfig,
selectImpressionNoiseMechanism(directNoiseMechanismOptions),
)
fulfillDurationMeasurement(
requisition,
requisitionSpec,
measurementSpec,
eventGroupSpecs,
directProtocol,
)
} else if (measurementSpec.hasImpression()) {
val directProtocol =
DirectProtocol(
directProtocolConfig,
selectWatchDurationNoiseMechanism(directNoiseMechanismOptions),
)
fulfillImpressionMeasurement(
requisition,
requisitionSpec,
measurementSpec,
eventGroupSpecs,
directProtocol,
)
} else {
logger.log(
Level.WARNING,
"Skipping ${requisition.name}: Measurement type not supported for direct fulfillment.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Measurement type not supported for direct fulfillment.",
)
}
} else if (protocols.any { it.hasLiquidLegionsV2() }) {
if (!measurementSpec.hasReach() && !measurementSpec.hasReachAndFrequency()) {
logger.log(
Level.WARNING,
"Skipping ${requisition.name}: Measurement type not supported for protocol llv2.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Measurement type not supported for protocol llv2.",
)
}
val protocolConfig = ProtocolConfig.Protocol.ProtocolCase.LIQUID_LEGIONS_V2
verifyProtocolConfig(requisition.name, protocolConfig)
verifyDuchyEntries(requisition, protocolConfig)
fulfillRequisitionForLiquidLegionsV2Measurement(
requisition,
measurementSpec,
requisitionFingerprint,
requisitionSpec.nonce,
eventGroupSpecs,
)
} else if (protocols.any { it.hasReachOnlyLiquidLegionsV2() }) {
if (!measurementSpec.hasReach()) {
logger.log(
Level.WARNING,
"Skipping ${requisition.name}: Measurement type not supported for protocol rollv2.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Measurement type not supported for protocol rollv2.",
)
}
val protocolConfig = ProtocolConfig.Protocol.ProtocolCase.REACH_ONLY_LIQUID_LEGIONS_V2
verifyProtocolConfig(requisition.name, protocolConfig)
verifyDuchyEntries(requisition, protocolConfig)
fulfillRequisitionForReachOnlyLiquidLegionsV2Measurement(
requisition,
measurementSpec,
requisitionFingerprint,
requisitionSpec.nonce,
eventGroupSpecs,
)
} else if (protocols.any { it.hasHonestMajorityShareShuffle() }) {
if (!measurementSpec.hasReach() && !measurementSpec.hasReachAndFrequency()) {
logger.log(
Level.WARNING,
"Skipping ${requisition.name}: Measurement type not supported for protocol hmss.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Measurement type not supported for protocol hmss.",
)
}
val protocolConfig = ProtocolConfig.Protocol.ProtocolCase.HONEST_MAJORITY_SHARE_SHUFFLE
verifyProtocolConfig(requisition.name, protocolConfig)
verifyDuchyEntries(requisition, protocolConfig)
fulfillRequisitionForHmssMeasurement(
requisition,
measurementSpec,
requisitionFingerprint,
requisitionSpec.nonce,
eventGroupSpecs,
)
} else {
logger.log(
Level.WARNING,
"Skipping ${requisition.name}: Protocol not set or not supported.",
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Protocol not set or not supported.",
)
}
} catch (refusalException: RequisitionRefusalException) {
refuseRequisition(
requisition.name,
refusalException.justification,
refusalException.message ?: "Refuse to fulfill requisition.",
)
}
}
}
private data class DirectProtocol(
val directProtocolConfig: ProtocolConfig.Direct,
val selectedDirectNoiseMechanism: DirectNoiseMechanism,
)
/**
* Builds [EventQuery.EventGroupSpec]s from a [requisitionSpec] by fetching [EventGroup]s.
*
* @throws InvalidSpecException if [requisitionSpec] is found to be invalid
*/
private suspend fun buildEventGroupSpecs(
requisitionSpec: RequisitionSpec
): List<EventQuery.EventGroupSpec> {
// TODO(@SanjayVas): Cache EventGroups.
return requisitionSpec.events.eventGroupsList.map {
val eventGroup =
try {
eventGroupsStub.getEventGroup(getEventGroupRequest { name = it.key })
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.NOT_FOUND -> InvalidSpecException("EventGroup $it not found", e)
else -> Exception("Error retrieving EventGroup $it", e)
}
}
if (!eventGroup.eventGroupReferenceId.startsWith(SIMULATOR_EVENT_GROUP_REFERENCE_ID_PREFIX)) {
throw InvalidSpecException("EventGroup ${it.key} not supported by this simulator")
}
EventQuery.EventGroupSpec(eventGroup, it.value)
}
}
private suspend fun chargeMpcPrivacyBudget(
requisitionName: String,
measurementSpec: MeasurementSpec,
eventSpecs: Iterable<RequisitionSpec.EventGroupEntry.Value>,
noiseMechanism: NoiseMechanism,
contributorCount: Int,
) {
logger.info("chargeMpcPrivacyBudget for requisition with $noiseMechanism noise mechanism...")
try {
if (noiseMechanism != NoiseMechanism.DISCRETE_GAUSSIAN) {
throw PrivacyBudgetManagerException(
PrivacyBudgetManagerExceptionType.INCORRECT_NOISE_MECHANISM
)
}
privacyBudgetManager.chargePrivacyBudgetInAcdp(
getMpcAcdpQuery(
Reference(measurementConsumerName, requisitionName, false),
measurementSpec,
eventSpecs,
contributorCount,
)
)
} catch (e: PrivacyBudgetManagerException) {
logger.log(Level.WARNING, "chargeMpcPrivacyBudget failed due to ${e.errorType}", e)
when (e.errorType) {
PrivacyBudgetManagerExceptionType.PRIVACY_BUDGET_EXCEEDED -> {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.INSUFFICIENT_PRIVACY_BUDGET,
"Privacy budget exceeded",
)
}
PrivacyBudgetManagerExceptionType.INVALID_PRIVACY_BUCKET_FILTER -> {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Invalid event filter",
)
}
PrivacyBudgetManagerExceptionType.INCORRECT_NOISE_MECHANISM -> {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Incorrect noise mechanism. Should be DISCRETE_GAUSSIAN for ACDP composition but is $noiseMechanism",
)
}
PrivacyBudgetManagerExceptionType.DATABASE_UPDATE_ERROR,
PrivacyBudgetManagerExceptionType.UPDATE_AFTER_COMMIT,
PrivacyBudgetManagerExceptionType.NESTED_TRANSACTION,
PrivacyBudgetManagerExceptionType.BACKING_STORE_CLOSED -> {
throw Exception("Unexpected PBM error", e)
}
}
}
}
private suspend fun chargeDirectPrivacyBudget(
requisitionName: String,
measurementSpec: MeasurementSpec,
eventSpecs: Iterable<RequisitionSpec.EventGroupEntry.Value>,
directNoiseMechanism: DirectNoiseMechanism,
) {
logger.info("chargeDirectPrivacyBudget for requisition $requisitionName...")
try {
if (directNoiseMechanism != DirectNoiseMechanism.CONTINUOUS_GAUSSIAN) {
throw PrivacyBudgetManagerException(
PrivacyBudgetManagerExceptionType.INCORRECT_NOISE_MECHANISM
)
}
privacyBudgetManager.chargePrivacyBudgetInAcdp(
getDirectAcdpQuery(
Reference(measurementConsumerName, requisitionName, false),
measurementSpec,
eventSpecs,
)
)
} catch (e: PrivacyBudgetManagerException) {
logger.log(Level.WARNING, "chargeDirectPrivacyBudget failed due to ${e.errorType}", e)
when (e.errorType) {
PrivacyBudgetManagerExceptionType.PRIVACY_BUDGET_EXCEEDED -> {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.INSUFFICIENT_PRIVACY_BUDGET,
"Privacy budget exceeded",
)
}
PrivacyBudgetManagerExceptionType.INVALID_PRIVACY_BUCKET_FILTER -> {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Invalid event filter",
)
}
PrivacyBudgetManagerExceptionType.INCORRECT_NOISE_MECHANISM -> {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Incorrect noise mechanism. Should be GAUSSIAN for ACDP composition but is $directNoiseMechanism",
)
}
PrivacyBudgetManagerExceptionType.DATABASE_UPDATE_ERROR,
PrivacyBudgetManagerExceptionType.UPDATE_AFTER_COMMIT,
PrivacyBudgetManagerExceptionType.NESTED_TRANSACTION,
PrivacyBudgetManagerExceptionType.BACKING_STORE_CLOSED -> {
throw Exception("Unexpected PBM error", e)
}
}
}
}
private fun logSketchDetails(sketch: Sketch) {
val sortedRegisters = sketch.registersList.sortedBy { it.index }
for (register in sortedRegisters) {
logger.log(Level.INFO) { "${register.index}, ${register.valuesList.joinToString()}" }
}
}
private fun generateSketch(
sketchConfig: SketchConfig,
measurementSpec: MeasurementSpec,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
): Sketch {
logger.info("Generating Sketch...")
val sketch =
SketchGenerator(eventQuery, sketchConfig, measurementSpec.vidSamplingInterval)
.generate(eventGroupSpecs)
logger.log(Level.INFO) { "SketchConfig:\n${sketch.config}" }
logger.log(Level.INFO) { "Registers Size:\n${sketch.registersList.size}" }
if (logSketchDetails) {
logSketchDetails(sketch)
}
return sketch
}
private fun logShareShuffleSketchDetails(sketch: IntArray) {
for (register in sketch) {
logger.log(Level.INFO) { "${register}" }
}
}
private fun generateHmssSketch(
vidToIndexMap: Map<Long, IndexedValue>,
measurementSpec: MeasurementSpec,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
): IntArray {
logger.info("Generating HMSS Sketch...")
val maximumFrequency =
if (measurementSpec.hasReachAndFrequency()) measurementSpec.reachAndFrequency.maximumFrequency
else 1
val sketch =
FrequencyVectorGenerator(vidToIndexMap, eventQuery, measurementSpec.vidSamplingInterval)
.generate(eventGroupSpecs)
.map { if (it > maximumFrequency) maximumFrequency else it }
.toIntArray()
logger.log(Level.INFO) { "Registers Size:\n${sketch.size}" }
if (logSketchDetails) {
logShareShuffleSketchDetails(sketch)
}
return sketch
}
private fun encryptLiquidLegionsV2Sketch(
sketch: Sketch,
ellipticCurveId: Int,
combinedPublicKey: AnySketchElGamalPublicKey,
maximumValue: Int,
): ByteString {
require(maximumValue > 0) { "Maximum value must be positive" }
logger.log(Level.INFO, "Encrypting Liquid Legions V2 Sketch...")
return sketchEncrypter.encrypt(sketch, ellipticCurveId, combinedPublicKey, maximumValue)
}
private fun encryptReachOnlyLiquidLegionsV2Sketch(
sketch: Sketch,
ellipticCurveId: Int,
combinedPublicKey: AnySketchElGamalPublicKey,
): ByteString {
logger.log(Level.INFO, "Encrypting Reach-Only Liquid Legions V2 Sketch...")
return sketchEncrypter.encrypt(sketch, ellipticCurveId, combinedPublicKey)
}
/**
* Fulfill Liquid Legions V2 Measurement's Requisition by creating an encrypted sketch and send to
* the duchy.
*/
private suspend fun fulfillRequisitionForLiquidLegionsV2Measurement(
requisition: Requisition,
measurementSpec: MeasurementSpec,
requisitionFingerprint: ByteString,
nonce: Long,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
) {
val llv2Protocol: ProtocolConfig.Protocol =
requireNotNull(
requisition.protocolConfig.protocolsList.find { protocol -> protocol.hasLiquidLegionsV2() }
) {
"Protocol with LiquidLegionsV2 is missing"
}
val liquidLegionsV2: ProtocolConfig.LiquidLegionsV2 = llv2Protocol.liquidLegionsV2
val combinedPublicKey = requisition.getCombinedPublicKey(liquidLegionsV2.ellipticCurveId)
chargeMpcPrivacyBudget(
requisition.name,
measurementSpec,
eventGroupSpecs.map { it.spec },
liquidLegionsV2.noiseMechanism,
requisition.duchiesCount,
)
val sketch =
try {
generateSketch(
liquidLegionsV2.sketchParams.toSketchConfig(),
measurementSpec,
eventGroupSpecs,
)
} catch (e: EventFilterValidationException) {
logger.log(
Level.WARNING,
"RequisitionFulfillmentWorkflow failed due to invalid event filter",
e,
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Invalid event filter (${e.code}): ${e.code.description}",
)
}
val encryptedSketch =
encryptLiquidLegionsV2Sketch(
sketch,
liquidLegionsV2.ellipticCurveId,
combinedPublicKey,
measurementSpec.reachAndFrequency.maximumFrequency.coerceAtLeast(1),
)
fulfillRequisition(requisition, requisitionFingerprint, nonce, encryptedSketch)
}
/**
* Fulfill Reach-Only Liquid Legions V2 Measurement's Requisition by creating an encrypted sketch
* and send to the duchy.
*/
private suspend fun fulfillRequisitionForReachOnlyLiquidLegionsV2Measurement(
requisition: Requisition,
measurementSpec: MeasurementSpec,
requisitionFingerprint: ByteString,
nonce: Long,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
) {
val protocolConfig: ProtocolConfig.ReachOnlyLiquidLegionsV2 =
requireNotNull(
requisition.protocolConfig.protocolsList.find { protocol ->
protocol.hasReachOnlyLiquidLegionsV2()
}
) {
"Protocol with ReachOnlyLiquidLegionsV2 is missing"
}
.reachOnlyLiquidLegionsV2
val combinedPublicKey: AnySketchElGamalPublicKey =
requisition.getCombinedPublicKey(protocolConfig.ellipticCurveId)
chargeMpcPrivacyBudget(
requisition.name,
measurementSpec,
eventGroupSpecs.map { it.spec },
protocolConfig.noiseMechanism,
requisition.duchiesCount,
)
val sketch =
try {
generateSketch(
protocolConfig.sketchParams.toSketchConfig(),
measurementSpec,
eventGroupSpecs,
)
} catch (e: EventFilterValidationException) {
logger.log(
Level.WARNING,
"RequisitionFulfillmentWorkflow failed due to invalid event filter",
e,
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Invalid event filter (${e.code}): ${e.code.description}",
)
}
val encryptedSketch =
encryptReachOnlyLiquidLegionsV2Sketch(
sketch,
protocolConfig.ellipticCurveId,
combinedPublicKey,
)
fulfillRequisition(requisition, requisitionFingerprint, nonce, encryptedSketch)
}
private suspend fun fulfillRequisition(
requisition: Requisition,
requisitionFingerprint: ByteString,
nonce: Long,
data: ByteString,
) {
logger.info("Fulfilling requisition ${requisition.name}...")
val requests: Flow<FulfillRequisitionRequest> = flow {
logger.info { "Emitting FulfillRequisitionRequests..." }
emit(
fulfillRequisitionRequest {
header = header {
name = requisition.name
this.requisitionFingerprint = requisitionFingerprint
this.nonce = nonce
}
}
)
emitAll(
data.asBufferedFlow(RPC_CHUNK_SIZE_BYTES).map {
fulfillRequisitionRequest { bodyChunk = bodyChunk { this.data = it } }
}
)
}
try {
requisitionFulfillmentStubsByDuchyId.values.first().fulfillRequisition(requests)
} catch (e: StatusException) {
throw Exception("Error fulfilling requisition ${requisition.name}", e)
}
}
private suspend fun fulfillRequisition(
requisition: Requisition,
requisitionFingerprint: ByteString,
nonce: Long,
encryptedSignedSeed: EncryptedMessage,
shareVector: FrequencyVector,
) {
logger.info("Fulfilling requisition ${requisition.name}...")
val requests: Flow<FulfillRequisitionRequest> = flow {
logger.info { "Emitting FulfillRequisitionRequests..." }
emit(
fulfillRequisitionRequest {
header = header {
name = requisition.name
this.requisitionFingerprint = requisitionFingerprint
this.nonce = nonce
this.honestMajorityShareShuffle = honestMajorityShareShuffle {
secretSeed = encryptedSignedSeed
registerCount = shareVector.dataList.size.toLong()
dataProviderCertificate = edpData.certificateKey.toName()
}
}
}
)
emitAll(
shareVector.toByteString().asBufferedFlow(RPC_CHUNK_SIZE_BYTES).map {
fulfillRequisitionRequest { bodyChunk = bodyChunk { this.data = it } }
}
)
}
try {
val duchyId = getDuchyWithoutPublicKey(requisition)
val requisitionFulfillmentStub =
requisitionFulfillmentStubsByDuchyId[duchyId]
?: throw Exception("Requisition fulfillment stub not found for $duchyId.")
requisitionFulfillmentStub.fulfillRequisition(requests)
} catch (e: StatusException) {
throw Exception("Error fulfilling requisition ${requisition.name}", e)
}
}
private fun getEncryptionKeyForShareSeed(requisition: Requisition): SignedMessage {
return requisition.duchiesList
.map { it.value.honestMajorityShareShuffle }
.singleOrNull { it.hasPublicKey() }
?.publicKey
?: throw IllegalArgumentException(
"Expected exactly one Duchy entry with an HMSS encryption public key."
)
}
private fun getDuchyWithoutPublicKey(requisition: Requisition): String {
return requisition.duchiesList
.singleOrNull { !it.value.honestMajorityShareShuffle.hasPublicKey() }
?.key
?: throw IllegalArgumentException(
"Expected exactly one Duchy entry with an HMSS encryption public key."
)
}
/** Fulfill Honest Majority Share Shuffle Measurement's Requisition. */
private suspend fun fulfillRequisitionForHmssMeasurement(
requisition: Requisition,
measurementSpec: MeasurementSpec,
requisitionFingerprint: ByteString,
nonce: Long,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
) {
val protocolConfig: ProtocolConfig.HonestMajorityShareShuffle =
requireNotNull(
requisition.protocolConfig.protocolsList.find { protocol ->
protocol.hasHonestMajorityShareShuffle()
}
) {
"Protocol with HonestMajorityShareShuffle is missing"
}
.honestMajorityShareShuffle
chargeMpcPrivacyBudget(
requisition.name,
measurementSpec,
eventGroupSpecs.map { it.spec },
protocolConfig.noiseMechanism,
requisition.duchiesCount - 1,
)
val frequencyVector =
try {
generateHmssSketch(vidToIndexMap, measurementSpec, eventGroupSpecs)
} catch (e: EventFilterValidationException) {
logger.log(
Level.WARNING,
"RequisitionFulfillmentWorkflow failed due to invalid event filter",
e,
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Invalid event filter (${e.code}): ${e.code.description}",
)
}
val secretShareGeneratorRequest = secretShareGeneratorRequest {
data += frequencyVector.toList()
ringModulus = protocolConfig.ringModulus
}
val secretShare =
SecretShare.parseFrom(
SecretShareGeneratorAdapter.generateSecretShares(secretShareGeneratorRequest.toByteArray())
)
val shareSeed = randomSeed { data = secretShare.shareSeed.key.concat(secretShare.shareSeed.iv) }
val signedShareSeed =
signRandomSeed(shareSeed, edpData.signingKeyHandle, edpData.signingKeyHandle.defaultAlgorithm)
val publicKey =
EncryptionPublicKey.parseFrom(getEncryptionKeyForShareSeed(requisition).message.value)
val shareSeedCiphertext = encryptRandomSeed(signedShareSeed, publicKey)
val shareVector = frequencyVector { data += secretShare.shareVectorList }
fulfillRequisition(requisition, requisitionFingerprint, nonce, shareSeedCiphertext, shareVector)
}
private fun Requisition.getCombinedPublicKey(curveId: Int): AnySketchElGamalPublicKey {
logger.info("Getting combined public key...")
val elGamalPublicKeys: List<AnySketchElGamalPublicKey> =
this.duchiesList.map {
val value: DuchyEntry.Value = it.value
val signedElGamalPublicKey: SignedMessage =
when (value.protocolCase) {
DuchyEntry.Value.ProtocolCase.LIQUID_LEGIONS_V2 ->
value.liquidLegionsV2.elGamalPublicKey
DuchyEntry.Value.ProtocolCase.REACH_ONLY_LIQUID_LEGIONS_V2 ->
value.reachOnlyLiquidLegionsV2.elGamalPublicKey
else -> throw Exception("Invalid protocol to get combined public key.")
}
signedElGamalPublicKey.unpack<ElGamalPublicKey>().toAnySketchElGamalPublicKey()
}
return SketchEncrypter.combineElGamalPublicKeys(curveId, elGamalPublicKeys)
}
/**
* Calculate direct reach and frequency for measurement with single EDP by summing up VIDs
* directly and fulfillDirectMeasurement
*/
private suspend fun fulfillDirectReachAndFrequencyMeasurement(
requisition: Requisition,
measurementSpec: MeasurementSpec,
nonce: Long,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
directProtocol: DirectProtocol,
) {
chargeDirectPrivacyBudget(
requisition.name,
measurementSpec,
eventGroupSpecs.map { it.spec },
directProtocol.selectedDirectNoiseMechanism,
)
logger.info("Calculating direct reach and frequency...")
val measurementResult =
buildDirectMeasurementResult(
directProtocol,
measurementSpec,
sampleVids(eventGroupSpecs, measurementSpec.vidSamplingInterval),
)
fulfillDirectMeasurement(requisition, measurementSpec, nonce, measurementResult)
}
/**
* Samples VIDs from multiple [EventQuery.EventGroupSpec]s with a
* [MeasurementSpec.VidSamplingInterval].
*/
private fun sampleVids(
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
vidSamplingInterval: MeasurementSpec.VidSamplingInterval,
): Iterable<Long> {
return try {
sampleVids(eventQuery, eventGroupSpecs, vidSamplingInterval.start, vidSamplingInterval.width)
} catch (e: EventFilterValidationException) {
logger.log(
Level.WARNING,
"RequisitionFulfillmentWorkflow failed due to invalid event filter",
e,
)
throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"Invalid event filter (${e.code}): ${e.code.description}",
)
}
}
private fun getPublisherNoiser(
privacyParams: DifferentialPrivacyParams,
directNoiseMechanism: DirectNoiseMechanism,
random: Random,
): AbstractNoiser =
when (directNoiseMechanism) {
DirectNoiseMechanism.NONE ->
object : AbstractNoiser() {
override val distribution = ConstantRealDistribution(0.0)
override val variance: Double
get() = distribution.numericalVariance
}
DirectNoiseMechanism.CONTINUOUS_LAPLACE ->
LaplaceNoiser(DpParams(privacyParams.epsilon, privacyParams.delta), random.asJavaRandom())
DirectNoiseMechanism.CONTINUOUS_GAUSSIAN ->
GaussianNoiser(DpParams(privacyParams.epsilon, privacyParams.delta), random.asJavaRandom())
}
/**
* Add publisher noise to calculated direct reach.
*
* @param reachValue Direct reach value.
* @param privacyParams Differential privacy params for reach.
* @param directNoiseMechanism Selected noise mechanism for direct reach.
* @return Noised non-negative reach value.
*/
private fun addReachPublisherNoise(
reachValue: Int,
privacyParams: DifferentialPrivacyParams,
directNoiseMechanism: DirectNoiseMechanism,
): Int {
val reachNoiser: AbstractNoiser =
getPublisherNoiser(privacyParams, directNoiseMechanism, random)
return max(0, reachValue + reachNoiser.sample().toInt())
}
/**
* Add publisher noise to calculated direct frequency.
*
* @param reachValue Direct reach value.
* @param frequencyMap Direct frequency.
* @param privacyParams Differential privacy params for frequency map.
* @param directNoiseMechanism Selected noise mechanism for direct frequency.
* @return Noised non-negative frequency map.
*/
private fun addFrequencyPublisherNoise(
reachValue: Int,
frequencyMap: Map<Int, Double>,
privacyParams: DifferentialPrivacyParams,
directNoiseMechanism: DirectNoiseMechanism,
): Map<Int, Double> {
val frequencyNoiser: AbstractNoiser =
getPublisherNoiser(privacyParams, directNoiseMechanism, random)
// Add noise to the histogram and cap negative values to zeros.
val frequencyHistogram: Map<Int, Int> =
frequencyMap.mapValues { (_, percentage) ->
// Round the noise for privacy.
val noisedCount: Int =
(percentage * reachValue).roundToInt() + (frequencyNoiser.sample()).roundToInt()
max(0, noisedCount)
}
val normalizationTerm: Double = frequencyHistogram.values.sum().toDouble()
// Normalize to get the distribution
return if (normalizationTerm != 0.0) {
frequencyHistogram.mapValues { (_, count) -> count / normalizationTerm }
} else {
frequencyHistogram.mapValues { 0.0 }
}
}
/**
* Add publisher noise to calculated impression.
*
* @param impressionValue Impression value.
* @param impressionMeasurementSpec Measurement spec of impression.
* @param directNoiseMechanism Selected noise mechanism for impression.
* @return Noised non-negative impression value.
*/
private fun addImpressionPublisherNoise(
impressionValue: Long,
impressionMeasurementSpec: MeasurementSpec.Impression,
directNoiseMechanism: DirectNoiseMechanism,
): Long {
val noiser: AbstractNoiser =
getPublisherNoiser(impressionMeasurementSpec.privacyParams, directNoiseMechanism, random)
// Noise needs to be scaled by maximumFrequencyPerUser.
val noise = noiser.sample() * impressionMeasurementSpec.maximumFrequencyPerUser
return max(0L, impressionValue + noise.roundToInt())
}
/**
* Build [Measurement.Result] of the measurement type specified in [MeasurementSpec].
*
* @param measurementSpec Measurement spec.
* @param samples sampled events.
* @return [Measurement.Result].
*/
private fun buildDirectMeasurementResult(
directProtocol: DirectProtocol,
measurementSpec: MeasurementSpec,
samples: Iterable<Long>,
): Measurement.Result {
val directProtocolConfig = directProtocol.directProtocolConfig
val directNoiseMechanism = directProtocol.selectedDirectNoiseMechanism
val protocolConfigNoiseMechanism = directNoiseMechanism.toProtocolConfigNoiseMechanism()
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Protobuf enum fields cannot be null.
return when (measurementSpec.measurementTypeCase) {
MeasurementSpec.MeasurementTypeCase.REACH_AND_FREQUENCY -> {
if (!directProtocolConfig.hasDeterministicCountDistinct()) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.DECLINED,
"No valid methodologies for direct reach computation.",
)
}
if (!directProtocolConfig.hasDeterministicDistribution()) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.DECLINED,
"No valid methodologies for direct frequency distribution computation.",
)
}
val (sampledReachValue, frequencyMap) =
MeasurementResults.computeReachAndFrequency(
samples,
measurementSpec.reachAndFrequency.maximumFrequency,
)
logger.info("Adding $directNoiseMechanism publisher noise to direct reach and frequency...")
val sampledNoisedReachValue =
addReachPublisherNoise(
sampledReachValue,
measurementSpec.reachAndFrequency.reachPrivacyParams,
directNoiseMechanism,
)
val noisedFrequencyMap =
addFrequencyPublisherNoise(
sampledReachValue,
frequencyMap,
measurementSpec.reachAndFrequency.frequencyPrivacyParams,
directNoiseMechanism,
)
val scaledNoisedReachValue =
(sampledNoisedReachValue / measurementSpec.vidSamplingInterval.width).toLong()
MeasurementKt.result {
reach = reach {
value = scaledNoisedReachValue
this.noiseMechanism = protocolConfigNoiseMechanism
deterministicCountDistinct = DeterministicCountDistinct.getDefaultInstance()
}
frequency = frequency {
relativeFrequencyDistribution.putAll(noisedFrequencyMap.mapKeys { it.key.toLong() })
this.noiseMechanism = protocolConfigNoiseMechanism
deterministicDistribution = DeterministicDistribution.getDefaultInstance()
}
}
}
MeasurementSpec.MeasurementTypeCase.IMPRESSION -> {
if (!directProtocolConfig.hasDeterministicCount()) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.DECLINED,
"No valid methodologies for impression computation.",
)
}
val sampledImpressionCount =
computeImpression(samples, measurementSpec.impression.maximumFrequencyPerUser)
logger.info("Adding $directNoiseMechanism publisher noise to impression...")
val sampledNoisedImpressionCount =
addImpressionPublisherNoise(
sampledImpressionCount,
measurementSpec.impression,
directNoiseMechanism,
)
val scaledNoisedImpressionCount =
(sampledNoisedImpressionCount / measurementSpec.vidSamplingInterval.width).toLong()
MeasurementKt.result {
impression = impression {
value = scaledNoisedImpressionCount
noiseMechanism = protocolConfigNoiseMechanism
deterministicCount = DeterministicCount.getDefaultInstance()
}
}
}
MeasurementSpec.MeasurementTypeCase.DURATION -> {
val externalDataProviderId =
apiIdToExternalId(DataProviderKey.fromName(edpData.name)!!.dataProviderId)
MeasurementKt.result {
watchDuration = watchDuration {
value = duration {
// Use a value based on the externalDataProviderId since it's a known value the
// MeasurementConsumerSimulator can verify.
seconds = log2(externalDataProviderId.toDouble()).toLong()
}
noiseMechanism = protocolConfigNoiseMechanism
customDirectMethodology = customDirectMethodology {
variance = variance { scalar = 0.0 }
}
}
}
}
MeasurementSpec.MeasurementTypeCase.POPULATION -> {
error("Measurement type not supported.")
}
MeasurementSpec.MeasurementTypeCase.REACH -> {
if (!directProtocolConfig.hasDeterministicCountDistinct()) {
throw RequisitionRefusalException(
Requisition.Refusal.Justification.DECLINED,
"No valid methodologies for direct reach computation.",
)
}
val sampledReachValue = MeasurementResults.computeReach(samples)
logger.info("Adding $directNoiseMechanism publisher noise to direct reach for reach-only")
val sampledNoisedReachValue =
addReachPublisherNoise(
sampledReachValue,
measurementSpec.reach.privacyParams,
directNoiseMechanism,
)
val scaledNoisedReachValue =
(sampledNoisedReachValue / measurementSpec.vidSamplingInterval.width).toLong()
MeasurementKt.result {
reach = reach {
value = scaledNoisedReachValue
this.noiseMechanism = protocolConfigNoiseMechanism
deterministicCountDistinct = DeterministicCountDistinct.getDefaultInstance()
}
}
}
MeasurementSpec.MeasurementTypeCase.MEASUREMENTTYPE_NOT_SET -> {
error("Measurement type not set.")
}
}
}
/**
* Selects the most preferred [DirectNoiseMechanism] for reach and frequency measurements from the
* overlap of a list of preferred [DirectNoiseMechanism] and a set of [DirectNoiseMechanism]
* [options].
*/
private fun selectReachAndFrequencyNoiseMechanism(
options: Set<DirectNoiseMechanism>
): DirectNoiseMechanism {
val preferences = DIRECT_MEASUREMENT_ACDP_NOISE_MECHANISM_PREFERENCES
return preferences.firstOrNull { preference -> options.contains(preference) }
?: throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"No valid noise mechanism option for reach or frequency measurements.",
)
}
/**
* Selects the most preferred [DirectNoiseMechanism] for impression measurements from the overlap
* of a list of preferred [DirectNoiseMechanism] and a set of [DirectNoiseMechanism] [options].
*/
private fun selectImpressionNoiseMechanism(
options: Set<DirectNoiseMechanism>
): DirectNoiseMechanism {
val preferences = DIRECT_MEASUREMENT_ACDP_NOISE_MECHANISM_PREFERENCES
return preferences.firstOrNull { preference -> options.contains(preference) }
?: throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"No valid noise mechanism option for impression measurements.",
)
}
/**
* Selects the most preferred [DirectNoiseMechanism] for watch duration measurements from the
* overlap of a list of preferred [DirectNoiseMechanism] and a set of [DirectNoiseMechanism]
* [options].
*/
private fun selectWatchDurationNoiseMechanism(
options: Set<DirectNoiseMechanism>
): DirectNoiseMechanism {
val preferences = DIRECT_MEASUREMENT_ACDP_NOISE_MECHANISM_PREFERENCES
return preferences.firstOrNull { preference -> options.contains(preference) }
?: throw RequisitionRefusalException(
Requisition.Refusal.Justification.SPEC_INVALID,
"No valid noise mechanism option for watch duration measurements.",
)
}
private suspend fun fulfillImpressionMeasurement(
requisition: Requisition,
requisitionSpec: RequisitionSpec,
measurementSpec: MeasurementSpec,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
directProtocol: DirectProtocol,
) {
chargeDirectPrivacyBudget(
requisition.name,
measurementSpec,
eventGroupSpecs.map { it.spec },
directProtocol.selectedDirectNoiseMechanism,
)
logger.info("Calculating impression...")
val measurementResult =
buildDirectMeasurementResult(
directProtocol,
measurementSpec,
sampleVids(eventGroupSpecs, measurementSpec.vidSamplingInterval),
)
fulfillDirectMeasurement(requisition, measurementSpec, requisitionSpec.nonce, measurementResult)
}
private suspend fun fulfillDurationMeasurement(
requisition: Requisition,
requisitionSpec: RequisitionSpec,
measurementSpec: MeasurementSpec,
eventGroupSpecs: Iterable<EventQuery.EventGroupSpec>,
directProtocol: DirectProtocol,
) {
chargeDirectPrivacyBudget(
requisition.name,
measurementSpec,
eventGroupSpecs.map { it.spec },
directProtocol.selectedDirectNoiseMechanism,
)
val measurementResult =
buildDirectMeasurementResult(directProtocol, measurementSpec, listOf<Long>().asIterable())
fulfillDirectMeasurement(requisition, measurementSpec, requisitionSpec.nonce, measurementResult)
}
companion object {
init {
System.loadLibrary("secret_share_generator_adapter")
}
private const val RPC_CHUNK_SIZE_BYTES = 32 * 1024 // 32 KiB
private val logger: Logger = Logger.getLogger(this::class.java.name)
// The direct noise mechanisms for ACDP composition in PBM for direct measurements in order
// of preference. Currently, ACDP composition only supports CONTINUOUS_GAUSSIAN noise for direct
// measurements.
private val DIRECT_MEASUREMENT_ACDP_NOISE_MECHANISM_PREFERENCES =
listOf(DirectNoiseMechanism.CONTINUOUS_GAUSSIAN)
// Resource ID for EventGroup that fails Requisitions with CONSENT_SIGNAL_INVALID if used.
private const val CONSENT_SIGNAL_INVALID_EVENT_GROUP_ID = "consent-signal-invalid"
// Resource ID for EventGroup that fails Requisitions with SPEC_INVALID if used.
private const val SPEC_INVALID_EVENT_GROUP_ID = "spec-invalid"
// Resource ID for EventGroup that fails Requisitions with INSUFFICIENT_PRIVACY_BUDGET if used.
private const val INSUFFICIENT_PRIVACY_BUDGET_EVENT_GROUP_ID = "insufficient-privacy-budget"
// Resource ID for EventGroup that fails Requisitions with UNFULFILLABLE if used.
private const val UNFULFILLABLE_EVENT_GROUP_ID = "unfulfillable"
// Resource ID for EventGroup that fails Requisitions with DECLINED if used.
private const val DECLINED_EVENT_GROUP_ID = "declined"
private fun getEventGroupReferenceIdPrefix(edpDisplayName: String): String {
return "$SIMULATOR_EVENT_GROUP_REFERENCE_ID_PREFIX-${edpDisplayName}"
}
fun getEventGroupReferenceIdSuffix(eventGroup: EventGroup, edpDisplayName: String): String {
val prefix = getEventGroupReferenceIdPrefix(edpDisplayName)
return eventGroup.eventGroupReferenceId.removePrefix(prefix)
}
fun buildEventTemplates(
eventMessageDescriptor: Descriptors.Descriptor
): List<EventGroup.EventTemplate> {
val eventTemplateTypes: List<Descriptors.Descriptor> =
eventMessageDescriptor.fields
.filter { it.type == Descriptors.FieldDescriptor.Type.MESSAGE }
.map { it.messageType }
.filter { it.options.hasExtension(EventAnnotationsProto.eventTemplate) }
return eventTemplateTypes.map { EventGroupKt.eventTemplate { type = it.fullName } }
}
}
}
private fun DirectNoiseMechanism.toProtocolConfigNoiseMechanism(): NoiseMechanism {
return when (this) {
DirectNoiseMechanism.NONE -> NoiseMechanism.NONE
DirectNoiseMechanism.CONTINUOUS_LAPLACE -> NoiseMechanism.CONTINUOUS_LAPLACE
DirectNoiseMechanism.CONTINUOUS_GAUSSIAN -> NoiseMechanism.CONTINUOUS_GAUSSIAN
}
}
/**
* Converts a [NoiseMechanism] to a nullable [DirectNoiseMechanism].
*
* @return [DirectNoiseMechanism] when there is a matched, otherwise null.
*/
private fun NoiseMechanism.toDirectNoiseMechanism(): DirectNoiseMechanism? {
return when (this) {
NoiseMechanism.NONE -> DirectNoiseMechanism.NONE
NoiseMechanism.CONTINUOUS_LAPLACE -> DirectNoiseMechanism.CONTINUOUS_LAPLACE
NoiseMechanism.CONTINUOUS_GAUSSIAN -> DirectNoiseMechanism.CONTINUOUS_GAUSSIAN
NoiseMechanism.NOISE_MECHANISM_UNSPECIFIED,
NoiseMechanism.GEOMETRIC,
NoiseMechanism.DISCRETE_GAUSSIAN,
NoiseMechanism.UNRECOGNIZED -> {
null
}
}
}
private fun ElGamalPublicKey.toAnySketchElGamalPublicKey(): AnySketchElGamalPublicKey {
val source = this
return anySketchElGamalPublicKey {
generator = source.generator
element = source.element
}
}
| 98 | null | 9 | 36 | b5c84f8051cd189e55f8c43ee2b9cc3f3a75e353 | 69,636 | cross-media-measurement | Apache License 2.0 |
hmpps-sqs-spring-boot-autoconfigure/src/main/kotlin/uk/gov/justice/hmpps/sqs/HmppsSqsProperties.kt | ministryofjustice | 370,951,976 | false | {"Kotlin": 269780, "Shell": 3882} | package uk.gov.justice.hmpps.sqs
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding
@ConstructorBinding
@ConfigurationProperties(prefix = "hmpps.sqs")
data class HmppsSqsProperties(
val provider: String = "aws",
val region: String = "eu-west-2",
val localstackUrl: String = "http://localhost:4566",
val queues: Map<String, QueueConfig> = mapOf(),
val topics: Map<String, TopicConfig> = mapOf(),
) {
data class QueueConfig(
val queueName: String,
val queueAccessKeyId: String = "",
val queueSecretAccessKey: String = "",
val asyncQueueClient: Boolean = false,
val subscribeTopicId: String = "",
val subscribeFilter: String = "",
val dlqName: String = "",
val dlqAccessKeyId: String = "",
val dlqSecretAccessKey: String = "",
val asyncDlqClient: Boolean = false,
)
data class TopicConfig(
val arn: String = "",
val accessKeyId: String = "",
val secretAccessKey: String = "",
val asyncClient: Boolean = false,
) {
private val arnRegex = Regex("arn:aws:sns:.*:.*:(.*)$")
val name: String
get() = if (arn.matches(arnRegex)) arnRegex.find(arn)!!.destructured.component1() else throw InvalidHmppsSqsPropertiesException("Topic ARN $arn has an invalid format")
}
init {
queues.forEach { (queueId, queueConfig) ->
queueIdMustBeLowerCase(queueId)
queueNamesMustExist(queueId, queueConfig)
awsQueueSecretsMustExist(queueId, queueConfig)
localstackTopicSubscriptionsMustExist(queueConfig, queueId)
}
topics.forEach { (topicId, topicConfig) ->
topicIdMustBeLowerCase(topicId)
awsTopicSecretsMustExist(topicId, topicConfig)
localstackTopicNameMustExist(topicId, topicConfig)
}
checkForAwsDuplicateValues()
checkForLocalStackDuplicateValues()
}
private fun queueIdMustBeLowerCase(queueId: String) {
if (queueId != queueId.lowercase()) throw InvalidHmppsSqsPropertiesException("queueId $queueId is not lowercase")
}
private fun queueNamesMustExist(queueId: String, queueConfig: QueueConfig) {
if (queueConfig.queueName.isEmpty()) throw InvalidHmppsSqsPropertiesException("queueId $queueId does not have a queue name")
}
private fun awsQueueSecretsMustExist(queueId: String, queueConfig: QueueConfig) {
if (provider == "aws") {
if (queueConfig.queueAccessKeyId.isEmpty()) throw InvalidHmppsSqsPropertiesException("queueId $queueId does not have a queue access key id")
if (queueConfig.queueSecretAccessKey.isEmpty()) throw InvalidHmppsSqsPropertiesException("queueId $queueId does not have a queue secret access key")
if (queueConfig.dlqName.isNotEmpty()) {
if (queueConfig.dlqAccessKeyId.isEmpty()) throw InvalidHmppsSqsPropertiesException("queueId $queueId does not have a DLQ access key id")
if (queueConfig.dlqSecretAccessKey.isEmpty()) throw InvalidHmppsSqsPropertiesException("queueId $queueId does not have a DLQ secret access key")
}
}
}
private fun localstackTopicSubscriptionsMustExist(
queueConfig: QueueConfig,
queueId: String
) {
if (provider == "localstack") {
if (queueConfig.subscribeTopicId.isNotEmpty().and(topics.containsKey(queueConfig.subscribeTopicId).not()))
throw InvalidHmppsSqsPropertiesException("queueId $queueId wants to subscribe to ${queueConfig.subscribeTopicId} but it does not exist")
}
}
private fun topicIdMustBeLowerCase(topicId: String) {
if (topicId != topicId.lowercase()) throw InvalidHmppsSqsPropertiesException("topicId $topicId is not lowercase")
}
private fun localstackTopicNameMustExist(topicId: String, topicConfig: TopicConfig) {
if (provider == "localstack") {
if (topicConfig.name.isEmpty()) throw InvalidHmppsSqsPropertiesException("topicId $topicId does not have a name")
}
}
private fun awsTopicSecretsMustExist(topicId: String, topicConfig: TopicConfig) {
if (provider == "aws") {
if (topicConfig.arn.isEmpty()) throw InvalidHmppsSqsPropertiesException("topicId $topicId does not have an arn")
if (topicConfig.accessKeyId.isEmpty()) throw InvalidHmppsSqsPropertiesException("topicId $topicId does not have an access key id")
if (topicConfig.secretAccessKey.isEmpty()) throw InvalidHmppsSqsPropertiesException("topicId $topicId does not have a secret access key")
}
}
private fun checkForAwsDuplicateValues() {
if (provider == "aws") {
mustNotContainDuplicates("queue names", queues, secret = false) { it.value.queueName }
mustNotContainDuplicates("queue access key ids", queues) { it.value.queueAccessKeyId }
mustNotContainDuplicates("queue secret access keys", queues) { it.value.queueSecretAccessKey }
mustNotContainDuplicates("dlq names", queues, secret = false) { it.value.dlqName }
mustNotContainDuplicates("dlq access key ids", queues) { it.value.dlqAccessKeyId }
mustNotContainDuplicates("dlq secret access keys", queues) { it.value.dlqSecretAccessKey }
mustNotContainDuplicates("topic arns", topics, secret = false) { it.value.arn }
mustNotContainDuplicates("topic access key ids", topics) { it.value.accessKeyId }
mustNotContainDuplicates("topic secret access keys", topics) { it.value.secretAccessKey }
}
}
private fun checkForLocalStackDuplicateValues() {
if (provider == "localstack") {
mustNotContainDuplicates("queue names", queues, secret = false) { it.value.queueName }
mustNotContainDuplicates("dlq names", queues, secret = false) { it.value.dlqName }
mustNotContainDuplicates("topic names", topics, secret = false) { it.value.name }
}
}
private fun <T> mustNotContainDuplicates(description: String, source: Map<String, T>, secret: Boolean = true, valueFinder: (Map.Entry<String, T>) -> String) {
val duplicateValues = source.mapValues(valueFinder).values.filter { it.isNotEmpty() }.groupingBy { it }.eachCount().filterValues { it > 1 }
if (duplicateValues.isNotEmpty()) {
val outputValues = if (secret.not()) duplicateValues.keys else duplicateValues.keys.map { "${it?.subSequence(0, 4)}******" }.toList()
throw InvalidHmppsSqsPropertiesException("Found duplicated $description: $outputValues")
}
}
}
class InvalidHmppsSqsPropertiesException(message: String) : IllegalStateException(message)
| 1 | Kotlin | 0 | 2 | a51d6983a20415dca4c6dbac3e499fd09d8f4bb3 | 6,403 | hmpps-spring-boot-sqs | MIT License |
src/main/kotlin/com/fournel/smilodon/config/SecurityConfig.kt | paulfournel | 784,785,441 | false | {"Kotlin": 81945, "Java": 759, "Dockerfile": 114} | package com.fournel.smilodon.config
import com.fournel.smilodon.user.JpaUserDetailsService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.core.userdetails.User
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.web.SecurityFilterChain
@Configuration
@EnableWebSecurity
class SecurityConfig(val jpaUserDetailsService: JpaUserDetailsService) {
@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
@Bean
@Throws(Exception::class)
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http.csrf().disable().cors().disable()
.authorizeHttpRequests { requests ->
requests
.antMatchers("/").permitAll()
.antMatchers("/follow").permitAll()
.antMatchers("/process_login").permitAll()
.antMatchers("/open-api/**").permitAll()
.antMatchers("/.well-known/**").permitAll()
.anyRequest().authenticated()
}
.userDetailsService(jpaUserDetailsService)
.formLogin { form ->
form
.loginPage("/error")
.loginProcessingUrl("/process_login")
.successHandler(SimpleSuccessAuthenticationSuccessHandler())
.permitAll()
}
.logout { logout -> logout.permitAll().logoutSuccessUrl("/") }
return http.build()
}
} | 0 | Kotlin | 0 | 2 | 3d332bc86a1eef4c1256e419570bfeba71e11eaf | 1,946 | smilodon-backend | MIT License |
olm/src/commonTest/kotlin/io/github/matrixkt/olm/Utils.common.kt | Dominaezzz | 205,671,029 | false | null | package io.github.matrixkt.olm
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@OptIn(ExperimentalContracts::class)
inline fun <T> withAccount(block: (Account) -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
val account = Account()
return try {
block(account)
} finally {
account.clear()
}
}
| 6 | Kotlin | 8 | 28 | 522e067eec51883f4859753c5ad9240a9535544f | 438 | matrix-kt | Apache License 2.0 |
xsolla-login-sdk/src/main/java/com/xsolla/android/login/entity/request/AuthViaDeviceIdBody.kt | xsolla | 233,092,015 | false | null | package com.xsolla.android.login.entity.request
import com.google.gson.annotations.SerializedName
data class AuthViaDeviceIdBody(
val device : String,
@SerializedName("device_id")
val deviceId: String
) | 1 | Kotlin | 5 | 9 | cf3861e571f3ebc45490d39c40b0f2698e835b2f | 216 | store-android-sdk | Apache License 2.0 |
composeApp/src/desktopMain/kotlin/main.kt | joreilly | 728,800,937 | false | null | import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
fun main() = application {
Window(onCloseRequest = ::exitApplication, title = "kotlin-multiplatform") {
App()
}
}
@Preview
@Composable
fun AppDesktopPreview() {
App()
}
| 6 | null | 8 | 98 | e3459b6bad15fbaa29ad544627fa121ec2df7b87 | 380 | ClimateTraceKMP | Apache License 2.0 |
app/src/main/java/com/alexbezhan/instagram/data/firebase/FirebaseUsersRepository.kt | alexbezhan | 129,704,036 | false | null | package com.app.instagram.data.firebase
import android.net.Uri
import androidx.lifecycle.LiveData
import com.app.instagram.common.Event
import com.app.instagram.common.EventBus
import com.app.instagram.common.task
import com.app.instagram.common.toUnit
import com.app.instagram.data.UsersRepository
import com.app.instagram.data.common.map
import com.app.instagram.data.firebase.common.*
import com.app.instagram.models.User
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
class FirebaseUsersRepository : UsersRepository {
override fun setUserImage(uid: String, downloadUri: Uri): Task<Unit> =
database.child("images").child(uid).push()
.setValue(downloadUri.toString()).toUnit()
override fun uploadUserImage(uid: String, imageUri: Uri): Task<Uri> =
task { taskSource ->
storage.child("users").child(uid).child("images")
.child(imageUri.lastPathSegment!!).putFile(imageUri)
.addOnCompleteListener {
if (it.isSuccessful) {
it.result?.storage?.downloadUrl?.addOnSuccessListener {
taskSource.setResult(it)
}
} else {
taskSource.setException(it.exception!!)
}
}
}
override fun createUser(user: User, password: String): Task<Unit> =
auth.createUserWithEmailAndPassword(user.email, password).onSuccessTask {
database.child("users").child(it!!.user!!.uid).setValue(user)
}.toUnit()
override fun isUserExistsForEmail(email: String): Task<Boolean> =
auth.fetchSignInMethodsForEmail(email).onSuccessTask {
val signInMethods = it?.signInMethods ?: emptyList<String>()
Tasks.forResult(signInMethods.isNotEmpty())
}
override fun getImages(uid: String): LiveData<List<String>> =
FirebaseLiveData(database.child("images").child(uid)).map {
it.children.map { it.getValue(String::class.java)!! }
}
override fun getUsers(): LiveData<List<User>> =
database.child("users").liveData().map {
it.children.map { it.asUser()!! }
}
override fun addFollow(fromUid: String, toUid: String): Task<Unit> =
getFollowsRef(fromUid, toUid).setValue(true).toUnit()
.addOnSuccessListener {
EventBus.publish(Event.CreateFollow(fromUid, toUid))
}
override fun deleteFollow(fromUid: String, toUid: String): Task<Unit> =
getFollowsRef(fromUid, toUid).removeValue().toUnit()
override fun addFollower(fromUid: String, toUid: String): Task<Unit> =
getFollowersRef(fromUid, toUid).setValue(true).toUnit()
override fun deleteFollower(fromUid: String, toUid: String): Task<Unit> =
getFollowersRef(fromUid, toUid).removeValue().toUnit()
private fun getFollowsRef(fromUid: String, toUid: String) =
database.child("users").child(fromUid).child("follows").child(toUid)
private fun getFollowersRef(fromUid: String, toUid: String) =
database.child("users").child(toUid).child("followers").child(fromUid)
override fun currentUid() = FirebaseAuth.getInstance().currentUser?.uid
override fun updateUserProfile(currentUser: User, newUser: User): Task<Unit> {
val updatesMap = mutableMapOf<String, Any?>()
if (newUser.name != currentUser.name) updatesMap["name"] = newUser.name
if (newUser.username != currentUser.username) updatesMap["username"] = newUser.username
if (newUser.website != currentUser.website) updatesMap["website"] = newUser.website
if (newUser.bio != currentUser.bio) updatesMap["bio"] = newUser.bio
if (newUser.email != currentUser.email) updatesMap["email"] = newUser.email
if (newUser.phone != currentUser.phone) updatesMap["phone"] = newUser.phone
return database.child("users").child(currentUid()!!).updateChildren(updatesMap).toUnit()
}
override fun updateEmail(currentEmail: String, newEmail: String, password: String): Task<Unit> {
val currentUser = auth.currentUser
return if (currentUser != null) {
val credential = EmailAuthProvider.getCredential(currentEmail, password)
currentUser.reauthenticate(credential).onSuccessTask {
currentUser.updateEmail(newEmail)
}.toUnit()
} else {
Tasks.forException(IllegalStateException("User is not authenticated"))
}
}
override fun uploadUserPhoto(localImage: Uri): Task<Uri> =
task { taskSource ->
storage.child("users/${currentUid()!!}/photo").putFile(localImage)
.addOnSuccessListener {
it.storage.downloadUrl.addOnSuccessListener { taskSource.setResult(it) }
}
}
override fun updateUserPhoto(downloadUrl: Uri): Task<Unit> =
database.child("users/${currentUid()!!}/photo").setValue(downloadUrl.toString()).toUnit()
override fun getUser(): LiveData<User> = getUser(currentUid()!!)
override fun getUser(uid: String): LiveData<User> =
database.child("users").child(uid).liveData().map {
it.asUser()!!
}
private fun DataSnapshot.asUser(): User? =
getValue(User::class.java)?.copy(uid = key!!)
} | 4 | null | 58 | 177 | a55df4aa21d4c728fc415483796a98cf2c288be2 | 5,541 | Instagram-Clone-Kotlin | MIT License |
app/src/main/java/com/alexbezhan/instagram/data/firebase/FirebaseUsersRepository.kt | alexbezhan | 129,704,036 | false | null | package com.app.instagram.data.firebase
import android.net.Uri
import androidx.lifecycle.LiveData
import com.app.instagram.common.Event
import com.app.instagram.common.EventBus
import com.app.instagram.common.task
import com.app.instagram.common.toUnit
import com.app.instagram.data.UsersRepository
import com.app.instagram.data.common.map
import com.app.instagram.data.firebase.common.*
import com.app.instagram.models.User
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
class FirebaseUsersRepository : UsersRepository {
override fun setUserImage(uid: String, downloadUri: Uri): Task<Unit> =
database.child("images").child(uid).push()
.setValue(downloadUri.toString()).toUnit()
override fun uploadUserImage(uid: String, imageUri: Uri): Task<Uri> =
task { taskSource ->
storage.child("users").child(uid).child("images")
.child(imageUri.lastPathSegment!!).putFile(imageUri)
.addOnCompleteListener {
if (it.isSuccessful) {
it.result?.storage?.downloadUrl?.addOnSuccessListener {
taskSource.setResult(it)
}
} else {
taskSource.setException(it.exception!!)
}
}
}
override fun createUser(user: User, password: String): Task<Unit> =
auth.createUserWithEmailAndPassword(user.email, password).onSuccessTask {
database.child("users").child(it!!.user!!.uid).setValue(user)
}.toUnit()
override fun isUserExistsForEmail(email: String): Task<Boolean> =
auth.fetchSignInMethodsForEmail(email).onSuccessTask {
val signInMethods = it?.signInMethods ?: emptyList<String>()
Tasks.forResult(signInMethods.isNotEmpty())
}
override fun getImages(uid: String): LiveData<List<String>> =
FirebaseLiveData(database.child("images").child(uid)).map {
it.children.map { it.getValue(String::class.java)!! }
}
override fun getUsers(): LiveData<List<User>> =
database.child("users").liveData().map {
it.children.map { it.asUser()!! }
}
override fun addFollow(fromUid: String, toUid: String): Task<Unit> =
getFollowsRef(fromUid, toUid).setValue(true).toUnit()
.addOnSuccessListener {
EventBus.publish(Event.CreateFollow(fromUid, toUid))
}
override fun deleteFollow(fromUid: String, toUid: String): Task<Unit> =
getFollowsRef(fromUid, toUid).removeValue().toUnit()
override fun addFollower(fromUid: String, toUid: String): Task<Unit> =
getFollowersRef(fromUid, toUid).setValue(true).toUnit()
override fun deleteFollower(fromUid: String, toUid: String): Task<Unit> =
getFollowersRef(fromUid, toUid).removeValue().toUnit()
private fun getFollowsRef(fromUid: String, toUid: String) =
database.child("users").child(fromUid).child("follows").child(toUid)
private fun getFollowersRef(fromUid: String, toUid: String) =
database.child("users").child(toUid).child("followers").child(fromUid)
override fun currentUid() = FirebaseAuth.getInstance().currentUser?.uid
override fun updateUserProfile(currentUser: User, newUser: User): Task<Unit> {
val updatesMap = mutableMapOf<String, Any?>()
if (newUser.name != currentUser.name) updatesMap["name"] = newUser.name
if (newUser.username != currentUser.username) updatesMap["username"] = newUser.username
if (newUser.website != currentUser.website) updatesMap["website"] = newUser.website
if (newUser.bio != currentUser.bio) updatesMap["bio"] = newUser.bio
if (newUser.email != currentUser.email) updatesMap["email"] = newUser.email
if (newUser.phone != currentUser.phone) updatesMap["phone"] = newUser.phone
return database.child("users").child(currentUid()!!).updateChildren(updatesMap).toUnit()
}
override fun updateEmail(currentEmail: String, newEmail: String, password: String): Task<Unit> {
val currentUser = auth.currentUser
return if (currentUser != null) {
val credential = EmailAuthProvider.getCredential(currentEmail, password)
currentUser.reauthenticate(credential).onSuccessTask {
currentUser.updateEmail(newEmail)
}.toUnit()
} else {
Tasks.forException(IllegalStateException("User is not authenticated"))
}
}
override fun uploadUserPhoto(localImage: Uri): Task<Uri> =
task { taskSource ->
storage.child("users/${currentUid()!!}/photo").putFile(localImage)
.addOnSuccessListener {
it.storage.downloadUrl.addOnSuccessListener { taskSource.setResult(it) }
}
}
override fun updateUserPhoto(downloadUrl: Uri): Task<Unit> =
database.child("users/${currentUid()!!}/photo").setValue(downloadUrl.toString()).toUnit()
override fun getUser(): LiveData<User> = getUser(currentUid()!!)
override fun getUser(uid: String): LiveData<User> =
database.child("users").child(uid).liveData().map {
it.asUser()!!
}
private fun DataSnapshot.asUser(): User? =
getValue(User::class.java)?.copy(uid = key!!)
} | 4 | null | 58 | 177 | a55df4aa21d4c728fc415483796a98cf2c288be2 | 5,541 | Instagram-Clone-Kotlin | MIT License |
idea/testData/wordSelection/TypeParameters/2.kt | JakeWharton | 99,388,807 | true | null | fun <selection><A, <caret>B></selection> foo() {
}
| 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 51 | kotlin | Apache License 2.0 |
app/src/main/java/cn/cqautotest/sunnybeach/ui/adapter/msg/LikeMsgAdapter.kt | anjiemo | 378,095,612 | false | null | package cn.cqautotest.sunnybeach.ui.adapter.msg
import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.core.text.parseAsHtml
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.RecyclerView
import cn.cqautotest.sunnybeach.databinding.LikeMsgListItemBinding
import cn.cqautotest.sunnybeach.ktx.*
import cn.cqautotest.sunnybeach.model.msg.LikeMsg
import cn.cqautotest.sunnybeach.ui.adapter.delegate.AdapterDelegate
import com.google.android.material.badge.BadgeUtils
/**
* author : <NAME>
* github : https://github.com/anjiemo/SunnyBeach
* time : 2021/10/25
* desc : 点赞列表消息适配器
*/
class LikeMsgAdapter(private val adapterDelegate: AdapterDelegate) :
PagingDataAdapter<LikeMsg.Content, LikeMsgAdapter.LikeMsgViewHolder>(diffCallback) {
inner class LikeMsgViewHolder(val binding: LikeMsgListItemBinding) : RecyclerView.ViewHolder(binding.root) {
constructor(parent: ViewGroup) : this(parent.asViewBinding<LikeMsgListItemBinding>())
@SuppressLint("UnsafeOptInUsageError")
fun onBinding(item: LikeMsg.Content?, position: Int) {
item ?: return
with(binding) {
ivAvatar.loadAvatar(false, item.avatar)
ivAvatar.post {
createDefaultStyleBadge(context, 0).apply {
BadgeUtils.attachBadgeDrawable(this, ivAvatar)
horizontalOffset = 12
verticalOffset = 12
isVisible = item.isRead.not()
}
}
cbNickName.text = item.nickname
tvDesc.text = item.timeText
tvReplyMsg.height = 0
tvChildReplyMsg.setDefaultEmojiParser()
tvChildReplyMsg.text = item.title.parseAsHtml()
}
}
}
override fun onViewAttachedToWindow(holder: LikeMsgViewHolder) {
super.onViewAttachedToWindow(holder)
adapterDelegate.onViewAttachedToWindow(holder)
}
override fun onBindViewHolder(holder: LikeMsgViewHolder, position: Int) {
holder.itemView.setFixOnClickListener { adapterDelegate.onItemClick(it, position) }
holder.onBinding(getItem(position), position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LikeMsgViewHolder = LikeMsgViewHolder(parent)
companion object {
private val diffCallback =
itemDiffCallback<LikeMsg.Content>({ oldItem, newItem -> oldItem.id == newItem.id }) { oldItem, newItem -> oldItem == newItem }
}
} | 0 | null | 18 | 95 | a2402da1cb6af963c829a69d9783053f15d866b5 | 2,595 | SunnyBeach | Apache License 2.0 |
core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectionObjectRenderer.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.reflect.jvm.internal
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.types.KotlinType
import kotlin.reflect.KParameter
internal object ReflectionObjectRenderer {
private val renderer = DescriptorRenderer.FQ_NAMES_IN_TYPES
private fun StringBuilder.appendReceiverType(receiver: ReceiverParameterDescriptor?) {
if (receiver != null) {
append(renderType(receiver.type))
append(".")
}
}
private fun StringBuilder.appendReceiversAndName(callable: CallableDescriptor) {
val dispatchReceiver = callable.dispatchReceiverParameter
val extensionReceiver = callable.extensionReceiverParameter
appendReceiverType(dispatchReceiver)
val addParentheses = dispatchReceiver != null && extensionReceiver != null
if (addParentheses) append("(")
appendReceiverType(extensionReceiver)
if (addParentheses) append(")")
append(renderer.renderName(callable.name))
}
fun renderCallable(descriptor: CallableDescriptor): String {
return when (descriptor) {
is PropertyDescriptor -> renderProperty(descriptor)
is FunctionDescriptor -> renderFunction(descriptor)
else -> error("Illegal callable: $descriptor")
}
}
// TODO: include visibility
fun renderProperty(descriptor: PropertyDescriptor): String {
return StringBuilder {
append(if (descriptor.isVar) "var " else "val ")
appendReceiversAndName(descriptor)
append(": ")
append(renderType(descriptor.type))
}.toString()
}
fun renderFunction(descriptor: FunctionDescriptor): String {
return StringBuilder {
append("fun ")
appendReceiversAndName(descriptor)
descriptor.valueParameters.joinTo(this, separator = ", ", prefix = "(", postfix = ")") {
renderType(it.type) // TODO: vararg
}
append(": ")
append(renderType(descriptor.returnType!!))
}.toString()
}
fun renderParameter(parameter: KParameterImpl): String {
return StringBuilder {
when (parameter.kind) {
KParameter.Kind.EXTENSION_RECEIVER -> append("extension receiver")
KParameter.Kind.INSTANCE -> append("instance")
KParameter.Kind.VALUE -> append("parameter #${parameter.index} ${parameter.name}")
}
append(" of ")
append(renderCallable(parameter.callable.descriptor))
}.toString()
}
fun renderType(type: KotlinType): String {
return renderer.renderType(type)
}
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 3,566 | kotlin | Apache License 2.0 |
demos/src/main/kotlin/scenes/MultipleObjects.kt | hannomalie | 330,376,962 | false | {"Kotlin": 1068277, "GLSL": 681257, "JavaScript": 3160, "Shell": 137, "Batchfile": 65} | package scenes
import de.hanno.hpengine.Engine
import de.hanno.hpengine.camera.Camera
import de.hanno.hpengine.component.CameraComponent
import de.hanno.hpengine.component.NameComponent
import de.hanno.hpengine.component.TransformComponent
import de.hanno.hpengine.graphics.envprobe.EnvironmentProbeComponent
import de.hanno.hpengine.graphics.light.point.PointLightComponent
import de.hanno.hpengine.transform.AABBData
import de.hanno.hpengine.world.addAnimatedModelEntity
import de.hanno.hpengine.world.addStaticModelEntity
import de.hanno.hpengine.world.loadScene
import org.joml.Vector3f
import java.util.concurrent.CompletableFuture
fun main() {
val demoAndEngineConfig = createDemoAndEngineConfig()
val engine = createEngine(demoAndEngineConfig)
engine.runMultipleObjects()
}
fun Engine.runMultipleObjects() {
world.loadScene {
addStaticModelEntity("Sponza", "assets/models/sponza.obj")
addStaticModelEntity("Ferrari", "assets/models/ferrari.obj", translation = Vector3f(100f, 10f, 0f))
addAnimatedModelEntity(
"Hellknight",
"assets/models/doom3monster/monster.md5mesh",
AABBData(
Vector3f(-60f, -10f, -35f),
Vector3f(60f, 130f, 50f)
)
)
addAnimatedModelEntity(
"Bob",
"assets/models/bob_lamp_update/bob_lamp_update_export.md5mesh",
AABBData( // This is not accurate, but big enough to not cause culling problems
Vector3f(-60f, -10f, -35f),
Vector3f(60f, 130f, 50f)
)
)
edit(create()).apply {
val transform = create(TransformComponent::class.java)
create(PointLightComponent::class.java)
add(NameComponent().apply { name = "PointLight" })
add(
CameraComponent(Camera(transform.transform))
)
}
val addEnvironmentProbes = false
if (addEnvironmentProbes) {
edit(create()).apply {
create(TransformComponent::class.java)
create(EnvironmentProbeComponent::class.java).apply {
size.set(100f)
}
add(NameComponent().apply { name = "EnvProbe0" })
}
edit(create()).apply {
create(TransformComponent::class.java).apply {
transform.translation(Vector3f(30f, 50f, 20f))
}
create(EnvironmentProbeComponent::class.java).apply {
size.set(100f)
}
add(NameComponent().apply { name = "EnvProbe1" })
}
}
}
simulate()
}
| 0 | Kotlin | 0 | 0 | d0ecc78d2d90033758d480b2383d8d5c3d2febd3 | 2,709 | hpengine | MIT License |
project-system-gradle/src/com/android/tools/idea/projectsystem/gradle/GradleClassFileFinder.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2018 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.projectsystem.gradle
import com.android.SdkConstants
import com.android.tools.idea.flags.StudioFlags
import com.android.tools.idea.projectsystem.ClassContent
import com.android.tools.idea.projectsystem.ClassFileFinder
import com.android.tools.idea.projectsystem.ProjectBuildTracker
import com.android.tools.idea.projectsystem.ProjectSyncModificationTracker
import com.android.tools.idea.projectsystem.getPathFromFqcn
import com.android.tools.idea.rendering.classloading.loaders.JarManager
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.Key
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.ParameterizedCachedValue
import com.intellij.psi.util.ParameterizedCachedValueProvider
import java.nio.file.Files
import java.nio.file.Path
import java.util.Optional
import java.util.regex.Pattern
import kotlin.io.path.extension
import kotlin.io.path.isRegularFile
/**
* [CompileRoots] of a module, including dependencies. [directories] is the list of paths to
* directories containing class outputs. [jars] constains a list of the jar outputs in the
* [CompileRoots] (typically R.jar files).
*/
private data class CompileRoots(val allRoots: List<Path>, val jarManager: JarManager?) {
private val RESOURCE_CLASS_NAME = Pattern.compile(".+\\.R(\\$[^.]+)?$")
/** Returns true if [className] is an R class name. */
private fun isResourceClassName(className: String): Boolean =
RESOURCE_CLASS_NAME.matcher(className).matches()
/** Cache to avoid querying the CompileRoots on every query since many of them are repeated. */
private val cache: Cache<String, Optional<ClassContent>> =
CacheBuilder.newBuilder()
.softValues()
.maximumSize(StudioFlags.GRADLE_CLASS_FINDER_CACHE_LIMIT.get())
.build()
/** List of paths to directories containing class outputs */
private val directories: List<Path>
get() = allRoots
.filter { Files.isDirectory(it) }
/** Contains a list of the jar outputs in the [CompileRoots] (typically R.jar files) */
private val jars: List<Path> by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
allRoots.filter { it.isRegularFile() && it.extension == SdkConstants.EXT_JAR }
}
/** Finds a class in the directories included in this [CompileRoots]. */
private fun findClassInDirectoryRoots(fqcn: String): ClassContent? {
return directories
.map { it.resolve(getPathFromFqcn(fqcn)).toFile() }
.firstOrNull { it.isFile() }
?.let { ClassContent.loadFromFile(it) }
}
/** Finds a class in the jars included in this [CompileRoots]. */
private fun findClassInJarRoots(fqcn: String): ClassContent? {
val entryPath = getPathFromFqcn(fqcn)
return jars.firstNotNullOfOrNull {
val bytes = jarManager?.loadFileFromJar(it, entryPath) ?: return@firstNotNullOfOrNull null
ClassContent.fromJarEntryContent(it.toFile(), bytes)
}
}
fun findClass(fqcn: String): ClassContent? =
cache
.get(fqcn) {
Optional.ofNullable(
if (isResourceClassName(fqcn)) {
findClassInJarRoots(fqcn) ?: findClassInDirectoryRoots(fqcn)
} else {
findClassInDirectoryRoots(fqcn) ?: findClassInJarRoots(fqcn)
}
)
}
.orElse(null)
companion object {
val EMPTY = CompileRoots(listOf(), null)
}
}
/**
* Calculates the output roots for the module, including all the dependencies. If
* [includeAndroidTests] is true, the output roots for test dependencies will be included.
*/
private fun Module.getNonCachedCompileOutputsIncludingDependencies(
includeAndroidTests: Boolean
): CompileRoots =
CompileRoots(
(this.getAllDependencies(includeAndroidTests))
.flatMap {
GradleClassFinderUtil.getModuleCompileOutputs(it, includeAndroidTests).toList()
}
.map { it.toPath() }
.toList(),
JarManager.getInstance(project),
)
.also {
Logger.getInstance(GradleClassFileFinder::class.java).debug("CompileRoots recalculated $it")
}
/**
* Returns a set containing the current [Module] and all its direct and transitive dependencies.
*/
fun Module.getAllDependencies(includeAndroidTests: Boolean): Set<Module> {
val dependencies = mutableSetOf(this)
val queue = ArrayDeque<Module>()
queue.add(this)
while (queue.isNotEmpty()) {
ModuleRootManager.getInstance(queue.removeFirst()).getDependencies(includeAndroidTests).forEach {
if (dependencies.add(it)) {
queue.add(it)
}
}
}
return dependencies
}
/** Key used to cache the [CompileRoots] for a non test module. */
private val PRODUCTION_ROOTS_KEY: Key<ParameterizedCachedValue<CompileRoots, Module>> =
Key.create("production roots")
/** [ParameterizedCachedValueProvider] to calculate the output roots for a non test module. */
private val PRODUCTION_ROOTS_PROVIDER =
ParameterizedCachedValueProvider<CompileRoots, Module> { module ->
CachedValueProvider.Result.create(
module.getNonCachedCompileOutputsIncludingDependencies(false),
ProjectSyncModificationTracker.getInstance(module.project),
ProjectBuildTracker.getInstance(module.project)
)
}
/** Key used to cache the [CompileRoots] for a test module. */
private val TEST_ROOTS_KEY: Key<ParameterizedCachedValue<CompileRoots, Module>> =
Key.create("test roots")
/** [ParameterizedCachedValueProvider] to calculated the output roots for a test module. */
private val TEST_ROOTS_PROVIDER =
ParameterizedCachedValueProvider<CompileRoots, Module> { module ->
CachedValueProvider.Result.create(
module.getNonCachedCompileOutputsIncludingDependencies(true),
ProjectSyncModificationTracker.getInstance(module.project),
ProjectBuildTracker.getInstance(module.project)
)
}
/** Returns the list of [Path]s to external JAR files referenced by the class loader. */
private fun Module.getCompileOutputs(includeAndroidTests: Boolean): CompileRoots {
if (this.isDisposed) {
return CompileRoots.EMPTY
}
return if (includeAndroidTests) {
CachedValuesManager.getManager(project)
.getParameterizedCachedValue(this, TEST_ROOTS_KEY, TEST_ROOTS_PROVIDER, false, this)
} else {
CachedValuesManager.getManager(project)
.getParameterizedCachedValue(
this,
PRODUCTION_ROOTS_KEY,
PRODUCTION_ROOTS_PROVIDER,
false,
this
)
}
}
/** A [ClassFileFinder] that finds classes into the compile roots of a Gradle project. */
class GradleClassFileFinder
private constructor(private val module: Module, private val includeAndroidTests: Boolean) :
ClassFileFinder {
override fun findClassFile(fqcn: String): ClassContent? {
return module.getCompileOutputs(includeAndroidTests).findClass(fqcn)
}
companion object {
@JvmOverloads
fun create(module: Module, includeAndroidTests: Boolean = false) =
GradleClassFileFinder(module, includeAndroidTests)
}
}
| 3 | null | 221 | 925 | 71cc8d80cd2fa6899d69c7f908539c5a4ad08265 | 7,817 | android | Apache License 2.0 |
embrace-android-payload/src/main/kotlin/io/embrace/android/embracesdk/internal/config/instrumented/RedactionConfig.kt | embrace-io | 704,537,857 | false | {"Kotlin": 2981564, "C": 189341, "Java": 150268, "C++": 13140, "CMake": 4261} | package io.embrace.android.embracesdk.internal.config.instrumented
/**
* Declares how the SDK should redact sensitive data
*/
@Suppress("FunctionOnlyReturningConstant")
@Swazzled
object RedactionConfig {
/**
* Provides a list of sensitive keys whose values should be redacted on capture.
*
* sdk_config.sensitive_keys_denylist
*/
fun getSensitiveKeysDenylist(): List<String>? = null
}
| 11 | Kotlin | 11 | 134 | 896e9aadf568ba527c76ec66f6f440baed29d1ee | 417 | embrace-android-sdk | Apache License 2.0 |
ui/src/main/java/com/mpapps/marvelcompose/ui/views/character/viewmodel/CharacterDetailViewModel.kt | Erickjhoel | 856,824,213 | false | {"Kotlin": 72528} | package com.mpapps.marvelcompose.ui.views.character.viewmodel
import android.net.Uri
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.mpapps.marvelcompose.domain.model.Characters
import com.mpapps.marvelcompose.domain.usecase.GetComicFromCharacterUseCase
import com.mpapps.marvelcompose.ui.infrastructure.BaseViewModel
import com.mpapps.marvelcompose.ui.infrastructure.error.UiError
import com.mpapps.marvelcompose.ui.views.character.state.CharacterDetailEffect
import com.mpapps.marvelcompose.ui.views.character.state.CharacterDetailEvent
import com.mpapps.marvelcompose.ui.views.character.state.CharacterDetailViewState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
internal class CharacterDetailViewModel @Inject constructor(
private val getComicFromCharacterUseCase: GetComicFromCharacterUseCase,
) : BaseViewModel<CharacterDetailEffect, CharacterDetailEvent, CharacterDetailViewState>() {
override fun setInitialState(): CharacterDetailViewState {
return CharacterDetailViewState(character = null)
}
override fun onEvent(event: CharacterDetailEvent) {
when (event) {
is CharacterDetailEvent.InitData -> initData(event.jsonCharacter)
}
}
private fun initData(jsonCharacter: String) {
val decodeJson = Uri.decode(jsonCharacter)
val characters = Gson().fromJson(decodeJson, Characters::class.java)
setState {
copy(character = characters)
}
getComics(characters.id)
}
private fun getComics(characterId: String) {
viewModelScope.launch {
getComicFromCharacterUseCase(characterId).collectLatest { result ->
result.fold({
handleError(it) {
setState {
copy(
isLoading = false,
uiError = UiError(it),
)
}
}
}) { data ->
setState {
copy(comicList = data)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 4e6140ca82dbe9e143f6aa3ea9aa2d64fefce1af | 2,307 | skeleton-Compose | Apache License 2.0 |
zoomimage-compose-sketch/src/main/java/com/github/panpf/zoomimage/compose/sketch/internal/AsyncImage.kt | panpf | 647,222,866 | false | null | package com.github.panpf.sketch.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.DefaultAlpha
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.drawscope.DrawScope.Companion.DefaultFilterQuality
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Constraints
import com.github.panpf.sketch.compose.AsyncImagePainter.Companion.DefaultTransform
import com.github.panpf.sketch.compose.AsyncImagePainter.State
import com.github.panpf.sketch.compose.internal.AsyncImageScaleDecider
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.resize.FixedScaleDecider
import com.github.panpf.sketch.resize.SizeResolver
import com.github.panpf.sketch.util.ifOrNull
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.mapNotNull
import com.github.panpf.sketch.util.Size as SketchSize
/**
* A composable that executes an [DisplayRequest] asynchronously and renders the result.
*
* @param imageUri [DisplayRequest.uriString] value.
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param placeholder A [Painter] that is displayed while the image is loading.
* @param error A [Painter] that is displayed when the image request is unsuccessful.
* @param uriEmpty A [Painter] that is displayed when the request's [DisplayRequest.uriString] is empty.
* @param onLoading Called when the image request begins loading.
* @param onSuccess Called when the image request completes successfully.
* @param onError Called when the image request completes unsuccessfully.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun AsyncImage(
imageUri: String?,
contentDescription: String?,
modifier: Modifier = Modifier,
placeholder: Painter? = null,
error: Painter? = null,
uriEmpty: Painter? = error,
onLoading: ((State.Loading) -> Unit)? = null,
onSuccess: ((State.Success) -> Unit)? = null,
onError: ((State.Error) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DefaultFilterQuality,
) = AsyncImage(
request = DisplayRequest(LocalContext.current, imageUri),
contentDescription = contentDescription,
modifier = modifier,
transform = transformOf(placeholder, error, uriEmpty),
onState = onStateOf(onLoading, onSuccess, onError),
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
filterQuality = filterQuality,
)
/**
* A composable that executes an [DisplayRequest] asynchronously and renders the result.
*
* @param imageUri [DisplayRequest.uriString] value.
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param placeholder A [Painter] that is displayed while the image is loading.
* @param error A [Painter] that is displayed when the image request is unsuccessful.
* @param uriEmpty A [Painter] that is displayed when the request's [DisplayRequest.uriString] is empty.
* @param onLoading Called when the image request begins loading.
* @param onSuccess Called when the image request completes successfully.
* @param onError Called when the image request completes unsuccessfully.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
@Deprecated(
"Please use the request version",
replaceWith = ReplaceWith("AsyncImage(request = DisplayRequest(LocalContext.current, imageUri), ...)")
)
fun AsyncImage(
imageUri: String?,
contentDescription: String?,
modifier: Modifier = Modifier,
placeholder: Painter? = null,
error: Painter? = null,
uriEmpty: Painter? = error,
onLoading: ((State.Loading) -> Unit)? = null,
onSuccess: ((State.Success) -> Unit)? = null,
onError: ((State.Error) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DefaultFilterQuality,
configBlock: (DisplayRequest.Builder.() -> Unit)? = null,
) = AsyncImage(
request = DisplayRequest(LocalContext.current, imageUri, configBlock),
contentDescription = contentDescription,
modifier = modifier,
transform = transformOf(placeholder, error, uriEmpty),
onState = onStateOf(onLoading, onSuccess, onError),
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
filterQuality = filterQuality,
)
/**
* A composable that executes an [DisplayRequest] asynchronously and renders the result.
*
* @param imageUri [DisplayRequest.uriString] value.
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param transform A callback to transform a new [State] before it's applied to the
* [AsyncImagePainter]. Typically this is used to modify the state's [Painter].
* @param onState Called when the state of this painter changes.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun AsyncImage(
imageUri: String?,
contentDescription: String?,
modifier: Modifier = Modifier,
transform: (State) -> State = DefaultTransform,
onState: ((State) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DefaultFilterQuality,
) = AsyncImage(
request = DisplayRequest(LocalContext.current, imageUri),
contentDescription = contentDescription,
modifier = modifier,
transform = transform,
onState = onState,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
filterQuality = filterQuality
)
/**
* A composable that executes an [DisplayRequest] asynchronously and renders the result.
*
* @param imageUri [DisplayRequest.uriString] value.
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param transform A callback to transform a new [State] before it's applied to the
* [AsyncImagePainter]. Typically this is used to modify the state's [Painter].
* @param onState Called when the state of this painter changes.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
@Deprecated(
"Please use the request version",
replaceWith = ReplaceWith("AsyncImage(request = DisplayRequest(LocalContext.current, imageUri), ...)")
)
fun AsyncImage(
imageUri: String?,
contentDescription: String?,
modifier: Modifier = Modifier,
transform: (State) -> State = DefaultTransform,
onState: ((State) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DefaultFilterQuality,
configBlock: (DisplayRequest.Builder.() -> Unit)? = null,
) = AsyncImage(
request = DisplayRequest(LocalContext.current, imageUri, configBlock),
contentDescription = contentDescription,
modifier = modifier,
transform = transform,
onState = onState,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
filterQuality = filterQuality
)
/**
* A composable that executes an [DisplayRequest] asynchronously and renders the result.
*
* @param request [DisplayRequest].
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param placeholder A [Painter] that is displayed while the image is loading.
* @param error A [Painter] that is displayed when the image request is unsuccessful.
* @param uriEmpty A [Painter] that is displayed when the request's [DisplayRequest.uriString] is null.
* @param onLoading Called when the image request begins loading.
* @param onSuccess Called when the image request completes successfully.
* @param onError Called when the image request completes unsuccessfully.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
@NonRestartableComposable
fun AsyncImage(
request: DisplayRequest,
contentDescription: String?,
modifier: Modifier = Modifier,
placeholder: Painter? = null,
error: Painter? = null,
uriEmpty: Painter? = error,
onLoading: ((State.Loading) -> Unit)? = null,
onSuccess: ((State.Success) -> Unit)? = null,
onError: ((State.Error) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DefaultFilterQuality,
) = AsyncImage(
request = request,
contentDescription = contentDescription,
modifier = modifier,
transform = transformOf(placeholder, error, uriEmpty),
onState = onStateOf(onLoading, onSuccess, onError),
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
filterQuality = filterQuality,
)
/**
* A composable that executes an [DisplayRequest] asynchronously and renders the result.
*
* @param request [DisplayRequest].
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param transform A callback to transform a new [State] before it's applied to the
* [AsyncImagePainter]. Typically this is used to modify the state's [Painter].
* @param onState Called when the state of this painter changes.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
*/
@Composable
fun AsyncImage(
request: DisplayRequest,
contentDescription: String?,
modifier: Modifier = Modifier,
transform: (State) -> State = DefaultTransform,
onState: ((State) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DefaultFilterQuality,
) {
// Create and execute the image request.
val newRequest = updateRequest(request, contentScale)
val painter = rememberAsyncImagePainter(
newRequest, transform, onState, contentScale, filterQuality
)
// Draw the content without a parent composable or subcomposition.
val sizeResolver = newRequest.resizeSizeResolver
Content(
modifier = if (sizeResolver is ConstraintsSizeResolver) {
modifier.then(sizeResolver)
} else {
modifier
},
painter = painter,
contentDescription = contentDescription,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter
)
}
/** Draws the current image content. */
@Composable
internal fun Content(
modifier: Modifier,
painter: Painter,
contentDescription: String?,
alignment: Alignment,
contentScale: ContentScale,
alpha: Float,
colorFilter: ColorFilter?,
) = Layout(
modifier = modifier
.contentDescription(contentDescription)
.clipToBounds()
.then(
ContentPainterModifier(
painter = painter,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter
)
),
measurePolicy = { _, constraints ->
layout(constraints.minWidth, constraints.minHeight) {}
}
)
@Composable
internal fun updateRequest(request: DisplayRequest, contentScale: ContentScale): DisplayRequest {
// return if (request.defined.sizeResolver == null) {
// val sizeResolver = if (contentScale == ContentScale.None) {
// SizeResolver(SketchSize.ORIGINAL)
// } else {
// remember { ConstraintsSizeResolver() }
// }
// request.newBuilder().size(sizeResolver).build()
// } else {
// request
// }
val noSizeResolver = request.definedOptions.resizeSizeResolver == null
val noResetScale = request.definedOptions.resizeScaleDecider == null
return if (noSizeResolver || noResetScale) {
val sizeResolver = ifOrNull(noSizeResolver) {
remember { ConstraintsSizeResolver() }
}
request.newDisplayRequest {
// If no other size resolver is set, pauses until the layout size is positive.
if (noSizeResolver && sizeResolver != null) {
resizeSize(sizeResolver)
}
// If no other scale resolver is set, use the content scale.
if (noResetScale) {
resizeScale(AsyncImageScaleDecider(FixedScaleDecider(contentScale.toScale())))
}
}
} else {
request
}
}
/** A [SizeResolver] that computes the size from the constrains passed during the layout phase. */
class ConstraintsSizeResolver : SizeResolver, LayoutModifier {
private val _constraints = MutableStateFlow(ZeroConstraints)
override suspend fun size(): SketchSize =
_constraints.mapNotNull(Constraints::toSizeOrNull).first()
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
// Cache the current constraints.
_constraints.value = constraints
// Measure and layout the content.
val placeable = measurable.measure(constraints)
return layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
fun setConstraints(constraints: Constraints) {
_constraints.value = constraints
}
// Equals and hashCode cannot be implemented because they are used in remember
}
@Stable
private fun Modifier.contentDescription(contentDescription: String?): Modifier {
@Suppress("LiftReturnOrAssignment")
if (contentDescription != null) {
return semantics {
this.contentDescription = contentDescription
this.role = Role.Image
}
} else {
return this
}
}
//@Stable
//private fun Constraints.toSizeOrNull() = when {
// isZero -> null
// else -> SketchSize(
// width = if (hasBoundedWidth) Dimension(maxWidth) else Dimension.Undefined,
// height = if (hasBoundedHeight) Dimension(maxHeight) else Dimension.Undefined
// )
//}
@Stable
private fun Constraints.toSizeOrNull() = when {
isZero -> null
hasBoundedWidth && hasBoundedHeight -> SketchSize(maxWidth, maxHeight)
else -> null
}
| 7 | null | 308 | 42 | c2cc8758b6f3d0ad9b5fca9aed2e51903af555a3 | 21,056 | zoomimage | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/native/KotlinNativeTargetPreset.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
// Old package for compatibility
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.gradle.plugin.mpp
import org.gradle.api.Project
import org.jetbrains.kotlin.compilerRunner.konanHome
import org.jetbrains.kotlin.compilerRunner.konanVersion
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.plugin.PropertiesProvider
import org.jetbrains.kotlin.gradle.targets.native.DisabledNativeTargetsReporter
import org.jetbrains.kotlin.gradle.targets.native.internal.NativeDistributionTypeProvider
import org.jetbrains.kotlin.gradle.targets.native.internal.PlatformLibrariesGenerator
import org.jetbrains.kotlin.gradle.targets.native.internal.setupKotlinNativePlatformDependencies
import org.jetbrains.kotlin.gradle.utils.NativeCompilerDownloader
import org.jetbrains.kotlin.gradle.utils.SingleActionPerProject
import org.jetbrains.kotlin.konan.CompilerVersion
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.konan.target.KonanTarget
abstract class AbstractKotlinNativeTargetPreset<T : KotlinNativeTarget>(
private val name: String,
val project: Project,
val konanTarget: KonanTarget
) : KotlinTargetPreset<T> {
init {
// This is required to obtain Kotlin/Native home in IDE plugin:
setupNativeHomePrivateProperty()
}
override fun getName(): String = name
private fun setupNativeHomePrivateProperty() = with(project) {
if (!hasProperty(KOTLIN_NATIVE_HOME_PRIVATE_PROPERTY))
extensions.extraProperties.set(KOTLIN_NATIVE_HOME_PRIVATE_PROPERTY, konanHome)
}
private val propertiesProvider = PropertiesProvider(project)
private val isKonanHomeOverridden: Boolean
get() = propertiesProvider.nativeHome != null
private fun setupNativeCompiler() = with(project) {
if (!isKonanHomeOverridden) {
val downloader = NativeCompilerDownloader(this)
if (propertiesProvider.nativeReinstall) {
logger.info("Reinstall Kotlin/Native distribution")
downloader.compilerDirectory.deleteRecursively()
}
downloader.downloadIfNeeded()
logger.info("Kotlin/Native distribution: $konanHome")
} else {
logger.info("User-provided Kotlin/Native distribution: $konanHome")
}
val distributionType = NativeDistributionTypeProvider(project).getDistributionType(konanVersion)
if (distributionType.mustGeneratePlatformLibs) {
PlatformLibrariesGenerator(project, konanTarget).generatePlatformLibsIfNeeded()
}
}
protected abstract fun createTargetConfigurator(): KotlinTargetConfigurator<T>
protected abstract fun instantiateTarget(name: String): T
override fun createTarget(name: String): T {
setupNativeCompiler()
val result = instantiateTarget(name).apply {
targetName = name
disambiguationClassifier = name
preset = this@AbstractKotlinNativeTargetPreset
val compilationFactory = KotlinNativeCompilationFactory(this)
compilations = project.container(compilationFactory.itemClass, compilationFactory)
}
createTargetConfigurator().configureTarget(result)
SingleActionPerProject.run(project, "setUpKotlinNativePlatformDependencies") {
project.gradle.projectsEvaluated {
project.setupKotlinNativePlatformDependencies()
}
}
if (!konanTarget.enabledOnCurrentHost) {
with(HostManager()) {
val supportedHosts = enabledByHost.filterValues { konanTarget in it }.keys
DisabledNativeTargetsReporter.reportDisabledTarget(project, result, supportedHosts)
}
}
return result
}
companion object {
private const val KOTLIN_NATIVE_HOME_PRIVATE_PROPERTY = "konanHome"
}
}
open class KotlinNativeTargetPreset(name: String, project: Project, konanTarget: KonanTarget) :
AbstractKotlinNativeTargetPreset<KotlinNativeTarget>(name, project, konanTarget) {
override fun createTargetConfigurator(): KotlinTargetConfigurator<KotlinNativeTarget> =
KotlinNativeTargetConfigurator()
override fun instantiateTarget(name: String): KotlinNativeTarget {
return project.objects.newInstance(KotlinNativeTarget::class.java, project, konanTarget)
}
}
open class KotlinNativeTargetWithHostTestsPreset(name: String, project: Project, konanTarget: KonanTarget) :
AbstractKotlinNativeTargetPreset<KotlinNativeTargetWithHostTests>(name, project, konanTarget) {
override fun createTargetConfigurator(): KotlinNativeTargetWithHostTestsConfigurator =
KotlinNativeTargetWithHostTestsConfigurator()
override fun instantiateTarget(name: String): KotlinNativeTargetWithHostTests =
project.objects.newInstance(KotlinNativeTargetWithHostTests::class.java, project, konanTarget)
}
open class KotlinNativeTargetWithSimulatorTestsPreset(name: String, project: Project, konanTarget: KonanTarget) :
AbstractKotlinNativeTargetPreset<KotlinNativeTargetWithSimulatorTests>(name, project, konanTarget) {
override fun createTargetConfigurator(): KotlinNativeTargetWithSimulatorTestsConfigurator =
KotlinNativeTargetWithSimulatorTestsConfigurator()
override fun instantiateTarget(name: String): KotlinNativeTargetWithSimulatorTests =
project.objects.newInstance(KotlinNativeTargetWithSimulatorTests::class.java, project, konanTarget)
}
internal val KonanTarget.isCurrentHost: Boolean
get() = this == HostManager.host
internal val KonanTarget.enabledOnCurrentHost
get() = HostManager().isEnabled(this)
// KonanVersion doesn't provide an API to compare versions,
// so we have to transform it to KotlinVersion first.
// Note: this check doesn't take into account the meta version (release, eap, dev).
internal fun CompilerVersion.isAtLeast(major: Int, minor: Int, patch: Int): Boolean =
KotlinVersion(this.major, this.minor, this.maintenance).isAtLeast(major, minor, patch)
| 132 | null | 5074 | 40,992 | 57fe6721e3afb154571eb36812fd8ef7ec9d2026 | 6,305 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/animeapp/data/manga/MangaTitleData.kt | Kuxln | 692,382,534 | false | {"Kotlin": 96156} | package com.example.animeapp.data.manga
data class MangaApiResponse (
val data: List<MangaTitleData>? = null,
val links: MangaLinks? = null
)
data class MangaTitleData (
val id: String? = null,
val attributes: MangaAttributes? = null
)
data class MangaLinks (
val next: String? = null
)
data class MangaAttributes (
val canonicalTitle: String? = null,
val description: String? = null,
val averageRating: String? = null,
val startDate: String? = null,
val endDate: String? = null,
val userCount: Int? = null,
val volumeCount: Int? = null,
val chapterCount: Int? = null,
val posterImage: MangaPosterImage? = null
)
data class MangaPosterImage (
val original: String? = null
)
| 0 | Kotlin | 0 | 0 | c1acec56060b4462c6738ff47ac76cae3c5eabd9 | 739 | AnimeApp | Apache License 2.0 |
lib/kt/REC/ephemerisDataLine.kt | DigitalArsenal | 252,182,359 | false | null | // automatically generated by the FlatBuffers compiler, do not modify
import com.google.flatbuffers.BaseVector
import com.google.flatbuffers.BooleanVector
import com.google.flatbuffers.ByteVector
import com.google.flatbuffers.Constants
import com.google.flatbuffers.DoubleVector
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.FloatVector
import com.google.flatbuffers.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
/**
* A single ephemeris data line
*/
@Suppress("unused")
@kotlin.ExperimentalUnsignedTypes
class ephemerisDataLine : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : ephemerisDataLine {
__init(_i, _bb)
return this
}
/**
* Epoch time, in ISO 8601 UTC format
*/
val EPOCH : String?
get() {
val o = __offset(4)
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val EPOCHAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1)
fun EPOCHInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1)
/**
* Position vector X-component km
*/
val X : Double
get() {
val o = __offset(6)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Position vector Y-component km
*/
val Y : Double
get() {
val o = __offset(8)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Position vector Z-component km
*/
val Z : Double
get() {
val o = __offset(10)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Velocity vector X-component km/s
*/
val X_DOT : Double
get() {
val o = __offset(12)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Velocity vector Y-component km/s
*/
val Y_DOT : Double
get() {
val o = __offset(14)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Velocity vector Z-component km/s
*/
val Z_DOT : Double
get() {
val o = __offset(16)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Optional: Acceleration vector X-component km/s/s
*/
val X_DDOT : Double
get() {
val o = __offset(18)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Optional: Acceleration vector Y-component km/s/s
*/
val Y_DDOT : Double
get() {
val o = __offset(20)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
/**
* Optional: Acceleration vector Z-component km/s/s
*/
val Z_DDOT : Double
get() {
val o = __offset(22)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_3_3()
fun getRootAsephemerisDataLine(_bb: ByteBuffer): ephemerisDataLine = getRootAsephemerisDataLine(_bb, ephemerisDataLine())
fun getRootAsephemerisDataLine(_bb: ByteBuffer, obj: ephemerisDataLine): ephemerisDataLine {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createephemerisDataLine(builder: FlatBufferBuilder, EPOCHOffset: Int, X: Double, Y: Double, Z: Double, X_DOT: Double, Y_DOT: Double, Z_DOT: Double, X_DDOT: Double, Y_DDOT: Double, Z_DDOT: Double) : Int {
builder.startTable(10)
addZ_DDOT(builder, Z_DDOT)
addY_DDOT(builder, Y_DDOT)
addX_DDOT(builder, X_DDOT)
addZ_DOT(builder, Z_DOT)
addY_DOT(builder, Y_DOT)
addX_DOT(builder, X_DOT)
addZ(builder, Z)
addY(builder, Y)
addX(builder, X)
addEPOCH(builder, EPOCHOffset)
return endephemerisDataLine(builder)
}
fun startephemerisDataLine(builder: FlatBufferBuilder) = builder.startTable(10)
fun addEPOCH(builder: FlatBufferBuilder, EPOCH: Int) = builder.addOffset(0, EPOCH, 0)
fun addX(builder: FlatBufferBuilder, X: Double) = builder.addDouble(1, X, 0.0)
fun addY(builder: FlatBufferBuilder, Y: Double) = builder.addDouble(2, Y, 0.0)
fun addZ(builder: FlatBufferBuilder, Z: Double) = builder.addDouble(3, Z, 0.0)
fun addX_DOT(builder: FlatBufferBuilder, X_DOT: Double) = builder.addDouble(4, X_DOT, 0.0)
fun addY_DOT(builder: FlatBufferBuilder, Y_DOT: Double) = builder.addDouble(5, Y_DOT, 0.0)
fun addZ_DOT(builder: FlatBufferBuilder, Z_DOT: Double) = builder.addDouble(6, Z_DOT, 0.0)
fun addX_DDOT(builder: FlatBufferBuilder, X_DDOT: Double) = builder.addDouble(7, X_DDOT, 0.0)
fun addY_DDOT(builder: FlatBufferBuilder, Y_DDOT: Double) = builder.addDouble(8, Y_DDOT, 0.0)
fun addZ_DDOT(builder: FlatBufferBuilder, Z_DDOT: Double) = builder.addDouble(9, Z_DDOT, 0.0)
fun endephemerisDataLine(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| 4 | null | 7 | 19 | 0a4bb4828fa8fe30758a2c5180b0b82b59cf17e5 | 5,570 | spacedatastandards.org | Apache License 2.0 |
_dialog/compose-dialog-assertion/src/main/java/io/androidalatan/compose/dialog/assertion/MockComposeAlertDialog.kt | android-alatan | 465,390,434 | false | null | package io.androidalatan.compose.dialog.assertion
import io.androidalatan.compose.dialog.api.ComposeAlertDialog
class MockComposeAlertDialog(
private val positiveButtonClickListener: ComposeAlertDialog.ButtonClickListener?,
private val negativeButtonClickListener: ComposeAlertDialog.ButtonClickListener?
) : ComposeAlertDialog {
var showCount = 0
var dismissCount = 0
private var isShowingFlag = false
override fun show() {
if (!isShowingFlag) {
showCount++
isShowingFlag = true
}
}
override fun isShowing(): Boolean {
return isShowingFlag
}
override fun dismiss() {
if (isShowingFlag) {
dismissCount++
}
}
fun clickPositiveButton() {
if (isShowing()) {
dismiss()
positiveButtonClickListener?.onClick()
}
}
fun clickNegativeButton() {
if (isShowing()) {
dismiss()
negativeButtonClickListener?.onClick()
}
}
} | 1 | Kotlin | 1 | 0 | 360274ca592da67575042469b80487b4e3daf761 | 1,031 | Alerts | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/cognito/ResourceServerScopeDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.cognito
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.cognito.ResourceServerScope
/**
* A scope for ResourceServer.
*
* Example:
* ```
* UserPool pool = new UserPool(this, "Pool");
* ResourceServerScope readOnlyScope =
* ResourceServerScope.Builder.create().scopeName("read").scopeDescription("Read-only access").build();
* ResourceServerScope fullAccessScope =
* ResourceServerScope.Builder.create().scopeName("*").scopeDescription("Full access").build();
* UserPoolResourceServer userServer = pool.addResourceServer("ResourceServer",
* UserPoolResourceServerOptions.builder()
* .identifier("users")
* .scopes(List.of(readOnlyScope, fullAccessScope))
* .build());
* UserPoolClient readOnlyClient = pool.addClient("read-only-client",
* UserPoolClientOptions.builder()
* // ...
* .oAuth(OAuthSettings.builder()
* // ...
* .scopes(List.of(OAuthScope.resourceServer(userServer, readOnlyScope)))
* .build())
* .build());
* UserPoolClient fullAccessClient = pool.addClient("full-access-client",
* UserPoolClientOptions.builder()
* // ...
* .oAuth(OAuthSettings.builder()
* // ...
* .scopes(List.of(OAuthScope.resourceServer(userServer, fullAccessScope)))
* .build())
* .build());
* ```
*/
@CdkDslMarker
public class ResourceServerScopeDsl {
private val cdkBuilder: ResourceServerScope.Builder = ResourceServerScope.Builder.create()
/**
* A description of the scope.
*
* @param scopeDescription A description of the scope.
*/
public fun scopeDescription(scopeDescription: String) {
cdkBuilder.scopeDescription(scopeDescription)
}
/**
* The name of the scope.
*
* @param scopeName The name of the scope.
*/
public fun scopeName(scopeName: String) {
cdkBuilder.scopeName(scopeName)
}
public fun build(): ResourceServerScope = cdkBuilder.build()
}
| 3 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,180 | awscdk-dsl-kotlin | Apache License 2.0 |
libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/kotlin/operations/FragmentModelsBuilder.kt | apollographql | 69,469,299 | false | {"Kotlin": 3463807, "Java": 198208, "CSS": 34435, "HTML": 5844, "JavaScript": 1191} | package com.apollographql.apollo3.compiler.codegen.kotlin.operations
import com.apollographql.apollo3.compiler.codegen.fragmentPackageName
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinOperationsContext
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinSymbols
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.flattenFragmentModels
import com.apollographql.apollo3.compiler.ir.IrFragmentDefinition
import com.apollographql.apollo3.compiler.ir.IrModelGroup
internal class FragmentModelsBuilder(
val context: KotlinOperationsContext,
val fragment: IrFragmentDefinition,
modelGroup: IrModelGroup,
private val addSuperInterface: Boolean,
flatten: Boolean,
) : CgFileBuilder {
private val packageName = context.layout.fragmentPackageName(fragment.filePath)
/**
* For experimental_operationBasedWithInterfaces, fragments may have interfaces that are
* only used locally. In that case, we can generate them as sealed interfaces
*/
private val localInheritance = modelGroup.models.any { !it.isInterface }
private val mainModelName = modelGroup.models.first().modelName
private val modelBuilders = modelGroup.flattenFragmentModels(flatten, context, mainModelName)
.map { model ->
ModelBuilder(
context = context,
model = model,
superClassName = if (addSuperInterface && model.id == fragment.dataModelGroup.baseModelId) KotlinSymbols.FragmentData else null,
path = listOf(packageName),
hasSubclassesInSamePackage = localInheritance,
adaptableWith = null,
isTopLevel = true
)
}
override fun prepare() {
modelBuilders.forEach { it.prepare() }
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = context.layout.fragmentName(fragment.name),
typeSpecs = modelBuilders.map { it.build() }
)
}
} | 174 | Kotlin | 659 | 3,750 | 174cb227efe76672cf2beac1affc7054f6bb2892 | 2,096 | apollo-kotlin | MIT License |
android-compose/inventory-app/app/src/main/java/com/example/inventory/ui/home/HomeViewModel.kt | mrgsrylm | 740,344,950 | false | null | package com.notas.inventory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.notas.inventory.data.Item
import com.notas.inventory.data.ItemsRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
class HoneViewModel(itemsRepository: ItemsRepository) : ViewModel() {
/**
* Holds home ui state. The list of items are retrieved from [ItemsRepository] and mapped to
* [HomeUiState]
*/
val homeUiState: StateFlow<HomeUiState> =
itemsRepository.getAllItemsStream().map { HomeUiState(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS),
initialValue = HomeUiState()
)
companion object {
private const val TIMEOUT_MILLIS = 5_000L
}
}
/**
* Ui State for HomeScreen
*/
data class HomeUiState(val itemList: List<Item> = listOf()) | 0 | null | 0 | 1 | 719dca756600fbdd75c228cd0998ddceb0ac63bc | 1,048 | kotlin-sandbox | MIT License |
core/model/src/main/java/com/tydev/imageGenerator/core/model/data/Message.kt | taiyoungkim | 644,446,711 | false | null | package com.tydev.imagegenerator.core.model.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Message(
@SerialName("role")
val role: String,
@SerialName("content")
val content: String
)
| 0 | Kotlin | 0 | 0 | 67392a8578c4195699cdd48ec6a2f5a978132437 | 267 | ImageGenerator | Apache License 2.0 |
src/jsMain/kotlin/Main.kt | kgit2 | 553,675,958 | false | {"Kotlin": 56864, "Just": 2746, "Rust": 1393, "JavaScript": 624, "Ruby": 354, "Dockerfile": 155} | @file:Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE")
import child_process.ChildProcess
import child_process.ChildProcessByStdio
fun main() {
val module = js("require('child_process')")
val options: dynamic = js("{stdio: [0, 1, 2]}")
val child: ChildProcess = module.spawn("ls", arrayOf("-l"), options) as ChildProcess
console.log(child)
// process.spawnargs()
// console.log(process)
}
| 1 | Kotlin | 0 | 37 | 71039e68febcef6352dfd9b872b7f93a6d83911d | 414 | kommand | Apache License 2.0 |
ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlAdapters.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.curl.internal
import io.ktor.client.engine.*
import io.ktor.client.engine.curl.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.cinterop.*
import libcurl.*
// These should have been CPointer<CURL> and CPointer<CURLM>, I suppose,
// but somehow cinterop tool makes them just opaque pointers.
internal typealias EasyHandle = COpaquePointer
internal typealias MultiHandle = COpaquePointer
internal fun CURLMcode.verify() {
if (this != CURLM_OK) {
throw CurlIllegalStateException("Unexpected curl verify: ${curl_multi_strerror(this)?.toKString()}")
}
}
internal fun CURLcode.verify() {
if (this != CURLE_OK) {
throw CurlIllegalStateException("Unexpected curl verify: ${curl_easy_strerror(this)?.toKString()}")
}
}
internal fun EasyHandle.option(option: CURLoption, optionValue: Int) {
curl_easy_setopt(this, option, optionValue).verify()
}
internal fun EasyHandle.option(option: CURLoption, optionValue: Long) {
curl_easy_setopt(this, option, optionValue).verify()
}
internal fun EasyHandle.option(option: CURLoption, optionValue: CPointer<*>) {
curl_easy_setopt(this, option, optionValue).verify()
}
internal fun EasyHandle.option(option: CURLoption, optionValue: CValuesRef<*>) {
curl_easy_setopt(this, option, optionValue).verify()
}
internal fun EasyHandle.option(option: CURLoption, optionValue: String) {
curl_easy_setopt(this, option, optionValue).verify()
}
internal fun EasyHandle.getInfo(info: CURLINFO, optionValue: CPointer<*>) {
curl_easy_getinfo(this, info, optionValue).verify()
}
internal fun HttpRequestData.headersToCurl(): CPointer<curl_slist> {
var result: CPointer<curl_slist>? = null
mergeHeaders(headers, body) { key, value ->
val header = "$key: $value"
result = curl_slist_append(result, header)
}
result = curl_slist_append(result, "Expect:")
return result!!
}
internal fun UInt.fromCurl(): HttpProtocolVersion = when (this) {
CURL_HTTP_VERSION_1_0 -> HttpProtocolVersion.HTTP_1_0
CURL_HTTP_VERSION_1_1 -> HttpProtocolVersion.HTTP_1_1
CURL_HTTP_VERSION_2_0 -> HttpProtocolVersion.HTTP_2_0
/* old curl fallback */
else -> HttpProtocolVersion.HTTP_1_1
}
| 269 | null | 976 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 2,381 | ktor | Apache License 2.0 |
app/src/main/java/com/adematici/covidturkey/activity/SplashScreen.kt | aticiadem | 338,003,274 | false | null | package com.adematici.covidturkey.activity
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.WindowInsets
import android.view.WindowManager
import com.adematici.covidturkey.R
class SplashScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
@Suppress("Deprecation")
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.R){
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
}
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}, 1500)
}
} | 0 | Kotlin | 0 | 7 | 3299436f9d5b80cd34756684a0291a95a181e8c7 | 1,084 | CovidTurkeyProject | MIT License |
common/src/main/java/com/edgeverse/wallet/common/utils/KotlinExt.kt | finn-exchange | 512,140,809 | false | null | package com.edgeverse.wallet.common.utils
import android.net.Uri
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import java.io.InputStream
import java.math.BigDecimal
import java.math.BigInteger
import java.util.concurrent.TimeUnit
private val PERCENTAGE_MULTIPLIER = 100.toBigDecimal()
fun BigDecimal.fractionToPercentage() = this * PERCENTAGE_MULTIPLIER
fun Float.percentageToFraction() = this / 100f
infix fun Int.floorMod(divisor: Int) = Math.floorMod(this, divisor)
val BigDecimal.isNonNegative: Boolean
get() = signum() >= 0
fun BigInteger?.orZero(): BigInteger = this ?: BigInteger.ZERO
fun Long.daysFromMillis() = TimeUnit.MILLISECONDS.toDays(this)
inline fun <T> List<T>.sumByBigInteger(extractor: (T) -> BigInteger) = fold(BigInteger.ZERO) { acc, element ->
acc + extractor(element)
}
suspend operator fun <T> Deferred<T>.invoke() = await()
inline fun <T> List<T>.sumByBigDecimal(extractor: (T) -> BigDecimal) = fold(BigDecimal.ZERO) { acc, element ->
acc + extractor(element)
}
inline fun <reified T> Any?.castOrNull(): T? {
return this as? T
}
fun <K, V> Map<K, V>.reversed() = HashMap<V, K>().also { newMap ->
entries.forEach { newMap[it.value] = it.key }
}
fun <T> Result<T>.requireException() = exceptionOrNull()!!
fun <T> Result<T>.requireValue() = getOrThrow()!!
fun InputStream.readText() = bufferedReader().use { it.readText() }
fun <T> List<T>.second() = get(1)
fun Int.quantize(factor: Int) = this - this % factor
@Suppress("UNCHECKED_CAST")
inline fun <K, V, R> Map<K, V>.mapValuesNotNull(crossinline mapper: (Map.Entry<K, V>) -> R?): Map<K, R> {
return mapValues(mapper)
.filterNotNull()
}
@Suppress("UNCHECKED_CAST")
inline fun <K, V> Map<K, V?>.filterNotNull(): Map<K, V> {
return filterValues { it != null } as Map<K, V>
}
fun String.bigIntegerFromHex() = removeHexPrefix().toBigInteger(16)
fun String.intFromHex() = removeHexPrefix().toInt(16)
/**
* Complexity: O(n * log(n))
*/
// TODO possible to optimize
fun List<Double>.median(): Double = sorted().let {
val middleRight = it[it.size / 2]
val middleLeft = it[(it.size - 1) / 2] // will be same as middleRight if list size is odd
(middleLeft + middleRight) / 2
}
fun generateLinearSequence(initial: Int, step: Int) = generateSequence(initial) { it + step }
fun <T> Set<T>.toggle(item: T): Set<T> = if (item in this) {
this - item
} else {
this + item
}
fun <T> List<T>.cycle(): Sequence<T> {
var i = 0
return generateSequence { this[i++ % this.size] }
}
inline fun <T> CoroutineScope.lazyAsync(crossinline producer: suspend () -> T) = lazy {
async { producer() }
}
inline fun <T> Iterable<T>.filterToSet(predicate: (T) -> Boolean): Set<T> = filterTo(mutableSetOf(), predicate)
fun String.nullIfEmpty(): String? = if (isEmpty()) null else this
fun String.ensureSuffix(suffix: String) = if (endsWith(suffix)) this else this + suffix
private val NAMED_PATTERN_REGEX = "\\{([a-zA-z]+)\\}".toRegex()
fun String.formatNamed(vararg values: Pair<String, String>) = formatNamed(values.toMap())
/**
* Replaces all parts in form of '{name}' to the corresponding value from values using 'name' as a key.
*
* @return formatted string
*/
fun String.formatNamed(values: Map<String, String>): String {
return NAMED_PATTERN_REGEX.replace(this) { matchResult ->
val argumentName = matchResult.groupValues.second()
values[argumentName] ?: "null"
}
}
inline fun <T> T?.defaultOnNull(lazyProducer: () -> T): T {
return this ?: lazyProducer()
}
fun <T> List<T>.modified(modification: T, condition: (T) -> Boolean): List<T> {
return modified(indexOfFirst(condition), modification)
}
fun <T> List<T>.removed(condition: (T) -> Boolean): List<T> {
return toMutableList().apply { removeAll(condition) }
}
fun <T> List<T>.added(toAdd: T): List<T> {
return toMutableList().apply { add(toAdd) }
}
fun <T> List<T>.modified(index: Int, modification: T): List<T> {
val newList = this.toMutableList()
newList[index] = modification
return newList
}
inline fun <T, R> List<T>.mapToSet(mapper: (T) -> R): Set<R> = mapTo(mutableSetOf(), mapper)
fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean) = indexOfFirst(predicate).takeIf { it >= 0 }
@Suppress("IfThenToElvis")
fun ByteArray?.optionalContentEquals(other: ByteArray?): Boolean {
return if (this == null) {
other == null
} else {
this.contentEquals(other)
}
}
fun Uri.Builder.appendNullableQueryParameter(name: String, value: String?) = apply {
value?.let { appendQueryParameter(name, value) }
}
| 0 | Kotlin | 1 | 0 | 6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d | 4,669 | edgeverse-wallet | Apache License 2.0 |
features/budget/src/main/java/com/anangkur/budgetku/budget/view/selectCategory/SelectCategoryActionListener.kt | anangkur | 270,303,728 | false | null | package com.anangkur.budgetku.budget.view.selectCategory
import com.anangkur.budgetku.budget.model.CategoryUiModel
interface SelectCategoryActionListener {
fun onClickCategory(data: CategoryUiModel)
} | 10 | null | 0 | 3 | 82dc439d0df25cc894de5fc8d2604f1670c6cf31 | 206 | Budget-Ku | MIT License |
eos-chain-actions/src/test/kotlin/com/memtrip/eos/chain/actions/transaction/TransferChainTest.kt | memtrip | 149,500,589 | false | null | package io.golos.commun4j.chain.actions.transaction
import com.memtrip.eos.chain.actions.Config
import com.memtrip.eos.chain.actions.SetupTransactions
import com.memtrip.eos.chain.actions.generateUniqueAccountName
import com.memtrip.eos.chain.actions.transaction.transfer.TransferChain
import com.memtrip.eos.chain.actions.transactionDefaultExpiry
import com.memtrip.eos.core.crypto.EosPrivateKey
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Assert.assertEquals
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@RunWith(JUnitPlatform::class)
class TransferChainTest : Spek({
given("an Api") {
val okHttpClient by memoized {
OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build()
}
val chainApi by memoized { io.golos.commun4j.http.rpc.Api(Config.CHAIN_API_BASE_URL, okHttpClient).chain }
val setupTransactions by memoized { SetupTransactions(chainApi) }
on("v1/chain/push_transaction -> transfer") {
val signatureProviderPrivateKey = EosPrivateKey("<KEY>")
/**
* First account
*/
val firstAccountPrivateKey = EosPrivateKey()
val firstAccountName = generateUniqueAccountName()
setupTransactions.createAccount(firstAccountName, firstAccountPrivateKey).blockingGet()
/**
* Second account
*/
val secondAccountPrivateKey = EosPrivateKey()
val secondAccountName = generateUniqueAccountName()
setupTransactions.createAccount(secondAccountName, secondAccountPrivateKey).blockingGet()
/**
* Send money from the signature provider to the first account
*/
val transfer1 = TransferChain(chainApi).transfer(
"eosio.token",
TransferChain.Args(
"memtripissue",
firstAccountName,
"0.0001 EOS",
"eos-swift test suite -> transfer тест"
),
io.golos.commun4j.chain.actions.transaction.TransactionContext(
"memtripissue",
signatureProviderPrivateKey,
transactionDefaultExpiry()
)
).blockingGet()
/**
* Transfer money from the first account to the second account
*/
val transfer2 = TransferChain(chainApi).transfer(
"eosio.token",
TransferChain.Args(
firstAccountName,
secondAccountName,
"0.0001 EOS",
"eos-swift test suite -> transfer 轮子把巨人挤出局"
),
io.golos.commun4j.chain.actions.transaction.TransactionContext(
firstAccountName,
firstAccountPrivateKey,
transactionDefaultExpiry()
)
).blockingGet()
/**
* Transfer money from the second account to the first account
*/
val transfer3 = TransferChain(chainApi).transfer(
"eosio.token",
TransferChain.Args(
secondAccountName,
firstAccountName,
"0.0001 EOS",
"eos-swift test suite -> тестируем testing 1234567890"
),
io.golos.commun4j.chain.actions.transaction.TransactionContext(
secondAccountName,
secondAccountPrivateKey,
transactionDefaultExpiry()
)
).blockingGet()
it("should return the transaction") {
// Transfer 1
assertTrue(transfer1.isSuccessful)
assertNotNull(transfer1.body)
val data1 = transfer1.body!!.processed.action_traces[0].act.data as Map<*, *>
assertEquals(
"eos-swift test suite -> transfer тест",
data1["memo"])
// Transfer 2
assertTrue(transfer2.isSuccessful)
assertNotNull(transfer2.body)
val data2 = transfer2.body!!.processed.action_traces[0].act.data as Map<*, *>
assertEquals(
"eos-swift test suite -> transfer 轮子把巨人挤出局",
data2["memo"])
// Transfer 3
assertTrue(transfer3.isSuccessful)
assertNotNull(transfer3.body)
val data3 = transfer3.body!!.processed.action_traces[0].act.data as Map<*, *>
assertEquals(
"eos-swift test suite -> тестируем testing 1234567890",
data3["memo"])
}
}
}
}) | 5 | null | 3 | 38 | 30006ce7047843ba3f2f8d43d657c7e7627a63ca | 5,526 | eos-jvm | Apache License 2.0 |
app/src/main/java/me/stanis/apps/minwos/ui/fragments/networks/NetworksFragment.kt | fstanis | 267,702,828 | false | null | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 me.stanis.apps.minwos.ui.fragments.networks
import android.Manifest.permission.POST_NOTIFICATIONS
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat.startForegroundService
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import me.stanis.apps.minwos.R
import me.stanis.apps.minwos.databinding.FragmentNetworksBinding
import me.stanis.apps.minwos.service.ForegroundStatusService
import me.stanis.apps.minwos.ui.help.HelpDialog
@AndroidEntryPoint
class NetworksFragment : Fragment() {
private val viewModel: NetworksViewModel by viewModels()
private lateinit var binding: FragmentNetworksBinding
private val helpDialog by lazy {
HelpDialog(
requireContext(),
getString(R.string.title_networks),
getString(R.string.help_networks),
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
super.onCreateView(inflater, container, savedInstanceState)
requireActivity().addMenuProvider(
object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menu.clear()
menuInflater.inflate(R.menu.action_menu_networks, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean =
[email protected](menuItem)
},
viewLifecycleOwner,
)
binding = FragmentNetworksBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewManager = LinearLayoutManager(context)
val viewAdapter = ConnectivityStatusAdapter()
with(binding.networksRecyclerView) {
layoutManager = viewManager
adapter = viewAdapter
}
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.connectivityStatus.collect { networkStatus ->
viewAdapter.connectivityStatus = networkStatus
}
}
}
}
private fun showHelp() {
helpDialog.show()
}
private fun tryToggleService() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ActivityCompat.checkSelfPermission(
requireContext(),
POST_NOTIFICATIONS,
) != PackageManager.PERMISSION_GRANTED
) {
permissionCheck.launch(POST_NOTIFICATIONS)
return
}
toggleService()
}
private fun toggleService() {
val intent = Intent(requireContext(), ForegroundStatusService::class.java)
intent.action = ForegroundStatusService.ACTION_TOGGLE_FOREGROUND_SERVICE
startForegroundService(requireContext(), intent)
}
private fun onMenuItemSelected(menuItem: MenuItem) =
when (menuItem.itemId) {
R.id.action_help -> {
showHelp()
true
}
R.id.action_refresh -> {
viewModel.refresh()
true
}
R.id.action_notification -> {
tryToggleService()
true
}
else -> false
}
private val permissionCheck =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
toggleService()
}
}
}
| 0 | Kotlin | 0 | 3 | 798046449dea912378337243aee3c33c1b28a152 | 4,984 | miNWos | Apache License 2.0 |
app/src/main/java/com/kcteam/features/billing/api/AddBillingRepo.kt | DebashisINT | 558,234,039 | false | null | package com.keshavindustryfsm.features.billing.api
import android.content.Context
import android.net.Uri
import com.fasterxml.jackson.databind.ObjectMapper
import com.keshavindustryfsm.app.FileUtils
import com.keshavindustryfsm.base.BaseResponse
import com.keshavindustryfsm.features.billing.model.AddBillingInputParamsModel
import com.keshavindustryfsm.features.dashboard.presentation.DashboardActivity
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
/**
* Created by Saikat on 20-02-2019.
*/
class AddBillingRepo(val apiService: AddBillingApi) {
fun addBillingDetails(addBillingDetails: AddBillingInputParamsModel): Observable<BaseResponse> {
return apiService.addBill(addBillingDetails)
}
fun addBillingDetailsMultipart(addBillingDetails: AddBillingInputParamsModel, image: String, context: Context): Observable<BaseResponse> {
var profile_img_data: MultipartBody.Part? = null
var profile_img_file: File? = null
if (image.startsWith("file"))
profile_img_file = FileUtils.getFile(context, Uri.parse(image))
else {
profile_img_file = File(image)
if (!profile_img_file?.exists()) {
profile_img_file?.createNewFile()
}
}
if (profile_img_file != null && profile_img_file.exists()) {
val profileImgBody = RequestBody.create(MediaType.parse("multipart/form-data"), profile_img_file)
profile_img_data = MultipartBody.Part.createFormData("billing_image", profile_img_file.name, profileImgBody)
} else {
var mFile: File
mFile = (context as DashboardActivity).getShopDummyImageFile()
val profileImgBody = RequestBody.create(MediaType.parse("multipart/form-data"), mFile)
profile_img_data = MultipartBody.Part.createFormData("billing_image", mFile.name, profileImgBody)
}
var shopObject: RequestBody? = null
var jsonInString = ""
try {
jsonInString = ObjectMapper().writeValueAsString(addBillingDetails)
shopObject = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonInString)
//shopObject = RequestBody.create(MediaType.parse("text/plain"), jsonInString)
} catch (e: Throwable) {
e.printStackTrace()
}
//return apiService.addBillWithImage(jsonInString, profile_img_data)
return apiService.addBillWithImage(shopObject!!, profile_img_data)
}
} | 0 | null | 1 | 1 | a9aabcf48662c76db18bcece75cae9ac961da1ed | 2,582 | NationalPlastic | Apache License 2.0 |
mediator/src/test/kotlin/no/nav/dagpenger/saksbehandling/mottak/RapidFilterBehandlingOpprettetMottakTest.kt | navikt | 571,475,339 | false | {"Kotlin": 322044, "PLpgSQL": 7983, "Mustache": 4238, "HTML": 699, "Dockerfile": 77} | package no.nav.dagpenger.saksbehandling.mottak
import io.kotest.matchers.shouldBe
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.MessageProblems
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class RapidFilterBehandlingOpprettetMottakTest {
private val testRapid = TestRapid()
private val testMessage =
mapOf(
"@event_name" to "behandling_opprettet",
"@id" to "id1",
"@opprettet" to "2024-02-27T10:41:52.800935377",
"søknadId" to "søknadId33",
"behandlingId" to "behandlingId4949494",
"ident" to "ident123",
)
@Test
fun `Skal behandle pakker med alle required keys`() {
val testListener = TestListener(testRapid)
testRapid.sendTestMessage(JsonMessage.newMessage(testMessage).toJson())
testListener.onPacketCalled shouldBe true
}
@ParameterizedTest
@CsvSource(
"søknadId, false",
"behandlingId, false",
"ident, false",
)
fun `Skal ikke behandle pakker som mangler required keys`(
requiredKey: String,
testResult: Boolean,
) {
val testListener = TestListener(testRapid)
val mutertTestMessage = JsonMessage.newMessage(testMessage.muterOgKonverterToJsonString { it.remove(requiredKey) }).toJson()
testRapid.sendTestMessage(mutertTestMessage)
testListener.onPacketCalled shouldBe testResult
}
private fun Map<String, Any>.muterOgKonverterToJsonString(block: (map: MutableMap<String, Any>) -> Unit): String {
val mutableMap = this.toMutableMap()
block.invoke(mutableMap)
return JsonMessage.newMessage(mutableMap).toJson()
}
private class TestListener(rapidsConnection: RapidsConnection) : River.PacketListener {
var onPacketCalled = false
lateinit var packet: JsonMessage
init {
River(rapidsConnection).apply(
BehandlingOpprettetMottak.rapidFilter,
).register(this)
}
override fun onPacket(
packet: JsonMessage,
context: MessageContext,
) {
this.onPacketCalled = true
this.packet = packet
}
override fun onError(
problems: MessageProblems,
context: MessageContext,
) {
println(problems.toExtendedReport())
}
override fun onSevere(
error: MessageProblems.MessageException,
context: MessageContext,
) {
println(error.problems.toExtendedReport())
}
}
}
| 1 | Kotlin | 0 | 0 | a1f4966ffb0ce62bbc587919cba93a355995987c | 2,904 | dp-saksbehandling | MIT License |
kotlin/demo/src/main/kotlin/com/uap/demo/service/GitHubService.kt | emanuelpeg | 496,223,575 | false | {"Kotlin": 6989, "Scala": 3681, "Clojure": 3625, "Groovy": 3573, "Java": 1906} | package com.uap.demo.service
import com.uap.demo.client.GitHubClient
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
interface GitHubService {
fun getLanguages(userName: String): List<String>
fun getSecundaryLanguages(userName: String): List<String>
fun getAllLanguages(userName: String): List<String>
}
@Service
class GitHubServiceImpl : GitHubService {
private val gitHubClient : GitHubClient
init {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
gitHubClient = retrofit.create(GitHubClient::class.java)
}
@Cacheable(value = ["Languages"])
override fun getLanguages(userName: String): List<String> {
val repos = gitHubClient.listRepos(userName)?.execute()?.body()
return if (repos == null) listOf()
else repos?.map { it!!.language }?.distinct().filter { it != null }
}
@Cacheable(value = ["SecundaryLanguages"])
override fun getSecundaryLanguages(userName: String): List<String> {
val repos = gitHubClient.listRepos(userName)?.execute()?.body()
return if (repos == null) listOf()
else repos?.flatMap { gitHubClient.repoLenguages(userName, it!!.name)?.execute()?.body()?.keySet() ?: setOf() }?.distinct()
}
@Cacheable(value = ["AllLanguages"])
override fun getAllLanguages(userName: String): List<String> =
this.getLanguages(userName).union(this.getSecundaryLanguages(userName)).distinct()
} | 0 | Kotlin | 0 | 1 | 101a21f133dfbe5744d13c395e232e42a60bf215 | 1,690 | profile | Apache License 2.0 |
kotlin/demo/src/main/kotlin/com/uap/demo/service/GitHubService.kt | emanuelpeg | 496,223,575 | false | {"Kotlin": 6989, "Scala": 3681, "Clojure": 3625, "Groovy": 3573, "Java": 1906} | package com.uap.demo.service
import com.uap.demo.client.GitHubClient
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
interface GitHubService {
fun getLanguages(userName: String): List<String>
fun getSecundaryLanguages(userName: String): List<String>
fun getAllLanguages(userName: String): List<String>
}
@Service
class GitHubServiceImpl : GitHubService {
private val gitHubClient : GitHubClient
init {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
gitHubClient = retrofit.create(GitHubClient::class.java)
}
@Cacheable(value = ["Languages"])
override fun getLanguages(userName: String): List<String> {
val repos = gitHubClient.listRepos(userName)?.execute()?.body()
return if (repos == null) listOf()
else repos?.map { it!!.language }?.distinct().filter { it != null }
}
@Cacheable(value = ["SecundaryLanguages"])
override fun getSecundaryLanguages(userName: String): List<String> {
val repos = gitHubClient.listRepos(userName)?.execute()?.body()
return if (repos == null) listOf()
else repos?.flatMap { gitHubClient.repoLenguages(userName, it!!.name)?.execute()?.body()?.keySet() ?: setOf() }?.distinct()
}
@Cacheable(value = ["AllLanguages"])
override fun getAllLanguages(userName: String): List<String> =
this.getLanguages(userName).union(this.getSecundaryLanguages(userName)).distinct()
} | 0 | Kotlin | 0 | 1 | 101a21f133dfbe5744d13c395e232e42a60bf215 | 1,690 | profile | Apache License 2.0 |
domain/src/main/java/com/oguzdogdu/domain/usecase/favorites/GetDeleteFromFavoritesUseCaseImpl.kt | oguzsout | 616,912,430 | false | {"Kotlin": 470573} | package com.oguzdogdu.domain.usecase.favorites
import com.oguzdogdu.domain.model.favorites.FavoriteImages
import com.oguzdogdu.domain.repository.WallpaperRepository
import javax.inject.Inject
class GetDeleteFromFavoritesUseCaseImpl
@Inject constructor(private val repository: WallpaperRepository) : GetDeleteFromFavoritesUseCase {
override suspend fun invoke(favoriteImage: FavoriteImages?) =
repository.deleteFavorites(favoriteImage)
} | 0 | Kotlin | 0 | 8 | 4ef08ffb85f49798251c8a15e81e7d3f0804524e | 450 | Wallies | MIT License |
AOS/RunWithMe/app/src/main/java/com/ssafy/runwithme/view/recommend/ScrapDialog.kt | HanYeop | 531,735,030 | false | {"Kotlin": 709496, "Java": 423758, "JavaScript": 47091, "CSS": 6540, "HTML": 2192, "Shell": 199, "Dockerfile": 176} | package com.ssafy.runwithme.view.recommend
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import com.ssafy.runwithme.R
import com.ssafy.runwithme.databinding.DialogScrapBinding
import com.ssafy.runwithme.utils.dialogResize
class ScrapDialog(context: Context, private val listener : ScrapDialogListener, private val isAdd : Boolean): Dialog(context) {
private lateinit var binding: DialogScrapBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.dialog_scrap,
null,
false
)
setContentView(binding.root)
initClickListener()
}
override fun onStart() {
super.onStart()
initView()
}
private fun initView(){
context.dialogResize(this, 0.9f, 0.3f)
// 배경 투명하게 바꿔줌
window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
if(isAdd){
binding.tvDialogHeader.text = "러닝 코스 스크랩 추가"
binding.etScrapTitle.visibility = View.VISIBLE
binding.tvScrapDelete.visibility = View.GONE
binding.btnOk.text = "추가"
} else {
binding.tvDialogHeader.text = "스크랩 삭제"
binding.tvScrapDelete.visibility = View.VISIBLE
binding.etScrapTitle.visibility = View.GONE
binding.btnOk.text = "삭제"
}
}
private fun initClickListener() {
binding.apply {
btnOk.setOnClickListener {
if(isAdd){
var title = etScrapTitle.text.toString()
listener.onItemAdd(title)
} else {
listener.onItemDelete()
}
dismiss()
}
btnCancel.setOnClickListener { dismiss() }
}
}
} | 0 | Kotlin | 0 | 4 | bf0a00a69c40361dbe44a8a3e159c9b69f1ade6f | 2,120 | RunWithMe | MIT License |
app/src/main/java/io/korostenskyi/chestnut/presentation/screen/settings/SettingsState.kt | korostenskyi | 401,812,198 | false | null | package io.korostenskyi.chestnut.presentation.screen.settings
import io.korostenskyi.chestnut.domain.model.ApplicationSettings
sealed class SettingsState {
object Idle : SettingsState()
data class Loaded(val settings: ApplicationSettings) : SettingsState()
}
| 3 | Kotlin | 0 | 0 | 5c7e285cb495e83bf9d9d29817fd0eb76f601a35 | 271 | Chestnut-Compose | MIT License |
vector/src/main/java/im/vector/directory/people/detail/PeopleDetailAdapter.kt | fhirfactory | 268,744,462 | true | {"Shell": 23, "Gradle": 3, "Java Properties": 2, "Markdown": 4, "Text": 4, "Ignore List": 2, "Batchfile": 1, "reStructuredText": 2, "YAML": 2, "Proguard": 1, "XML": 441, "Kotlin": 269, "Java": 180, "JSON": 3, "HTML": 3, "JavaScript": 5} | package im.vector.directory.people.detail
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import im.vector.Matrix
import im.vector.R
import im.vector.directory.people.model.DirectoryPeople
import im.vector.directory.role.OnDataSetChange
import im.vector.directory.role.RoleViewHolder
import im.vector.directory.role.model.DummyRole
import im.vector.ui.themes.ThemeUtils
import kotlinx.android.synthetic.main.item_role_detail_category1.view.*
import org.matrix.androidsdk.MXSession
class PeopleDetailAdapter(val context: Context) :
RecyclerView.Adapter<RecyclerView.ViewHolder>(), OnDataSetChange {
private val models = mutableListOf<PeopleDetailAdapterModel>()
private val TYPE_EMAIL = 1
private val TYPE_PHONE = 2
private val TYPE_ROLE = 3
var mSession: MXSession? = null
var textSize: Float = 0.0F
var spanTextBackgroundColor: Int
var spanTextColor: Int
init {
mSession = Matrix.getInstance(context).defaultSession
textSize = 12 * context.resources.displayMetrics.scaledDensity // sp to px
spanTextBackgroundColor = ThemeUtils.getColor(context, R.attr.vctr_text_spanable_text_background_color)
spanTextColor = ThemeUtils.getColor(context, R.attr.vctr_text_reverse_color)
}
inner class EmailPhoneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var heading: TextView? = null
var officialName: TextView? = null
var secondaryName: TextView? = null
init {
heading = itemView.heading
officialName = itemView.officialName
secondaryName = itemView.secondaryName
}
fun bind(peopleDetailAdapterModel: PeopleDetailAdapterModel) {
heading?.text = when (peopleDetailAdapterModel.type) {
TYPE_PHONE -> "Phone"
TYPE_EMAIL -> "Email"
else -> ""
}
officialName?.text = peopleDetailAdapterModel.value
secondaryName?.visibility = View.GONE
}
}
fun setData(people: DirectoryPeople) {
this.models.clear()
this.models.add(PeopleDetailAdapterModel("<EMAIL>", null, TYPE_EMAIL))
this.models.add(PeopleDetailAdapterModel("0455552522", null, TYPE_PHONE))
notifyDataSetChanged()
}
fun setData(roles: MutableList<DummyRole>) {
for (role in roles) {
this.models.add(PeopleDetailAdapterModel(null, role, TYPE_ROLE))
}
notifyDataSetChanged()
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): RecyclerView.ViewHolder {
// create a new view
return when (viewType) {
TYPE_EMAIL, TYPE_PHONE -> EmailPhoneViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_role_detail_category1, parent, false))
TYPE_ROLE -> RoleViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_directory_role, parent, false))
else -> EmailPhoneViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_role_detail_category1, parent, false))
}
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (models[position].type) {
TYPE_ROLE -> (holder as RoleViewHolder).bind(context, mSession, models[position].role!!, spanTextBackgroundColor, spanTextColor, textSize, this, position)
TYPE_EMAIL, TYPE_PHONE -> (holder as EmailPhoneViewHolder).bind(models[position])
}
}
override fun getItemViewType(position: Int): Int {
return models[position].type
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount() = models.size
override fun onDataChange(position: Int) {
notifyItemChanged(position)
}
}
data class PeopleDetailAdapterModel(val value: String?, val role: DummyRole?, val type: Int) | 3 | Java | 0 | 2 | f74e29711e6a2927784cb9d7581596f53d30a5cd | 4,282 | pegacorn-communicate-app-android | Apache License 2.0 |
adoptium-updater-parent/adoptium-api-v3-updater/src/main/kotlin/net/adoptium/api/v3/ReleaseIncludeFilter.kt | adoptium | 349,432,712 | false | null | package net.adoptium.api.v3
import net.adoptium.api.v3.config.APIConfig
import net.adoptium.api.v3.mapping.ReleaseMapper
import net.adoptium.api.v3.models.Vendor
import java.time.Duration
import java.time.ZonedDateTime
enum class ReleaseFilterType {
RELEASES_ONLY,
SNAPSHOTS_ONLY,
ALL
}
class ReleaseIncludeFilter(
private val now: ZonedDateTime,
private val filterType: ReleaseFilterType,
private val includeAll: Boolean = false,
private val excludedVendors: Set<Vendor> = VENDORS_EXCLUDED_FROM_FULL_UPDATE
) {
companion object {
val VENDORS_EXCLUDED_FROM_FULL_UPDATE = setOf(Vendor.adoptopenjdk)
val INCLUDE_ALL = ReleaseIncludeFilter(TimeSource.now(), ReleaseFilterType.ALL, true)
}
fun filterVendor(vendor: Vendor): Boolean {
return if (includeAll || APIConfig.UPDATE_ADOPTOPENJDK) {
true // include all vendors
} else {
!excludedVendors.contains(vendor)
}
}
fun filter(vendor: Vendor, startTime: String, isPrerelease: Boolean): Boolean {
return filter(vendor, ReleaseMapper.parseDate(startTime), isPrerelease)
}
fun filter(vendor: Vendor, startTime: ZonedDateTime, isPrerelease: Boolean): Boolean {
if (includeAll || APIConfig.UPDATE_ADOPTOPENJDK) {
return true // include all vendors
} else {
if (excludedVendors.contains(vendor)) {
return false
}
var include = true
if (filterType == ReleaseFilterType.RELEASES_ONLY) {
return !isPrerelease
} else if (filterType == ReleaseFilterType.SNAPSHOTS_ONLY) {
include = isPrerelease
}
return include && Duration.between(startTime, now).toDays() < APIConfig.UPDATE_DAY_CUTOFF
// exclude AdoptOpenjdk
// Don't Update releases more than a year old
}
}
}
| 26 | null | 26 | 34 | f7ee106a1ace802a4f57a01ed9c1baf378e0c5ab | 1,933 | api.adoptium.net | Apache License 2.0 |
adoptium-updater-parent/adoptium-api-v3-updater/src/main/kotlin/net/adoptium/api/v3/ReleaseIncludeFilter.kt | adoptium | 349,432,712 | false | null | package net.adoptium.api.v3
import net.adoptium.api.v3.config.APIConfig
import net.adoptium.api.v3.mapping.ReleaseMapper
import net.adoptium.api.v3.models.Vendor
import java.time.Duration
import java.time.ZonedDateTime
enum class ReleaseFilterType {
RELEASES_ONLY,
SNAPSHOTS_ONLY,
ALL
}
class ReleaseIncludeFilter(
private val now: ZonedDateTime,
private val filterType: ReleaseFilterType,
private val includeAll: Boolean = false,
private val excludedVendors: Set<Vendor> = VENDORS_EXCLUDED_FROM_FULL_UPDATE
) {
companion object {
val VENDORS_EXCLUDED_FROM_FULL_UPDATE = setOf(Vendor.adoptopenjdk)
val INCLUDE_ALL = ReleaseIncludeFilter(TimeSource.now(), ReleaseFilterType.ALL, true)
}
fun filterVendor(vendor: Vendor): Boolean {
return if (includeAll || APIConfig.UPDATE_ADOPTOPENJDK) {
true // include all vendors
} else {
!excludedVendors.contains(vendor)
}
}
fun filter(vendor: Vendor, startTime: String, isPrerelease: Boolean): Boolean {
return filter(vendor, ReleaseMapper.parseDate(startTime), isPrerelease)
}
fun filter(vendor: Vendor, startTime: ZonedDateTime, isPrerelease: Boolean): Boolean {
if (includeAll || APIConfig.UPDATE_ADOPTOPENJDK) {
return true // include all vendors
} else {
if (excludedVendors.contains(vendor)) {
return false
}
var include = true
if (filterType == ReleaseFilterType.RELEASES_ONLY) {
return !isPrerelease
} else if (filterType == ReleaseFilterType.SNAPSHOTS_ONLY) {
include = isPrerelease
}
return include && Duration.between(startTime, now).toDays() < APIConfig.UPDATE_DAY_CUTOFF
// exclude AdoptOpenjdk
// Don't Update releases more than a year old
}
}
}
| 26 | null | 26 | 34 | f7ee106a1ace802a4f57a01ed9c1baf378e0c5ab | 1,933 | api.adoptium.net | Apache License 2.0 |
app/src/main/java/com/iamageo/movie/conn/MainRepository.kt | EASY-CODES | 399,637,051 | false | null | package com.iamageo.movie.conn
import com.iamageo.movie.conn.RetrofitService
class MainRepository constructor(private val retrofitService: RetrofitService) {
suspend fun getAllMovies() = retrofitService.getAllMovies()
}
| 0 | Kotlin | 0 | 0 | 6aaedebac7297e2c0229bfa4a239ca41dade070f | 228 | breakingbad_characters | MIT License |
mercado-livro/src/main/kotlin/com/mercadolivro/controller/response/BookResponse.kt | juliocarvalho2019 | 633,990,981 | false | null | package com.mercadolivro.controller.response
import com.mercadolivro.enums.BookStatus
import com.mercadolivro.model.CustomerModel
import java.math.BigDecimal
data class BookResponse(
var id: Int? = null,
var name: String,
var price: BigDecimal,
var customer: CustomerModel? = null,
var status: BookStatus? = null
)
| 0 | null | 0 | 1 | a554bb1eeae0850d39e1e95c0ea3aa7cccdef71c | 341 | Mercado-livro | Apache License 2.0 |
spring-web/src/main/kotlin/org/springframework/web/client/RestOperationsExtensions.kt | koushikkothagal | 276,991,204 | false | null | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.client
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.RequestEntity
import org.springframework.http.ResponseEntity
import java.net.URI
/**
* Extension for [RestOperations.getForObject] providing a `getForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.getForObject(url: String, vararg uriVariables: Any): T =
getForObject(url, T::class.java, *uriVariables) as T
/**
* Extension for [RestOperations.getForObject] providing a `getForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.getForObject(url: String, uriVariables: Map<String, Any?>): T =
getForObject(url, T::class.java, uriVariables) as T
/**
* Extension for [RestOperations.getForObject] providing a `getForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.getForObject(url: URI): T =
getForObject(url, T::class.java) as T
/**
* Extension for [RestOperations.getForEntity] providing a `getForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0.2
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.getForEntity(url: URI): ResponseEntity<T> =
getForEntity(url, T::class.java)
/**
* Extension for [RestOperations.getForEntity] providing a `getForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.getForEntity(url: String, vararg uriVariables: Any): ResponseEntity<T> =
getForEntity(url, T::class.java, *uriVariables)
/**
* Extension for [RestOperations.getForEntity] providing a `getForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0.2
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.getForEntity(url: String, uriVariables: Map<String, *>): ResponseEntity<T> =
getForEntity(url, T::class.java, uriVariables)
/**
* Extension for [RestOperations.patchForObject] providing a `patchForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0.2
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.patchForObject(url: String, request: Any? = null,
vararg uriVariables: Any): T =
patchForObject(url, request, T::class.java, *uriVariables) as T
/**
* Extension for [RestOperations.patchForObject] providing a `patchForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0.2
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.patchForObject(url: String, request: Any? = null,
uriVariables: Map<String, *>): T =
patchForObject(url, request, T::class.java, uriVariables) as T
/**
* Extension for [RestOperations.patchForObject] providing a `patchForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0.2
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.patchForObject(url: URI, request: Any? = null): T =
patchForObject(url, request, T::class.java) as T
/**
* Extension for [RestOperations.postForObject] providing a `postForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.postForObject(url: String, request: Any? = null,
vararg uriVariables: Any): T =
postForObject(url, request, T::class.java, *uriVariables) as T
/**
* Extension for [RestOperations.postForObject] providing a `postForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.postForObject(url: String, request: Any? = null,
uriVariables: Map<String, *>): T =
postForObject(url, request, T::class.java, uriVariables) as T
/**
* Extension for [RestOperations.postForObject] providing a `postForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.postForObject(url: URI, request: Any? = null): T =
postForObject(url, request, T::class.java) as T
/**
* Extension for [RestOperations.postForEntity] providing a `postForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.postForEntity(url: String, request: Any? = null,
vararg uriVariables: Any): ResponseEntity<T> =
postForEntity(url, request, T::class.java, *uriVariables)
/**
* Extension for [RestOperations.postForEntity] providing a `postForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.postForEntity(url: String, request: Any? = null,
uriVariables: Map<String, *>): ResponseEntity<T> =
postForEntity(url, request, T::class.java, uriVariables)
/**
* Extension for [RestOperations.postForEntity] providing a `postForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.postForEntity(url: URI, request: Any? = null): ResponseEntity<T> =
postForEntity(url, request, T::class.java)
/**
* Extension for [RestOperations.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.exchange(url: String, method: HttpMethod,
requestEntity: HttpEntity<*>? = null, vararg uriVariables: Any): ResponseEntity<T> =
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {}, *uriVariables)
/**
* Extension for [RestOperations.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.exchange(url: String, method: HttpMethod,
requestEntity: HttpEntity<*>? = null, uriVariables: Map<String, *>): ResponseEntity<T> =
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {}, uriVariables)
/**
* Extension for [RestOperations.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.exchange(url: URI, method: HttpMethod,
requestEntity: HttpEntity<*>? = null): ResponseEntity<T> =
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [RestOperations.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Jon Schneider
* @author Sebastien Deleuze
* @since 5.0
*/
@Throws(RestClientException::class)
inline fun <reified T> RestOperations.exchange(requestEntity: RequestEntity<*>): ResponseEntity<T> =
exchange(requestEntity, object : ParameterizedTypeReference<T>() {})
| 1 | null | 41 | 8 | 362e228142287f3f1042fa8a71c2ef4773f84e55 | 11,678 | spring-framework | Apache License 2.0 |
src/main/kotlin/com/example/validatecontrolcharacterssample/ValidateControlCharactersSampleApplication.kt | atr0phy | 628,216,843 | false | null | package com.example.validatecontrolcharacterssample
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class ValidateControlCharactersSampleApplication
fun main(args: Array<String>) {
runApplication<ValidateControlCharactersSampleApplication>(*args)
}
| 0 | Kotlin | 0 | 1 | a52ded90ad526b834b8676a278a5bc5a9e6e3c35 | 346 | validate-control-characters-sample | MIT License |
feature/note/src/main/java/com/teamwiney/notecollection/NoteScreen.kt | AdultOfNineteen | 639,481,288 | false | null | package com.teamwiney.notecollection
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemContentType
import androidx.paging.compose.itemKey
import com.teamwiney.core.common.WineyAppState
import com.teamwiney.core.common.WineyBottomSheetState
import com.teamwiney.core.common.navigation.HomeDestinations
import com.teamwiney.core.common.navigation.NoteDestinations
import com.teamwiney.core.common.`typealias`.SheetContent
import com.teamwiney.core.design.R
import com.teamwiney.notecollection.components.EmptyNote
import com.teamwiney.notecollection.components.NoteFilterDefaultItem
import com.teamwiney.notecollection.components.NoteFilterResetButton
import com.teamwiney.notecollection.components.NoteSelectedFilterChip
import com.teamwiney.notecollection.components.NoteSortBottomSheet
import com.teamwiney.notecollection.components.NoteWineCard
import com.teamwiney.ui.components.HeightSpacer
import com.teamwiney.ui.components.HeightSpacerWithLine
import com.teamwiney.ui.components.home.HomeLogo
import com.teamwiney.ui.theme.WineyTheme
import kotlinx.coroutines.flow.collectLatest
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun NoteScreen(
appState: WineyAppState,
viewModel: NoteViewModel = hiltViewModel(),
bottomSheetState: WineyBottomSheetState
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val effectFlow = viewModel.effect
val tastingNotes = uiState.tastingNotes.collectAsLazyPagingItems()
val tastingNotesRefreshState = tastingNotes.loadState.refresh
BackHandler {
if (bottomSheetState.bottomSheetState.isVisible) {
bottomSheetState.hideBottomSheet()
} else {
appState.navController.navigateUp()
}
}
LaunchedEffect(tastingNotesRefreshState) {
if (tastingNotesRefreshState is LoadState.Error) {
val errorMessage = tastingNotesRefreshState.error.message ?: "네트워크 오류가 발생했습니다."
appState.showSnackbar(errorMessage)
}
}
LaunchedEffect(true) {
viewModel.getTastingNotes()
effectFlow.collectLatest { effect ->
when (effect) {
is NoteContract.Effect.NavigateTo -> {
appState.navigate(effect.destination, effect.navOptions)
}
is NoteContract.Effect.ShowSnackBar -> {
appState.showSnackbar(effect.message)
}
}
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(WineyTheme.colors.background_1)
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(WineyTheme.colors.background_1)
) {
HomeLogo(
onClick = {
appState.navigate(HomeDestinations.Analysis.ROUTE)
},
hintPopupOpen = false
)
Text(
modifier = Modifier.padding(horizontal = 24.dp),
text = buildAnnotatedString {
withStyle(style = SpanStyle(WineyTheme.colors.main_3)) {
append("${uiState.tastingNotesCount}개")
}
append("의 노트를 작성했어요!")
},
color = WineyTheme.colors.gray_50,
style = WineyTheme.typography.headline
)
HeightSpacer(height = 14.dp)
NoteFilterSection(
uiState = uiState,
viewModel = viewModel,
showBottomSheet = bottomSheetState::showBottomSheet
)
if (uiState.tastingNotesCount == 0L) {
if (uiState.isLoading) {
SkeletonNote()
} else {
EmptyNote()
}
}
LazyVerticalGrid(
columns = GridCells.Fixed(2),
contentPadding = PaddingValues(horizontal = 24.dp, vertical = 15.dp),
verticalArrangement = Arrangement.spacedBy(21.dp),
horizontalArrangement = Arrangement.spacedBy(15.dp)
) {
items(
count = tastingNotes.itemCount,
key = tastingNotes.itemKey(),
contentType = tastingNotes.itemContentType()
) { index ->
tastingNotes[index]?.let {
NoteWineCard(
color = it.wineType,
name = it.name,
origin = it.country,
starRating = it.starRating,
onClick = {
appState.navigate("${NoteDestinations.DETAIL}?noteId=${it.id}")
}
)
}
}
}
}
FloatingActionButton(
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(bottom = 34.dp, end = 24.dp),
shape = CircleShape,
containerColor = WineyTheme.colors.main_2,
contentColor = WineyTheme.colors.gray_50,
onClick = {
appState.navigate(NoteDestinations.Write.ROUTE)
}) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_pencil_29),
contentDescription = "IC_PENCIL",
modifier = Modifier.size(29.dp),
tint = WineyTheme.colors.gray_50
)
}
}
}
@Composable
private fun SkeletonNote() {
LazyVerticalGrid(
columns = GridCells.Fixed(2),
contentPadding = PaddingValues(horizontal = 24.dp, vertical = 15.dp),
verticalArrangement = Arrangement.spacedBy(21.dp),
horizontalArrangement = Arrangement.spacedBy(15.dp)
) {
items(
count = 4,
) { index ->
Column(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
) {
Box(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(7.dp))
.border(
BorderStroke(
1.dp, brush = Brush.linearGradient(
colors = listOf(
Color(0xFF9671FF),
Color(0x109671FF),
)
)
),
RoundedCornerShape(7.dp)
)
.background(WineyTheme.colors.gray_950)
)
}
}
}
}
@Composable
fun NoteFilterSection(
uiState: NoteContract.State,
viewModel: NoteViewModel,
showBottomSheet: (SheetContent) -> Unit
) {
Column {
HeightSpacerWithLine(
modifier = Modifier.padding(bottom = 15.dp),
color = WineyTheme.colors.gray_900
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
LazyRow(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.verticalScroll(rememberScrollState()),
contentPadding = PaddingValues(horizontal = 24.dp),
horizontalArrangement = Arrangement.spacedBy(5.dp)
) {
if (uiState.buyAgainSelected ||
uiState.selectedTypeFilter.isNotEmpty() ||
uiState.selectedCountryFilter.isNotEmpty()
) {
item {
NoteFilterResetButton {
viewModel.resetFilter()
}
}
}
item {
NoteFilterDefaultItem(
name = uiState.sortItems[uiState.selectedSort],
onClick = {
showBottomSheet {
NoteSortBottomSheet(
sortItems = uiState.sortItems,
selectedSort = uiState.sortItems[uiState.selectedSort],
onSelectSort = viewModel::updateSelectedSort,
applyFilter = {
viewModel.processEvent(NoteContract.Event.ApplyFilter)
}
)
}
}
)
}
if (uiState.buyAgainSelected) {
item {
NoteSelectedFilterChip(
name = "재구매 의사",
onClose = {
viewModel.updateBuyAgainSelected(true)
viewModel.getTastingNotes()
},
onClick = {
viewModel.processEvent(NoteContract.Event.ShowFilter)
}
)
}
}
if (uiState.selectedTypeFilter.isEmpty()) {
item {
NoteFilterDefaultItem(
name = "와인종류",
onClick = { viewModel.processEvent(NoteContract.Event.ShowFilter) }
)
}
} else {
uiState.selectedTypeFilter.forEach { option ->
item {
NoteSelectedFilterChip(
name = option.type,
onClose = {
viewModel.removeFilter(option.type)
viewModel.processEvent(NoteContract.Event.ApplyFilter)
}
)
}
}
}
if (uiState.selectedCountryFilter.isEmpty()) {
item {
NoteFilterDefaultItem(
name = "생산지",
onClick = { viewModel.processEvent(NoteContract.Event.ShowFilter) }
)
}
} else {
uiState.selectedCountryFilter.forEach { option ->
item {
NoteSelectedFilterChip(
name = option.country,
onClose = {
viewModel.removeFilter(option.country)
viewModel.processEvent(NoteContract.Event.ApplyFilter)
}
)
}
}
}
}
Row(
modifier = Modifier.padding(end = 24.dp),
horizontalArrangement = Arrangement.spacedBy(7.dp),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(
modifier = Modifier
.width(1.dp)
.height(45.dp)
.background(color = WineyTheme.colors.gray_900)
)
Box(
modifier = Modifier
.clip(RoundedCornerShape(20.dp))
.background(WineyTheme.colors.point_1)
.clickable {
viewModel.processEvent(NoteContract.Event.ShowFilter)
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_filter_24),
contentDescription = "IC_FILTER",
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 5.dp)
.size(24.dp),
tint = WineyTheme.colors.gray_50
)
}
}
}
HeightSpacerWithLine(
modifier = Modifier.padding(top = 15.dp),
color = WineyTheme.colors.gray_900
)
}
} | 8 | null | 1 | 8 | 79f7635276bf5ac57d344233fea3c7eb40942315 | 14,947 | WINEY-Android | MIT License |
app/src/main/kotlin/com/tarantini/pantry/app/deps.kt | anthony-tarantini | 700,600,450 | false | {"Kotlin": 40742, "HTML": 19079, "HCL": 12504, "TypeScript": 8736, "JavaScript": 350, "SCSS": 148} | package com.tarantini.pantry.app
import com.sksamuel.hoplite.env.Environment
import com.tarantini.pantry.datastore.createDataSource
import com.tarantini.pantry.images.ImageService
import com.tarantini.pantry.item.ItemDatastore
import com.tarantini.pantry.item.ItemService
import com.tarantini.pantry.user.UserDatastore
import com.tarantini.pantry.user.UserService
import com.tarantini.pantry.userItem.UserItemDatastore
import com.zaxxer.hikari.HikariDataSource
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
/**
* Creates all the dependencies used by this service wrapped in a [Dependencies] object.
*
* @param env the variable for the environment eg STAGING or PROD.
* @param serviceName a unique name for this service used in logs and metrics
* @param config the loaded configuration values.
*/
fun createDependencies(env: Environment, serviceName: String, config: Config): Dependencies {
// val registry = createDatadogMeterRegistry(config.datadog, env, serviceName)
val ds = createDataSource(config.db, null)
val itemDatastore = ItemDatastore(ds)
val itemService = ItemService(itemDatastore)
val userDatastore = UserDatastore(ds)
val userItemDatastore = UserItemDatastore(ds)
val userService = UserService(userDatastore, userItemDatastore)
val httpClient = HttpClient(OkHttp) {
engine {
config {
followRedirects(true)
}
}
}
val imageService = ImageService(httpClient, config.assets)
return Dependencies(
// registry,
ds,
httpClient,
itemDatastore,
itemService,
userDatastore,
userService,
userItemDatastore,
imageService
)
}
/**
* The [Dependencies] object is a god object that contains all the dependencies of the project.
*
* In an dependency injection framework like Spring, this is created automagically for you and is
* called ApplicationContext.
*/
data class Dependencies(
// val registry: MeterRegistry,
val ds: HikariDataSource,
val httpClient: HttpClient,
val itemDatastore: ItemDatastore,
val itemService: ItemService,
val userDatastore: UserDatastore,
val userService: UserService,
val userItemDatastore: UserItemDatastore,
val imageService: ImageService
)
| 0 | Kotlin | 0 | 0 | d92b4819b74de5017932ce305191edc14d9ec913 | 2,265 | pantry-server | Apache License 2.0 |
ruby-call-signature/src/main/java/org/jetbrains/ruby/codeInsight/types/signature/serialization/RmcDirectory.kt | JetBrains | 85,180,339 | false | null | package org.jetbrains.ruby.codeInsight.types.signature.serialization
import org.jetbrains.ruby.codeInsight.types.signature.GemInfo
import org.jetbrains.ruby.codeInsight.types.signature.SignatureInfo
import java.io.*
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
interface RmcDirectory {
fun save(gemInfo: GemInfo, signatures: List<SignatureInfo>)
fun listGems() : List<GemInfo>
fun load(gemInfo: GemInfo): List<SignatureInfo>
}
class RmcDirectoryImpl(private val directory: File) : RmcDirectory {
init {
if (!directory.exists() || !directory.isDirectory) {
throw IOException("Existing directory excepted")
}
}
override fun load(gemInfo: GemInfo): List<SignatureInfo> {
val inputFile = File(directory, gemInfo2Filename(gemInfo))
FileInputStream(inputFile).use {
GZIPInputStream(it).use {
DataInputStream(it).use {
return SignatureInfoSerialization.deserialize(it)
}
}
}
}
override fun save(gemInfo: GemInfo, signatures: List<SignatureInfo>) {
val outputFile = File(directory, gemInfo2Filename(gemInfo))
FileOutputStream(outputFile).use {
GZIPOutputStream(it).use {
DataOutputStream(it).use {
SignatureInfoSerialization.serialize(signatures, it)
}
}
}
}
override fun listGems(): List<GemInfo> = directory.listFiles().mapNotNull { file2GemInfo(it) }
private fun gemInfo2Filename(gemInfo: GemInfo) = "${gemInfo.name}-${gemInfo.version}.rmc"
private fun file2GemInfo(file: File): GemInfo? {
if (file.extension != "rmc") {
return null
}
val name = file.nameWithoutExtension.substringBeforeLast('-')
val version = file.nameWithoutExtension.substringAfterLast('-')
if (name == "" || version == "") {
return null
}
return GemInfo(name, version)
}
}
| 17 | null | 8 | 135 | df63525a226c4926614a3937546b570b68bc42aa | 2,040 | ruby-type-inference | Apache License 2.0 |
L2/hangman/app/src/main/java/com/example/hangman/Game.kt | Spiryd | 609,987,379 | false | {"Kotlin": 71319, "Java": 2655} | package com.example.hangman
class Game(word: String) {
var word: String
var numberOfFailedGuesses: Int = 0
var guessedChars: MutableList<Char> = mutableListOf()
var gameOver: Boolean = false
var gameWon: Boolean = false
init {
this.word = word
}
fun isWon(): Boolean{
var tmpWord = word.toMutableList()
for (char in guessedChars){
while (tmpWord.contains(char)){
tmpWord.remove(char)
}
}
return tmpWord.size == 0
}
// returns false if letter not found
fun handleOnClick(letter: CharSequence): Boolean{
var guess = letter.first().lowercaseChar()
guessedChars.add(guess)
if (!word.contains(guess)){
numberOfFailedGuesses++
}
if (numberOfFailedGuesses >= 9){
gameOver = true
}else if (isWon()){
gameWon = true
}
return word.contains(guess)
}
fun toText(): String{
var toBePrinted: CharArray = CharArray(word.length)
for (i in toBePrinted.indices){
toBePrinted[i] = '?'
}
for (char in guessedChars){
if (word.contains(char)){
toBePrinted[word.indexOf(char)] = char
}
}
return String(toBePrinted)
}
} | 0 | Kotlin | 0 | 0 | 68e31374c5e9f2c737bb970025affc017d7174ee | 1,335 | MobileApplications | The Unlicense |
src/main/kotlin/com/mt/notion/common/request/richText/EquationRequest.kt | motui | 479,945,371 | false | null | package com.mt.notion.common.request.richText
import com.mt.notion.common.Expression
import com.mt.notion.common.RichTextType
/**
* Equation
*
* Equation objects contain the following information within the equation property:
*
* @author it.motui
*/
data class EquationRequest(
override val annotations: AnnotationsRequest?,
override val type: RichTextType = RichTextType.Equation,
val equation: Expression
) : RichTextRequest
| 0 | Kotlin | 0 | 1 | 80b7b256d8d7c34b15cf79d1e5f539c8ef4736b4 | 447 | notion-sdk-kotlin | MIT License |
compose/src/commonMain/kotlin/androidx/constraintlayout/core/parser/CLParser.kt | Lavmee | 711,725,142 | false | {"Kotlin": 3000082} | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.core.parser
class CLParser(private val mContent: String) {
private var mHasComment = false
private var mLineNumber = 0
internal enum class TYPE {
UNKNOWN,
OBJECT,
ARRAY,
NUMBER,
STRING,
KEY,
TOKEN,
}
// @TODO: add description
@Throws(CLParsingException::class)
fun parse(): CLObject {
@Suppress("unused")
val root: CLObject
val content = mContent.toCharArray()
@Suppress("unused")
var currentElement: CLElement?
val length = content.size
// First, let's find the root element start
mLineNumber = 1
var startIndex = -1
for (i in 0 until length) {
val c = content[i]
if (c == '{') {
startIndex = i
break
}
if (c == '\n') {
mLineNumber++
}
}
if (startIndex == -1) {
throw CLParsingException("invalid json content", null)
}
// We have a root object, let's start
root = CLObject.allocate(content)
root.setLine(mLineNumber)
root.start = startIndex.toLong()
currentElement = root
for (i in startIndex + 1 until length) {
val c = content[i]
if (c == '\n') {
mLineNumber++
}
if (mHasComment) {
if (c == '\n') {
mHasComment = false
} else {
continue
}
}
if (false) {
println("Looking at $i : <$c>")
}
if (currentElement == null) {
break
}
if (currentElement.isDone()) {
currentElement = getNextJsonElement(i, c, currentElement, content)
} else if (currentElement is CLObject) {
if (c == '}') {
currentElement.end = (i - 1).toLong()
} else {
currentElement = getNextJsonElement(i, c, currentElement, content)
}
} else if (currentElement is CLArray) {
if (c == ']') {
currentElement.end = (i - 1).toLong()
} else {
currentElement = getNextJsonElement(i, c, currentElement, content)
}
} else if (currentElement is CLString) {
val ck = content[currentElement.start.toInt()]
if (ck == c) {
currentElement.start += 1
currentElement.end = (i - 1).toLong()
}
} else {
if (currentElement is CLToken) {
val token = currentElement
if (!token.validate(c, i.toLong())) {
throw CLParsingException(
"parsing incorrect token " + token.content() + " at line " + mLineNumber,
token,
)
}
}
if (currentElement is CLKey || currentElement is CLString) {
val ck = content[currentElement.start.toInt()]
if ((ck == '\'' || ck == '"') && ck == c) {
currentElement.start += 1
currentElement.end = (i - 1).toLong()
}
}
if (!currentElement.isDone()) {
if ((c == '}') || (c == ']') || (c == ',') || (c == ' ') || (c == '\t') || (c == '\r') || (c == '\n') || (c == ':')) {
currentElement.end = (i - 1).toLong()
if (c == '}' || c == ']') {
currentElement = currentElement.getContainer()
currentElement!!.end = (i - 1).toLong()
if (currentElement is CLKey) {
currentElement = currentElement.getContainer()
currentElement!!.end = (i - 1).toLong()
}
}
}
}
}
if (currentElement.isDone() && ((currentElement !is CLKey || currentElement.mElements.size > 0))) {
currentElement = currentElement.getContainer()
}
}
// Close all open elements --
// allow us to be more resistant to invalid json, useful during editing.
while (currentElement != null && !currentElement.isDone()) {
(currentElement as? CLString)?.start = (currentElement.start.toInt() + 1).toLong()
currentElement.end = (length - 1).toLong()
currentElement = currentElement.getContainer()
}
if (DEBUG) {
println("Root: " + root.toJSON())
}
return root
}
@Throws(CLParsingException::class)
private fun getNextJsonElement(
position: Int,
c: Char,
currentElement: CLElement,
content: CharArray,
): CLElement {
var currentElement: CLElement? = currentElement
when (c) {
' ', ':', ',', '\t', '\r', '\n' -> {}
'{' -> {
currentElement = createElement(
currentElement, position, TYPE.OBJECT, true, content,
)
}
'[' -> {
currentElement = createElement(
currentElement, position, TYPE.ARRAY, true, content,
)
}
']', '}' -> {
currentElement!!.end = (position - 1).toLong()
currentElement = currentElement.getContainer()
currentElement!!.end = position.toLong()
}
'"', '\'' -> {
currentElement = if (currentElement is CLObject) {
createElement(
currentElement, position, TYPE.KEY, true, content,
)
} else {
createElement(
currentElement, position, TYPE.STRING, true, content,
)
}
}
'/' -> {
if (position + 1 < content.size && content[position + 1] == '/') {
mHasComment = true
}
}
'-', '+', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
currentElement = createElement(
currentElement, position, TYPE.NUMBER, true, content,
)
}
else -> {
if ((currentElement is CLContainer && currentElement !is CLObject)) {
currentElement = createElement(
currentElement, position, TYPE.TOKEN, true, content,
)
val token = currentElement as CLToken?
if (!token!!.validate(c, position.toLong())) {
throw CLParsingException(
("incorrect token <" + c + "> at line " + mLineNumber),
token,
)
}
} else {
currentElement = createElement(
currentElement, position, TYPE.KEY, true, content,
)
}
}
}
return (currentElement)!!
}
private fun createElement(
currentElement: CLElement?,
position: Int,
type: TYPE,
applyStart: Boolean,
content: CharArray,
): CLElement? {
var position = position
var newElement: CLElement? = null
if (DEBUG) {
println("CREATE " + type + " at " + content[position])
}
when (type) {
TYPE.OBJECT -> {
newElement = CLObject.allocate(content)
position++
}
TYPE.ARRAY -> {
newElement = CLArray.allocate(content)
position++
}
TYPE.STRING -> {
newElement = CLString.allocate(content)
}
TYPE.NUMBER -> {
newElement = CLNumber.allocate(content)
}
TYPE.KEY -> {
newElement = CLKey.allocate(content)
}
TYPE.TOKEN -> {
newElement = CLToken.allocate(content)
}
else -> {}
}
if (newElement == null) {
return null
}
newElement.setLine(mLineNumber)
if (applyStart) {
newElement.start = position.toLong()
}
if (currentElement is CLContainer) {
newElement.setContainer(currentElement)
}
return newElement
}
companion object {
const val DEBUG = false
@Throws(CLParsingException::class)
fun parse(string: String): CLObject {
return CLParser(string).parse()
}
}
}
| 6 | Kotlin | 1 | 9 | 1109ad273c2434eecf2090299f10df50db0edb1c | 9,777 | constraintlayout-compose-multiplatform | Apache License 2.0 |
feature-ledger-impl/src/main/java/io/novafoundation/nova/feature_ledger_impl/domain/account/common/selectAddress/SelectAddressLedgerInteractor.kt | novasamatech | 415,834,480 | false | {"Kotlin": 7662708, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_ledger_impl.domain.account.common.selectAddress
import io.novafoundation.nova.feature_ledger_api.sdk.application.substrate.LedgerSubstrateAccount
import io.novafoundation.nova.feature_ledger_api.sdk.application.substrate.SubstrateLedgerApplication
import io.novafoundation.nova.feature_ledger_api.sdk.device.LedgerDevice
import io.novafoundation.nova.feature_ledger_api.sdk.discovery.LedgerDeviceDiscoveryService
import io.novafoundation.nova.feature_ledger_api.sdk.discovery.findDevice
import io.novafoundation.nova.feature_wallet_api.data.network.blockhain.assets.AssetSourceRegistry
import io.novafoundation.nova.runtime.ext.accountIdOf
import io.novafoundation.nova.runtime.ext.utilityAsset
import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain
import java.math.BigInteger
class LedgerAccountWithBalance(
val index: Int,
val account: LedgerSubstrateAccount,
val balance: BigInteger,
val chainAsset: Chain.Asset
)
interface SelectAddressLedgerInteractor {
suspend fun getDevice(deviceId: String): LedgerDevice
suspend fun loadLedgerAccount(chain: Chain, deviceId: String, accountIndex: Int): Result<LedgerAccountWithBalance>
suspend fun verifyLedgerAccount(chain: Chain, deviceId: String, accountIndex: Int): Result<Unit>
}
class RealSelectAddressLedgerInteractor(
private val substrateLedgerApplication: SubstrateLedgerApplication,
private val ledgerDeviceDiscoveryService: LedgerDeviceDiscoveryService,
private val assetSourceRegistry: AssetSourceRegistry,
) : SelectAddressLedgerInteractor {
override suspend fun getDevice(deviceId: String): LedgerDevice {
return findDevice(deviceId)
}
override suspend fun loadLedgerAccount(chain: Chain, deviceId: String, accountIndex: Int) = runCatching {
val device = findDevice(deviceId)
val ledgerAccount = substrateLedgerApplication.getAccount(device, chain.id, accountIndex, confirmAddress = false)
val utilityAsset = chain.utilityAsset
val accountId = chain.accountIdOf(ledgerAccount.publicKey)
val balanceSource = assetSourceRegistry.sourceFor(utilityAsset).balance
val balance = balanceSource.queryTotalBalance(chain, utilityAsset, accountId)
LedgerAccountWithBalance(accountIndex, ledgerAccount, balance, utilityAsset)
}
override suspend fun verifyLedgerAccount(chain: Chain, deviceId: String, accountIndex: Int): Result<Unit> = kotlin.runCatching {
val device = findDevice(deviceId)
substrateLedgerApplication.getAccount(device, chain.id, accountIndex, confirmAddress = true)
}
private suspend fun findDevice(deviceId: String): LedgerDevice {
return ledgerDeviceDiscoveryService.findDevice(deviceId) ?: throw IllegalArgumentException("Device not found")
}
}
| 13 | Kotlin | 5 | 9 | 66a5c0949aee03a5ebe870a1b0d5fa3ae929516f | 2,841 | nova-wallet-android | Apache License 2.0 |
bgw-gui/src/main/kotlin/tools/aqua/bgw/animation/FlipAnimation.kt | tudo-aqua | 377,420,862 | false | {"Kotlin": 1198455, "TypeScript": 2013, "JavaScript": 1242, "HTML": 507, "CSS": 359, "Ruby": 131} | /*
* Copyright 2021-2023 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* 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("unused")
package tools.aqua.bgw.animation
import tools.aqua.bgw.components.gamecomponentviews.GameComponentView
import tools.aqua.bgw.core.DEFAULT_ANIMATION_SPEED
import tools.aqua.bgw.visual.Visual
/**
* A flip [Animation].
*
* Sets background to given [fromVisual] than contracts background in half the given duration,
* switches to [toVisual] and extends again in half the given duration.
*
* @constructor Creates a [FlipAnimation] for the given [GameComponentView].
*
* @param T Generic [GameComponentView].
* @param gameComponentView [GameComponentView] to animate.
* @property fromVisual Initial [Visual].
* @property toVisual Resulting [Visual].
* @param duration Duration in milliseconds. Default: [DEFAULT_ANIMATION_SPEED].
*/
class FlipAnimation<T : GameComponentView>(
gameComponentView: T,
val fromVisual: Visual,
val toVisual: Visual,
duration: Int = DEFAULT_ANIMATION_SPEED
) : ComponentAnimation<T>(componentView = gameComponentView, duration = duration)
| 31 | Kotlin | 16 | 24 | 266db439e4443d10bc1ec7eb7d9032f29daf6981 | 1,672 | bgw | Apache License 2.0 |
primitive/src/commonTest/kotlin/kollections/ListTest.kt | aSoft-Ltd | 537,964,662 | false | {"Kotlin": 118799} | package kollections
import kommander.expect
import kotlin.test.Test
class ListTest {
@Test
fun should_be_able_to_create_an_empty_list() {
val list = listOf<Int>()
expect(list.size).toBe(0)
}
@Test
fun should_be_able_to_add_items_to_a_list() {
val list = mutableListOf<Int>()
repeat(10) { list.add(10) }
expect(list.size).toBe(10)
}
@Test
fun should_be_able_to_create_a_list_with_items() {
val list1 = listOf(1, 2, 3, 4)
expect(list1.size).toBe(4)
val list2 = mutableListOf(1, 2, 3, 4)
expect(list2.size).toBe(4)
}
@Test
fun should_be_able_to_iterate_a_list() {
for (num in listOf(1, 2, 3, 4)) {
println(num)
}
}
@Test
fun should_print_pretty() {
println(listOf(1, 2, 3, 4, 5))
}
@Test
fun can_get_the_iterator_out() {
val list = listOf(1, 2, 3, 4, 5)
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
println(item)
}
}
@Test
fun should_be_able_to_loop_through_a_mutable_list() {
mutableListOf("A", "B", "C", "D").forEach {
println(it)
}
}
@Test
fun should_be_able_to_loop_through_an_empty_mutable_list() {
println("Empty one")
mutableListOf<String>().forEach {
println(it)
}
}
@Test
fun should_convert_a_list_into_a_set() {
var count = 0
val list = listOf(4, 5, 2, 5, 7, 8, 9).filter { it < 6 }.toSet()
list.forEach { count += it }
expect(count).toBe(4 + 5 + 2)
}
} | 0 | Kotlin | 1 | 7 | c67aa46ec5d02128cbcef7a276c652603b97a551 | 1,681 | kollections | MIT License |
messaging_rabbitmq/src/test/kotlin/com/hexagonkt/messaging/rabbitmq/RabbitMqClientTest.kt | ramyaravindranath | 410,515,677 | false | null | package com.hexagonkt.messaging.rabbitmq
import com.hexagonkt.helpers.Logger
import com.hexagonkt.messaging.rabbitmq.RabbitMqClient.Companion.createConnectionFactory
import com.hexagonkt.serialization.serialize
import org.testng.annotations.Test
import java.net.URI
import kotlin.test.assertFailsWith
@Test class RabbitMqClientTest {
private val log: Logger = Logger(this)
@Test fun `Create a connection factory with empty URI fails` () {
assertFailsWith(IllegalArgumentException::class) {
createConnectionFactory(URI(""))
}
}
@Test fun `Create a connection factory with invalid URI fails` () {
assertFailsWith(IllegalArgumentException::class) {
createConnectionFactory(URI("http://localhost"))
}
}
@Test fun `Create a connection factory without parameters succeed` () {
val uri = "amqp://user:pass@localhost:12345"
val cf = createConnectionFactory(URI(uri))
assert(cf.host == "localhost")
assert(cf.port == 12345)
}
@Test fun `Create a connection factory with one parameter succeed` () {
val uri = "amqp://user:pass@localhost:12345?channelCacheSize=50"
val cf = createConnectionFactory(URI(uri))
assert(cf.host == "localhost")
assert(cf.port == 12345)
}
@Test fun `Create a connection factory with two parameter succeed` () {
val uri = "amqp://user:pass@localhost:12345?channelCacheSize=50&heartbeat=25"
val cf = createConnectionFactory(URI(uri))
assert(cf.host == "localhost")
assert(cf.port == 12345)
}
@Test fun `Create a connection factory with all parameters succeed` () {
val opts = listOf(
"channelCacheSize=50",
"heartbeat=25",
"automaticRecovery=true",
"recoveryInterval=5",
"shutdownTimeout=5"
)
val opt = opts.joinToString("&")
val uri = "amqp://user:pass@localhost:12345?$opt"
val cf = createConnectionFactory(URI(uri))
assert(cf.host == "localhost")
assert(cf.port == 12345)
}
@Test fun `Create a connection factory with empty parameters succeed` () {
val opts = listOf(
"channelCacheSize",
"heartbeat",
"automaticRecovery",
"recoveryInterval",
"shutdownTimeout"
)
val opt = opts.joinToString("&")
val uri = "amqp://user:pass@localhost:12345?$opt"
val cf = createConnectionFactory(URI(uri))
assert(cf.host == "localhost")
assert(cf.port == 12345)
}
@Test fun `Rabbit client disconnects properly` () {
val client = RabbitMqClient(URI("amqp://guest:guest@localhost"))
assert(client.connected)
client.close()
assert(!client.connected)
client.close()
assert(!client.connected)
}
@Test fun `Consumers handle numbers properly` () {
val consumer = RabbitMqClient(URI("amqp://guest:guest@localhost"))
consumer.declareQueue("int_op")
consumer.declareQueue("long_op")
consumer.declareQueue("list_op")
consumer.consume("int_op", String::class, String::toInt)
consumer.consume("long_op", String::class, String::toLong)
consumer.consume("list_op", List::class) { it }
val client = RabbitMqClient(URI("amqp://guest:guest@localhost"))
assert(client.call("int_op", "123") == "123")
assert(client.call("long_op", "456") == "456")
assert(client.call("list_op", listOf(1, 3, 4).serialize()) == listOf(1, 3, 4).serialize())
client.close()
consumer.deleteQueue("int_op")
consumer.deleteQueue("long_op")
consumer.deleteQueue("list_op")
consumer.close()
}
@Test fun `Consumers handle no reply messages` () {
val consumer = RabbitMqClient(URI("amqp://guest:guest@localhost"))
consumer.declareQueue("int_handler")
consumer.declareQueue("long_handler")
consumer.declareQueue("exception_handler")
consumer.consume("int_handler", String::class) { log.info { it } }
consumer.consume("long_handler", String::class) { log.info { it } }
consumer.consume("exception_handler", String::class) { throw RuntimeException(it) }
val client = RabbitMqClient(URI("amqp://guest:guest@localhost"))
client.publish("int_handler", "123")
client.publish("long_handler", "456")
client.publish("exception_handler", "error")
client.publish("exception_handler", "")
client.close()
consumer.deleteQueue("int_handler")
consumer.deleteQueue("long_handler")
consumer.deleteQueue("exception_handler")
consumer.close()
}
}
| 8 | null | 0 | 1 | 4e233a24af0fea9d10b4946e21a7d60d1f7c60f3 | 4,776 | hexagon_extra | MIT License |
compiler/testData/loadJava/compiledKotlinWithStdlib/contracts/logicOperators.kt | JakeWharton | 99,388,807 | false | null | // !LANGUAGE: +AllowContractsForCustomFunctions +ReadDeserializedContracts
// !USE_EXPERIMENTAL: kotlin.contracts.ExperimentalContracts
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package test
import kotlin.contracts.*
fun orSequence(x: Any?, y: Any?, b: Boolean) {
contract {
returns() implies (x is String || y is Int || !b)
}
}
class A
class B
fun andSequence(x: Any?, y: Any?, b:Boolean) {
contract {
returns() implies (x is A && x is B && ((y is A) && b))
}
} | 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 516 | kotlin | Apache License 2.0 |
app/src/main/java/nerd/tuxmobil/fahrplan/congress/notifications/NotificationHelper.kt | grote | 114,628,676 | false | null | package nerd.tuxmobil.fahrplan.congress.notifications
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.ContextWrapper
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import nerd.tuxmobil.fahrplan.congress.R
import nerd.tuxmobil.fahrplan.congress.extensions.getNotificationManager
internal class NotificationHelper(context: Context) : ContextWrapper(context) {
private val notificationManager: NotificationManager by lazy {
getNotificationManager()
}
init {
createChannels()
}
fun createChannels(){
createNotificationChannel(SESSION_ALARM_CHANNEL_ID, sessionAlarmChannelName, sessionAlarmChannelDescription)
createNotificationChannel(SCHEDULE_UPDATE_CHANNEL_ID, scheduleUpdateChannelName, scheduleUpdateChannelDescription)
}
fun getSessionAlarmNotificationBuilder(
contentIntent: PendingIntent,
contentTitle: String,
occurredAt: Long,
sound: Uri?,
deleteIntent: PendingIntent
): NotificationCompat.Builder =
getNotificationBuilder(SESSION_ALARM_CHANNEL_ID, contentIntent, sessionAlarmContentText, sound)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setContentTitle(contentTitle)
.setDefaults(Notification.DEFAULT_LIGHTS or Notification.DEFAULT_VIBRATE)
.setWhen(occurredAt)
.setDeleteIntent(deleteIntent)
fun getScheduleUpdateNotificationBuilder(
contentIntent: PendingIntent,
contentText: String,
changesCount: Int,
sound: Uri?
): NotificationCompat.Builder =
getNotificationBuilder(SCHEDULE_UPDATE_CHANNEL_ID, contentIntent, contentText, sound)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setContentTitle(sessionAlarmContentTitle)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setSubText(getScheduleUpdateContentText(changesCount))
@JvmOverloads
fun notify(id: Int, builder: NotificationCompat.Builder, isInsistent: Boolean = false) {
val notification = builder.build()
if (isInsistent) {
notification.flags = notification.flags or Notification.FLAG_INSISTENT
}
notificationManager.notify(id, notification)
}
/**
* Cancels all existing schedule update notifications.
*/
fun cancelScheduleUpdateNotification() {
notificationManager.cancel(SCHEDULE_UPDATE_ID)
}
private fun createNotificationChannel(id: String, name: String, descriptionText: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
with(NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT)) {
description = descriptionText
lightColor = color
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(this)
}
}
}
private fun getNotificationBuilder(
channelId: String,
contentIntent: PendingIntent,
contentText: String,
sound: Uri?) =
NotificationCompat.Builder(this, channelId)
.setAutoCancel(true)
.setColor(color)
.setContentIntent(contentIntent)
.setContentText(contentText)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSmallIcon(smallIcon)
.setSound(sound)
private val sessionAlarmChannelDescription: String
get() = getString(R.string.notifications_session_alarm_channel_description)
private val sessionAlarmChannelName: String
get() = getString(R.string.notifications_session_alarm_channel_name)
private val sessionAlarmContentTitle: String
get() = getString(R.string.notifications_session_alarm_content_title)
private val sessionAlarmContentText: String
get() = getString(R.string.notifications_session_alarm_content_text)
private val scheduleUpdateChannelDescription: String
get() = getString(R.string.notifications_schedule_update_channel_description)
private val scheduleUpdateChannelName: String
get() = getString(R.string.notifications_schedule_update_channel_name)
private fun getScheduleUpdateContentText(changesCount: Int): String =
resources.getQuantityString(R.plurals.notifications_schedule_changes, changesCount, changesCount)
private val color: Int
get() = ContextCompat.getColor(this, R.color.colorAccent)
private val smallIcon: Int
get() = R.drawable.ic_notification
companion object {
private const val SESSION_ALARM_CHANNEL_ID = "SESSION_ALARM_CHANNEL"
private const val SCHEDULE_UPDATE_CHANNEL_ID = "SCHEDULE_UPDATE_CHANNEL"
const val SCHEDULE_UPDATE_ID = 2
}
}
| 76 | null | 99 | 3 | 761d339bf804698760db17ba00990e164f90cff2 | 5,224 | EventFahrplan | Apache License 2.0 |
src/main/kotlin/no/nav/tjenestepensjon/simulering/v1/soap/NorwegianSoapResponseInterceptor.kt | navikt | 184,583,998 | false | {"Kotlin": 338844, "Dockerfile": 97} | package no.nav.tjenestepensjon.simulering.v1.soap
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.ws.WebServiceMessage
import org.springframework.ws.client.support.interceptor.ClientInterceptor
import org.springframework.ws.context.MessageContext
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMResult
import javax.xml.transform.dom.DOMSource
class NorwegianSoapResponseInterceptor : ClientInterceptor {
private val logger = KotlinLogging.logger {}
private val transformer: Transformer = TransformerFactory.newInstance().newTransformer()
override fun handleRequest(messageContext: MessageContext) = true
override fun handleResponse(messageContext: MessageContext): Boolean {
reformatPayload(messageContext.response)
return true
}
override fun handleFault(messageContext: MessageContext): Boolean {
reformatPayload(messageContext.response)
return true
}
override fun afterCompletion(messageContext: MessageContext, ex: Exception?) {
}
private fun reformatPayload(message: WebServiceMessage) {
try {
val domResult = DOMResult()
transformer.transform(message.payloadSource, domResult)
val body = domResult.node?.apply {
if (nodeValue != null) {
nodeValue = nodeValue
.replace("Ø", "Oe").replace("ø", "oe")
.replace("Å", "Aa").replace("å", "aa")
.replace("Æ", "Ae").replace("æ", "ae")
}
}
if (body != null) {
val newMessageSource = DOMSource(body)
transformer.transform(newMessageSource, message.payloadResult)
}
} catch (e: Throwable) {
logger.error(e) { "Error reformatting payload ${e.message}" }
}
}
} | 8 | Kotlin | 0 | 0 | f9180440c8a800035dffbb5363af7918072c6ac9 | 1,950 | tjenestepensjon-simulering | MIT License |
kohttp-test/src/test/kotlin/io/github/rybalkinsd/kohttp/interceptors/SigningInterceptorTest.kt | rybalkinsd | 141,764,280 | false | null | package io.github.rybalkinsd.kohttp.interceptors
import io.github.rybalkinsd.kohttp.client.defaultHttpClient
import io.github.rybalkinsd.kohttp.client.fork
import io.github.rybalkinsd.kohttp.dsl.httpGet
import io.github.rybalkinsd.kohttp.interceptors.SigningInterceptor
import io.github.rybalkinsd.kohttp.jackson.ext.asJson
import org.junit.Test
import java.security.MessageDigest
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SigningInterceptorTest {
@Test
fun `signs request with MD5 algorithm`() {
val urlEncoder = Base64.getUrlEncoder()
val md5 = MessageDigest.getInstance("md5")
val client = defaultHttpClient.fork {
interceptors {
+SigningInterceptor("key") {
val query = (query() ?: "").toByteArray()
urlEncoder.encodeToString(md5.digest(query))
}
}
}
val s = "foo=bar&random=213".toByteArray(Charsets.UTF_8)
val expected = urlEncoder.encodeToString(md5.digest(s))
httpGet(client = client) {
host = "postman-echo.com"
path = "/get"
param {
"foo" to "bar"
"random" to 213
}
}.use {
val parsedResponse = it.asJson()
assertTrue { it.code() == 200 }
assertEquals(expected, parsedResponse["args"]["key"].asText())
}
}
}
| 38 | Kotlin | 41 | 470 | d7ea236df5bf899a73ebffe3ba8669074711c8df | 1,465 | kohttp | Apache License 2.0 |
test/com/intellij/completion/tracker/PrefixChangeListenerTest.kt | JetBrains | 45,971,220 | false | null | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.completion.tracker
import com.intellij.codeInsight.completion.LightFixtureCompletionTestCase
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.impl.PrefixChangeListener
import org.assertj.core.api.Assertions
class PrefixChangeListenerTest: LightFixtureCompletionTestCase() {
private val beforeChange = mutableListOf<LookupElement>()
private val afterChange = mutableListOf<LookupElement>()
private val lastLookupState = mutableListOf<LookupElement>()
override fun setUp() {
super.setUp()
setupCompletionContext(myFixture)
}
fun `test prefix change listener`() {
myFixture.completeBasic()
lookup.setPrefixChangeListener(object : PrefixChangeListener {
override fun afterAppend(c: Char) {
afterChange.clear()
afterChange.addAll(lookup.items)
}
override fun afterTruncate() {
afterChange.clear()
afterChange.addAll(lookup.items)
}
override fun beforeTruncate() {
beforeChange.clear()
beforeChange.addAll(lookup.items)
}
override fun beforeAppend(c: Char) {
beforeChange.clear()
beforeChange.addAll(lookup.items)
}
})
lastLookupState.clear()
lastLookupState.addAll(lookup.items)
afterChange.clear()
afterChange.addAll(lastLookupState)
check { myFixture.type('r') }
Assertions.assertThat(afterChange.size).isLessThan(beforeChange.size)
check { myFixture.type('u') }
Assertions.assertThat(afterChange.size).isLessThanOrEqualTo(beforeChange.size)
check { myFixture.type('\b') }
Assertions.assertThat(afterChange.size).isGreaterThanOrEqualTo(beforeChange.size)
check { myFixture.type('\b') }
Assertions.assertThat(afterChange.size).isGreaterThan(beforeChange.size)
}
private fun check(action: () -> Unit) {
lastLookupState.clear()
lastLookupState.addAll(lookup.items)
Assertions.assertThat(afterChange).isEqualTo(lastLookupState)
action()
Assertions.assertThat(beforeChange).isEqualTo(lastLookupState)
}
} | 2 | null | 2 | 8 | 3db7f480f7996504ee4edf3265469c88f182cae3 | 2,698 | intellij-stats-collector | Apache License 2.0 |
runtime/src/test/java/io/novafoundation/nova/runtime/multiNetwork/asset/EvmErc20AssetSyncServiceTest.kt | novasamatech | 415,834,480 | false | null | package io.novafoundation.nova.runtime.multiNetwork.asset
import com.google.gson.Gson
import io.novafoundation.nova.core_db.dao.ChainAssetDao
import io.novafoundation.nova.core_db.dao.ChainDao
import io.novafoundation.nova.core_db.model.chain.AssetSourceLocal
import io.novafoundation.nova.core_db.model.chain.ChainAssetLocal
import io.novafoundation.nova.runtime.multiNetwork.asset.remote.AssetFetcher
import io.novafoundation.nova.runtime.multiNetwork.asset.remote.model.EVMAssetRemote
import io.novafoundation.nova.runtime.multiNetwork.asset.remote.model.EVMInstanceRemote
import io.novafoundation.nova.runtime.multiNetwork.chain.mappers.chainAssetIdOfErc20Token
import io.novafoundation.nova.runtime.multiNetwork.chain.mappers.mapEVMAssetRemoteToLocalAssets
import io.novafoundation.nova.runtime.multiNetwork.chain.model.ChainId
import io.novafoundation.nova.test_shared.emptyDiff
import io.novafoundation.nova.test_shared.insertsElement
import io.novafoundation.nova.test_shared.removesElement
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.lenient
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class EvmErc20AssetSyncServiceTest {
private val chainId = "chainId"
private val contractAddress = "0xc748673057861a797275CD8A068AbB95A902e8de"
private val assetId = chainAssetIdOfErc20Token(contractAddress)
private val buyProviders = mapOf("transak" to mapOf("network" to "ETHEREUM"))
private val REMOTE_ASSET = EVMAssetRemote(
symbol = "USDT",
precision = 6,
priceId = "usd",
name = "USDT",
icon = "https://url.com",
instances = listOf(
EVMInstanceRemote(chainId, contractAddress, buyProviders)
)
)
private val gson = Gson()
private val LOCAL_ASSETS = createLocalCopy(REMOTE_ASSET)
@Mock
lateinit var dao: ChainAssetDao
@Mock
lateinit var chaindao: ChainDao
@Mock
lateinit var assetFetcher: AssetFetcher
lateinit var evmAssetSyncService: EvmAssetsSyncService
@Before
fun setup() {
evmAssetSyncService = EvmAssetsSyncService(chaindao, dao, assetFetcher, gson)
}
@Test
fun `should insert new asset`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(emptyList())
remoteReturns(listOf(REMOTE_ASSET))
evmAssetSyncService.syncUp()
verify(dao).updateAssets(
insertAsset(chainId, assetId),
)
}
}
@Test
fun `should not insert the same asset`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(LOCAL_ASSETS)
remoteReturns(listOf(REMOTE_ASSET))
evmAssetSyncService.syncUp()
verify(dao).updateAssets(emptyDiff())
}
}
@Test
fun `should update assets's own params`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(LOCAL_ASSETS)
remoteReturns(listOf(REMOTE_ASSET.copy(name = "new name")))
evmAssetSyncService.syncUp()
verify(dao).updateAssets(
insertAsset(chainId, assetId),
)
}
}
@Test
fun `should remove asset`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(LOCAL_ASSETS)
remoteReturns(emptyList())
evmAssetSyncService.syncUp()
verify(dao).updateAssets(
removeAsset(chainId, assetId),
)
}
}
@Test
fun `should not overwrite enabled state`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(LOCAL_ASSETS.map { it.copy(enabled = false) })
remoteReturns(listOf(REMOTE_ASSET))
evmAssetSyncService.syncUp()
verify(dao).updateAssets(
emptyDiff(),
)
}
}
@Test
fun `should not modify manual assets`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(LOCAL_ASSETS)
localReturnsManual(emptyList())
remoteReturns(listOf(REMOTE_ASSET))
evmAssetSyncService.syncUp()
verify(dao).updateAssets(
emptyDiff(),
)
}
}
@Test
fun `should not insert assets for non-present chain`() {
runBlocking {
localHasChains(chainId)
localReturnsERC20(emptyList())
remoteReturns(listOf(REMOTE_ASSET.copy(instances = listOf(EVMInstanceRemote("changedChainId", contractAddress, buyProviders)))))
evmAssetSyncService.syncUp()
verify(dao).updateAssets(emptyDiff())
}
}
private suspend fun remoteReturns(assets: List<EVMAssetRemote>) {
`when`(assetFetcher.getEVMAssets()).thenReturn(assets)
}
private suspend fun localReturnsERC20(assets: List<ChainAssetLocal>) {
`when`(dao.getAssetsBySource(AssetSourceLocal.ERC20)).thenReturn(assets)
}
private suspend fun localHasChains(vararg chainIds: ChainId) {
`when`(chaindao.getAllChainIds()).thenReturn(chainIds.toList())
}
private suspend fun localReturnsManual(assets: List<ChainAssetLocal>) {
lenient().`when`(dao.getAssetsBySource(AssetSourceLocal.MANUAL)).thenReturn(assets)
}
private fun insertAsset(chainId: String, id: Int) = insertsElement<ChainAssetLocal> { it.chainId == chainId && it.id == id }
private fun removeAsset(chainId: String, id: Int) = removesElement<ChainAssetLocal> { it.chainId == chainId && it.id == id }
private fun createLocalCopy(remote: EVMAssetRemote): List<ChainAssetLocal> {
return mapEVMAssetRemoteToLocalAssets(remote, gson)
}
}
| 5 | null | 9 | 9 | b39307cb56302ce7298582dbd03f33f6b2e2a807 | 5,983 | nova-wallet-android | Apache License 2.0 |
catalog/src/main/java/net/pixiv/charcoal/android/catalog/typography/TypographyActivity.kt | pixiv | 580,258,047 | false | {"Kotlin": 120287, "JavaScript": 12005, "Java": 2332} | package net.pixiv.charcoal.android.catalog.typography
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.wada811.viewbinding.viewBinding
import net.pixiv.charcoal.android.catalog.R
import net.pixiv.charcoal.android.catalog.databinding.ActivityTypographyBinding
import net.pixiv.charcoal.android.catalog.extension.setSupportActionBarWithHomeButtonAndTitle
class TypographyActivity : AppCompatActivity(R.layout.activity_typography) {
private val binding by viewBinding(ActivityTypographyBinding::bind)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBarWithHomeButtonAndTitle(binding.toolBar, "Typography")
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
companion object {
fun createIntent(context: Context): Intent {
return Intent(context, TypographyActivity::class.java)
}
}
}
| 10 | Kotlin | 5 | 28 | cd47a135bb1101c4171d36f7098eb135f6b53ab1 | 1,250 | charcoal-android | Apache License 2.0 |
app/src/main/java/com/prafullm/jetcomposer/screens/Home.kt | everton4292 | 380,003,498 | true | {"Kotlin": 31637} | package com.prafullm.jetcomposer.screens
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.prafullm.jetcomposer.R
import com.prafullm.jetcomposer.model.Destination
import com.prafullm.jetcomposer.model.HomeItem
@ExperimentalMaterialApi
@Composable
fun HomeScreen(
screens: List<HomeItem>,
onItemClick:(destination: Destination) -> Unit,
onThemeSwitch: () -> Unit
) {
Column(
Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background)) {
HomeHeader(onThemeSwitch)
HomeList(
modifier = Modifier.weight(1f),
screens = screens,
onItemClick = onItemClick
)
}
}
@Composable
fun HomeHeader(onThemeSwitch:() -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(bottom = 24.dp, top = 24.dp)) {
Text(
text = "Jet Composer",
fontSize = 32.sp,
fontWeight = FontWeight.Black,
fontFamily = FontFamily.Serif,
color = MaterialTheme.colors.onSurface,
modifier = Modifier
.weight(1f)
.padding(start = 24.dp, end = 16.dp)
)
val icon = if (MaterialTheme.colors.isLight) {
ImageVector.vectorResource(id = R.drawable.ic_round_wb_sunny_24)
} else {
ImageVector.vectorResource(id = R.drawable.ic_round_nightlight_24)
}
IconButton(
onClick = onThemeSwitch
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colors.onSurface,
modifier = Modifier.rotate(-45f)
)
}
Spacer(modifier = Modifier.width(20.dp))
}
}
@ExperimentalMaterialApi
@Composable
fun HomeList(modifier: Modifier, screens: List<HomeItem>, onItemClick: (destination: Destination) -> Unit) {
LazyColumn(
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, bottom = 20.dp, top = 8.dp),
verticalArrangement = Arrangement.spacedBy(20.dp),
modifier = modifier.fillMaxWidth()) {
items(screens) { screen ->
HomeListItem(screen = screen, onItemClick = onItemClick)
}
item {
HomeListFooter()
}
}
}
@Composable
fun HomeListFooter() {
Text(
text = "Created & maintained by @NotYourPM",
color = MaterialTheme.colors.secondary,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Light,
fontSize = 13.sp,
modifier = Modifier
.fillMaxWidth()
.alpha(0.5f)
.padding(vertical = 16.dp)
)
}
@ExperimentalMaterialApi
@Composable
fun HomeListItem(screen: HomeItem, onItemClick: (destination: Destination) -> Unit) {
Card(
backgroundColor = MaterialTheme.colors.surface,
shape = RoundedCornerShape(16.dp),
elevation = 0.dp,
modifier = Modifier
.fillMaxWidth(),
onClick = { onItemClick(screen.destination) }
) {
Row(
Modifier
.fillMaxWidth()
.padding(20.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(Modifier.weight(1f)) {
Text(
text = stringResource(id = screen.title),
fontSize = 18.sp,
fontWeight = FontWeight.Medium,
maxLines = 1,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = stringResource(id = screen.subtitle),
fontSize = 14.sp,
fontWeight = FontWeight.Light,
maxLines = 1,
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colors.secondary
)
}
Icon(
imageVector = ImageVector.vectorResource(id = R.drawable.ic_round_chevron_right_24),
contentDescription = "",
tint = MaterialTheme.colors.onSurface
)
}
}
}
@ExperimentalAnimationApi
@ExperimentalMaterialApi
@Composable
@Preview
fun ListItemPreview() {
HomeListItem(
screen = HomeItem(
title = R.string.item_tv_static,
subtitle = R.string.item_tv_static_sub,
destination = Destination.TvStatic
),
onItemClick = {}
)
} | 0 | null | 0 | 0 | 69a1dc31ea5f77da51f75fd07f6069051fbb375e | 5,657 | JetComposer | MIT License |
ambassador-application/src/main/kotlin/com/roche/ambassador/projects/ProjectHistoryDto.kt | filipowm | 409,076,487 | false | null | package com.roche.ambassador.projects
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import com.roche.ambassador.model.Visibility
import com.roche.ambassador.storage.project.ProjectHistoryEntity
import java.time.LocalDate
import java.time.LocalDateTime
@JsonPropertyOrder("id", "name", "indexedDate", "score")
data class ProjectHistoryDto(
val url: String?,
val name: String,
val description: String?,
val topics: List<String>?,
val visibility: Visibility,
val lastUpdatedDate: LocalDate?,
val mainLanguage: String?,
val criticalityScore: Double,
val activityScore: Double,
val stars: Int,
val score: Double,
val indexedDate: LocalDateTime
) {
companion object {
fun from(projectHistoryEntity: ProjectHistoryEntity): ProjectHistoryDto {
val project = projectHistoryEntity.project
return ProjectHistoryDto(
project.url, project.name,
project.description, project.topics, project.visibility,
project.lastActivityDate, project.getMainLanguage(),
project.getScores().criticality, project.getScores().activity,
project.stats.stars ?: 0, project.getScores().total, projectHistoryEntity.indexedDate
)
}
}
}
| 22 | Kotlin | 0 | 9 | 87b3db67dea1a19df1011337babb42b068d21171 | 1,301 | the-ambassador | Apache License 2.0 |
app/src/main/java/com/thedefiapp/usecases/mappers/ConvertToPortfolioTotalBalanceUseCase.kt | saulmaos | 459,017,062 | false | null | package com.thedefiapp.usecases.mappers
import com.thedefiapp.data.models.PortfolioTotalBalance
import com.thedefiapp.data.remote.response.ComplexProtocolListResponse
import com.thedefiapp.data.remote.response.TotalBalanceResponse
import com.thedefiapp.data.repositories.AddressProvider
import com.thedefiapp.usecases.utils.ConvertToFormattedNumberUseCase
import com.thedefiapp.utils.DEFAULT_AMOUNT_OF_DECIMALS_FOR_PRICES
import com.thedefiapp.utils.toShortAddressFormat
import javax.inject.Inject
class ConvertToPortfolioTotalBalanceUseCase @Inject constructor(
private val convertToFormattedNumberUseCase: ConvertToFormattedNumberUseCase,
private val addressProvider: AddressProvider
) {
operator fun invoke(
totalBalanceResponse: TotalBalanceResponse,
complexProtocolListResponse: List<ComplexProtocolListResponse>
): PortfolioTotalBalance {
var todayEarnings = 0.0
complexProtocolListResponse.map { protocol ->
protocol.portfolioItems.forEach {
todayEarnings += it.stats.dailyNetYieldUsdValue
}
}
return PortfolioTotalBalance(
totalBalance = convertToFormattedNumberUseCase(totalBalanceResponse.totalUsdValue),
todayEarnings = convertToFormattedNumberUseCase(
todayEarnings,
amountOfDecimals = DEFAULT_AMOUNT_OF_DECIMALS_FOR_PRICES
),
address = addressProvider.getAddress().toShortAddressFormat()
)
}
}
| 0 | Kotlin | 1 | 0 | b58abbc9cc98d9534a876fba4400121acb222586 | 1,505 | thedefiapp | MIT License |
src/opennlp-conll/main/opennlp/ext/conll/treebank/POSTagset.kt | rhdunn | 418,266,921 | false | null | // Copyright (C) 2021 <NAME>. SPDX-License-Identifier: Apache-2.0
package opennlp.ext.conll.treebank
// Reference: [CoNLL-X Format](https://ilk.uvt.nl/~emarsi/download/pubs/14964.pdf)
// Reference: [CoNLL-U Format](https://universaldependencies.org/format.html)
enum class POSTagset(val conllxField: String, val conlluField: String) {
Universal("CPOSTAG", "UPOS"),
LanguageSpecific("POSTAG", "XPOS"),
UniversalAndPTB("CPOSTAG-PTB", "UPOS-PTB")
}
| 0 | Kotlin | 0 | 3 | 3b0f35236af1773bf28a5ccec8c2e8bf7a3de9b2 | 459 | opennlp-extensions | Apache License 2.0 |
cli/src/main/kotlin/io/github/nickacpt/patchify/cli/model/WorkspaceDefinition.kt | NickAcPT | 287,130,022 | false | null | package io.github.nickacpt.patchify.cli.model
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.github.nickacpt.patchify.core.model.PatchifyWorkspace
import java.nio.file.Path
import kotlin.io.path.pathString
data class WorkspaceDefinition(
val sourceDir: String,
val patchesDir: String,
) {
companion object {
private val mapper = jacksonObjectMapper()
fun fromJson(json: String): WorkspaceDefinition {
return mapper.readValue(json, WorkspaceDefinition::class.java)
}
fun toJson(workspace: WorkspaceDefinition): String {
return mapper.writeValueAsString(workspace)
}
fun fromWorkspace(workspace: PatchifyWorkspace, currentPath: Path): WorkspaceDefinition {
return WorkspaceDefinition(
sourceDir = currentPath.relativize(workspace.sourceDirectory).pathString,
patchesDir = currentPath.relativize(workspace.patchesDirectory).pathString
)
}
fun toWorkspace(definition: WorkspaceDefinition, currentPath: Path): PatchifyWorkspace {
return PatchifyWorkspace(
sourceDirectory = currentPath.resolve(definition.sourceDir),
patchesDirectory = currentPath.resolve(definition.patchesDir)
)
}
}
}
| 0 | Kotlin | 0 | 5 | b9753014e7b553bcbee9a596dedc321aa0409f49 | 1,338 | Patchify | MIT License |
common/src/main/java/common/AppContext.kt | lcszc | 256,382,727 | false | {"Kotlin": 201531} | package common
import javax.inject.Qualifier
@Qualifier @Retention annotation class AppContext
| 2 | Kotlin | 2 | 35 | a2f02de29c4c074b5ecbda4a46349ac5b864842d | 97 | Boletinhos | MIT License |
utbot-js/src/main/kotlin/framework/codegen/model/constructor/tree/JsTestFrameworkManager.kt | UnitTestBot | 480,810,501 | false | null | package framework.codegen.model.constructor.tree
import framework.codegen.Mocha
import framework.codegen.jsAssertEquals
import framework.codegen.jsAssertThrows
import org.utbot.framework.codegen.domain.context.CgContext
import org.utbot.framework.codegen.domain.context.TestClassContext
import org.utbot.framework.codegen.domain.models.CgAnnotation
import org.utbot.framework.codegen.domain.models.CgValue
import org.utbot.framework.codegen.domain.models.CgVariable
import org.utbot.framework.codegen.services.framework.TestFrameworkManager
import org.utbot.framework.plugin.api.ClassId
class MochaManager(context: CgContext) : TestFrameworkManager(context) {
override val isExpectedExceptionExecutionBreaking: Boolean = true
override fun expectException(exception: ClassId, block: () -> Unit) {
require(testFramework is Mocha) { "According to settings, Mocha.js was expected, but got: $testFramework" }
val lambda = statementConstructor.lambda(exception) { block() }
+assertions[jsAssertThrows](lambda, "Error", exception.name)
}
override fun addDataProviderAnnotations(dataProviderMethodName: String) {
error("Parametrized tests are not supported for JavaScript")
}
override fun createArgList(length: Int): CgVariable {
error("Parametrized tests are not supported for JavaScript")
}
override fun addParameterizedTestAnnotations(dataProviderMethodName: String?) {
error("Parametrized tests are not supported for JavaScript")
}
override fun passArgumentsToArgsVariable(argsVariable: CgVariable, argsArray: CgVariable, executionIndex: Int) {
error("Parametrized tests are not supported for JavaScript")
}
override fun addTestDescription(description: String) {
TODO("Not yet implemented")
}
override val dataProviderMethodsHolder: TestClassContext
get() = error("Parametrized tests are not supported for JavaScript")
override fun addAnnotationForNestedClasses() {
error("Nested classes annotation does not exist in Mocha")
}
override fun assertEquals(expected: CgValue, actual: CgValue) {
+assertions[jsAssertEquals](expected, actual)
}
override fun disableTestMethod(reason: String) {
}
}
| 415 | Kotlin | 38 | 91 | abb62682c70d7d2ecc4ad610851d304f7ad716e4 | 2,270 | UTBotJava | Apache License 2.0 |
core/src/main/java/dev/sunnyday/core/propertydelegate/propertyOf.kt | SunnyDayDev | 178,215,276 | false | null | package dev.sunnyday.core.propertydelegate
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <O, T> propertyOf(owner: O, prop: ReadWriteProperty<O, T>) = object :
ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T = prop.getValue(owner, property)
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) =
prop.setValue(owner, property, value)
}
fun <O, T> propertyOf(owner: O, prop: ReadOnlyProperty<O, T>) =
ReadOnlyProperty<Any, T> { _, property -> prop.getValue(owner, property) } | 0 | Kotlin | 0 | 0 | ec79bad3cc61ecb2e0b2fa651caa6f73ccf39b33 | 639 | core | MIT License |
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/InterfaceDelegationLowering.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.jvm.lower
import org.jetbrains.kotlin.backend.common.ClassLoweringPass
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.backend.jvm.JvmLoweredStatementOrigin
import org.jetbrains.kotlin.backend.jvm.descriptors.DefaultImplsClassDescriptor
import org.jetbrains.kotlin.backend.jvm.descriptors.DefaultImplsClassDescriptorImpl
import org.jetbrains.kotlin.codegen.isDefinitelyNotDefaultImplsMethod
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrBlockBodyImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrGetValueImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl
import org.jetbrains.kotlin.ir.util.createParameterDeclarations
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.resolve.DescriptorUtils
class InterfaceDelegationLowering(val state: GenerationState) : IrElementTransformerVoid(), ClassLoweringPass {
override fun lower(irClass: IrClass) {
val descriptor = irClass.descriptor
if (DescriptorUtils.isInterface(descriptor)) {
return
}
irClass.transformChildrenVoid(this)
generateInterfaceMethods(irClass, descriptor)
}
private fun generateInterfaceMethods(irClass: IrClass, descriptor: ClassDescriptor) {
val classDescriptor = if (descriptor is DefaultImplsClassDescriptor) descriptor.correspondingInterface else descriptor
for ((interfaceFun, value) in CodegenUtil.getNonPrivateTraitMethods(classDescriptor)) {
//skip java 8 default methods
if (!interfaceFun.isDefinitelyNotDefaultImplsMethod()) {
val inheritedFun =
if (classDescriptor !== descriptor) {
InterfaceLowering.createDefaultImplFunDescriptor(
descriptor as DefaultImplsClassDescriptorImpl,
interfaceFun,
classDescriptor,
state.typeMapper
)
} else {
value
}
generateDelegationToDefaultImpl(irClass, interfaceFun, inheritedFun)
}
}
}
private fun generateDelegationToDefaultImpl(irClass: IrClass, interfaceFun: FunctionDescriptor, inheritedFun: FunctionDescriptor) {
val irBody = IrBlockBodyImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET)
val irFunction = IrFunctionImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, IrDeclarationOrigin.DEFINED, inheritedFun, irBody)
irFunction.createParameterDeclarations()
irClass.declarations.add(irFunction)
val interfaceDescriptor = interfaceFun.containingDeclaration as ClassDescriptor
val defaultImpls = InterfaceLowering.createDefaultImplsClassDescriptor(interfaceDescriptor)
val defaultImplFun =
InterfaceLowering.createDefaultImplFunDescriptor(defaultImpls, interfaceFun.original, interfaceDescriptor, state.typeMapper)
val returnType = inheritedFun.returnType!!
val irCallImpl =
IrCallImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, defaultImplFun, null, JvmLoweredStatementOrigin.DEFAULT_IMPLS_DELEGATION)
irBody.statements.add(IrReturnImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, inheritedFun, irCallImpl))
var shift = 0
if (inheritedFun.dispatchReceiverParameter != null) {
irCallImpl.putValueArgument(0, IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, interfaceFun.dispatchReceiverParameter!!))
shift = 1
}
inheritedFun.valueParameters.mapIndexed { i, valueParameterDescriptor ->
irCallImpl.putValueArgument(i + shift, IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, valueParameterDescriptor, null))
}
}
}
| 3 | null | 4 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 4,960 | kotlin | Apache License 2.0 |
app/src/main/java/de/cleema/android/projects/list/ProjectsViewModel.kt | sandstorm | 840,235,083 | false | {"Kotlin": 955115, "Ruby": 1773} | /*
* Created by Kumpels and Friends on 2022-12-15
* Copyright © 2022 Kumpels and Friends. All rights reserved.
*/
package de.cleema.android.projects.list
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.cleema.android.core.data.ProjectsRepository
import de.cleema.android.core.data.UserRepository
import de.cleema.android.projects.list.ProjectsUiState.*
import de.cleema.android.shared.RegionForCurrentUserUseCase
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject
sealed interface ProjectsUiState {
data class Content(val projects: List<de.cleema.android.core.models.Project>) : ProjectsUiState
data class Error(val reason: String) : ProjectsUiState
object Loading : ProjectsUiState
}
@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class ProjectsViewModel @Inject constructor(
private val projectsRepository: ProjectsRepository,
userRepository: UserRepository
) : ViewModel() {
private val regionForCurrentUserUseCase = RegionForCurrentUserUseCase(userRepository)
private var selectedRegion = MutableStateFlow<UUID?>(null)
val uiState: StateFlow<ProjectsUiState> =
selectedRegion
.onStart { emit(regionForCurrentUserUseCase().id) }
.filterNotNull()
.flatMapLatest { regionId ->
projectsRepository.getProjectsStream(regionId = regionId).map { result ->
result.fold(onSuccess = ::Content, onFailure = {
Error(it.localizedMessage ?: it.toString())
})
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = Loading
)
fun favClicked(uuid: UUID) {
when (val state = uiState.value) {
is Content ->
state.projects.find { it.id == uuid }?.let { project ->
viewModelScope.launch {
projectsRepository.fav(
project.id,
project.isFaved.not()
)
}
}
else -> return
}
}
fun setRegion(regionId: UUID) {
selectedRegion.value = regionId
}
}
| 0 | Kotlin | 0 | 1 | ddcb7ddedbbefb8045e7299e14a2ad47329fc53e | 2,486 | cleema-android | MIT License |
tools/cli/src/main/kotlin/foundry/cli/shellsentry/ShellSentryCli.kt | slackhq | 481,715,971 | false | {"Kotlin": 1070954, "Shell": 11155, "HTML": 1503, "Swift": 207} | /*
* Copyright (C) 2023 Slack Technologies, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 slack.cli.shellsentry
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.path
import com.google.auto.service.AutoService
import org.jetbrains.annotations.TestOnly
import slack.cli.CommandFactory
import slack.cli.projectDirOption
/**
* Executes a command with Bugsnag tracing and retries as needed. This CLI is a shim over
* [ShellSentry].
*
* Example:
* ```
* $ ./<binary> --bugsnag-key=1234 --verbose --configurationFile config.json ./gradlew build
* ```
*/
public class ShellSentryCli : CliktCommand(DESCRIPTION) {
private companion object {
const val DESCRIPTION = "Executes a command with Bugsnag tracing and retries as needed."
}
@AutoService(CommandFactory::class)
public class Factory : CommandFactory {
override val key: String = "shell-sentry"
override val description: String = DESCRIPTION
override fun create(): CliktCommand = ShellSentryCli()
}
internal val projectDir by projectDirOption()
internal val verbose by option("--verbose", "-v").flag()
internal val bugsnagKey by option("--bugsnag-key", envvar = "PE_BUGSNAG_KEY")
internal val configurationFile by
option("--config", envvar = "PE_CONFIGURATION_FILE")
.path(mustExist = true, canBeFile = true, canBeDir = false)
internal val debug by option("--debug", "-d").flag()
@get:TestOnly
internal val noExit by
option(
"--no-exit",
help = "Instructs this CLI to not exit the process with the status code. Test only!"
)
.flag()
@get:TestOnly internal val parseOnly by option("--parse-only").flag(default = false)
internal val args by argument().multiple()
override fun run() {
if (parseOnly) return
return ShellSentry.create(this).exec()
}
}
| 6 | Kotlin | 4 | 430 | 433b2e4b98288fbd59ef7b475be8616f1a1fe859 | 2,619 | foundry | Apache License 2.0 |
arrow-libs/optics/arrow-optics-test/src/commonMain/kotlin/arrow/optics/test/laws/LensLaws.kt | lukaszkalnik | 427,116,886 | false | null | package arrow.optics.test.laws
import arrow.core.compose
import arrow.core.identity
import arrow.optics.Lens
import arrow.core.test.laws.Law
import arrow.core.test.laws.equalUnderTheLaw
import io.kotest.property.Arb
import io.kotest.property.PropertyContext
import io.kotest.property.arbitrary.constant
import io.kotest.property.checkAll
public object LensLaws {
public fun <A, B> laws(
lensGen: Arb<Lens<A, B>>,
aGen: Arb<A>,
bGen: Arb<B>,
funcGen: Arb<(B) -> B>,
eqa: (A, A) -> Boolean = { a, b -> a == b },
eqb: (B, B) -> Boolean = { a, b -> a == b }
): List<Law> =
listOf(
Law("Lens law: get set") { lensGetSet(lensGen, aGen, eqa) },
Law("Lens law: set get") { lensSetGet(lensGen, aGen, bGen, eqb) },
Law("Lens law: is set idempotent") { lensSetIdempotent(lensGen, aGen, bGen, eqa) },
Law("Lens law: modify identity") { lensModifyIdentity(lensGen, aGen, eqa) },
Law("Lens law: compose modify") { lensComposeModify(lensGen, aGen, funcGen, eqa) },
Law("Lens law: consistent set modify") { lensConsistentSetModify(lensGen, aGen, bGen, eqa) }
)
/**
* Warning: Use only when a `Gen.constant()` applies
*/
public fun <A, B> laws(
lens: Lens<A, B>,
aGen: Arb<A>,
bGen: Arb<B>,
funcGen: Arb<(B) -> B>,
eqa: (A, A) -> Boolean = { a, b -> a == b },
eqb: (B, B) -> Boolean = { a, b -> a == b }
): List<Law> = laws(Arb.constant(lens), aGen, bGen, funcGen, eqa, eqb)
public suspend fun <A, B> lensGetSet(lensGen: Arb<Lens<A, B>>, aGen: Arb<A>, eq: (A, A) -> Boolean): PropertyContext =
checkAll(100, lensGen, aGen) { lens, a ->
lens.run {
set(a, get(a)).equalUnderTheLaw(a, eq)
}
}
public suspend fun <A, B> lensSetGet(lensGen: Arb<Lens<A, B>>, aGen: Arb<A>, bGen: Arb<B>, eq: (B, B) -> Boolean): PropertyContext =
checkAll(100, lensGen, aGen, bGen) { lens, a, b ->
lens.run {
get(set(a, b)).equalUnderTheLaw(b, eq)
}
}
public suspend fun <A, B> lensSetIdempotent(lensGen: Arb<Lens<A, B>>, aGen: Arb<A>, bGen: Arb<B>, eq: (A, A) -> Boolean): PropertyContext =
checkAll(100, lensGen, aGen, bGen) { lens, a, b ->
lens.run {
set(set(a, b), b).equalUnderTheLaw(set(a, b), eq)
}
}
public suspend fun <A, B> lensModifyIdentity(lensGen: Arb<Lens<A, B>>, aGen: Arb<A>, eq: (A, A) -> Boolean): PropertyContext =
checkAll(100, lensGen, aGen) { lens, a ->
lens.run {
modify(a, ::identity).equalUnderTheLaw(a, eq)
}
}
public suspend fun <A, B> lensComposeModify(lensGen: Arb<Lens<A, B>>, aGen: Arb<A>, funcGen: Arb<(B) -> B>, eq: (A, A) -> Boolean): PropertyContext =
checkAll(100, lensGen, aGen, funcGen, funcGen) { lens, a, f, g ->
lens.run {
modify(modify(a, f), g).equalUnderTheLaw(modify(a, g compose f), eq)
}
}
public suspend fun <A, B> lensConsistentSetModify(lensGen: Arb<Lens<A, B>>, aGen: Arb<A>, bGen: Arb<B>, eq: (A, A) -> Boolean): PropertyContext =
checkAll(100, lensGen, aGen, bGen) { lens, a, b ->
lens.run {
set(a, b).equalUnderTheLaw(modify(a) { b }, eq)
}
}
}
| 1 | null | 0 | 1 | 73fa3847df1f04e634a02bba527917389b59d7df | 3,157 | arrow | Apache License 2.0 |
src/main/kotlin/com/hiberus/anaya/redmineeditor/utils/SimpleListCell.kt | anayaHiberus | 645,313,511 | false | {"Kotlin": 191286, "Java": 692, "Batchfile": 473, "Shell": 282, "CSS": 43} | package com.hiberus.anaya.redmineeditor.utils
import javafx.fxml.FXMLLoader
import javafx.scene.control.ContentDisplay
import javafx.scene.control.ListCell
import java.net.URL
/**
* A ListCell that loads its data from a fxml file
* Adapted from https://stackoverflow.com/a/47526952
*
* @param fxml the fxml file to load (from the module root)
* @param <T> type of data for this cell
*/
abstract class SimpleListCell<T>(fxml: URL) : ListCell<T>() {
init {
// initialize ListCell by loading the fxml file
FXMLLoader(fxml).apply {
setController(this@SimpleListCell)
setRoot(this@SimpleListCell)
load()
}
}
public override fun updateItem(item: T, empty: Boolean) {
super.updateItem(item, empty)
if (empty || item == null) {
// empty cell
text = null
contentDisplay = ContentDisplay.TEXT_ONLY
style = null // clear style
} else {
// cell with content
update()
contentDisplay = ContentDisplay.GRAPHIC_ONLY
}
}
/** Update here the content of the cell */
protected abstract fun update()
}
| 1 | Kotlin | 0 | 3 | b0bac42c74907f2b29b832a2e6bd1d57f3831e5f | 1,194 | redmineeditor | Creative Commons Attribution 4.0 International |
src/main/kotlin/org/http4k/intellij/step/QuestionnaireStep.kt | http4k | 844,511,114 | false | {"Kotlin": 28752} | package org.http4k.intellij.step
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import org.http4k.intellij.utils.setNextTo
import org.http4k.intellij.wizard.Questionnaire
class QuestionnaireStep(
private val questionnaire: Questionnaire,
private val wizardContext: WizardContext,
private val onComplete: OnComplete
) : ModuleWizardStep() {
init {
wizardContext.setNextTo(false)
}
override fun getComponent() = QuestionnaireView(questionnaire, onComplete)
override fun updateDataModel() {
wizardContext.setNextTo(true)
}
}
| 0 | Kotlin | 0 | 2 | 324d2e4f24fff1d0495187e6743bb687830286a2 | 645 | intellij-plugin | Apache License 2.0 |
core/src/commonMain/kotlin/com/boswelja/ephemeris/core/data/CalendarPageSource.kt | boswelja | 455,066,630 | false | {"Kotlin": 149027} | package com.boswelja.ephemeris.core.data
import com.boswelja.ephemeris.core.model.CalendarPage
import kotlinx.datetime.LocalDate
/**
* The core calendar page source interface. Calendar page sources are used to provide a layout to
* calendar pages. See [CalendarMonthPageSource] and [CalendarWeekPageSource] for default
* implementations.
*/
public interface CalendarPageSource {
/**
* Whether this page source has dates that may overlap from one page to the next. Ephemeris may
* use this to determine whether additional updates are necessary when changing a date.
*/
public val hasOverlappingDates: Boolean
/**
* Defines the maximum number of pages to be displayed. Pages are zero-based, therefore negative
* values represent pages before the start page, and positive values represent pages after the
* start page. Note the total number of pages should not exceed [Int.MAX_VALUE].
*/
public val maxPageRange: IntRange
/**
* Takes a page number and a DisplayDate producer, and returns a set of rows to display in the
* calendar UI. This should not implement any caching itself, caching is handled by consumers.
*/
public fun loadPageData(page: Int): CalendarPage
/**
* Get the page number for the given date. This function should be as lightweight as possible,
* as no results here are cached.
*/
public fun getPageFor(date: LocalDate): Int
/**
* Maps the given internal position of a zero-based pager to the page number. Note this is not
* necessary if we have a pager that supports negative numbers in the first place.
*/
public fun mapInternalPositionToPage(position: Int): Int {
return position + maxPageRange.first
}
/**
* Maps the given page number to an internal zero-based position. Note this is not
* necessary if we have a pager that supports negative numbers in the first place.
*/
public fun mapPageToInternalPosition(page: Int): Int {
return page - maxPageRange.first
}
}
| 6 | Kotlin | 3 | 9 | 180c45500ca9505fdd36bd853295f4eb0fac11cb | 2,064 | Ephemeris | MIT License |
feature-staking-impl/src/main/java/jp/co/soramitsu/feature_staking_impl/presentation/staking/redeem/RedeemViewModel.kt | soramitsu | 278,060,397 | false | null | package jp.co.soramitsu.feature_staking_impl.presentation.staking.redeem
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import jp.co.soramitsu.common.R
import jp.co.soramitsu.common.address.AddressIconGenerator
import jp.co.soramitsu.common.base.BaseViewModel
import jp.co.soramitsu.common.mixin.api.Validatable
import jp.co.soramitsu.common.resources.ResourceManager
import jp.co.soramitsu.common.utils.format
import jp.co.soramitsu.common.utils.formatAsCurrency
import jp.co.soramitsu.common.utils.inBackground
import jp.co.soramitsu.common.utils.requireException
import jp.co.soramitsu.common.utils.requireValue
import jp.co.soramitsu.common.validation.ValidationExecutor
import jp.co.soramitsu.common.validation.progressConsumer
import jp.co.soramitsu.feature_account_api.presenatation.actions.ExternalAccountActions
import jp.co.soramitsu.feature_staking_api.domain.model.StakingState
import jp.co.soramitsu.feature_staking_impl.domain.StakingInteractor
import jp.co.soramitsu.feature_staking_impl.domain.staking.redeem.RedeemInteractor
import jp.co.soramitsu.feature_staking_impl.domain.validations.reedeem.RedeemValidationPayload
import jp.co.soramitsu.feature_staking_impl.domain.validations.reedeem.RedeemValidationSystem
import jp.co.soramitsu.feature_staking_impl.presentation.StakingRouter
import jp.co.soramitsu.feature_wallet_api.data.mappers.mapAssetToAssetModel
import jp.co.soramitsu.feature_wallet_api.domain.model.Asset
import jp.co.soramitsu.feature_wallet_api.domain.model.amountFromPlanks
import jp.co.soramitsu.feature_wallet_api.presentation.mixin.FeeLoaderMixin
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.math.BigDecimal
class RedeemViewModel(
private val router: StakingRouter,
private val interactor: StakingInteractor,
private val redeemInteractor: RedeemInteractor,
private val resourceManager: ResourceManager,
private val validationExecutor: ValidationExecutor,
private val validationSystem: RedeemValidationSystem,
private val iconGenerator: AddressIconGenerator,
private val feeLoaderMixin: FeeLoaderMixin.Presentation,
private val externalAccountActions: ExternalAccountActions.Presentation,
private val payload: RedeemPayload
) : BaseViewModel(),
Validatable by validationExecutor,
FeeLoaderMixin by feeLoaderMixin,
ExternalAccountActions by externalAccountActions {
private val _showNextProgress = MutableLiveData(false)
val showNextProgress: LiveData<Boolean> = _showNextProgress
private val accountStakingFlow = interactor.selectedAccountStakingStateFlow()
.filterIsInstance<StakingState.Stash>()
.share()
private val assetFlow = accountStakingFlow
.flatMapLatest { interactor.assetFlow(it.controllerAddress) }
.share()
val amountLiveData = assetFlow.map { asset ->
val redeemable = asset.redeemable
redeemable.format() to asset.token.fiatAmount(redeemable)?.formatAsCurrency()
}
.inBackground()
.asLiveData()
val assetModelLiveData = assetFlow.map { asset ->
mapAssetToAssetModel(asset, resourceManager, Asset::redeemable, R.string.staking_redeemable_format)
}
val originAddressModelLiveData = accountStakingFlow.map {
val address = it.controllerAddress
val account = interactor.getAccount(address)
iconGenerator.createAddressModel(address, AddressIconGenerator.SIZE_SMALL, account.name)
}
.inBackground()
.asLiveData()
init {
loadFee()
}
fun confirmClicked() {
maybeGoToNext()
}
fun backClicked() {
router.back()
}
fun originAccountClicked() {
val address = originAddressModelLiveData.value?.address ?: return
val externalActionsPayload = ExternalAccountActions.Payload.fromAddress(address)
externalAccountActions.showExternalActions(externalActionsPayload)
}
private fun loadFee() {
feeLoaderMixin.loadFee(
coroutineScope = viewModelScope,
feeConstructor = { asset ->
val feeInPlanks = redeemInteractor.estimateFee(accountStakingFlow.first())
asset.token.amountFromPlanks(feeInPlanks)
},
onRetryCancelled = ::backClicked
)
}
private fun requireFee(block: (BigDecimal) -> Unit) = feeLoaderMixin.requireFee(
block,
onError = { title, message -> showError(title, message) }
)
private fun maybeGoToNext() = requireFee { fee ->
launch {
val asset = assetFlow.first()
val validationPayload = RedeemValidationPayload(
fee = fee,
asset = asset
)
validationExecutor.requireValid(
validationSystem = validationSystem,
payload = validationPayload,
validationFailureTransformer = { redeemValidationFailure(it, resourceManager) },
progressConsumer = _showNextProgress.progressConsumer()
) {
sendTransaction(it)
}
}
}
private fun sendTransaction(redeemValidationPayload: RedeemValidationPayload) = launch {
val result = redeemInteractor.redeem(accountStakingFlow.first(), redeemValidationPayload.asset)
_showNextProgress.value = false
if (result.isSuccess) {
showMessage(resourceManager.getString(R.string.common_transaction_submitted))
when {
payload.overrideFinishAction != null -> payload.overrideFinishAction.invoke(router)
result.requireValue().willKillStash -> router.returnToMain()
else -> router.returnToStakingBalance()
}
} else {
showError(result.requireException())
}
}
}
| 3 | null | 15 | 55 | 756c1fea772274ad421de1b215a12bf4e2798d12 | 6,038 | fearless-Android | Apache License 2.0 |
shieldCore/src/main/java/com/dianping/shield/node/processor/impl/section/NormalSectionNodeProcessor.kt | Meituan-Dianping | 113,555,063 | false | null | package com.dianping.shield.node.processor.impl.section
import com.dianping.shield.entity.CellType
import com.dianping.shield.node.cellnode.RowRangeHolder
import com.dianping.shield.node.cellnode.ShieldDisplayNode
import com.dianping.shield.node.cellnode.ShieldRow
import com.dianping.shield.node.cellnode.ShieldSection
import com.dianping.shield.node.cellnode.callback.lazyload.DefaultShieldRowProvider
import com.dianping.shield.node.cellnode.callback.lazyload.DefaultShieldRowProviderWithItem
import com.dianping.shield.node.processor.ProcessorHolder
import com.dianping.shield.node.useritem.SectionItem
import com.dianping.shield.utils.RangeRemoveableArrayList
import java.util.*
/**
* Created by zhi.he on 2018/6/25.
* 处理Normal Row
*/
class NormalSectionNodeProcessor(private val processorHolder: ProcessorHolder) : SectionNodeProcessor() {
// private var rowDividerStyleProcessor = BaseRowNodeProcessor(context, defaultTheme)
// var processorChain = ProcessorChain(processorHolder)
// .addProcessor(BaseRowNodeProcessor::class.java)
override fun handleShieldSection(sectionItem: SectionItem, shieldSection: ShieldSection): Boolean {
//ShieldSection层面上默认延迟加载ShieldRow
shieldSection.rangeDispatcher.clear()
var rowSize = if (sectionItem.isLazyLoad) {
sectionItem.rowCount
} else {
sectionItem.rowItems?.size ?: 0
}
shieldSection.isLazyLoad = true
if (sectionItem.isLazyLoad) {
sectionItem.lazyLoadRowItemProvider?.let {
shieldSection.rowProvider = DefaultShieldRowProvider(it, processorHolder)
}
} else {
sectionItem.rowItems?.let {
shieldSection.rowProvider = DefaultShieldRowProviderWithItem(it, processorHolder)
}
}
sectionItem.headerRowItem?.let {
shieldSection.hasHeaderCell = true
rowSize++
}
sectionItem.footerRowItem?.let {
shieldSection.hasFooterCell = true
rowSize++
}
//rowsize是包含header和footer的总行数
shieldSection.shieldRows ?: let {
shieldSection.shieldRows = RangeRemoveableArrayList(arrayOfNulls<ShieldRow>(rowSize).asList())
}
//HeaderCell直接生成
sectionItem.headerRowItem?.let { headerRowItem ->
//读取Header Cell
shieldSection.shieldRows?.set(0, ShieldRow().apply {
// rowIndex = 0
sectionParent = shieldSection
cellType = CellType.HEADER
typePrefix = sectionParent?.cellParent?.name
shieldDisplayNodes = ArrayList(arrayOfNulls<ShieldDisplayNode>(headerRowItem.viewItems?.size
?: 0).asList())
processorHolder.rowProcessorChain.startProcessor(headerRowItem, this)
})
}
//FooterCell直接生成
sectionItem.footerRowItem?.let { footerRowItem ->
//读取Footer Cell
shieldSection.shieldRows?.set(rowSize - 1, ShieldRow().apply {
// rowIndex = rowSize - 1
sectionParent = shieldSection
cellType = CellType.FOOTER
typePrefix = sectionParent?.cellParent?.name
shieldDisplayNodes = ArrayList(arrayOfNulls<ShieldDisplayNode>(footerRowItem.viewItems?.size
?: 0).asList())
processorHolder.rowProcessorChain.startProcessor(footerRowItem, this)
})
}
//所有的行都作为RangeHolder加入RangeDispatcher
val rowRangeList = ArrayList<RowRangeHolder>()
for (i in 0 until rowSize) {
rowRangeList.add(RowRangeHolder().apply {
if (i == 0 && shieldSection.hasHeaderCell) {
dNodeCount = shieldSection.shieldRows?.get(0)?.shieldDisplayNodes?.size ?: 0
} else if (i == rowSize - 1 && shieldSection.hasFooterCell) {
dNodeCount = shieldSection.shieldRows?.get(rowSize - 1)?.shieldDisplayNodes?.size ?: 0
} else {
//这个row index 为 inner index
val rowIndex = if (shieldSection.hasHeaderCell) i - 1 else i
dNodeCount = shieldSection.rowProvider?.getRowNodeCount(rowIndex, shieldSection) ?: 0
}
})
}
shieldSection.rangeDispatcher.addAll(rowRangeList)
shieldSection.sectionTitle = sectionItem.sectionTitle
return false
}
} | 8 | Java | 117 | 936 | 7618a1845d896f358b6edf8fde95622d315eda52 | 4,553 | Shield | MIT License |
app/src/main/java/com/agritracker/plus/RootActivity.kt | FelipeACP | 793,833,208 | false | {"Kotlin": 102008, "Python": 1401} | package com.agritracker.plus
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
/// Root of all AppCompatActivities where all general stuff goes
class RootActivity : AppCompatActivity() {
private var authListener: FirebaseAuth.AuthStateListener? = null
private lateinit var auth: FirebaseAuth
private var currentUserId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//get firebase auth instance
auth = FirebaseAuth.getInstance()
//get current user
val user: FirebaseUser? = FirebaseAuth.getInstance().currentUser
user?.let {
currentUserId = it.uid
}
authListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
val user = firebaseAuth.currentUser
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(Intent(this@RootActivity, LoginActivity::class.java))
finish()
}
}
}
override fun onStart() {
super.onStart()
authListener?.let { auth.addAuthStateListener(it) }
}
override fun onStop() {
super.onStop()
authListener?.let { auth.removeAuthStateListener(it) }
}
}
| 0 | Kotlin | 0 | 0 | 390e2930e18864c3125a74b242a3c30e94ae3dc5 | 1,479 | agritracker-android | Apache License 2.0 |
app/src/main/java/ca/on/hojat/gamenews/feature_news/presentation/mapping/GamingNewsItemUiModelMapper.kt | hojat72elect | 574,228,468 | false | null | package ca.on.hojat.gamenews.feature_news.presentation.mapping
import ca.on.hojat.gamenews.core.formatters.ArticlePublicationDateFormatter
import ca.on.hojat.gamenews.feature_news.domain.entities.Article
import ca.on.hojat.gamenews.feature_news.domain.entities.ImageType
import ca.on.hojat.gamenews.feature_news.presentation.widgets.GamingNewsItemUiModel
import com.paulrybitskyi.hiltbinder.BindType
import javax.inject.Inject
internal interface GamingNewsItemUiModelMapper {
fun mapToUiModel(article: Article): GamingNewsItemUiModel
}
@BindType(installIn = BindType.Component.VIEW_MODEL)
internal class GamingNewsItemUiModelMapperImpl @Inject constructor(
private val publicationDateFormatter: ArticlePublicationDateFormatter
) : GamingNewsItemUiModelMapper {
override fun mapToUiModel(article: Article): GamingNewsItemUiModel {
return GamingNewsItemUiModel(
id = article.id,
imageUrl = article.imageUrls[ImageType.ORIGINAL],
title = article.title,
lede = article.lede,
publicationDate = article.formatPublicationDate(),
siteDetailUrl = article.siteDetailUrl
)
}
private fun Article.formatPublicationDate(): String {
return publicationDateFormatter.formatPublicationDate(publicationDate)
}
}
/**
* Just maps from the [Article] in our domain, to [GamingNewsItemUiModel] in UI layer.
* we do this to make the data ready to be shown in composables.
*/
internal fun GamingNewsItemUiModelMapper.mapToUiModels(
articles: List<Article>,
): List<GamingNewsItemUiModel> {
return articles.map(::mapToUiModel)
}
| 0 | Kotlin | 0 | 2 | 80ff667af63e00b09aac129bb1206f520452700a | 1,640 | GameHub | Apache License 2.0 |
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/modifiers/SelectionController.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text.modifiers
import androidx.compose.foundation.text.TextDragObserver
import androidx.compose.foundation.text.selection.MouseSelectionObserver
import androidx.compose.foundation.text.selection.MultiWidgetSelectionDelegate
import androidx.compose.foundation.text.selection.Selectable
import androidx.compose.foundation.text.selection.SelectionAdjustment
import androidx.compose.foundation.text.selection.SelectionRegistrar
import androidx.compose.foundation.text.selection.hasSelection
import androidx.compose.foundation.text.selection.selectionGestureInput
import androidx.compose.foundation.text.textPointerIcon
import androidx.compose.runtime.RememberObserver
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.input.pointer.pointerHoverIcon
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.style.TextOverflow
internal open class StaticTextSelectionParams(
val layoutCoordinates: LayoutCoordinates?,
val textLayoutResult: TextLayoutResult?
) {
companion object {
val Empty = StaticTextSelectionParams(null, null)
}
open fun getPathForRange(start: Int, end: Int): Path? {
return textLayoutResult?.getPathForRange(start, end)
}
open val shouldClip: Boolean
get() = textLayoutResult?.let {
it.layoutInput.overflow != TextOverflow.Visible && it.hasVisualOverflow
} ?: false
// if this copy shows up in traces, this class may become mutable
fun copy(
layoutCoordinates: LayoutCoordinates? = this.layoutCoordinates,
textLayoutResult: TextLayoutResult? = this.textLayoutResult
): StaticTextSelectionParams {
return StaticTextSelectionParams(
layoutCoordinates,
textLayoutResult
)
}
}
/**
* Holder for selection modifiers while we wait for pointerInput to be ported to new modifiers.
*/
// This is _basically_ a Modifier.Node but moved into remember because we need to do pointerInput
internal class SelectionController(
private val selectableId: Long,
private val selectionRegistrar: SelectionRegistrar,
private val backgroundSelectionColor: Color,
// TODO: Move these into Modifier.element eventually
private var params: StaticTextSelectionParams = StaticTextSelectionParams.Empty
) : RememberObserver {
private var selectable: Selectable? = null
val modifier: Modifier = selectionRegistrar
.makeSelectionModifier(
selectableId = selectableId,
layoutCoordinates = { params.layoutCoordinates },
)
.pointerHoverIcon(textPointerIcon)
override fun onRemembered() {
selectable = selectionRegistrar.subscribe(
MultiWidgetSelectionDelegate(
selectableId = selectableId,
coordinatesCallback = { params.layoutCoordinates },
layoutResultCallback = { params.textLayoutResult }
)
)
}
override fun onForgotten() {
val localSelectable = selectable
if (localSelectable != null) {
selectionRegistrar.unsubscribe(localSelectable)
selectable = null
}
}
override fun onAbandoned() {
val localSelectable = selectable
if (localSelectable != null) {
selectionRegistrar.unsubscribe(localSelectable)
selectable = null
}
}
fun updateTextLayout(textLayoutResult: TextLayoutResult) {
val prevTextLayoutResult = params.textLayoutResult
// Don't notify on null. We don't want every new Text that enters composition to
// notify a selectable change. It was already handled when it was created.
if (prevTextLayoutResult != null &&
prevTextLayoutResult.layoutInput.text != textLayoutResult.layoutInput.text
) {
// Text content changed, notify selection to update itself.
selectionRegistrar.notifySelectableChange(selectableId)
}
params = params.copy(textLayoutResult = textLayoutResult)
}
fun updateGlobalPosition(coordinates: LayoutCoordinates) {
params = params.copy(layoutCoordinates = coordinates)
selectionRegistrar.notifyPositionChange(selectableId)
}
fun draw(drawScope: DrawScope) {
val selection = selectionRegistrar.subselections[selectableId] ?: return
val start = if (!selection.handlesCrossed) {
selection.start.offset
} else {
selection.end.offset
}
val end = if (!selection.handlesCrossed) {
selection.end.offset
} else {
selection.start.offset
}
if (start == end) return
val lastOffset = selectable?.getLastVisibleOffset() ?: 0
val clippedStart = start.coerceAtMost(lastOffset)
val clippedEnd = end.coerceAtMost(lastOffset)
val selectionPath = params.getPathForRange(clippedStart, clippedEnd) ?: return
with(drawScope) {
if (params.shouldClip) {
clipRect {
drawPath(selectionPath, backgroundSelectionColor)
}
} else {
drawPath(selectionPath, backgroundSelectionColor)
}
}
}
}
// this is not chained, but is a standalone factory
@Suppress("ModifierFactoryExtensionFunction")
private fun SelectionRegistrar.makeSelectionModifier(
selectableId: Long,
layoutCoordinates: () -> LayoutCoordinates?,
): Modifier {
val longPressDragObserver = object : TextDragObserver {
/**
* The beginning position of the drag gesture. Every time a new drag gesture starts, it wil be
* recalculated.
*/
var lastPosition = Offset.Zero
/**
* The total distance being dragged of the drag gesture. Every time a new drag gesture starts,
* it will be zeroed out.
*/
var dragTotalDistance = Offset.Zero
override fun onDown(point: Offset) {
// Not supported for long-press-drag.
}
override fun onUp() {
// Nothing to do.
}
override fun onStart(startPoint: Offset) {
layoutCoordinates()?.let {
if (!it.isAttached) return
notifySelectionUpdateStart(
layoutCoordinates = it,
startPosition = startPoint,
adjustment = SelectionAdjustment.Word,
isInTouchMode = true
)
lastPosition = startPoint
}
// selection never started
if (!hasSelection(selectableId)) return
// Zero out the total distance that being dragged.
dragTotalDistance = Offset.Zero
}
override fun onDrag(delta: Offset) {
layoutCoordinates()?.let {
if (!it.isAttached) return
// selection never started, did not consume any drag
if (!hasSelection(selectableId)) return
dragTotalDistance += delta
val newPosition = lastPosition + dragTotalDistance
// Notice that only the end position needs to be updated here.
// Start position is left unchanged. This is typically important when
// long-press is using SelectionAdjustment.WORD or
// SelectionAdjustment.PARAGRAPH that updates the start handle position from
// the dragBeginPosition.
val consumed = notifySelectionUpdate(
layoutCoordinates = it,
previousPosition = lastPosition,
newPosition = newPosition,
isStartHandle = false,
adjustment = SelectionAdjustment.CharacterWithWordAccelerate,
isInTouchMode = true
)
if (consumed) {
lastPosition = newPosition
dragTotalDistance = Offset.Zero
}
}
}
override fun onStop() {
if (hasSelection(selectableId)) {
notifySelectionUpdateEnd()
}
}
override fun onCancel() {
if (hasSelection(selectableId)) {
notifySelectionUpdateEnd()
}
}
}
val mouseSelectionObserver = object : MouseSelectionObserver {
var lastPosition = Offset.Zero
override fun onExtend(downPosition: Offset): Boolean {
layoutCoordinates()?.let { layoutCoordinates ->
if (!layoutCoordinates.isAttached) return false
val consumed = notifySelectionUpdate(
layoutCoordinates = layoutCoordinates,
newPosition = downPosition,
previousPosition = lastPosition,
isStartHandle = false,
adjustment = SelectionAdjustment.None,
isInTouchMode = false
)
if (consumed) {
lastPosition = downPosition
}
return hasSelection(selectableId)
}
return false
}
override fun onExtendDrag(dragPosition: Offset): Boolean {
layoutCoordinates()?.let { layoutCoordinates ->
if (!layoutCoordinates.isAttached) return false
if (!hasSelection(selectableId)) return false
val consumed = notifySelectionUpdate(
layoutCoordinates = layoutCoordinates,
newPosition = dragPosition,
previousPosition = lastPosition,
isStartHandle = false,
adjustment = SelectionAdjustment.None,
isInTouchMode = false
)
if (consumed) {
lastPosition = dragPosition
}
}
return true
}
override fun onStart(
downPosition: Offset,
adjustment: SelectionAdjustment
): Boolean {
layoutCoordinates()?.let {
if (!it.isAttached) return false
notifySelectionUpdateStart(
layoutCoordinates = it,
startPosition = downPosition,
adjustment = adjustment,
isInTouchMode = false
)
lastPosition = downPosition
return hasSelection(selectableId)
}
return false
}
override fun onDrag(
dragPosition: Offset,
adjustment: SelectionAdjustment
): Boolean {
layoutCoordinates()?.let {
if (!it.isAttached) return false
if (!hasSelection(selectableId)) return false
val consumed = notifySelectionUpdate(
layoutCoordinates = it,
previousPosition = lastPosition,
newPosition = dragPosition,
isStartHandle = false,
adjustment = adjustment,
isInTouchMode = false
)
if (consumed) {
lastPosition = dragPosition
}
}
return true
}
override fun onDragDone() {
notifySelectionUpdateEnd()
}
}
return Modifier.selectionGestureInput(mouseSelectionObserver, longPressDragObserver)
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 13,114 | androidx | Apache License 2.0 |
Android/Intermediate/Concurrency/code/HelloConcurrency2/app/src/main/java/com/example/helloconcurrency2/MainActivity.kt | Ice-House-Engineering | 262,230,937 | false | null | package com.example.helloconcurrency2
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
const val LOG = "android-coroutines"
class MainActivity : AppCompatActivity() {
suspend fun downloadFile(): String {
delay(1000)
return "Downloaded File"
}
suspend fun readDataFromDatabase(): String {
delay(1000)
return "Data From Database"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking {
Log.d(LOG, "Before executing methods")
val result1 = downloadFile()
val result2 = readDataFromDatabase()
Log.d(LOG, "After executing methods, getting result: ${result1 + result2}")
}
runBlocking {
Log.d(LOG, "Before async")
val deferredDownload = async { downloadFile() }
val deferredDatabase = async { readDataFromDatabase() }
val result1 = deferredDownload.await()
val result2 = deferredDatabase.await()
Log.d(LOG, "After async's await, getting result: ${result1 + result2}")
}
}
}
| 2 | Kotlin | 47 | 169 | ac6ff819a03f8eb01055ebbb2bf08a95f011e09b | 1,339 | academy-curriculum | Creative Commons Attribution 4.0 International |
app/src/main/kotlin/com/mgaetan89/showsrage/helper/TextHelper.kt | id-ks | 107,322,013 | true | {"Kotlin": 664263} | package com.mgaetan89.showsrage.helper
import android.support.v4.app.Fragment
import android.view.View
import android.widget.TextView
import java.util.*
fun String?.hasText() = !this.isNullOrBlank() && !"N/A".equals(this, true)
fun setText(fragment: Fragment, textView: TextView, text: String?, label: Int, layout: View?) {
if (text.hasText()) {
if (layout == null) {
textView.text = fragment.getString(label, text)
textView.visibility = View.VISIBLE
} else {
layout.visibility = View.VISIBLE
textView.text = text
}
} else {
layout?.visibility = View.GONE
textView.visibility = View.GONE
}
}
fun String.toLocale(): Locale? {
if (this.isNullOrEmpty()) {
return null
}
val defaultLocale = Locale.getDefault()
Locale.setDefault(Locale.ENGLISH)
val locale = Locale.getAvailableLocales().filter { locale ->
locale.displayLanguage.startsWith(this, true)
}.firstOrNull { it != null }
Locale.setDefault(defaultLocale)
return locale
}
| 0 | Kotlin | 0 | 0 | 8b32e27b8e468f13b942313a80761569a61f4f05 | 1,083 | ShowsRage | Apache License 2.0 |
recycliprocessor/src/main/java/com/detmir/recycli/processors/RecyclerProcessorKsp.kt | detmir | 358,579,304 | false | null | package com.detmir.recycli.processors
import com.detmir.recycli.annotations.RecyclerItemState
import com.detmir.recycli.annotations.RecyclerItemStateBinder
import com.detmir.recycli.annotations.RecyclerItemView
import com.detmir.recycli.annotations.RecyclerItemViewHolder
import com.detmir.recycli.annotations.RecyclerItemViewHolderCreator
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSFile
class RecyclerProcessorKsp(
private val codeGenerator: CodeGenerator,
private val logger: KSPLogger,
private val options: Map<String, String>
) : SymbolProcessor {
private var packageName: ArrayList<String> = ArrayList()
override fun process(resolver: Resolver): List<KSAnnotated> {
val indexToStateMap = mutableMapOf<Int, String>()
val stateToIndexMap = mutableMapOf<String, Int>()
val stateToViewMap = mutableMapOf<String, MutableList<ViewProps>>()
val stateSealedAliases = mutableMapOf<Int, Int>()
val completeMap = mutableMapOf<String, ViewProps>()
val iWrap = IWrap()
val allElementsInvolved = mutableSetOf<KSClassDeclaration>()
val filesInvolved = mutableListOf<KSFile>()
logRelease("Recycli start processing", logger)
// STATE CLASSES
val stateSymbols = resolver
.getSymbolsWithAnnotation(RecyclerItemState::class.java.canonicalName)
.filterIsInstance<KSClassDeclaration>()
val stateSymbolsIterator = stateSymbols.iterator()
// VIEWS CLASSES
val viewSymbols = resolver
.getSymbolsWithAnnotation(RecyclerItemView::class.java.canonicalName)
.filterIsInstance<KSClassDeclaration>().iterator()
val viewSymbolsIterator = viewSymbols.iterator()
// VIEWHOLDER CLASSES
val viewHolderSymbols = resolver
.getSymbolsWithAnnotation(RecyclerItemViewHolder::class.java.canonicalName)
.filterIsInstance<KSClassDeclaration>().iterator()
val viewHolderSymbolsIterator = viewHolderSymbols.iterator()
// Exit from the processor in case nothing is annotated with @RecyclerItemState, @RecyclerItemView, @RecyclerItemViewHolder
if (
!(stateSymbolsIterator.hasNext() || viewSymbolsIterator.hasNext() || viewHolderSymbolsIterator.hasNext())
) {
logRelease("Recycli end processing, nothing found", logger)
return emptyList()
}
// PROCESS STATE CLASSES
while (stateSymbolsIterator.hasNext()) {
val stateClazz = stateSymbolsIterator.next()
allElementsInvolved.add(stateClazz)
stateClazz.containingFile?.let(filesInvolved::add)
fillStates(
stateElement = stateClazz,
stateToIndexMap = stateToIndexMap,
indexToStateMap = indexToStateMap,
iWrap = iWrap,
stateSealedAliases = stateSealedAliases,
allElementsInvolved = allElementsInvolved,
)
}
// PROCESS VIEW CLASSES
while (viewSymbolsIterator.hasNext()) {
val viewClazz = viewSymbolsIterator.next()
viewClazz.containingFile?.let(filesInvolved::add)
allElementsInvolved.add(viewClazz)
fillViewProps(
viewElement = viewClazz,
stateToIndexMap = stateToIndexMap,
stateToViewMap = stateToViewMap,
type = Type.VIEW
)
}
// PROCESS VIEWHOLDER CLASSES
while (viewHolderSymbolsIterator.hasNext()) {
val holderClazz = viewHolderSymbolsIterator.next()
holderClazz.containingFile?.let(filesInvolved::add)
allElementsInvolved.add(holderClazz)
fillViewProps(
viewElement = holderClazz,
stateToIndexMap = stateToIndexMap,
stateToViewMap = stateToViewMap,
type = Type.VIEW_HOLDER
)
}
//HANDLE SEALED CLASSES
fillWithSealedClasses(
stateToIndexMap = stateToIndexMap,
indexToStateMap = indexToStateMap,
stateToViewMap = stateToViewMap,
stateSealedAliases = stateSealedAliases,
completeMap = completeMap
)
// CREATE RecyclerBinderImpl
RecyclerFileProviderKsp.generateBinderClass(
filesInvolved = filesInvolved,
codeGenerator = codeGenerator,
packageName = packageName.joinToString("."),
completeMap = completeMap,
)
logRelease("Recycli end processing, ${filesInvolved.size} files found", logger)
// Don't need any multi round processing
return emptyList()
}
private fun craftSealedClass(
logger: KSPLogger,
element: KSClassDeclaration,
topClassIndex: Int,
iWrap: IWrap,
indexToStateMap: MutableMap<Int, String>,
stateToIndexMap: MutableMap<String, Int>,
stateSealedAliases: MutableMap<Int, Int>,
allElementsInvolved: MutableSet<KSClassDeclaration>
) {
element.getSealedSubclasses().forEach { enclosedElement ->
val enclosedElementQualifiedName = enclosedElement.qualifiedName?.asString()
if (enclosedElementQualifiedName != null) {
allElementsInvolved.add(enclosedElement)
iWrap.i++
indexToStateMap[iWrap.i] = enclosedElementQualifiedName
stateToIndexMap[enclosedElementQualifiedName] = iWrap.i
stateSealedAliases[iWrap.i] = topClassIndex
craftSealedClass(
logger = logger,
element = enclosedElement,
topClassIndex = topClassIndex,
iWrap = iWrap,
indexToStateMap = indexToStateMap,
stateToIndexMap = stateToIndexMap,
stateSealedAliases = stateSealedAliases,
allElementsInvolved = allElementsInvolved
)
}
}
}
private fun getTopPackage(element: KSClassDeclaration) {
val enclosingPackage = element.packageName.asString()
val arr = enclosingPackage.split(".")
if (packageName.isEmpty()) {
packageName = ArrayList(arr)
}
val newPackageName = ArrayList<String>()
arr.forEachIndexed { index, s ->
val curAtIndex = packageName.getOrNull(index)
if (curAtIndex == s) {
newPackageName.add(s)
}
}
packageName = newPackageName
}
private fun fillStates(
stateElement: KSClassDeclaration,
stateToIndexMap: MutableMap<String, Int>,
indexToStateMap: MutableMap<Int, String>,
iWrap: IWrap,
stateSealedAliases: MutableMap<Int, Int>,
allElementsInvolved: MutableSet<KSClassDeclaration>,
) {
getTopPackage(stateElement)
val stateClazzName = stateElement.qualifiedName?.asString()
if (stateClazzName != null) {
indexToStateMap[iWrap.i] = stateClazzName
stateToIndexMap[stateClazzName] = iWrap.i
stateSealedAliases[iWrap.i] = iWrap.i
val topClassIndex = iWrap.i
craftSealedClass(
logger = logger,
element = stateElement,
topClassIndex = topClassIndex,
iWrap = iWrap,
indexToStateMap = indexToStateMap,
stateToIndexMap = stateToIndexMap,
stateSealedAliases = stateSealedAliases,
allElementsInvolved = allElementsInvolved
)
iWrap.i++
}
}
private fun fillViewProps(
viewElement: KSClassDeclaration,
stateToIndexMap: MutableMap<String, Int>,
stateToViewMap: MutableMap<String, MutableList<ViewProps>>,
type: Type
) {
var viewCreatorClassName: String? = null
if (type == Type.VIEW_HOLDER) {
val decl = viewElement.declarations.iterator()
while (decl.hasNext() && viewCreatorClassName == null) {
val decls = decl.next()
if (decls is KSClassDeclaration && decls.classKind == ClassKind.OBJECT) {
val declIterator = decls.getAllFunctions().iterator()
while (declIterator.hasNext() && viewCreatorClassName == null) {
val declFunction = declIterator.next()
val isRecyclerItemViewHolderCreator =
declFunction.annotations.firstOrNull { ksAnnotation ->
ksAnnotation.shortName.asString() == RecyclerItemViewHolderCreator::class.java.simpleName //"RecyclerItemViewHolderCreator"
}
if (isRecyclerItemViewHolderCreator != null) {
viewCreatorClassName = declFunction.qualifiedName?.asString()
}
}
}
}
} else {
viewCreatorClassName = viewElement.qualifiedName?.asString()
}
if (viewCreatorClassName == null) {
logger.error("jksps KSP RecyclerItemCreator not found for ${viewElement.qualifiedName?.asString()} ")
return
}
val binderFunctionsIterator = viewElement.getAllFunctions().iterator()
while (binderFunctionsIterator.hasNext()) {
val binderFunction = binderFunctionsIterator.next()
val isRecyclerItemViewBinderAnnotation =
binderFunction.annotations.firstOrNull { ksAnnotation ->
ksAnnotation.shortName.asString() == RecyclerItemStateBinder::class.java.simpleName //"RecyclerItemStateBinder"
}
if (isRecyclerItemViewBinderAnnotation != null) {
if (binderFunction.parameters.size == 1) {
binderFunction.parameters.forEach { binderParameter ->
val currentStateClass: String? =
binderParameter.type.resolve().declaration.qualifiedName?.asString()
if (currentStateClass == null) {
logger.error("jksps KSP binder function must be one arhument function with state ${binderFunction.qualifiedName?.asString()} in ${viewElement.qualifiedName?.asString()}")
}
val viewElementqualifiedName = viewElement.qualifiedName?.asString()
if (stateToIndexMap.containsKey(currentStateClass) && viewElementqualifiedName != null) {
val viewProps = ViewProps(
index = 0,
viewCreatorClassName = viewCreatorClassName,
binderFunctionName = binderFunction.simpleName.asString(),
viewBinderClassName = viewElementqualifiedName,
type = type
)
if (currentStateClass != null) {
val currentStateViewsList = stateToViewMap.getOrPut(
currentStateClass,
{ mutableListOf() })
currentStateViewsList.add(viewProps)
}
}
}
} else {
logger.error("jksps KSP RecyclerStateBinder function must be one parameter function")
}
}
}
var i = 0
stateToViewMap.forEach { (_, viewPropsMap) ->
viewPropsMap.forEach { viewProps ->
viewProps.index = i
i++
}
}
}
private fun fillWithSealedClasses(
stateToIndexMap: MutableMap<String, Int>,
stateToViewMap: MutableMap<String, MutableList<ViewProps>>,
stateSealedAliases: MutableMap<Int, Int>,
indexToStateMap: MutableMap<Int, String>,
completeMap: MutableMap<String, ViewProps>
) {
//SEALED STATES VIEWS
val addSealed = mutableMapOf<String, MutableList<ViewProps>>()
stateToViewMap.forEach { stateToViewMapEntry ->
val currentStateClass = stateToViewMapEntry.key
val currentStateClassIndex = stateToIndexMap[currentStateClass]
stateSealedAliases.filter { stateSealedAliasesEntry ->
stateSealedAliasesEntry.value == currentStateClassIndex && currentStateClassIndex != stateSealedAliasesEntry.key
}.forEach {
val sealedStateClass = indexToStateMap[it.key]
if (!stateToViewMap.contains(sealedStateClass)) {
val currentViewProps = stateToViewMap[currentStateClass]
if (sealedStateClass != null && currentViewProps != null) {
addSealed[sealedStateClass] = currentViewProps
}
}
}
}
var completeIndex = 0
stateToViewMap.putAll(addSealed)
stateToViewMap.forEach {
val state = it.key
it.value.forEach { viewProps ->
if (!completeMap.containsKey("$state#default")) {
completeMap.putIfAbsent(
"$state#default",
viewProps
)
completeIndex++
}
completeMap[state + "#" + viewProps.viewBinderClassName] = viewProps
completeIndex++
}
}
}
fun logRelease(message: String, logger: KSPLogger) {
if (ALLOW_RELEASE_LOG) {
logger.info(message)
}
}
fun logDebug(message: String, logger: KSPLogger) {
if (ALLOW_DEBUG_LOG) {
logger.info(message)
}
}
companion object {
const val ALLOW_DEBUG_LOG = false
const val ALLOW_RELEASE_LOG = true
}
enum class Type {
VIEW, VIEW_HOLDER
}
data class ViewProps(
var index: Int,
var type: Type,
val viewCreatorClassName: String,
val viewBinderClassName: String,
val binderFunctionName: String
)
data class IWrap(
var i: Int = 0
)
}
| 3 | Kotlin | 3 | 32 | 5e12ba06400f02f93441af9ed6a5b17c436cd67d | 14,842 | recycli | Apache License 2.0 |
app/src/main/kotlin/com/flixclusive/mobile/MobileAppNavigator.kt | rhenwinch | 659,237,375 | false | null | package com.flixclusive.mobile
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import com.flixclusive.core.ui.common.navigation.RepositorySearchScreenNavigator
import com.flixclusive.core.ui.common.navigation.UpdateDialogNavigator
import com.flixclusive.feature.mobile.about.destinations.AboutScreenDestination
import com.flixclusive.feature.mobile.film.FilmScreenNavigator
import com.flixclusive.feature.mobile.film.destinations.FilmScreenDestination
import com.flixclusive.feature.mobile.genre.destinations.GenreScreenDestination
import com.flixclusive.feature.mobile.home.HomeNavigator
import com.flixclusive.feature.mobile.player.PlayerScreenNavigator
import com.flixclusive.feature.mobile.player.destinations.PlayerScreenDestination
import com.flixclusive.feature.mobile.preferences.PreferencesScreenNavigator
import com.flixclusive.feature.mobile.provider.ProvidersScreenNavigator
import com.flixclusive.feature.mobile.provider.info.ProviderInfoNavigator
import com.flixclusive.feature.mobile.provider.info.destinations.ProviderInfoScreenDestination
import com.flixclusive.feature.mobile.provider.settings.destinations.ProviderSettingsScreenDestination
import com.flixclusive.feature.mobile.provider.whats_new.destinations.ProviderWhatsNewScreenDestination
import com.flixclusive.feature.mobile.recentlyWatched.destinations.RecentlyWatchedScreenDestination
import com.flixclusive.feature.mobile.repository.destinations.RepositoryScreenDestination
import com.flixclusive.feature.mobile.repository.search.destinations.RepositorySearchScreenDestination
import com.flixclusive.feature.mobile.search.SearchScreenNavigator
import com.flixclusive.feature.mobile.searchExpanded.destinations.SearchExpandedScreenDestination
import com.flixclusive.feature.mobile.seeAll.destinations.SeeAllScreenDestination
import com.flixclusive.feature.mobile.settings.destinations.SettingsScreenDestination
import com.flixclusive.feature.mobile.update.destinations.UpdateDialogDestination
import com.flixclusive.feature.mobile.update.destinations.UpdateScreenDestination
import com.flixclusive.feature.mobile.watchlist.destinations.WatchlistScreenDestination
import com.flixclusive.feature.splashScreen.SplashScreenNavigator
import com.flixclusive.gradle.entities.ProviderData
import com.flixclusive.gradle.entities.Repository
import com.flixclusive.model.configuration.CategoryItem
import com.flixclusive.model.tmdb.Film
import com.flixclusive.model.tmdb.Genre
import com.flixclusive.model.tmdb.TMDBEpisode
import com.flixclusive.util.navGraph
import com.flixclusive.util.navigateIfResumed
import com.ramcosta.composedestinations.dynamic.within
import com.ramcosta.composedestinations.navigation.navigate
import com.ramcosta.composedestinations.navigation.popUpTo
internal class MobileAppNavigator(
private val destination: NavDestination,
private val navController: NavController,
private val closeApp: () -> Unit,
) : HomeNavigator, SearchScreenNavigator, PreferencesScreenNavigator, UpdateDialogNavigator, FilmScreenNavigator, SplashScreenNavigator, PlayerScreenNavigator, ProvidersScreenNavigator,
RepositorySearchScreenNavigator, ProviderInfoNavigator {
override fun goBack() {
navController.navigateUp()
}
override fun openSearchExpandedScreen() {
navController.navigateIfResumed(SearchExpandedScreenDestination within destination.navGraph())
}
override fun openSeeAllScreen(item: CategoryItem) {
navController.navigateIfResumed(SeeAllScreenDestination(item = item) within destination.navGraph())
}
override fun openFilmScreen(film: Film) {
navController.navigateIfResumed(
FilmScreenDestination(
film = film,
startPlayerAutomatically = false
) within destination.navGraph()
)
}
override fun openGenreScreen(genre: Genre) {
navController.navigateIfResumed(GenreScreenDestination(genre = genre) within destination.navGraph())
}
override fun openWatchlistScreen() {
navController.navigateIfResumed(WatchlistScreenDestination within destination.navGraph())
}
override fun openRecentlyWatchedScreen() {
navController.navigateIfResumed(RecentlyWatchedScreenDestination within destination.navGraph())
}
override fun openSettingsScreen() {
navController.navigateIfResumed(SettingsScreenDestination within destination.navGraph())
}
override fun openAboutScreen() {
navController.navigateIfResumed(AboutScreenDestination within destination.navGraph())
}
override fun checkForUpdates() {
navController.navigateIfResumed(UpdateDialogDestination within destination.navGraph())
}
override fun openUpdateScreen(
newVersion: String,
updateUrl: String,
updateInfo: String?,
isComingFromSplashScreen: Boolean
) {
navController.navigateIfResumed(
UpdateScreenDestination(
newVersion = newVersion,
updateUrl = updateUrl,
updateInfo = updateInfo,
isComingFromSplashScreen = isComingFromSplashScreen
)
)
}
override fun openHomeScreen() {
navController.navigate(MobileNavGraphs.home) {
popUpTo(MobileNavGraphs.root) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
override fun onExitApplication() {
closeApp()
}
override fun onEpisodeChange(
film: Film,
episodeToPlay: TMDBEpisode
) {
navController.navigate(
PlayerScreenDestination(
film = film,
episodeToPlay = episodeToPlay
)
) {
launchSingleTop = true
}
}
override fun openProviderSettings(providerData: ProviderData) {
navController.navigateIfResumed(
ProviderSettingsScreenDestination(providerData = providerData) within destination.navGraph()
)
}
override fun openAddRepositoryScreen() {
navController.navigateIfResumed(
RepositorySearchScreenDestination within destination.navGraph()
)
}
override fun openRepositoryScreen(repository: Repository) {
navController.navigateIfResumed(
RepositoryScreenDestination(repository = repository) within destination.navGraph()
)
}
override fun testProviders(providers: List<ProviderData>) {
// TODO("Not yet implemented")
}
override fun seeWhatsNew(providerData: ProviderData) {
navController.navigateIfResumed(
ProviderWhatsNewScreenDestination(providerData = providerData) within destination.navGraph()
)
}
override fun openProviderInfo(providerData: ProviderData) {
navController.navigateIfResumed(
ProviderInfoScreenDestination(providerData = providerData) within destination.navGraph()
)
}
} | 29 | null | 9 | 325 | 7b6ada69290e1afc0deb6fb3d4a9ab7f79ea3fb2 | 7,044 | Flixclusive | MIT License |
mobikulOC/src/main/java/webkul/opencart/mobikul/helper/NetworkIssue.kt | fortunedev223 | 435,488,584 | false | {"Kotlin": 1128789, "Java": 655153} | package webkul.opencart.mobikul.helper
import android.content.Context
import webkul.opencart.mobikul.utils.SweetAlertBox
class NetworkIssue {
companion object {
fun getNetworkIssue(message: String, mContext: Context) {
SweetAlertBox.instance.retryNetWorkCall(context = mContext)
}
}
} | 0 | Kotlin | 0 | 0 | fe2513dab910dc471810fa37d6c01c848712c295 | 322 | Boutiquey_Android | MIT License |
bitcoincore/src/main/kotlin/io/horizontalsystems/bitcoincore/managers/IrregularOutputFinder.kt | horizontalsystems | 147,199,533 | false | null | package io.definenulls.bitcoincore.managers
import io.definenulls.bitcoincore.core.IStorage
import io.definenulls.bitcoincore.models.TransactionOutput
import io.definenulls.bitcoincore.transactions.scripts.ScriptType
import io.definenulls.bitcoincore.utils.Utils
interface IIrregularOutputFinder {
fun hasIrregularOutput(outputs: List<TransactionOutput>): Boolean
}
class IrregularOutputFinder(private val storage: IStorage) : IIrregularOutputFinder, IBloomFilterProvider {
private val irregularScriptTypes = listOf(ScriptType.P2WPKHSH, ScriptType.P2WPKH, ScriptType.P2PK, ScriptType.P2TR)
// IIrregularOutputFinder
override fun hasIrregularOutput(outputs: List<TransactionOutput>): Boolean {
return outputs.any { it.publicKeyPath != null && irregularScriptTypes.contains(it.scriptType) }
}
// IBloomFilterProvider
override var bloomFilterManager: BloomFilterManager? = null
override fun getBloomFilterElements(): List<ByteArray> {
val elements = mutableListOf<ByteArray>()
val transactionOutputs = storage.lastBlock()?.height?.let { lastBlockHeight ->
// get transaction outputs which are unspent or spent in last 100 blocks
storage.getOutputsForBloomFilter(lastBlockHeight - 100, irregularScriptTypes)
} ?: listOf()
for (output in transactionOutputs) {
val outpoint = output.transactionHash + Utils.intToByteArray(output.index).reversedArray()
elements.add(outpoint)
}
return elements
}
}
| 39 | Kotlin | 76 | 96 | 110018d54d82bb4e3c2a1d6b0ddd1bb9eeff9167 | 1,543 | bitcoin-kit-android | MIT License |
PaperVision/src/main/kotlin/io/github/deltacv/papervision/codegen/vision/Targets.kt | deltacv | 421,245,458 | false | {"Kotlin": 516821, "Java": 6199} | package io.github.deltacv.papervision.codegen.vision
import io.github.deltacv.papervision.codegen.CodeGen
import io.github.deltacv.papervision.codegen.Visibility
import io.github.deltacv.papervision.codegen.build.ConValue
import io.github.deltacv.papervision.codegen.build.Parameter
import io.github.deltacv.papervision.codegen.build.Variable
import io.github.deltacv.papervision.codegen.build.type.JavaTypes
import io.github.deltacv.papervision.codegen.build.type.JvmOpenCvTypes
import io.github.deltacv.papervision.codegen.dsl.targets
fun CodeGen.Current.enableTargets() = this {
if(!codeGen.hasFlag("targetsEnabled")) {
targets(enableTargetsIfNeeded = false) {
scope {
clearTargets()
}
group {
private(targets)
}
codeGen.classEndScope {
val labelParameter = Parameter(JavaTypes.String, "label")
val rectTargetParameter = Parameter(JvmOpenCvTypes.Rect, "rect")
method(
Visibility.PRIVATE,
VoidType,
"addTarget",
labelParameter,
rectTargetParameter,
isSynchronized = true
) {
targets("add", TargetType.new(labelParameter, rectTargetParameter))
}
separate()
val rectArrayListTargetsParameter = Parameter(JavaTypes.ArrayList(JvmOpenCvTypes.Rect), "rects")
method(
Visibility.PRIVATE,
VoidType,
"addTargets",
labelParameter,
rectArrayListTargetsParameter,
isSynchronized = true
) {
foreach(Variable(JvmOpenCvTypes.Rect, "rect"), rectArrayListTargetsParameter) {
"addTarget"(labelParameter, it)
}
}
separate()
method(
Visibility.PRIVATE,
VoidType,
"clearTargets",
isSynchronized = true
) {
targets("clear")
}
separate()
method(Visibility.PUBLIC, TargetType.arrayType(), "getTargets", isSynchronized = true) {
val array = Variable("array", TargetType.newArray(targets.callValue("size", IntType)))
local(array)
separate()
ifCondition(targets.callValue("isEmpty", BooleanType).condition()) {
returnMethod(array)
}
separate()
forLoop(Variable(IntType, "i"), int(0), targets.callValue("size", IntType) - int(1)) {
array.arraySet(it, targets.callValue("get", TargetType, it).castTo(TargetType))
}
separate()
returnMethod(array)
}
separate()
val targetsWithLabel = Variable("targetsWithLabel", JavaTypes.ArrayList(TargetType).new())
method(Visibility.PUBLIC, JavaTypes.ArrayList(TargetType), "getTargetsWithLabel", labelParameter, isSynchronized = true) {
local(targetsWithLabel)
separate()
foreach(Variable(TargetType, "target"), targets) {
val label = it.propertyValue("label", JavaTypes.String)
ifCondition(label.callValue("equals", BooleanType, labelParameter).condition()) {
targetsWithLabel("add", it)
}
}
separate()
returnMethod(targetsWithLabel)
}
separate()
clazz(Visibility.PUBLIC, TargetType.className) {
val labelVariable = Variable("label", ConValue(JavaTypes.String, null))
val rectVariable = Variable("rect", ConValue(JvmOpenCvTypes.Rect, null))
instanceVariable(Visibility.PUBLIC, labelVariable, isFinal = true)
instanceVariable(Visibility.PUBLIC, rectVariable, isFinal = true)
separate()
constructor(Visibility.PROTECTED, TargetType, labelParameter, rectTargetParameter) {
labelVariable instanceSet labelParameter
rectVariable instanceSet rectTargetParameter
}
}
}
}
codeGen.addFlag("targetsEnabled")
}
} | 0 | Kotlin | 2 | 5 | 6b2740e89e46f99d9dd50aed18db7981d5b3895b | 4,743 | PaperVision | MIT License |
modules/vui/src/main/kotlin/org/teamvoided/voidlib/vui/v2/node/MovableNode.kt | TeamVoided | 570,651,037 | false | null | package org.teamvoided.voidlib.vui.v2.node
import org.teamvoided.voidlib.core.datastructures.vector.Vec2i
import org.teamvoided.voidlib.vui.v2.event.ui.Event.InputEvent.*
open class MovableNode(val node: Node): Node() {
protected var selected = false
protected var offset = Vec2i(0, 0)
init {
this.size = node.size.copy()
this.globalPos = node.globalPos.copy()
addChild(node)
}
override fun onMousePress(event: MousePressEvent) {
if (isTouching(event.pos)) {
selected = true
offset = (event.pos.to2i() - this.globalPos)
event.cancel()
}
}
override fun onMouseRelease(event: MouseReleaseEvent) {
if (selected) {
selected = false
event.cancel()
}
}
override fun onMouseDrag(event: MouseDragEvent) {
if (selected) {
val nPos = (event.pos.to2i() - offset + event.delta.to2i())
this.globalPos = nPos
node.globalPos = nPos
event.cancel()
}
}
} | 0 | null | 0 | 2 | e73eae050b5ebd5d578394ca67a2b250c886fc8a | 1,065 | VoidLib | MIT License |
rider-fsharp/src/main/java/com/jetbrains/rider/plugins/fsharp/logs/FSharpLogTraceScenarios.kt | denis417 | 298,582,128 | true | {"F#": 1304325, "C#": 608402, "Kotlin": 152758, "Lex": 88263, "Java": 18652, "HTML": 74} | package com.jetbrains.rider.plugins.fsharp.logs
import com.jetbrains.rdclient.diagnostics.LogTraceScenario
object FSharpLogTraceScenarios {
object FcsReactorMonitor : LogTraceScenario("JetBrains.ReSharper.Plugins.FSharp.FcsReactorMonitor")
object FcsProjectProvider : LogTraceScenario("JetBrains.ReSharper.Plugins.FSharp.Checker.FcsProjectProvider")
}
| 0 | F# | 0 | 0 | 84861a44b6a4dc209f38eb5d340d957ba82c15be | 362 | fsharp-support | Apache License 2.0 |
core/src/main/java/com/marknjunge/core/mpesa/NetworkProvider.kt | hari2babloo | 194,399,315 | true | {"Kotlin": 176208} | package com.marknjunge.core.mpesa
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
internal class NetworkProvider {
private val apiUrl = "https://sandbox.safaricom.co.ke/"
val mpesaService: MpesaService
init {
val retrofit = provideRetrofit(apiUrl)
mpesaService = retrofit.create<MpesaService>(MpesaService::class.java)
}
private fun provideRetrofit(url: String): Retrofit {
return Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(provideLoggingCapableHttpClient())
.build()
}
private fun provideLoggingCapableHttpClient(): OkHttpClient {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC
return OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
}
} | 0 | Kotlin | 0 | 0 | dfa2cd9ff4749f82c9cedaf4cfd8a1ee01f5a128 | 1,194 | JustJava-Android | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.