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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
compiler/tests-spec/testData/diagnostics/linked/expressions/comparison-expressions/p-5/pos/1.1.kt
|
JetBrains
| 3,432,266
| false
| null |
// FIR_IDENTICAL
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_VARIABLE -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE -UNUSED_VALUE -UNUSED_PARAMETER -UNUSED_EXPRESSION
// SKIP_TXT
/*
* KOTLIN DIAGNOSTICS SPEC TEST (POSITIVE)
*
* SPEC VERSION: 0.1-218
* MAIN LINK: expressions, comparison-expressions -> paragraph 5 -> sentence 1
* PRIMARY LINKS: overloadable-operators -> paragraph 4 -> sentence 1
* NUMBER: 1
* DESCRIPTION: All comparison expressions always have type kotlin.Boolean.
* HELPERS: checkType
*/
class A(val a: Int) {
var isCompared = false
operator fun compareTo(other: A): Int = run {
isCompared = true
this.a - other.a
}
}
// TESTCASE NUMBER: 1
fun case1() {
val a1 = A(-1)
val a2 = A(-3)
val x = a1 < a2
x checkType { check<Boolean>() }
}
// TESTCASE NUMBER: 2
fun case2() {
val a1 = A(-1)
val a2 = A(-3)
val x = a1 > a2
x checkType { check<Boolean>() }
}
// TESTCASE NUMBER: 3
fun case3() {
val a1 = A(-1)
val a2 = A(-3)
val x = a1 <= a2
x checkType { check<Boolean>() }
}
// TESTCASE NUMBER: 4
fun case4() {
val a1 = A(-1)
val a2 = A(-3)
val x = a1 >= a2
x checkType { check<Boolean>() }
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,224
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/sph/sgnetworkdata/userInterface/NetworkDataDetailFragment.kt
|
123Yogendra
| 224,653,827
| false
| null |
package com.sph.sgnetworkdata.userInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.sph.sgnetworkdata.R
import com.sph.sgnetworkdata.network.model.Record
import kotlinx.android.synthetic.main.dialoge_network_data_detail.*
class NetworkDataDetailFragment(private var recordList: MutableList<Record>?) :
BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View =
inflater.inflate(R.layout.dialoge_network_data_detail, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// update value
tvDialogeDataDetailYear.text =
getString(R.string.year, recordList!!.get(0).quarter!!.split("-")[0].toString())
tvDialogeDetailDataQ1.text = getDataDetail()
ivDialogeClose.setOnClickListener{
dismiss()
}
}
private fun getDataDetail(): String {
var mobileData = ""
var data = 0.0
recordList!!.forEachIndexed{index, record ->
if (index != 0 && data > record.volumeOfMobileData!!.toDouble()) {
mobileData += record.quarter + " -> " + record.volumeOfMobileData + " \u25BC \n\n"
}
else {
mobileData += record.quarter + " -> " + record.volumeOfMobileData + "\n\n"
}
data = record.volumeOfMobileData!!.toDouble()
}
return mobileData
}
}
| 0
|
Kotlin
|
0
| 0
|
4d7d3ff7b56e65d11dd31e6e8f0559634b7352db
| 1,705
|
SGNetworkData
|
Apache License 2.0
|
app/src/main/java/com/thinkdevs/cryptomarket/adapter/BitCoinAdapter.kt
|
kevinjam
| 125,894,653
| false
| null |
package com.thinkdevs.cryptomarket.adapter
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.constraintlayout.widget.ConstraintLayout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.thinkdevs.cryptomarket.R
import com.thinkdevs.cryptomarket.constant.COIN_DETAILS
import com.thinkdevs.cryptomarket.controller.MoreActivity
import com.thinkdevs.cryptomarket.model.CryptoModel
/**
* Created by kevinjanvier on 19/03/2018.
*/
class BitCoinAdapter(var context: Context, var list: ArrayList<CryptoModel>) : androidx.recyclerview.widget.RecyclerView.Adapter<BitCoinAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent!!.context).inflate(R.layout.item_coin, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return list.count()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder!!.bindview(list[position], context)
}
inner class ViewHolder(itemView: View?) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView!!) {
val coinName = itemView!!.findViewById<TextView>(R.id.coinName)
val marketcoin = itemView!!.findViewById<TextView>(R.id.marketcoin)
val priceCoin = itemView!!.findViewById<TextView>(R.id.priceCoin)
val changeCoin = itemView!!.findViewById<TextView>(R.id.changeCoin)
val coinImage = itemView!!.findViewById<ImageView>(R.id.coinImage)
val id_more = itemView!!.findViewById<ConstraintLayout>(R.id.id_more)
fun bindview(model: CryptoModel, context: Context) {
coinName.text = model.name
marketcoin.text = "$ ${model.market_cap_usd}"
priceCoin.text = "Price: $${model.price_usd}"
changeCoin.text ="Change: ${model.percent_change_24h} %"
if (model.percent_change_24h.startsWith("-")){
if (model.percent_change_24h.startsWith("-1") || model.percent_change_24h.contentEquals("-2")){
println("Less than 5")
changeCoin.setTextColor(Color.RED)
}else{
println("Greater Than 5")
changeCoin.setTextColor(Color.BLUE)
}
}else{
changeCoin.setTextColor(Color.MAGENTA)
}
when {
model.symbol == "BTC" -> {
val resouldId = context.resources.getIdentifier("ic_bitcoin", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ETH" -> {
val resouldId = context.resources.getIdentifier("ic_ethereum", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XRP" -> {
val resouldId = context.resources.getIdentifier("ic_ripple", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BCH" -> {
val resouldId = context.resources.getIdentifier("ic_bitcoin_cash", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "LTC" -> {
val resouldId = context.resources.getIdentifier("ic_litecoin", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ADA" -> {
val resouldId = context.resources.getIdentifier("ic_ada", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "NEO" -> {
val resouldId = context.resources.getIdentifier("ic_neo", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XLM" -> {
val resouldId = context.resources.getIdentifier("ic_xml", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "EOS" -> {
val resouldId = context.resources.getIdentifier("ic_eos", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ADA" -> {
val resouldId = context.resources.getIdentifier("ic_ada", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ADX" -> {
val resouldId = context.resources.getIdentifier("ic_adx", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "STEEM" -> {
val resouldId = context.resources.getIdentifier("ic_steemd", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "FCT" -> {
val resouldId = context.resources.getIdentifier("ic_fct", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "R" -> {
val resouldId = context.resources.getIdentifier("ic_steemd", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SC" -> {
val resouldId = context.resources.getIdentifier("ic_sc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SKY" -> {
val resouldId = context.resources.getIdentifier("ic_sky", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BNT" -> {
val resouldId = context.resources.getIdentifier("ic_bnt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BCN" -> {
val resouldId = context.resources.getIdentifier("ic_bcn", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BTS" -> {
val resouldId = context.resources.getIdentifier("ic_bts", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "CNX" -> {
val resouldId = context.resources.getIdentifier("ic_cnx", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "WAVES" -> {
val resouldId = context.resources.getIdentifier("ic_waves", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "DCR" -> {
val resouldId = context.resources.getIdentifier("ic_dcr", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BTM" -> {
val resouldId = context.resources.getIdentifier("ic_btm", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BAT" -> {
val resouldId = context.resources.getIdentifier("ic_bat", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BLOCK" -> {
val resouldId = context.resources.getIdentifier("ic_block", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BNB" -> {
val resouldId = context.resources.getIdentifier("ic_bnb", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BTCD" -> {
val resouldId = context.resources.getIdentifier("ic_btcd", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "BTG" -> {
val resouldId = context.resources.getIdentifier("ic_btg", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "CVC" -> {
val resouldId = context.resources.getIdentifier("ic_cvc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "DASH" -> {
val resouldId = context.resources.getIdentifier("ic_dash", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "DGB" -> {
val resouldId = context.resources.getIdentifier("ic_dgb", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "DOGE" -> {
val resouldId = context.resources.getIdentifier("ic_doge", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "EDG" -> {
val resouldId = context.resources.getIdentifier("ic_edg", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "EMC2" -> {
val resouldId = context.resources.getIdentifier("ic_emc2", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ETC" -> {
val resouldId = context.resources.getIdentifier("ic_etc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ETHOS" -> {
val resouldId = context.resources.getIdentifier("ic_ethos", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ETP" -> {
val resouldId = context.resources.getIdentifier("ic_etp", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "FUN" -> {
val resouldId = context.resources.getIdentifier("ic_fun", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "GAME" -> {
val resouldId = context.resources.getIdentifier("ic_game", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "GAS" -> {
val resouldId = context.resources.getIdentifier("ic_gas", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "GBYTE" -> {
val resouldId = context.resources.getIdentifier("ic_gbyte", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "GNO" -> {
val resouldId = context.resources.getIdentifier("ic_gno", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "GNT" -> {
val resouldId = context.resources.getIdentifier("ic_gnt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "GRS" -> {
val resouldId = context.resources.getIdentifier("ic_grs", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "HSR" -> {
val resouldId = context.resources.getIdentifier("ic_hsr", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ICN" -> {
val resouldId = context.resources.getIdentifier("ic_icn", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "KMD" -> {
val resouldId = context.resources.getIdentifier("ic_kmd", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "KNC" -> {
val resouldId = context.resources.getIdentifier("ic_knc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "LSK" -> {
val resouldId = context.resources.getIdentifier("ic_lsk", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "MAID" -> {
val resouldId = context.resources.getIdentifier("ic_maid", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "MCO" -> {
val resouldId = context.resources.getIdentifier("ic_mco", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "MNX" -> {
val resouldId = context.resources.getIdentifier("ic_mnx", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "MONA" -> {
val resouldId = context.resources.getIdentifier("ic_mona", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "MTL" -> {
val resouldId = context.resources.getIdentifier("ic_mtl", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "NAV" -> {
val resouldId = context.resources.getIdentifier("ic_nav", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "NXS" -> {
val resouldId = context.resources.getIdentifier("ic_nxs", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "NXT" -> {
val resouldId = context.resources.getIdentifier("ic_nxt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "OMG" -> {
val resouldId = context.resources.getIdentifier("ic_omg", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "PAY" -> {
val resouldId = context.resources.getIdentifier("ic_pay", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "PIVX" -> {
val resouldId = context.resources.getIdentifier("ic_pivx", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "POT" -> {
val resouldId = context.resources.getIdentifier("ic_pot", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "POWER" -> {
val resouldId = context.resources.getIdentifier("ic_power", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "PPC" -> {
val resouldId = context.resources.getIdentifier("ic_ppc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "PPT" -> {
val resouldId = context.resources.getIdentifier("ic_ppt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "PURA" -> {
val resouldId = context.resources.getIdentifier("ic_pura", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "QASH" -> {
val resouldId = context.resources.getIdentifier("ic_qash", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "QTUM" -> {
val resouldId = context.resources.getIdentifier("ic_qtum", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "RDN" -> {
val resouldId = context.resources.getIdentifier("ic_rdn", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "REP" -> {
val resouldId = context.resources.getIdentifier("ic_rep", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SALT" -> {
val resouldId = context.resources.getIdentifier("ic_salt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SAN" -> {
val resouldId = context.resources.getIdentifier("ic_san", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SNGLS" -> {
val resouldId = context.resources.getIdentifier("ic_sngls", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SNT" -> {
val resouldId = context.resources.getIdentifier("ic_snt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "START" -> {
val resouldId = context.resources.getIdentifier("ic_start", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "STORJ" -> {
val resouldId = context.resources.getIdentifier("ic_storj", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "SYS" -> {
val resouldId = context.resources.getIdentifier("ic_sys", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "TRX" -> {
val resouldId = context.resources.getIdentifier("ic_trx", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "UBQ" -> {
val resouldId = context.resources.getIdentifier("ic_ubq", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "USDT" -> {
val resouldId = context.resources.getIdentifier("ic_usdt", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "VEN" -> {
val resouldId = context.resources.getIdentifier("ic_ven", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "VTC" -> {
val resouldId = context.resources.getIdentifier("ic_vtc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "WTC" -> {
val resouldId = context.resources.getIdentifier("ic_wtc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XEM" -> {
val resouldId = context.resources.getIdentifier("ic_xem", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XLM" -> {
val resouldId = context.resources.getIdentifier("ic_xlm", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XMR" -> {
val resouldId = context.resources.getIdentifier("ic_xmr", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XRP" -> {
val resouldId = context.resources.getIdentifier("ic_xrp", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XUC" -> {
val resouldId = context.resources.getIdentifier("ic_xuc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XVG" -> {
val resouldId = context.resources.getIdentifier("ic_xvg", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "XZC" -> {
val resouldId = context.resources.getIdentifier("ic_xzc", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ZEC" -> {
val resouldId = context.resources.getIdentifier("ic_zec", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ZEN" -> {
val resouldId = context.resources.getIdentifier("ic_zen", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
model.symbol == "ZRX" -> {
val resouldId = context.resources.getIdentifier("ic_zrx", "drawable", context.packageName)
coinImage.setImageResource(resouldId)
}
}
id_more.setOnClickListener {
val intent=Intent(context, MoreActivity::class.java)
intent.putExtra(COIN_DETAILS, model)
context.startActivity(intent)
}
}
}
}
| 2
|
Kotlin
|
0
| 0
|
9790b8bba7e43b11fb3641a06021ba9624abb4d6
| 18,900
|
CryptoMarket
|
Apache License 2.0
|
core/network/src/main/kotlin/com/najudoryeong/mineme/core/network/model/HomeMainResource.kt
|
NaJuDoRyeong
| 689,891,643
| false
|
{"Kotlin": 395682}
|
/*
* Copyright 2023 KDW03
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.najudoryeong.mineme.core.network.model
import kotlinx.serialization.Serializable
@Serializable
data class NetworkHomeMainResource constructor(
val couple: NetworkCouple,
val newStory: NetworkNewStory,
)
@Serializable
data class NetworkCouple(
val name: String = "",
val startDate: String = "",
val me: NetworkPerson,
val mine: NetworkPerson,
)
@Serializable
data class NetworkPerson(
val profileImage: String = "",
val nickname: String = "",
val description: String = "",
val instaId: String = "",
val birthday: String = "",
val gender: String = "",
)
@Serializable
data class NetworkNewStory(
val postId: Int = -1,
val region: String = "",
val date: String = "",
val thumbnailImage: String = "",
)
| 0
|
Kotlin
|
0
| 0
|
4a9a4178e6ba6adc9507bad01a7e62609d5aca98
| 1,371
|
mineme_AOS_new
|
Apache License 2.0
|
src/main/kotlin/no/njoh/pulseengine/core/scene/interfaces/Initiable.kt
|
NiklasJohansen
| 239,208,354
| false
|
{"Kotlin": 846455, "GLSL": 39054, "PostScript": 178}
|
package no.njoh.pulseengine.core.scene.interfaces
import no.njoh.pulseengine.core.PulseEngine
/**
* Gives the entity the ability to be initiated.
*/
interface Initiable
{
/**
* Called once when the entity is created.
*/
fun onCreate() { }
/**
* Called once when the scene starts.
*/
fun onStart(engine: PulseEngine) { }
}
| 0
|
Kotlin
|
0
| 1
|
c45a8028e1cef5259b76281a7d6083bcbfc51915
| 363
|
PulseEngine
|
MIT License
|
src/main/kotlin/uk/co/ben_gibson/git/link/ui/Icons.kt
|
cdambo
| 419,691,103
| true
|
{"Kotlin": 89867}
|
package uk.co.ben_gibson.git.link.ui
import com.intellij.openapi.util.IconLoader
object Icons {
val GITLAB = IconLoader.getIcon("/icons/gitlab.svg", javaClass)
val BITBUCKET = IconLoader.getIcon("/icons/bitbucket.svg", javaClass)
val GOGS = IconLoader.getIcon("/icons/gogs.svg", javaClass)
val AZURE = IconLoader.getIcon("/icons/azure.svg", javaClass)
val GITEA = IconLoader.getIcon("/icons/gitea.svg", javaClass)
val GIT = IconLoader.getIcon("/icons/git.svg", javaClass)
val GIT_LINK = IconLoader.getIcon("/icons/gitlink.svg", javaClass)
}
| 0
|
Kotlin
|
0
| 0
|
2a82df9f0c0d3c83fc599c89745357af8e648dbd
| 570
|
GitLink
|
MIT License
|
runtime/serde/common/src/aws/smithy/kotlin/runtime/serde/SdkSerializable.kt
|
smithy-lang
| 294,823,838
| false
| null |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package aws.smithy.kotlin.runtime.serde
import aws.smithy.kotlin.runtime.InternalApi
@InternalApi
public interface SdkSerializable {
public fun serialize(serializer: Serializer)
}
// FIXME - baby steps
// Glue code for marrying raw serialize functions to SdkSerializable
@InternalApi
public typealias SerializeFn<T> = (serializer: Serializer, input: T) -> Unit
@InternalApi
public fun <T> StructSerializer.field(descriptor: SdkFieldDescriptor, input: T, serializeFn: SerializeFn<T>) {
field(descriptor, SdkSerializableLambda(input, serializeFn))
}
private data class SdkSerializableLambda<T>(
private val input: T,
private val serializeFn: SerializeFn<T>,
) : SdkSerializable {
override fun serialize(serializer: Serializer) {
serializeFn(serializer, input)
}
}
// FIXME - this causes backing classes to be generated behind the scenes and contributes to the overall jar size
@InternalApi
public fun <T> asSdkSerializable(input: T, serializeFn: SerializeFn<T>): SdkSerializable = SdkSerializableLambda(input, serializeFn)
| 36
| null |
26
| 82
|
ad18e2fb043f665df9add82083c17877a23f8610
| 1,176
|
smithy-kotlin
|
Apache License 2.0
|
libautomata/src/main/java/com/mathewsachin/libautomata/ScreenshotManager.kt
|
Fate-Grand-Automata
| 245,391,245
| false
| null |
package com.mathewsachin.libautomata
import com.mathewsachin.libautomata.dagger.ScriptScope
import com.mathewsachin.libautomata.extensions.ITransformationExtensions
import javax.inject.Inject
/**
* A static class responsible for taking screenshots via a [IScreenshotService]. The screenshots are
* scaled and cropped and can be cached for a while using [snapshot].
*/
@ScriptScope
class ScreenshotManager @Inject constructor(
val gameAreaManager: GameAreaManager,
val screenshotService: IScreenshotService,
val platformImpl: IPlatformImpl,
val transformationExtensions: ITransformationExtensions
) : AutoCloseable {
var usePreviousSnap = false
private var previousPattern: IPattern? = null
private var resizeTarget: IPattern? = null
/**
* Takes a screenshot, crops it to the game area and then scales it to the image scale so
* it can be used for image comparisons.
*/
private fun getScaledScreenshot(): IPattern {
val sshot = screenshotService.takeScreenshot()
.crop(gameAreaManager.gameArea)
val scale = transformationExtensions.screenToImageScale()
if (scale != null) {
if (resizeTarget == null) {
resizeTarget = platformImpl.getResizableBlankPattern()
}
sshot.resize(resizeTarget!!, sshot.Size * scale)
return resizeTarget!!
}
return sshot
}
/**
* Takes a screenshot and sets [usePreviousSnap] to `true`. All following [getScreenshot]
* calls will use the same screenshot, until [usePreviousSnap] is set to `false` again.
*
* The screenshot image can be retrieved using [getScreenshot].
*/
fun snapshot() {
previousPattern = getScaledScreenshot()
usePreviousSnap = true
}
/**
* Takes a screenshot, crops it to the game area and then scales it to the image scale so
* it can be used for image comparisons.
*
* If [usePreviousSnap] is set to true, a cached screenshot is returned instead.
*
* @return an [IPattern] with the screenshot image data
*/
fun getScreenshot(): IPattern {
if (usePreviousSnap) {
previousPattern?.let { return it }
}
return getScaledScreenshot().also {
previousPattern = it
}
}
/**
* Takes a screenshot and caches it for the duration of the function invocation. This is
* useful when you want to reuse the same screenshot for multiple image searches.
*
* @param Action a function to invoke which will use the cached screenshot
*/
fun <T> useSameSnapIn(Action: () -> T): T {
snapshot()
try {
return Action()
} finally {
usePreviousSnap = false
}
}
/**
* Releases the memory reserved for the cached screenshot and helper images.
*/
override fun close() {
previousPattern?.close()
previousPattern = null
resizeTarget?.close()
resizeTarget = null
}
}
| 66
| null |
103
| 407
|
eb88f240c75569bf8414caa91af705e1dd870c6f
| 3,065
|
FGA
|
MIT License
|
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/utils/SanityFilters.kt
|
navikt
| 435,813,834
| false
| null |
package no.nav.mulighetsrommet.api.utils
import no.nav.mulighetsrommet.api.clients.vedtak.Innsatsgruppe
fun byggLokasjonsFilter(lokasjoner: List<String>): String {
if (lokasjoner.isEmpty()) return ""
return """
&& lokasjon in ${lokasjoner.toSanityListe()}
""".trimIndent()
}
fun byggEnhetOgFylkeFilter(enhetsId: String, fylkeId: String): String {
return """
&& ('enhet.lokal.$enhetsId' in enheter[]._ref || (enheter[0] == null && 'enhet.fylke.$fylkeId' == fylke._ref))
""".trimIndent()
}
fun byggTiltakstypeFilter(tiltakstyper: List<String>): String {
if (tiltakstyper.isEmpty()) return ""
return """
&& tiltakstype->_id in ${tiltakstyper.toSanityListe()}
""".trimIndent()
}
fun byggSokeFilter(sokestreng: String): String {
if (sokestreng.isBlank()) return ""
return """
&& [tiltaksgjennomforingNavn, string(tiltaksnummer.current), tiltakstype->tiltakstypeNavn, lokasjon, kontaktinfoArrangor->selskapsnavn, oppstartsdato] match "*$sokestreng*"
""".trimIndent()
}
fun byggInnsatsgruppeFilter(innsatsgruppe: String?): String {
if (innsatsgruppe.isNullOrBlank()) return ""
return """
&& tiltakstype->innsatsgruppe->nokkel in ${utledInnsatsgrupper(innsatsgruppe).toSanityListe()}
""".trimIndent()
}
private fun List<String>.toSanityListe(): String {
return "[${this.joinToString { "'$it'" }}]"
}
fun utledInnsatsgrupper(innsatsgruppe: String): List<String> {
return when (innsatsgruppe) {
Innsatsgruppe.STANDARD_INNSATS.name -> listOf(Innsatsgruppe.STANDARD_INNSATS.name)
Innsatsgruppe.SITUASJONSBESTEMT_INNSATS.name -> listOf(
Innsatsgruppe.STANDARD_INNSATS.name,
Innsatsgruppe.SITUASJONSBESTEMT_INNSATS.name,
)
Innsatsgruppe.SPESIELT_TILPASSET_INNSATS.name -> listOf(
Innsatsgruppe.STANDARD_INNSATS.name,
Innsatsgruppe.SITUASJONSBESTEMT_INNSATS.name,
Innsatsgruppe.SPESIELT_TILPASSET_INNSATS.name,
)
Innsatsgruppe.VARIG_TILPASSET_INNSATS.name -> listOf(
Innsatsgruppe.STANDARD_INNSATS.name,
Innsatsgruppe.SITUASJONSBESTEMT_INNSATS.name,
Innsatsgruppe.SPESIELT_TILPASSET_INNSATS.name,
Innsatsgruppe.VARIG_TILPASSET_INNSATS.name,
)
else -> emptyList()
}
}
| 6
|
Kotlin
|
1
| 4
|
6640d59e1270e6819f7dd7431511a668969255f2
| 2,368
|
mulighetsrommet
|
MIT License
|
app/src/main/java/com/example/data/datasource/network/base/AbstractModule.kt
|
CroogeADL
| 204,532,737
| false
| null |
package com.example.data.datasource.network.base
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext
abstract class AbstractModule<T>(protected val service: T) : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
}
| 0
|
Kotlin
|
0
| 0
|
0d966fefd6791fbaf3c457158e72cdfef26346c6
| 336
|
mvp-architecture-complete
|
MIT License
|
app/src/main/java/com/renaisn/reader/ui/book/import/local/ImportBookViewModel.kt
|
RenaisnNce
| 598,532,496
| false
| null |
package com.renaisn.reader.ui.book.import.local
import android.app.Application
import android.net.Uri
import androidx.documentfile.provider.DocumentFile
import com.renaisn.reader.base.BaseViewModel
import com.renaisn.reader.constant.AppLog
import com.renaisn.reader.constant.AppPattern.bookFileRegex
import com.renaisn.reader.constant.PreferKey
import com.renaisn.reader.model.localBook.LocalBook
import com.renaisn.reader.utils.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import java.io.File
import java.util.*
class ImportBookViewModel(application: Application) : BaseViewModel(application) {
var rootDoc: FileDoc? = null
val subDocs = arrayListOf<FileDoc>()
var sort = context.getPrefInt(PreferKey.localBookImportSort)
var dataCallback: DataCallback? = null
var dataFlowStart: (() -> Unit)? = null
val dataFlow = callbackFlow<List<FileDoc>> {
val list = Collections.synchronizedList(ArrayList<FileDoc>())
dataCallback = object : DataCallback {
override fun setItems(fileDocs: List<FileDoc>) {
list.clear()
list.addAll(fileDocs)
trySend(list)
}
override fun addItems(fileDocs: List<FileDoc>) {
list.addAll(fileDocs)
trySend(list)
}
override fun clear() {
list.clear()
trySend(emptyList())
}
}
withContext(Main) {
dataFlowStart?.invoke()
}
awaitClose {
dataCallback = null
}
}.map { docList ->
when (sort) {
2 -> docList.sortedWith(
compareBy({ !it.isDir }, { -it.lastModified }, { it.name })
)
1 -> docList.sortedWith(
compareBy({ !it.isDir }, { -it.size }, { it.name })
)
else -> docList.sortedWith(
compareBy({ !it.isDir }, { it.name })
)
}
}.flowOn(IO)
fun addToBookshelf(uriList: HashSet<String>, finally: () -> Unit) {
execute {
uriList.forEach {
LocalBook.importFile(Uri.parse(it))
}
}.onError {
context.toastOnUi("添加书架失败,请尝试重新选择文件夹")
AppLog.put("添加书架失败\n${it.localizedMessage}", it)
}.onFinally {
finally.invoke()
}
}
fun deleteDoc(uriList: HashSet<String>, finally: () -> Unit) {
execute {
uriList.forEach {
val uri = Uri.parse(it)
if (uri.isContentScheme()) {
DocumentFile.fromSingleUri(context, uri)?.delete()
} else {
uri.path?.let { path ->
File(path).delete()
}
}
}
}.onFinally {
finally.invoke()
}
}
fun loadDoc(fileDoc: FileDoc) {
execute {
val docList = fileDoc.list { item ->
when {
item.name.startsWith(".") -> false
item.isDir -> true
else -> item.name.matches(bookFileRegex)
}
}
dataCallback?.setItems(docList!!)
}.onError {
context.toastOnUi("获取文件列表出错\n${it.localizedMessage}")
}
}
fun scanDoc(
fileDoc: FileDoc,
isRoot: Boolean,
scope: CoroutineScope,
finally: (() -> Unit)? = null
) {
if (isRoot) {
dataCallback?.clear()
}
if (!scope.isActive) {
finally?.invoke()
return
}
kotlin.runCatching {
val list = ArrayList<FileDoc>()
fileDoc.list()!!.forEach { docItem ->
if (!scope.isActive) {
finally?.invoke()
return
}
if (docItem.isDir) {
scanDoc(docItem, false, scope)
} else if (docItem.name.endsWith(".txt", true)
|| docItem.name.endsWith(".epub", true) || docItem.name.endsWith(
".pdf",
true
) || docItem.name.endsWith(".umd", true)
) {
list.add(docItem)
}
}
if (!scope.isActive) {
finally?.invoke()
return
}
if (list.isNotEmpty()) {
dataCallback?.addItems(list)
}
}.onFailure {
context.toastOnUi("扫描文件夹出错\n${it.localizedMessage}")
}
if (isRoot) {
finally?.invoke()
}
}
interface DataCallback {
fun setItems(fileDocs: List<FileDoc>)
fun addItems(fileDocs: List<FileDoc>)
fun clear()
}
}
| 1
|
Kotlin
|
1
| 4
|
4ac03e214e951f7f4f337d4da1f7e39fa715d1c0
| 5,190
|
Renaisn_Android
|
MIT License
|
app/src/main/java/jp/seo/station/ekisagasu/ui/dialog/LogOutputConfDialog.kt
|
Seo-4d696b75
| 247,417,963
| false
| null |
package jp.seo.station.ekisagasu.ui.dialog
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import jp.seo.station.ekisagasu.R
import jp.seo.station.ekisagasu.databinding.DialogLogOutputConfigBinding
@AndroidEntryPoint
class LogOutputConfDialog : DialogFragment() {
val viewModel: LogOutputConfViewModel by viewModels()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DataBindingUtil.inflate<DialogLogOutputConfigBinding>(
layoutInflater,
R.layout.dialog_log_output_config,
null,
false,
)
binding.radioGroupFileExtension.setOnCheckedChangeListener { group, checkedId ->
viewModel.onChecked(checkedId)
}
binding.viewModel = viewModel
return AlertDialog.Builder(requireContext()).apply {
setTitle(R.string.dialog_log_output_config_title)
setPositiveButton(R.string.dialog_button_positive) { _, _ ->
viewModel.writeLog()
dismiss()
}
setNegativeButton(R.string.dialog_button_negative) { _, _ ->
dismiss()
}
setView(binding.root)
}.create().apply {
setCanceledOnTouchOutside(false)
}
}
}
| 1
|
Kotlin
|
0
| 0
|
99cda72b3a3b68a99254ce578595f5270674f536
| 1,494
|
checkhelper
|
MIT License
|
platform/platform-impl/src/com/intellij/ide/impl/trustedProjects/LocatedProject.kt
|
errandir
| 27,763,579
| false
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.impl.trustedProjects
import com.intellij.openapi.project.Project
import java.nio.file.Path
class LocatedProject(
val projectRoots: List<Path>,
val project: Project?
) {
companion object {
fun locateProject(projectRoot: Path, project: Project?): LocatedProject {
return locateProject(project) { getProjectRoots(projectRoot, project) }
}
fun locateProject(project: Project): LocatedProject {
return locateProject(project) { getProjectRoots(project) }
}
private fun locateProject(
project: Project?,
getProjectRoots: ProjectLocator.() -> List<Path>
): LocatedProject {
val projectRoots = LinkedHashSet<Path>()
ProjectLocator.EP_NAME.forEachExtensionSafe { locator ->
projectRoots.addAll(locator.getProjectRoots())
}
return LocatedProject(projectRoots.toList(), project)
}
}
}
| 1
| null |
1
| 1
|
1d359da14d759f924f64811b84c8aeccb1d1188c
| 1,015
|
intellij-community
|
Apache License 2.0
|
src/main/kotlin/dev/akif/exchangerates/CurrencyRepository.kt
|
makiftutuncu
| 745,133,540
| false
|
{"Kotlin": 4899}
|
package dev.akif.exchangerates
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Repository
@Repository
class CurrencyRepository {
companion object {
private val log: Logger = LoggerFactory.getLogger(CurrencyRepository::class.java)
}
fun all(): Set<String> {
log.info("Loading currencies")
return setOf("USD", "EUR", "TRY", "GBP")
}
}
| 4
|
Kotlin
|
0
| 0
|
6074b4338dde981f7ae42b20a60446f72b64a7bd
| 421
|
periodik-example
|
MIT License
|
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/FilterDialogFragment.kt
|
SagarBChauhan
| 216,040,454
| false
| null |
package com.google.firebase.example.fireeats.kotlin
import android.content.Context
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.firebase.example.fireeats.R
import com.google.firebase.example.fireeats.kotlin.model.Restaurant
import com.google.firebase.firestore.Query
import kotlinx.android.synthetic.main.dialog_filters.*
import kotlinx.android.synthetic.main.dialog_filters.view.*
/**
* Dialog Fragment containing filter form.
*/
class FilterDialogFragment : DialogFragment() {
private lateinit var rootView: View
private var filterListener: FilterListener? = null
private val selectedCategory: String?
get() {
val selected = spinnerCategory.selectedItem as String
return if (getString(R.string.value_any_category) == selected) {
null
} else {
selected
}
}
private val selectedCity: String?
get() {
val selected = spinnerCity.selectedItem as String
return if (getString(R.string.value_any_city) == selected) {
null
} else {
selected
}
}
private val selectedPrice: Int
get() {
val selected = spinnerPrice.selectedItem as String
return when (selected) {
getString(R.string.price_1) -> 1
getString(R.string.price_2) -> 2
getString(R.string.price_3) -> 3
else -> -1
}
}
private val selectedSortBy: String?
get() {
val selected = spinnerSort.selectedItem as String
if (getString(R.string.sort_by_rating) == selected) {
return Restaurant.FIELD_AVG_RATING
}
if (getString(R.string.sort_by_price) == selected) {
return Restaurant.FIELD_PRICE
}
return if (getString(R.string.sort_by_popularity) == selected) {
Restaurant.FIELD_POPULARITY
} else {
null
}
}
private val sortDirection: Query.Direction
get() {
val selected = spinnerSort.selectedItem as String
if (getString(R.string.sort_by_rating) == selected) {
return Query.Direction.DESCENDING
}
if (getString(R.string.sort_by_price) == selected) {
return Query.Direction.ASCENDING
}
return if (getString(R.string.sort_by_popularity) == selected) {
Query.Direction.DESCENDING
} else {
Query.Direction.DESCENDING
}
}
val filters: Filters
get() {
val filters = Filters()
filters.category = selectedCategory
filters.city = selectedCity
filters.price = selectedPrice
filters.sortBy = selectedSortBy
filters.sortDirection = sortDirection
return filters
}
interface FilterListener {
fun onFilter(filters: Filters)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.dialog_filters, container, false)
rootView.buttonSearch.setOnClickListener { onSearchClicked() }
rootView.buttonCancel.setOnClickListener { onCancelClicked() }
return rootView
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is FilterListener) {
filterListener = context
}
}
override fun onResume() {
super.onResume()
dialog.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
}
fun onSearchClicked() {
filterListener?.onFilter(filters)
dismiss()
}
fun onCancelClicked() {
dismiss()
}
fun resetFilters() {
spinnerCategory?.setSelection(0)
spinnerCity?.setSelection(0)
spinnerPrice?.setSelection(0)
spinnerSort?.setSelection(0)
}
companion object {
val TAG = "FilterDialog"
}
}
| 18
| null |
1
| 5
|
d886d348a681f41f02e78d720cb74fb8c162e339
| 4,420
|
quickstart-android
|
Creative Commons Attribution 4.0 International
|
API/src/main/kotlin/net/sourcebot/api/command/argument/SourceAdapter.kt
|
TheSourceCodeLLC
| 271,902,483
| false
| null |
package net.sourcebot.api.command.argument
import me.hwiggy.kommander.InvalidSyntaxException
import me.hwiggy.kommander.arguments.Adapter
import me.hwiggy.kommander.arguments.BoundAdapter
import me.hwiggy.kommander.arguments.or
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.entities.TextChannel
import net.sourcebot.api.DurationUtils
import net.sourcebot.api.command.argument.resolvable.RoleResolvable
import net.sourcebot.api.command.argument.resolvable.UserResolvable
import java.time.Duration
/**
* Holder object for additional adapters
*/
@Suppress("UNCHECKED_CAST", "UNUSED")
object SourceAdapter {
/**
* Creates an [Adapter] that returns a Member for a [Guild] obtained through extra parameters
* If multiple Members are matched, [InvalidSyntaxException] is thrown
*/
@JvmStatic fun member(guild: Guild, arg: String): Member? {
val target = arg.replace("<@!?(\\d+)>".toRegex(), "$1")
return runCatching { guild.retrieveMemberById(target).complete() }.getOrElse {
target.runCatching(guild::getMemberByTag).getOrElse {
guild.getMembersByEffectiveName(target, true).let {
when {
it.isEmpty() -> null
it.size == 1 -> it[0]
else -> throw InvalidSyntaxException("Argument '$target' matches multiple members!")
}
}
}
}
}
@JvmStatic fun member() = Adapter.single { arg, extra ->
member(extra["guild"], arg)
}
/**
* Creates an [Adapter] that returns a User for a [JDA] obtained through extra parameters
* If multiple Users are matched, [InvalidSyntaxException] is thrown
*
*/
@JvmStatic fun user() = Adapter.single { arg, extra ->
UserResolvable(extra["jda"], arg).resolve()
}
@JvmStatic fun role(guild: Guild, arg: String): Role? {
val target = arg.replace("<@&(\\d+)>".toRegex(), "$1").lowercase()
return if (target == "everyone") guild.publicRole
else target.runCatching(guild::getRoleById).getOrElse {
guild.getRolesByName(target, true).let {
when {
it.isEmpty() -> null
it.size == 1 -> it[0]
else -> throw InvalidSyntaxException("Argument '$target' matches multiple roles!")
}
}
}
}
/**
* Creates an [Adapter] that returns a Role for a [Guild] obtained through extra parameters
* If multiple Roles are matched, [InvalidSyntaxException] is thrown
*/
@JvmStatic fun role() = Adapter.single { arg, extra ->
RoleResolvable(extra["guild"], arg).resolve()
}
@JvmStatic fun textChannel() = Adapter.single { arg, extra ->
val guild: Guild by extra
textChannel(guild, arg)
}
@JvmStatic fun textChannel(guild: Guild, arg: String): TextChannel? {
val target = arg.replace("<#(\\d+)>".toRegex(), "$1")
return target.runCatching(guild::getTextChannelById).getOrElse {
guild.getTextChannelsByName(target, true).let {
when {
it.isEmpty() -> null
it.size == 1 -> it[0]
else -> throw InvalidSyntaxException(
"Argument '$target' matches multiple channels!"
)
}
}
}
}
@JvmStatic fun category() = Adapter.single { arg, extra ->
val guild: Guild by extra
category(guild, arg)
}
@JvmStatic fun category(guild: Guild, arg: String) = arg.runCatching(guild::getCategoryById).getOrElse {
guild.getCategoriesByName(arg, true).let {
when {
it.isEmpty() -> null
it.size == 1 -> it[0]
else -> throw InvalidSyntaxException("Argument '$arg' matches multiple categories!")
}
}
}
@JvmStatic fun guildMessageChannel() = textChannel() or category()
@JvmStatic fun duration() = Adapter.single { it ->
it.runCatching(DurationUtils::parseDuration).getOrNull()
}
@JvmStatic fun duration(
min: String? = null,
max: String? = null,
error: String? = null
): BoundAdapter<Duration> {
val lower = min?.let(DurationUtils::parseDuration)
val upper = max?.let(DurationUtils::parseDuration)
return duration().bound(lower, upper, error, Duration::getSeconds)
}
}
| 5
| null |
8
| 11
|
785254fd3cff07b5781f9ed4d0cc95d643c2b2b0
| 4,649
|
Source
|
MIT License
|
Corona-Warn-App/src/androidTest/java/de/rki/coronawarnapp/ui/submission/SubmissionTestResultAvailableFragmentTest.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.ui.submission
import androidx.lifecycle.MutableLiveData
import androidx.test.ext.junit.runners.AndroidJUnit4
import dagger.Module
import dagger.android.ContributesAndroidInjector
import de.rki.coronawarnapp.coronatest.CoronaTestProvider
import de.rki.coronawarnapp.coronatest.type.BaseCoronaTest
import de.rki.coronawarnapp.coronatest.type.TestIdentifier
import de.rki.coronawarnapp.datadonation.analytics.modules.keysubmission.AnalyticsKeySubmissionCollector
import de.rki.coronawarnapp.presencetracing.checkins.CheckInRepository
import de.rki.coronawarnapp.submission.SubmissionRepository
import de.rki.coronawarnapp.submission.auto.AutoSubmission
import de.rki.coronawarnapp.submission.data.tekhistory.TEKHistoryUpdater_Factory_Impl
import de.rki.coronawarnapp.ui.submission.resultavailable.SubmissionTestResultAvailableFragment
import de.rki.coronawarnapp.ui.submission.resultavailable.SubmissionTestResultAvailableFragmentArgs
import de.rki.coronawarnapp.ui.submission.resultavailable.SubmissionTestResultAvailableViewModel
import de.rki.coronawarnapp.util.shortcuts.AppShortcutsHelper
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.spyk
import kotlinx.coroutines.flow.flowOf
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import testhelpers.BaseUITest
import testhelpers.Screenshot
import testhelpers.TestDispatcherProvider
import testhelpers.launchFragmentInContainer2
import testhelpers.takeScreenshot
@RunWith(AndroidJUnit4::class)
class SubmissionTestResultAvailableFragmentTest : BaseUITest() {
lateinit var viewModel: SubmissionTestResultAvailableViewModel
@MockK lateinit var submissionRepository: SubmissionRepository
@MockK lateinit var tekHistoryUpdaterFactory: TEKHistoryUpdater_Factory_Impl
@MockK lateinit var autoSubmission: AutoSubmission
@MockK lateinit var appShortcutsHelper: AppShortcutsHelper
@MockK lateinit var analyticsKeySubmissionCollector: AnalyticsKeySubmissionCollector
@MockK lateinit var checkInRepository: CheckInRepository
@MockK lateinit var testType: BaseCoronaTest.Type
@MockK lateinit var coronaTestProvider: CoronaTestProvider
private val resultAvailableFragmentArgs =
SubmissionTestResultAvailableFragmentArgs(testIdentifier = "").toBundle()
@Before
fun setup() {
MockKAnnotations.init(this, relaxed = true)
every { submissionRepository.testForType(any()) } returns flowOf()
every { appShortcutsHelper.disableAllShortcuts() } returns Result.success(Unit)
viewModel = spyk(
SubmissionTestResultAvailableViewModel(
dispatcherProvider = TestDispatcherProvider(),
tekHistoryUpdaterFactory = tekHistoryUpdaterFactory,
autoSubmission = autoSubmission,
analyticsKeySubmissionCollector = analyticsKeySubmissionCollector,
checkInRepository = checkInRepository,
coronaTestProvider = coronaTestProvider,
testIdentifier = ""
)
)
setupMockViewModel(
object : SubmissionTestResultAvailableViewModel.Factory {
override fun create(testIdentifier: TestIdentifier): SubmissionTestResultAvailableViewModel = viewModel
}
)
}
@After
fun teardown() {
clearAllViewModels()
}
@Test
@Screenshot
fun capture_fragment_with_consent() {
every { viewModel.consent } returns MutableLiveData(true)
launchFragmentInContainer2<SubmissionTestResultAvailableFragment>(
fragmentArgs = resultAvailableFragmentArgs
)
takeScreenshot<SubmissionTestResultAvailableFragment>(suffix = "_consent")
}
@Test
@Screenshot
fun capture_fragment_without_consent() {
every { viewModel.consent } returns MutableLiveData(false)
launchFragmentInContainer2<SubmissionTestResultAvailableFragment>(
fragmentArgs = resultAvailableFragmentArgs
)
takeScreenshot<SubmissionTestResultAvailableFragment>(suffix = "_no_consent")
}
}
@Module
abstract class SubmissionTestResultTestAvailableModule {
@ContributesAndroidInjector
abstract fun submissionTestResultScreen(): SubmissionTestResultAvailableFragment
}
| 6
| null |
516
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 4,384
|
cwa-app-android
|
Apache License 2.0
|
lint-checks/src/main/java/com/uber/lintchecks/SystemCurrentTimeMillisDetector.kt
|
uber
| 183,370,095
| false
| null |
/*
* Copyright (C) 2019. Uber Technologies
*
* 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.uber.lintchecks
import com.android.tools.lint.client.api.JavaEvaluator
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import com.uber.lintchecks.android.createImplementation
import org.jetbrains.uast.UCallExpression
/**
* Prevent usage of System.currentTimeMillis.
*/
class SystemCurrentTimeMillisDetector : Detector(), SourceCodeScanner {
companion object {
private const val ISSUE_ID = "SystemCurrentTimeMillis"
private const val BRIEF_DESCRIPTION = "Don't use System.currentTimeMillis"
const val LINT_ERROR_MESSAGE = """Don't use System.currentTimeMillis.
Please prefer an abstraction like Clock, as this is easily mocked, injected, and tested."""
val ISSUE = Issue.create(
id = ISSUE_ID,
briefDescription = BRIEF_DESCRIPTION,
explanation = LINT_ERROR_MESSAGE,
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.ERROR,
implementation = createImplementation<SystemCurrentTimeMillisDetector>())
}
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (!getApplicableMethodNames().contains(node.methodName)) return
val evaluator = context.evaluator
if (node.methodName == "currentTimeMillis" && isSystemType(evaluator, node)) {
context.report(ISSUE, context.getLocation(node), LINT_ERROR_MESSAGE)
}
}
private fun isSystemType(evaluator: JavaEvaluator, node: UCallExpression): Boolean {
return evaluator.isMemberInClass(node.resolve(), "java.lang.System")
}
override fun getApplicableMethodNames(): List<String> = listOf("currentTimeMillis")
}
| 2
|
Kotlin
|
8
| 62
|
1cc2d30171896525c8a1974f99e3f090037ba453
| 2,558
|
lint-checks
|
Apache License 2.0
|
jdk_17_maven/cs/rest/familie-tilbake/src/test/kotlin/no/nav/familie/tilbake/behandling/FagsakServiceTest.kt
|
WebFuzzing
| 94,008,854
| false
|
{"Java": 22427324, "Kotlin": 8594997, "JavaScript": 4556501, "HTML": 2139000, "TypeScript": 701370, "CSS": 427693, "Gherkin": 416527, "C#": 314846, "Handlebars": 199012, "Python": 134818, "Jupyter Notebook": 94581, "Perl": 82062, "Shell": 53769, "Less": 29035, "Starlark": 23296, "XSLT": 18724, "Awk": 17751, "EJS": 13193, "Lua": 11843, "Dockerfile": 11527, "SCSS": 7939, "PLpgSQL": 4478, "TSQL": 4320, "R": 4250, "Pug": 3626, "TeX": 3261, "Smarty": 2380, "Lex": 1418, "Thrift": 1245, "Ruby": 683, "Procfile": 316, "Mermaid": 187}
|
package no.nav.familie.tilbake.behandling
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import no.nav.familie.kontrakter.felles.Fagsystem
import no.nav.familie.kontrakter.felles.Ressurs
import no.nav.familie.kontrakter.felles.Språkkode
import no.nav.familie.kontrakter.felles.tilbakekreving.Ytelsestype
import no.nav.familie.prosessering.domene.Task
import no.nav.familie.prosessering.internal.TaskService
import no.nav.familie.tilbake.OppslagSpringRunnerTest
import no.nav.familie.tilbake.behandling.domain.Behandling
import no.nav.familie.tilbake.behandling.domain.Behandlingsstatus
import no.nav.familie.tilbake.behandling.domain.Behandlingstype
import no.nav.familie.tilbake.behandling.domain.Bruker
import no.nav.familie.tilbake.behandling.domain.Fagsak
import no.nav.familie.tilbake.behandling.domain.Institusjon
import no.nav.familie.tilbake.behandling.task.OpprettBehandlingManueltTask
import no.nav.familie.tilbake.common.repository.findByIdOrThrow
import no.nav.familie.tilbake.config.Constants
import no.nav.familie.tilbake.data.Testdata
import no.nav.familie.tilbake.integration.pdl.internal.Kjønn
import no.nav.familie.tilbake.kravgrunnlag.ØkonomiXmlMottattRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.web.client.exchange
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import org.springframework.web.util.UriComponentsBuilder
import java.time.LocalDate
import java.util.Properties
import java.util.UUID
internal class FagsakServiceTest : OppslagSpringRunnerTest() {
@Autowired
private lateinit var fagsakRepository: FagsakRepository
@Autowired
private lateinit var behandlingRepository: BehandlingRepository
@Autowired
private lateinit var økonomiXmlMottattRepository: ØkonomiXmlMottattRepository
@Autowired
private lateinit var taskService: TaskService
@Autowired
private lateinit var fagsakService: FagsakService
@Test
fun test() {
headers.setBearerAuth(lokalTestToken())
val uriHentSaksnummer = UriComponentsBuilder.fromHttpUrl(localhost("/api/fagsystem/EF/fagsak/123456/v1")).toUriString()
val response: ResponseEntity<Ressurs<Map<String, String>>> =
restTemplate.exchange(
uriHentSaksnummer,
HttpMethod.GET,
HttpEntity<String>(headers),
)
println(response)
}
@Test
fun `hentFagsak skal hente fagsak for barnetrygd`() {
val eksternFagsakId = UUID.randomUUID().toString()
val behandling = opprettBehandling(Ytelsestype.BARNETRYGD, eksternFagsakId)
val fagsakDto = fagsakService.hentFagsak(Fagsystem.BA, eksternFagsakId)
fagsakDto.eksternFagsakId shouldBe eksternFagsakId
fagsakDto.språkkode shouldBe Språkkode.NB
fagsakDto.ytelsestype shouldBe Ytelsestype.BARNETRYGD
fagsakDto.fagsystem shouldBe Fagsystem.BA
fagsakDto.institusjon shouldBe null
val brukerDto = fagsakDto.bruker
brukerDto.personIdent shouldBe "32132132111"
brukerDto.navn shouldBe "testverdi"
brukerDto.kjønn shouldBe Kjønn.MANN
brukerDto.fødselsdato shouldBe LocalDate.now().minusYears(20)
brukerDto.dødsdato shouldBe null
val behandlinger = fagsakDto.behandlinger
behandlinger.size shouldBe 1
val behandlingsoppsummeringtDto = behandlinger.toList()[0]
behandlingsoppsummeringtDto.behandlingId shouldBe behandling.id
behandlingsoppsummeringtDto.eksternBrukId shouldBe behandling.eksternBrukId
behandlingsoppsummeringtDto.status shouldBe behandling.status
behandlingsoppsummeringtDto.type shouldBe behandling.type
}
@Test
fun `hentFagsak skal hente fagsak for død person`() {
val eksternFagsakId = UUID.randomUUID().toString()
val behandling = opprettBehandling(Ytelsestype.BARNETRYGD, eksternFagsakId, "doed1234")
val fagsakDto = fagsakService.hentFagsak(Fagsystem.BA, eksternFagsakId)
fagsakDto.eksternFagsakId shouldBe eksternFagsakId
fagsakDto.språkkode shouldBe Språkkode.NB
fagsakDto.ytelsestype shouldBe Ytelsestype.BARNETRYGD
fagsakDto.fagsystem shouldBe Fagsystem.BA
val brukerDto = fagsakDto.bruker
brukerDto.personIdent shouldBe "do<PASSWORD>"
brukerDto.navn shouldBe "testverdi"
brukerDto.kjønn shouldBe Kjønn.MANN
brukerDto.fødselsdato shouldBe LocalDate.now().minusYears(20)
brukerDto.dødsdato shouldBe LocalDate.of(2022, 4, 1)
val behandlinger = fagsakDto.behandlinger
behandlinger.size shouldBe 1
val behandlingsoppsummeringtDto = behandlinger.toList()[0]
behandlingsoppsummeringtDto.behandlingId shouldBe behandling.id
behandlingsoppsummeringtDto.eksternBrukId shouldBe behandling.eksternBrukId
behandlingsoppsummeringtDto.status shouldBe behandling.status
behandlingsoppsummeringtDto.type shouldBe behandling.type
}
@Test
fun `hentFagsak skal hente og oppdatere fagsak for barnetrygd`() {
val eksternFagsakId = UUID.randomUUID().toString()
opprettBehandling(Ytelsestype.BARNETRYGD, eksternFagsakId, "12345678910")
// Antar mock PDL client returnerer 32132132111
// første kall mot PDL får differanse på ident og kaster endretPersonIdentPublisher event
fagsakService.hentFagsak(Fagsystem.BA, eksternFagsakId)
val fagsakDto = fagsakService.hentFagsak(Fagsystem.BA, eksternFagsakId)
fagsakDto.eksternFagsakId shouldBe eksternFagsakId
fagsakDto.språkkode shouldBe Språkkode.NB
fagsakDto.ytelsestype shouldBe Ytelsestype.BARNETRYGD
fagsakDto.fagsystem shouldBe Fagsystem.BA
val brukerDto = fagsakDto.bruker
brukerDto.personIdent shouldBe "12345678910"
brukerDto.navn shouldBe "testverdi"
brukerDto.kjønn shouldBe Kjønn.MANN
brukerDto.fødselsdato shouldBe LocalDate.now().minusYears(20)
}
@Test
fun `hentFagsak skal hente fagsak for barnetrygd med institusjon`() {
val eksternFagsakId = UUID.randomUUID().toString()
val behandling =
opprettBehandling(
ytelsestype = Ytelsestype.BARNETRYGD,
eksternFagsakId = eksternFagsakId,
institusjon = Institusjon(organisasjonsnummer = "998765432"),
)
val fagsakDto = fagsakService.hentFagsak(Fagsystem.BA, eksternFagsakId)
fagsakDto.eksternFagsakId shouldBe eksternFagsakId
fagsakDto.språkkode shouldBe Språkkode.NB
fagsakDto.ytelsestype shouldBe Ytelsestype.BARNETRYGD
fagsakDto.fagsystem shouldBe Fagsystem.BA
fagsakDto.institusjon shouldNotBe null
fagsakDto.institusjon!!.organisasjonsnummer shouldBe "998765432"
fagsakDto.institusjon!!.navn shouldBe "Testinstitusjon"
val brukerDto = fagsakDto.bruker
brukerDto.personIdent shouldBe "32132132111"
brukerDto.navn shouldBe "testverdi"
brukerDto.kjønn shouldBe Kjønn.MANN
brukerDto.fødselsdato shouldBe LocalDate.now().minusYears(20)
brukerDto.dødsdato shouldBe null
val behandlinger = fagsakDto.behandlinger
behandlinger.size shouldBe 1
val behandlingsoppsummeringtDto = behandlinger.toList()[0]
behandlingsoppsummeringtDto.behandlingId shouldBe behandling.id
behandlingsoppsummeringtDto.eksternBrukId shouldBe behandling.eksternBrukId
behandlingsoppsummeringtDto.status shouldBe behandling.status
behandlingsoppsummeringtDto.type shouldBe behandling.type
}
@Test
fun `hentFagsak skal ikke hente fagsak for barnetrygd når det ikke finnes`() {
val eksternFagsakId = UUID.randomUUID().toString()
val exception = shouldThrow<RuntimeException> { fagsakService.hentFagsak(Fagsystem.BA, eksternFagsakId) }
exception.message shouldBe "Fagsak finnes ikke for Barnetrygd og $eksternFagsakId"
}
@Test
fun `finnesÅpenTilbakekrevingsbehandling skal returnere false om fagsak ikke finnes`() {
val finnesBehandling = fagsakService.finnesÅpenTilbakekrevingsbehandling(Fagsystem.BA, UUID.randomUUID().toString())
finnesBehandling.finnesÅpenBehandling.shouldBeFalse()
}
@Test
fun `finnesÅpenTilbakekrevingsbehandling skal returnere false om behandling er avsluttet`() {
val eksternFagsakId = UUID.randomUUID().toString()
var behandling = opprettBehandling(Ytelsestype.BARNETRYGD, eksternFagsakId)
behandling = behandlingRepository.findByIdOrThrow(behandling.id)
behandlingRepository.update(behandling.copy(status = Behandlingsstatus.AVSLUTTET))
val finnesBehandling = fagsakService.finnesÅpenTilbakekrevingsbehandling(Fagsystem.BA, eksternFagsakId)
finnesBehandling.finnesÅpenBehandling.shouldBeFalse()
}
@Test
fun `finnesÅpenTilbakekrevingsbehandling skal returnere true om det finnes en åpen behandling`() {
val eksternFagsakId = UUID.randomUUID().toString()
opprettBehandling(Ytelsestype.BARNETRYGD, eksternFagsakId)
val finnesBehandling = fagsakService.finnesÅpenTilbakekrevingsbehandling(Fagsystem.BA, eksternFagsakId)
finnesBehandling.finnesÅpenBehandling.shouldBeTrue()
}
@Test
fun `kanBehandlingOpprettesManuelt skal returnere false når det finnes en åpen tilbakekrevingsbehandling`() {
val eksternFagsakId = UUID.randomUUID().toString()
opprettBehandling(Ytelsestype.BARNETRYGD, eksternFagsakId)
val respons = fagsakService.kanBehandlingOpprettesManuelt(eksternFagsakId, Ytelsestype.BARNETRYGD)
respons.kanBehandlingOpprettes.shouldBeFalse()
respons.kravgrunnlagsreferanse.shouldBeNull()
respons.melding shouldBe "Det finnes allerede en åpen tilbakekrevingsbehandling. Den ligger i saksoversikten."
}
@Test
fun `kanBehandlingOpprettesManuelt skal returnere false når det ikke finnes et frakoblet kravgrunnlag`() {
val respons = fagsakService.kanBehandlingOpprettesManuelt(UUID.randomUUID().toString(), Ytelsestype.BARNETRYGD)
respons.kanBehandlingOpprettes.shouldBeFalse()
respons.kravgrunnlagsreferanse.shouldBeNull()
respons.melding shouldBe "Det finnes ingen feilutbetaling på saken, så du kan ikke opprette tilbakekrevingsbehandling."
}
@Test
fun `kanBehandlingOpprettesManuelt skal returnere false når det allerede finnes en opprettelse request`() {
val mottattXml = Testdata.økonomiXmlMottatt
økonomiXmlMottattRepository.insert(mottattXml)
val properties = Properties()
properties["eksternFagsakId"] = mottattXml.eksternFagsakId
properties["ytelsestype"] = Ytelsestype.BARNETRYGD.kode
properties["eksternId"] = mottattXml.referanse
taskService.save(Task(type = OpprettBehandlingManueltTask.TYPE, properties = properties, payload = ""))
val respons = fagsakService.kanBehandlingOpprettesManuelt(mottattXml.eksternFagsakId, Ytelsestype.BARNETRYGD)
respons.kanBehandlingOpprettes.shouldBeFalse()
respons.kravgrunnlagsreferanse.shouldBeNull()
respons.melding shouldBe "Det finnes allerede en forespørsel om å opprette tilbakekrevingsbehandling. " +
"Behandlingen vil snart bli tilgjengelig i saksoversikten. Dersom den ikke dukker opp, " +
"ta kontakt med brukerstøtte for å rapportere feilen."
}
@Test
fun `kanBehandlingOpprettesManuelt skal returnere true når det finnes et frakoblet grunnlag`() {
val mottattXml = Testdata.økonomiXmlMottatt
økonomiXmlMottattRepository.insert(mottattXml)
val respons = fagsakService.kanBehandlingOpprettesManuelt(mottattXml.eksternFagsakId, Ytelsestype.BARNETRYGD)
respons.kanBehandlingOpprettes.shouldBeTrue()
respons.kravgrunnlagsreferanse shouldBe mottattXml.referanse
respons.melding shouldBe "Det er mulig å opprette behandling manuelt."
}
@Nested
inner class HentVedtakForFagsak {
@Test
internal fun `skal returnere tom liste hvis det ikke finnes noen vedtak for fagsak`() {
assertThat(fagsakService.hentVedtakForFagsak(Fagsystem.EF, UUID.randomUUID().toString()))
.isEmpty()
}
}
private fun opprettBehandling(
ytelsestype: Ytelsestype,
eksternFagsakId: String,
personIdent: String = "32132132111",
institusjon: Institusjon? = null,
): Behandling {
val fagsak =
Fagsak(
eksternFagsakId = eksternFagsakId,
bruker = Bruker(personIdent, Språkkode.NB),
ytelsestype = ytelsestype,
fagsystem = FagsystemUtil.hentFagsystemFraYtelsestype(ytelsestype),
institusjon = institusjon,
)
fagsakRepository.insert(fagsak)
val behandling =
Behandling(
fagsakId = fagsak.id,
type = Behandlingstype.TILBAKEKREVING,
ansvarligSaksbehandler = Constants.BRUKER_ID_VEDTAKSLØSNINGEN,
behandlendeEnhet = "8020",
behandlendeEnhetsNavn = "Oslo",
manueltOpprettet = false,
begrunnelseForTilbakekreving = null,
)
behandlingRepository.insert(behandling)
return behandling
}
}
| 7
|
Java
|
16
| 26
|
1777aafb22c6fc7c1bc7db96c86b6ea70e38a36e
| 13,851
|
EMB
|
Apache License 2.0
|
app/src/main/java/com/ctech/eaty/ui/home/viewmodel/HorizontalAdsItemViewModel.kt
|
dbof10
| 116,687,959
| false
| null |
package com.ctech.eaty.ui.home.viewmodel
data class HorizontalAdsItemViewModel(val id: Int, val adId: String)
| 2
| null |
11
| 49
|
2e3445debaedfea03f9b44ab62744046fe07f1cc
| 110
|
hunt-android
|
Apache License 2.0
|
CustomUiSubtitleViewKotlin/src/main/java/com/bitmovin/player/samples/custom/ui/subtitleview/MainActivity.kt
|
bitmovin
| 84,928,314
| false
| null |
package com.bitmovin.player.samples.custom.ui.subtitleview
import android.os.Bundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.bitmovin.player.PlayerView
import com.bitmovin.player.SubtitleView
import com.bitmovin.player.api.Player
import com.bitmovin.player.api.PlayerConfig
import com.bitmovin.player.api.source.SourceConfig
import com.bitmovin.player.api.source.SourceType
import com.bitmovin.player.api.ui.StyleConfig
import com.bitmovin.player.samples.custom.ui.subtitleview.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var player: Player
private lateinit var playerView: PlayerView
private lateinit var subtitleView: SubtitleView
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Create new StyleConfig
val styleConfig = StyleConfig()
// Disable default Bitmovin UI
styleConfig.isUiEnabled = false
// Creating a new PlayerConfig
// Assign created StyleConfig to the PlayerConfig
val playerConfig = PlayerConfig(styleConfig = styleConfig)
// Creating a PlayerView and get it's Player instance.
playerView = PlayerView(this, Player.create(this, playerConfig)).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
player = playerView.player!!
player.load(SourceConfig("https://bitmovin-a.akamaihd.net/content/sintel/sintel.mpd", SourceType.Dash))
// Creating a SubtitleView and assign the current player instance.
subtitleView = SubtitleView(this)
subtitleView.setPlayer(player)
// Setup minimalistic controls for the player
binding.playerControls.setPlayer(player)
// Add the SubtitleView to the layout
binding.playerContainer.addView(subtitleView)
// Add the PlayerView to the layout as first position (so it is the behind the SubtitleView)
binding.playerContainer.addView(playerView, 0)
}
override fun onStart() {
super.onStart()
playerView.onStart()
}
override fun onResume() {
super.onResume()
playerView.onResume()
}
override fun onPause() {
playerView.onPause()
super.onPause()
}
override fun onStop() {
playerView.onStop()
super.onStop()
}
override fun onDestroy() {
playerView.onDestroy()
super.onDestroy()
}
}
| 0
| null |
37
| 54
|
be08c4474ad2dccc33c084092fb5e19c3d302b21
| 2,722
|
bitmovin-player-android-samples
|
Lucent Public License Version 1.0
|
demo/src/main/kotlin/xyz/yggdrazil/midgard/math/fortune/Edge.kt
|
ygdrasil-io
| 69,387,299
| false
|
{"CSS": 22156, "HTML": 4434, "JavaScript": 48}
|
package xyz.yggdrazil.midgard.math.fortune
import xyz.yggdrazil.midgard.math.geometry.Point
import xyz.yggdrazil.midgard.math.geometry.Rectangle
import java.util.*
/**
* The line segment connecting the two Sites is part of the Delaunay
* triangulation; the line segment connecting the two Vertices is part of the
* Voronoi diagram
* @author ashaw
*/
class Edge private constructor() {
// the equation of the edge: ax + by = c
var a: Double = 0.toDouble()
var b: Double = 0.toDouble()
var c: Double = 0.toDouble()
// the two Voronoi vertices that the edge connects
// (if one of them is null, the edge extends to infinity)
var leftVertex: Vertex? = null
private set
var rightVertex: Vertex? = null
private set
// Once clipVertices() is called, this Dictionary will hold two Points
// representing the clipped coordinates of the left and right ends...
var clippedEnds: HashMap<LR, Point>? = null
private set
// the two input Sites for which this Edge is a bisector:
private var sites: HashMap<LR, Site>? = null
// unless the entire Edge is outside the bounds.
// In that case visible will be false:
val visible: Boolean
get() = clippedEnds != null
var leftSite: Site
get() = sites!![LR.LEFT]!!
set(s) {
sites!!.put(LR.LEFT, s)
}
var rightSite: Site
get() = sites!![LR.RIGHT]!!
set(s) {
sites!!.put(LR.RIGHT, s)
}
private val edgeIndex: Int
fun delaunayLine(): LineSegment {
// draw a line connecting the input Sites for which the edge is a bisector:
return LineSegment(leftSite.coord, rightSite.coord)
}
fun voronoiEdge(): LineSegment? {
if (!visible) {
return null
}
return LineSegment(clippedEnds!![LR.LEFT]!!,
clippedEnds!![LR.RIGHT]!!)
}
fun setVertex(leftRight: LR, v: Vertex) {
if (leftRight == LR.LEFT) {
leftVertex = v
} else {
rightVertex = v
}
}
val isPartOfConvexHull: Boolean
get() = leftVertex == null || rightVertex == null
fun sitesDistance(): Double {
return Point.distance(leftSite.coord, rightSite.coord)
}
fun site(leftRight: LR): Site {
return sites!![leftRight]!!
}
init {
edgeIndex = nedges++
init()
}
private fun init() {
sites = HashMap<LR, Site>()
}
override fun toString(): String {
return "Edge $edgeIndex; sites ${sites!![LR.LEFT]}, ${sites!![LR.RIGHT]}; endVertices ${leftVertex?.vertexIndex}, ${rightVertex?.vertexIndex}::"
}
/**
* Set clippedVertices to contain the two ends of the portion of the
* Voronoi edge that is visible within the bounds. If no part of the Edge
* falls within the bounds, leave clippedVertices null.
* @param bounds
*/
fun clipVertices(bounds: Rectangle) {
val xmin = bounds.x
val ymin = bounds.y
val xmax = bounds.right
val ymax = bounds.bottom
val vertex0: Vertex?
val vertex1: Vertex?
var x0: Double
var x1: Double
var y0: Double
var y1: Double
if (a == 1.0 && b >= 0.0) {
vertex0 = rightVertex
vertex1 = leftVertex
} else {
vertex0 = leftVertex
vertex1 = rightVertex
}
if (a == 1.0) {
y0 = ymin
if (vertex0 != null && vertex0.y > ymin) {
y0 = vertex0.y
}
if (y0 > ymax) {
return
}
x0 = c - b * y0
y1 = ymax
if (vertex1 != null && vertex1.y < ymax) {
y1 = vertex1.y
}
if (y1 < ymin) {
return
}
x1 = c - b * y1
if (x0 > xmax && x1 > xmax || x0 < xmin && x1 < xmin) {
return
}
if (x0 > xmax) {
x0 = xmax
y0 = (c - x0) / b
} else if (x0 < xmin) {
x0 = xmin
y0 = (c - x0) / b
}
if (x1 > xmax) {
x1 = xmax
y1 = (c - x1) / b
} else if (x1 < xmin) {
x1 = xmin
y1 = (c - x1) / b
}
} else {
x0 = xmin
if (vertex0 != null && vertex0.x > xmin) {
x0 = vertex0.x
}
if (x0 > xmax) {
return
}
y0 = c - a * x0
x1 = xmax
if (vertex1 != null && vertex1.x < xmax) {
x1 = vertex1.x
}
if (x1 < xmin) {
return
}
y1 = c - a * x1
if (y0 > ymax && y1 > ymax || y0 < ymin && y1 < ymin) {
return
}
if (y0 > ymax) {
y0 = ymax
x0 = (c - y0) / a
} else if (y0 < ymin) {
y0 = ymin
x0 = (c - y0) / a
}
if (y1 > ymax) {
y1 = ymax
x1 = (c - y1) / a
} else if (y1 < ymin) {
y1 = ymin
x1 = (c - y1) / a
}
}
clippedEnds = HashMap<LR, Point>()
if (vertex0 == leftVertex) {
clippedEnds!!.put(LR.LEFT, Point(x0, y0))
clippedEnds!!.put(LR.RIGHT, Point(x1, y1))
} else {
clippedEnds!!.put(LR.RIGHT, Point(x0, y0))
clippedEnds!!.put(LR.LEFT, Point(x1, y1))
}
}
companion object {
private var nedges = 0
val DELETED = Edge()
/**
* This is the only way to create a new Edge
* @param site0
* *
* @param site1
* *
* @return
*/
fun createBisectingEdge(site0: Site, site1: Site): Edge {
val dx: Double
val dy: Double
val absdx: Double
val absdy: Double
val a: Double
val b: Double
var c: Double
dx = site1._x - site0._x
dy = site1._y - site0._y
absdx = if (dx > 0) dx else -dx
absdy = if (dy > 0) dy else -dy
c = site0._x * dx + site0._y * dy + (dx * dx + dy * dy) * 0.5
if (absdx > absdy) {
a = 1.0
b = dy / dx
c /= dx
} else {
b = 1.0
a = dx / dy
c /= dy
}
val edge = Edge()
edge.leftSite = site0
edge.rightSite = site1
site0.addEdge(edge)
site1.addEdge(edge)
edge.leftVertex = null
edge.rightVertex = null
edge.a = a
edge.b = b
edge.c = c
return edge
}
fun compareSitesDistances_MAX(edge0: Edge, edge1: Edge): Double {
val length0 = edge0.sitesDistance()
val length1 = edge1.sitesDistance()
if (length0 < length1) {
return 1.0
}
if (length0 > length1) {
return -1.0
}
return 0.0
}
fun compareSitesDistances(edge0: Edge, edge1: Edge): Double {
return -compareSitesDistances_MAX(edge0, edge1)
}
}
}
| 0
|
CSS
|
0
| 0
|
a6fc81ccdcd08a3682fe462ca1123991fe1ff664
| 7,545
|
World-generator
|
MIT License
|
app/src/androidTest/java/vtsen/hashnode/dev/androidnews/ComposeTest.kt
|
vinchamp77
| 455,775,581
| false
|
{"Kotlin": 172657}
|
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vtsen.hashnode.dev.androidnews
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import org.junit.Rule
import org.junit.Test
import vtsen.hashnode.dev.androidnews.ui.main.MainActivity
class ComposeTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun bottomNavigationNames_areValid() {
var text = composeTestRule.activity.getString(R.string.home)
composeTestRule.onNodeWithText(text).assertExists()
text = composeTestRule.activity.getString(R.string.unread_articles)
composeTestRule.onNodeWithText(text).assertExists()
text = composeTestRule.activity.getString(R.string.bookmarks)
composeTestRule.onNodeWithText(text).assertExists()
}
@Test
fun clickBookmarks_clearBookmarks_showsNoArticles() {
/* This test is not done yet, work in progress
var text = composeTestRule.activity.getString(R.string.bookmarks)
composeTestRule.onNodeWithText(text).performClick()
*/
}
}
| 18
|
Kotlin
|
8
| 62
|
992c997733a3495bfa09977c6f6329e77b415e5d
| 1,677
|
AndroidNews
|
Apache License 2.0
|
saved-sites/saved-sites-impl/src/main/java/com/duckduckgo/savedsites/impl/bookmarks/BookmarksQueryListener.kt
|
duckduckgo
| 78,869,127
| false
| null |
/*
* Copyright (c) 2023 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.savedsites.impl.bookmarks
import androidx.lifecycle.viewModelScope
import com.duckduckgo.common.utils.ConflatedJob
import com.duckduckgo.savedsites.api.models.SavedSite.Favorite
import com.duckduckgo.savedsites.impl.bookmarks.BookmarksAdapter.BookmarkFolderItem
import com.duckduckgo.savedsites.impl.bookmarks.BookmarksAdapter.BookmarkItem
import com.duckduckgo.savedsites.impl.bookmarks.BookmarksAdapter.BookmarksItemTypes
import java.util.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class BookmarksQueryListener(
private val viewModel: BookmarksViewModel,
private val bookmarksAdapter: BookmarksAdapter,
) {
private var searchJob = ConflatedJob()
fun onQueryTextChange(newText: String) {
searchJob += viewModel.viewModelScope.launch {
delay(DEBOUNCE_PERIOD)
viewModel.onSearchQueryUpdated(newText)
val favorites = viewModel.viewState.value?.favorites
viewModel.viewState.value?.bookmarkItems?.let { bookmarks ->
val filteredBookmarks = filterBookmarks(newText, bookmarks, favorites)
bookmarksAdapter.setItems(filteredBookmarks, false, true)
}
}
}
fun cancelSearch() {
searchJob.cancel()
}
private fun filterBookmarks(
query: String,
bookmarks: List<BookmarksItemTypes>,
favorites: List<Favorite>?,
): List<BookmarksItemTypes> {
val lowercaseQuery = query.lowercase(Locale.getDefault())
return bookmarks.filter {
when (it) {
is BookmarkItem -> {
val lowercaseTitle = it.bookmark.title.lowercase(Locale.getDefault())
lowercaseTitle.contains(lowercaseQuery) || it.bookmark.url.contains(lowercaseQuery)
}
is BookmarkFolderItem -> {
val lowercaseTitle = it.bookmarkFolder.name.lowercase(Locale.getDefault())
lowercaseTitle.contains(lowercaseQuery)
}
else -> false
}
}.map {
when (it) {
is BookmarkItem -> {
val isFavorite = favorites?.any { favorite -> favorite.id == it.bookmark.id } ?: false
BookmarkItem(it.bookmark.copy(isFavorite = isFavorite))
}
is BookmarkFolderItem -> it
else -> throw IllegalStateException("Unknown bookmarks item type")
}
}
}
companion object {
private const val DEBOUNCE_PERIOD = 400L
}
}
| 71
| null |
901
| 3,823
|
6415f0f087a11a51c0a0f15faad5cce9c790417c
| 3,206
|
Android
|
Apache License 2.0
|
app/src/main/java/com/stfalcon/new_uaroads_android/features/tracks/service/TracksServiceSubComponent.kt
|
stfalcon-studio
| 49,490,060
| false
| null |
/*
* Copyright (c) 2017 stfalcon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stfalcon.new_uaroads_android.features.places
import dagger.Subcomponent
import dagger.android.AndroidInjector
/*
* Created by <NAME> on 4/5/17.
*/
@Subcomponent(modules = arrayOf(LocationChooserModule::class))
interface LocationChooserSubComponent : AndroidInjector<LocationChooserActivity> {
@Subcomponent.Builder
abstract class Builder : AndroidInjector.Builder<LocationChooserActivity>()
}
| 1
| null |
6
| 24
|
1332f62043a91206f0c6fdbade6ac31e6864b8cc
| 1,048
|
uaroads_android
|
Apache License 2.0
|
pager/src/sharedTest/kotlin/com/google/accompanist/pager/PagerTest.kt
|
jianku
| 398,699,472
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.pager
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.assertIsNotSelected
import androidx.compose.ui.test.assertIsSelectable
import androidx.compose.ui.test.assertIsSelected
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onParent
import androidx.compose.ui.test.performScrollTo
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.withContext
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
private const val LongSwipeDistance = 0.95f
private const val MediumSwipeDistance = 0.8f
private const val ShortSwipeDistance = 0.45f
private const val FastVelocity = 4000f
private const val MediumVelocity = 1500f
private const val SlowVelocity = 300f
@OptIn(ExperimentalPagerApi::class) // Pager is currently experimental
abstract class PagerTest {
protected abstract val offscreenLimit: Int
protected abstract val infiniteLoop: Boolean
@get:Rule
val composeTestRule = createComposeRule()
/**
* This is a workaround for https://issuetracker.google.com/issues/179492185.
* Ideally we would have a way to get the applier scope from the rule
*/
protected lateinit var applierScope: CoroutineScope
@Test
fun layout() {
val pagerState = setPagerContent(pageCount = 10)
assertPagerLayout(0, pagerState.pageCount)
}
@Test
fun swipe() {
val pagerState = setPagerContent(pageCount = 10)
if (infiniteLoop) {
// First test swiping towards end, from 0 to -1
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = LongSwipeDistance,
velocity = MediumVelocity,
)
// ...and assert that we now laid out from page 9
assertPagerLayout(9, pagerState.pageCount)
// Now swipe towards start, from page 9 to page 0
composeTestRule.onNodeWithTag("9")
.swipeAcrossCenter(
distancePercentage = -LongSwipeDistance,
velocity = MediumVelocity,
)
// ...and assert that we now laid out from page 0
assertPagerLayout(0, pagerState.pageCount)
} else {
// First test swiping towards end, from 0 to -1, which should no-op
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = LongSwipeDistance,
velocity = MediumVelocity,
)
// ...and assert that nothing happened
assertPagerLayout(0, pagerState.pageCount)
// Now swipe towards start, from page 0 to page 1
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = -LongSwipeDistance,
velocity = MediumVelocity,
)
// ...and assert that we now laid out from page 1
assertPagerLayout(1, pagerState.pageCount)
}
}
@Test
fun swipeToEndAndBack() {
val pagerState = setPagerContent(pageCount = 4)
// Now swipe towards start, from page 0 to page 1 and assert the layout
composeTestRule.onNodeWithTag("0").swipeAcrossCenter(-LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(1)
assertPagerLayout(1, pagerState.pageCount)
// Repeat for 1 -> 2
composeTestRule.onNodeWithTag("1").swipeAcrossCenter(-LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(2)
assertPagerLayout(2, pagerState.pageCount)
// Repeat for 2 -> 3
composeTestRule.onNodeWithTag("2").swipeAcrossCenter(-LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(3)
assertPagerLayout(3, pagerState.pageCount)
if (infiniteLoop) {
// Swipe past the last item to first item.
composeTestRule.onNodeWithTag("3").swipeAcrossCenter(-LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(0)
assertPagerLayout(0, pagerState.pageCount)
// Swipe back to last item.
composeTestRule.onNodeWithTag("0").swipeAcrossCenter(LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(3)
assertPagerLayout(3, pagerState.pageCount)
} else {
// Swipe past the last item. We shouldn't move
composeTestRule.onNodeWithTag("3").swipeAcrossCenter(-LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(3)
assertPagerLayout(3, pagerState.pageCount)
}
// Swipe back from 3 -> 2
composeTestRule.onNodeWithTag("3").swipeAcrossCenter(LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(2)
assertPagerLayout(2, pagerState.pageCount)
// Swipe back from 2 -> 1
composeTestRule.onNodeWithTag("2").swipeAcrossCenter(LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(1)
assertPagerLayout(1, pagerState.pageCount)
// Swipe back from 1 -> 0
composeTestRule.onNodeWithTag("1").swipeAcrossCenter(LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(0)
assertPagerLayout(0, pagerState.pageCount)
if (infiniteLoop) {
// Swipe past the first item to last item.
composeTestRule.onNodeWithTag("0").swipeAcrossCenter(LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(3)
assertPagerLayout(3, pagerState.pageCount)
// Swipe back to first item.
composeTestRule.onNodeWithTag("3").swipeAcrossCenter(-LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(0)
assertPagerLayout(0, pagerState.pageCount)
} else {
// Swipe past the first item. We shouldn't move
composeTestRule.onNodeWithTag("0").swipeAcrossCenter(LongSwipeDistance)
composeTestRule.waitForIdle()
assertThat(pagerState.currentPage).isEqualTo(0)
assertPagerLayout(0, pagerState.pageCount)
}
}
@Test
fun mediumDistance_fastSwipe_toFling() {
val pagerState = setPagerContent(pageCount = 10)
// Now swipe towards start, from page 0 to page 1, over a medium distance of the item width.
// This should trigger a fling()
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = -MediumSwipeDistance,
velocity = FastVelocity,
)
// ...and assert that we now laid out from page 1
assertPagerLayout(1, pagerState.pageCount)
}
@Test
fun mediumDistance_slowSwipe_toSnapForward() {
val pagerState = setPagerContent(pageCount = 10)
// Now swipe towards start, from page 0 to page 1, over a medium distance of the item width.
// This should trigger a spring to position 1
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = -MediumSwipeDistance,
velocity = SlowVelocity,
)
// ...and assert that we now laid out from page 1
assertPagerLayout(1, pagerState.pageCount)
}
@Test
fun shortDistance_fastSwipe_toFling() {
val pagerState = setPagerContent(pageCount = 10)
// Now swipe towards start, from page 0 to page 1, over a short distance of the item width.
// This should trigger a fling to page 1
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = -ShortSwipeDistance,
velocity = FastVelocity,
)
// ...and assert that we now laid out from page 1
assertPagerLayout(1, pagerState.pageCount)
}
@Test
fun shortDistance_slowSwipe_toSnapBack() {
val pagerState = setPagerContent(pageCount = 10)
// Now swipe towards start, from page 0 to page 1, over a short distance of the item width.
// This should trigger a spring back to the original position
composeTestRule.onNodeWithTag("0")
.swipeAcrossCenter(
distancePercentage = -ShortSwipeDistance,
velocity = SlowVelocity,
)
// ...and assert that we 'sprang back' to page 0
assertPagerLayout(0, pagerState.pageCount)
}
@Test
fun scrollToPage() = suspendTest {
val pagerState = setPagerContent(pageCount = 10)
pagerState.scrollToPage(3)
assertThat(pagerState.currentPage).isEqualTo(3)
assertPagerLayout(3, pagerState.pageCount)
pagerState.scrollToPage(0)
assertThat(pagerState.currentPage).isEqualTo(0)
assertPagerLayout(0, pagerState.pageCount)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun animateScrollToPage() = suspendTest {
val pagerState = setPagerContent(pageCount = 10)
withContext(applierScope.coroutineContext) {
pagerState.animateScrollToPage(3)
}
composeTestRule.awaitIdle()
assertThat(pagerState.currentPage).isEqualTo(3)
assertPagerLayout(3, pagerState.pageCount)
withContext(applierScope.coroutineContext) {
pagerState.animateScrollToPage(0)
}
composeTestRule.awaitIdle()
assertThat(pagerState.currentPage).isEqualTo(0)
assertPagerLayout(0, pagerState.pageCount)
}
@Test
@Ignore("Currently broken") // TODO: Will fix this once we move to Modifier.scrollable()
fun a11yScroll() {
val pagerState = setPagerContent(pageCount = 10)
// Perform a scroll to item 1
composeTestRule.onNodeWithTag("1").performScrollTo()
// ...and assert that we scrolled to page 1
assertPagerLayout(1, pagerState.pageCount)
}
/**
* Swipe across the center of the node. The major axis of the swipe is defined by the
* overriding test.
*
* @param velocity Target end velocity for the swipe.
* @param distancePercentage The swipe distance in percentage of the node's size.
* Negative numbers mean swipe towards the start, positive towards the end.
*/
abstract fun SemanticsNodeInteraction.swipeAcrossCenter(
distancePercentage: Float,
velocity: Float = MediumVelocity
): SemanticsNodeInteraction
// TODO: add test for state restoration?
private fun assertPagerLayout(currentPage: Int, pageCount: Int) {
// The pages which are expected to be laid out, using the given current page,
// offscreenLimit and page limit
val pageRange = (currentPage - offscreenLimit)..(currentPage + offscreenLimit)
val expectedLaidOutPages = if (infiniteLoop) {
pageRange.toList()
} else {
pageRange.filter { it in 0 until pageCount }.toList()
}
// Go through all of the pages, and assert the expected layout state
(0 until pageCount).forEach { _page ->
val page = expectedLaidOutPages.find { it == _page }
if (page != null) {
// If this page is expected to be laid out, assert that it exists and is
// laid out in the correct position
composeTestRule.onNodeWithTag(page.toString())
.assertExists()
.assertLaidOutItemPosition(page, currentPage)
.onParent()
.assertIsSelectable()
.assertWhen(page == currentPage) { assertIsSelected() }
.assertWhen(page != currentPage) { assertIsNotSelected() }
} else {
// If this page is not expected to be laid out, assert that it doesn't exist
composeTestRule.onNodeWithTag(_page.toString()).assertDoesNotExist()
}
}
}
protected abstract fun SemanticsNodeInteraction.assertLaidOutItemPosition(
page: Int,
currentPage: Int,
): SemanticsNodeInteraction
protected abstract fun setPagerContent(pageCount: Int): PagerState
}
| 0
| null |
0
| 2
|
4e24003060bbd65f90d2a86641c800d76a35bde2
| 13,481
|
accompanist
|
Apache License 2.0
|
jps-plugin/testData/incremental/withJava/other/conflictingPlatformDeclarations/fun1.kt
|
JakeWharton
| 99,388,807
| false
| null |
@file:JvmName("Utils")
@file:JvmMultifileClass
package test
fun function(list: List<Any>) {
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 95
|
kotlin
|
Apache License 2.0
|
transformationlayout/src/main/kotlin/com/skydoves/transformationlayout/TransformationActivity.kt
|
skydoves
| 243,753,387
| false
|
{"Kotlin": 85324}
|
/*
* Designed and developed by 2020 weltech (weltech)
*
* 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.weltech.transformationlayout
import android.os.Bundle
import androidx.activity.ComponentActivity
import com.weltech.transformationlayout.TransformationCompat.activityTransitionName
/** An abstract activity extending [ComponentActivity] with registering transformation automatically. */
public abstract class TransformationActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
onTransformationEndContainer(intent.getParcelableExtra(activityTransitionName))
super.onCreate(savedInstanceState)
}
}
| 5
|
Kotlin
|
187
| 2,185
|
6383bcba9363a8b869d5e264133272c6ab0b4c3e
| 1,168
|
TransformationLayout
|
Apache License 2.0
|
transformationlayout/src/main/kotlin/com/skydoves/transformationlayout/TransformationActivity.kt
|
skydoves
| 243,753,387
| false
|
{"Kotlin": 85324}
|
/*
* Designed and developed by 2020 weltech (weltech)
*
* 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.weltech.transformationlayout
import android.os.Bundle
import androidx.activity.ComponentActivity
import com.weltech.transformationlayout.TransformationCompat.activityTransitionName
/** An abstract activity extending [ComponentActivity] with registering transformation automatically. */
public abstract class TransformationActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
onTransformationEndContainer(intent.getParcelableExtra(activityTransitionName))
super.onCreate(savedInstanceState)
}
}
| 5
|
Kotlin
|
187
| 2,185
|
6383bcba9363a8b869d5e264133272c6ab0b4c3e
| 1,168
|
TransformationLayout
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ef/sak/vedtak/historikk/AndelHistorikkUtil.kt
|
navikt
| 206,805,010
| false
|
{"Kotlin": 3869315, "Gherkin": 163948, "Dockerfile": 180}
|
package no.nav.familie.ef.sak.vedtak.historikk
import no.nav.familie.ef.sak.vedtak.domain.AktivitetType
import no.nav.familie.ef.sak.vedtak.domain.PeriodetypeBarnetilsyn
import no.nav.familie.ef.sak.vedtak.domain.VedtaksperiodeType
import no.nav.familie.kontrakter.felles.ef.StønadType
object AndelHistorikkUtil {
fun List<AndelHistorikkDto>.slåSammen(harSammeVerdi: (AndelHistorikkDto, AndelHistorikkDto) -> Boolean): List<AndelHistorikkDto> {
return this.fold(mutableListOf()) { acc, entry ->
val last = acc.lastOrNull()
if (last != null && harSammeVerdi(last, entry)) {
acc.removeLast()
acc.add(last.copy(andel = last.andel.copy(periode = last.andel.periode.copy(tom = entry.andel.periode.tom))))
} else {
acc.add(entry)
}
acc
}
}
fun sammenhengende(
first: AndelHistorikkDto,
second: AndelHistorikkDto,
) =
first.andel.periode.påfølgesAv(second.andel.periode)
fun periodeTypeOvergangsstønad(
stønadstype: StønadType,
vedtaksperiode: Vedtakshistorikkperiode,
): VedtaksperiodeType? =
when {
stønadstype != StønadType.OVERGANGSSTØNAD -> null
vedtaksperiode is VedtakshistorikkperiodeOvergangsstønad -> vedtaksperiode.periodeType
vedtaksperiode is Sanksjonsperiode -> VedtaksperiodeType.SANKSJON
vedtaksperiode is Opphørsperiode -> null
else -> error("Kan ikke mappe ${vedtaksperiode.javaClass.simpleName}")
}
fun periodeTypeBarnetilsyn(
stønadstype: StønadType,
vedtaksperiode: Vedtakshistorikkperiode,
): PeriodetypeBarnetilsyn? =
when {
stønadstype != StønadType.BARNETILSYN -> null
vedtaksperiode is VedtakshistorikkperiodeBarnetilsyn -> vedtaksperiode.periodetype
vedtaksperiode is Sanksjonsperiode -> PeriodetypeBarnetilsyn.SANKSJON_1_MND
vedtaksperiode is Opphørsperiode -> null
else -> error("Kan ikke mappe ${vedtaksperiode.javaClass.simpleName}")
}
fun aktivitetOvergangsstønad(
stønadstype: StønadType,
vedtaksperiode: Vedtakshistorikkperiode,
): AktivitetType? =
when {
stønadstype != StønadType.OVERGANGSSTØNAD -> null
vedtaksperiode is VedtakshistorikkperiodeOvergangsstønad -> vedtaksperiode.aktivitet
vedtaksperiode is Sanksjonsperiode -> AktivitetType.IKKE_AKTIVITETSPLIKT
vedtaksperiode is Opphørsperiode -> AktivitetType.IKKE_AKTIVITETSPLIKT
else -> error("Kan ikke mappe ${vedtaksperiode.javaClass.simpleName}")
}
}
data class HistorikkKonfigurasjon(
val brukIkkeVedtatteSatser: Boolean,
)
| 7
|
Kotlin
|
2
| 0
|
d1d8385ead500c4d24739b970940af854fa5fe2c
| 2,786
|
familie-ef-sak
|
MIT License
|
src/main/kotlin/org/abimon/eternalJukebox/data/database/JDBCDatabase.kt
|
UnderMybrella
| 83,624,855
| false
|
{"HTML": 283980, "Kotlin": 199402, "JavaScript": 45048, "CSS": 8097, "Dockerfile": 1483, "Shell": 644, "Ruby": 188, "Batchfile": 78}
|
package org.abimon.eternalJukebox.data.database
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
object JDBCDatabase: HikariDatabase() {
override val ds: HikariDataSource
init {
Class.forName("com.mysql.jdbc.Driver")
.getDeclaredConstructor()
.newInstance()
val config = HikariConfig("hikari.properties")
config.jdbcUrl = databaseOptions["jdbcUrl"]?.toString() ?: throw IllegalStateException("jdbcUrl was not provided!")
config.username = databaseOptions["username"]?.toString()
config.password = databaseOptions["password"]?.toString()
config.initializationFailTimeout = 0
val cloudSqlInstance = databaseOptions["cloudSqlInstance"]?.toString()
if(cloudSqlInstance != null) {
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory")
config.addDataSourceProperty("cloudSqlInstance", cloudSqlInstance)
}
// config.addDataSourceProperty("useServerPrepStmts", databaseOptions["userServerPrepStmts"]?.toString() ?: "true")
// config.addDataSourceProperty("cachePrepStmts", databaseOptions["cachePrepStmts"]?.toString() ?: "true")
// config.addDataSourceProperty("prepStmtCacheSize", databaseOptions["prepStmtCacheSize"]?.toString() ?: "250")
// config.addDataSourceProperty("prepStmtCacheSqlLimit", databaseOptions["prepStmtCacheSqlLimit"]?.toString() ?: "2048")
// config.addDataSourceProperty("useLocalSessionState", "true")
// config.addDataSourceProperty("rewriteBatchedStatements", "true")
// config.addDataSourceProperty("cacheResultSetMetadata", "true")
// config.addDataSourceProperty("cacheServerConfiguration", "true")
// config.addDataSourceProperty("elideSetAutoCommits", "true")
// config.addDataSourceProperty("maintainTimeStats", "false")
ds = HikariDataSource(config)
initialise()
}
}
| 109
|
HTML
|
147
| 787
|
f4ef7a2014154467b7ed37b3caa9a47e7a4bf011
| 1,987
|
EternalJukebox
|
MIT License
|
openai-core/src/commonMain/kotlin/com.aallam.openai.api/moderation/ModerationRequest.kt
|
Aallam
| 345,180,734
| false
| null |
package com.aallam.openai.api.moderation
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Request to classify if text violates OpenAI's Content Policy.
*/
@Serializable
public class ModerationRequest(
/**
* The input text to classify.
*/
@SerialName("input") public val input: List<String>,
/**
* Moderation model.
* Defaults to [ModerationModel.Latest].
*/
@SerialName("model") public val model: ModerationModel? = null,
) {
/**
* Convenience constructor with [input] as [String].
*/
public constructor(input: String, model: ModerationModel? = null) : this(listOf(input), model)
}
| 3
|
Kotlin
|
5
| 102
|
41e1406464748b9fe800d47fa10ab967f3b2b4e8
| 686
|
openai-kotlin
|
MIT License
|
openai-core/src/commonMain/kotlin/com.aallam.openai.api/moderation/ModerationRequest.kt
|
Aallam
| 345,180,734
| false
| null |
package com.aallam.openai.api.moderation
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Request to classify if text violates OpenAI's Content Policy.
*/
@Serializable
public class ModerationRequest(
/**
* The input text to classify.
*/
@SerialName("input") public val input: List<String>,
/**
* Moderation model.
* Defaults to [ModerationModel.Latest].
*/
@SerialName("model") public val model: ModerationModel? = null,
) {
/**
* Convenience constructor with [input] as [String].
*/
public constructor(input: String, model: ModerationModel? = null) : this(listOf(input), model)
}
| 3
|
Kotlin
|
5
| 102
|
41e1406464748b9fe800d47fa10ab967f3b2b4e8
| 686
|
openai-kotlin
|
MIT License
|
feature/stocks/src/main/java/com/roquebuarque/smartstocks/stocks/di/StockModule.kt
|
RBJUR
| 385,636,037
| false
| null |
package com.roquebuarque.smartstocks.stocks.di
import com.google.gson.Gson
import com.roquebuarque.smartstocks.stocks.domain.provider.StockService
import com.tinder.scarlet.Scarlet
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class StockModule {
@Provides
@Singleton
fun provideStockService(scarlet: Scarlet): StockService {
return scarlet.create(service = StockService::class.java)
}
@Provides
@Singleton
fun provideGson(): Gson {
return Gson()
}
}
| 0
|
Kotlin
|
0
| 3
|
09861c8858cd456227be862880c08fa66c6ba6a3
| 670
|
SmartStocks
|
The Unlicense
|
tests/spring-boot/src/test/kotlin/io/github/radeklos/cloudlock/test/springboot/DummyControllerTest.kt
|
radeklos
| 566,824,559
| false
| null |
package io.github.radeklos.cloudlock.test.springboot
import io.kotest.core.spec.style.FunSpec
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
@AutoConfigureMockMvc
@SpringBootTest(classes = [Application::class])
class DummyControllerTest(var mockMvc: MockMvc) : FunSpec({
test("should ping controller") {
mockMvc.get("/dummy")
.andExpect {
status { isOk() }
}
}
})
| 12
|
Kotlin
|
0
| 0
|
785934d9000aa94e06925e17ee4534ace0cc80af
| 620
|
cloudlock
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppschallengesupportinterventionplanapi/entity/ContributoryFactor.kt
|
ministryofjustice
| 797,799,207
| false
|
{"Kotlin": 459135, "Mermaid": 28674, "Shell": 1890, "Dockerfile": 1372}
|
package uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.entity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
import java.time.LocalDateTime
import java.util.UUID
@Entity
@Table(name = "contributory_factor")
data class ContributoryFactor(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val contributoryFactorId: Long = 0,
@Column(unique = true, nullable = false)
val contributoryFactorUuid: UUID = UUID.randomUUID(),
val comment: String? = null,
@Column(nullable = false)
val createdAt: LocalDateTime,
@Column(nullable = false, length = 32)
val createdBy: String,
@Column(nullable = false, length = 255)
val createdByDisplayName: String,
val lastModifiedAt: LocalDateTime? = null,
@Column(length = 32)
val lastModifiedBy: String? = null,
@Column(length = 255)
val lastModifiedByDisplayName: String? = null,
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(
name = "referral_id",
referencedColumnName = "referral_id",
)
val referral: Referral,
@ManyToOne
@JoinColumn(name = "contributory_factor_type_id", insertable = false, updatable = false)
val contributoryFactorType: ReferenceData,
)
| 2
|
Kotlin
|
0
| 0
|
7f16233d45d78d0a9392deca75d5cc8fcb9f23c7
| 1,463
|
hmpps-challenge-support-intervention-plan-api
|
MIT License
|
app/src/main/java/com/softaai/dsa_kotlin/mergesort/MergeSort.kt
|
amoljp19
| 537,774,597
| false
|
{"Kotlin": 139041}
|
package com.softaai.dsa_kotlin.mergesort
/**
* Created by amoljp19 on 11/22/2022.
* softAai Apps.
*/
fun <T : Comparable<T>> List<T>.mergeSort() : List<T>{
if(this.size < 2) return this
val middle = this.size / 2
val left = this.subList(0, middle).mergeSort()
val right = this.subList(middle, this.size).mergeSort()
return merge(left, right)
}
fun<T : Comparable<T>> merge(left : List<T>, right : List<T>) : List<T>{
var leftIndex = 0
var rightIndex = 0
val result = mutableListOf<T>()
while (leftIndex < left.size && rightIndex < right.size){
val leftElement = left[leftIndex]
val rightElement = right[rightIndex]
if(leftElement < rightElement){
result.add(leftElement)
leftIndex++
}else if(leftElement > rightElement){
result.add(rightElement)
rightIndex++
}else{
result.add(leftElement)
leftIndex++
result.add(rightElement)
rightIndex++
}
}
if(leftIndex < left.size){
result.addAll(left.subList(leftIndex, left.size))
}else if(rightIndex < right.size){
result.addAll(right.subList(rightIndex, right.size))
}
return result
}
| 0
|
Kotlin
|
0
| 1
|
3dabfbb1e506bec741aed3aa13607a585b26ac4c
| 1,261
|
DSA_KOTLIN
|
Apache License 2.0
|
gui-app/src/main/kotlin/dev/robocode/tankroyale/gui/extensions/PathExt.kt
|
robocode-dev
| 457,523,927
| false
|
{"Kotlin": 529081, "Java": 419155, "C#": 407446, "SCSS": 1367, "TypeScript": 1071, "Shell": 83}
|
package dev.robocode.tankroyale.gui.extensions
import java.nio.file.Path
object PathExt {
fun Path.getFileExtension(): String? {
val filename = toString()
val lastIndex = filename.lastIndexOf('.')
if (lastIndex == -1) {
return null
}
return filename.substring(lastIndex + 1)
}
}
| 4
|
Kotlin
|
17
| 97
|
a5e74e40b3d7eab271f77202754a133b2af48f25
| 341
|
tank-royale
|
Apache License 2.0
|
library/src/main/java/io/github/toyota32k/bindit/AlphaBinding.kt
|
toyota-m2k
| 643,389,596
| false
|
{"Kotlin": 303845}
|
@file:Suppress("unused")
package io.github.toyota32k.binder
import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
class AlphaBinding(
override val data:LiveData<Float>
) : BaseBinding<Float>(BindingMode.OneWay) {
override fun onDataChanged(v: Float?) {
if(v!=null) {
view?.apply {
alpha = v
}
}
}
companion object {
fun create(owner: LifecycleOwner, view: View, data:LiveData<Float>): AlphaBinding {
return AlphaBinding(data).apply { connect(owner,view) }
}
}
}
fun Binder.alphaBinding(owner: LifecycleOwner, view: View, data:LiveData<Float>): Binder
= add(AlphaBinding.create(owner, view, data))
fun Binder.alphaBinding(view: View, data:LiveData<Float>): Binder
= add(AlphaBinding.create(requireOwner, view, data))
| 0
|
Kotlin
|
0
| 0
|
aafe02366dbca3142fb72c7639c3b647eb16846d
| 879
|
bind-it
|
Apache License 2.0
|
src/main/kotlin/notifications/framework/Platform.kt
|
MarcelBraghetto
| 113,415,227
| false
| null |
package com.aimicor.navcompose.android
/*
MIT License
Copyright (c) 2024 Aimicor Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import androidx.compose.runtime.compositionLocalOf
import androidx.navigation.NavHostController
/**
* Provides an instance of the NavHostController within the scope of the NavHost.
* @see compositionLocalOf
* @see com.aimicor.navcompose.android.NavHost
*/
val LocalNavController =
compositionLocalOf<NavHostController> { error("Local NavHostController not set. Use NavHost that takes NavComposable as start destination") }
| 0
| null |
1
| 3
|
74b1a7064baa4b1af0184c7751c7df697cf6b842
| 1,550
|
AmazonSNSDemo
|
MIT License
|
kcrud-base/src/main/kotlin/kcrud/base/scheduling/listener/JobTriggerListener.kt
|
perracodex
| 682,128,013
| false
| null |
/*
* Copyright (c) 2024-Present <NAME>. All rights reserved.
* This work is licensed under the terms of the MIT license.
* For a copy, see <https://opensource.org/licenses/MIT>
*/
package kcrud.base.scheduler.listeners
import kcrud.base.infrastructure.utils.Tracer
import kcrud.base.scheduler.annotation.JobSchedulerAPI
import kcrud.base.security.service.AuthenticationTokenService
import org.quartz.JobExecutionContext
import org.quartz.Trigger
import org.quartz.Trigger.CompletedExecutionInstruction
import org.quartz.TriggerListener
@JobSchedulerAPI
class KcrudTriggerListener : TriggerListener {
private val tracer = Tracer<AuthenticationTokenService>()
override fun getName() = KcrudTriggerListener::class.simpleName
override fun triggerFired(trigger: Trigger, context: JobExecutionContext) {
tracer.debug(message = "Job scheduler trigger fired: ${trigger.key}")
}
override fun triggerComplete(
trigger: Trigger,
context: JobExecutionContext,
triggerInstructionCode: CompletedExecutionInstruction
) {
tracer.debug(message = "Job scheduler trigger completed: ${trigger.key}")
}
override fun triggerMisfired(trigger: Trigger) {
tracer.debug(message = "Job scheduler trigger misfired: ${trigger.key}")
}
override fun vetoJobExecution(trigger: Trigger, context: JobExecutionContext) = false
}
| 0
| null |
0
| 2
|
1ee4c849845715d7a719e51acded637e6c3a6821
| 1,394
|
Kcrud
|
MIT License
|
shared/src/commonMain/kotlin/com/mod/marveluniverse/domain/utils/flows/CommonMutableStateFlow.kt
|
Moujarkash
| 596,891,616
| false
| null |
package com.mod.marveluniverse.domain.utils.flows
import kotlinx.coroutines.flow.MutableStateFlow
expect class CommonMutableStateFlow<T>(mutableStateFlow: MutableStateFlow<T>): MutableStateFlow<T>
fun <T> MutableStateFlow<T>.toCommonMutableStateFlow() = CommonMutableStateFlow(this)
| 0
|
Kotlin
|
0
| 0
|
7666e686e1395485e9a2f2ed17efa793a679ee2e
| 285
|
Marvel-Universe-
|
MIT License
|
jtransc-utils/src/com/jtransc/injector/Injector.kt
|
jtransc
| 51,313,992
| false
| null |
package com.jtransc.injector
import com.jtransc.annotation.JTranscKeep
import com.jtransc.annotation.JTranscKeepConstructors
import com.jtransc.error.invalidOp
import java.lang.reflect.InvocationTargetException
@Suppress("UNCHECKED_CAST")
class Injector() {
val maps = hashMapOf<Class<*>, () -> Any>(
Injector::class.java to { this@Injector }
)
inline fun <reified T : Any> get(): T = getInstance(T::class.java)
inline fun <reified T : Any> getOrNull(): T? = getInstanceOrNull(T::class.java)
inline fun <reified T : Any> get(default: () -> T): T = if (T::class.java in maps) getInstance(T::class.java) else default()
fun <T : Any> getInstance(clazz: Class<T>): T {
return getInstanceOrNull(clazz)
?: invalidOp("Cannot automap '$clazz' not @Singleton or @Prototype")
}
fun <T : Any> getInstanceOrNull(clazz: Class<T>): T? {
if (clazz !in maps) {
val allAnnotations = getAllAnnotations(clazz)
val isSingleton = allAnnotations.filterIsInstance<Singleton?>().isNotEmpty()
val isPrototype = allAnnotations.filterIsInstance<Prototype?>().isNotEmpty()
if (!isSingleton && !isPrototype) {
return null
}
mapImplementation(clazz, clazz)
}
return this.maps[clazz]!!() as T
}
internal fun <T : Any> createInstance(clazz: Class<T>): T {
val c = clazz.constructors.firstOrNull() ?: invalidOp("No constructors for $clazz")
try {
return c.newInstance(*(c.parameterTypes.map { this.getInstance(it) }).toTypedArray()) as T
} catch (e: InvocationTargetException) {
throw InvocationTargetException(e, "Can't construct class $clazz : $c")
}
}
private fun getAllAnnotations(clazz: Class<*>): List<Annotation> {
return if (clazz.superclass == null) {
clazz.annotations.toList()
} else {
clazz.annotations.toList() + getAllAnnotations(clazz.superclass)
} + clazz.interfaces.flatMap { getAllAnnotations(it) }
}
fun mapImplementation(classInterface: Class<*>, classImpl: Class<*>) {
val allAnnotations = getAllAnnotations(classImpl)
val isSingleton = allAnnotations.filterIsInstance<Singleton?>().isNotEmpty()
var cached: Any? = null
this.maps[classInterface] = {
if (isSingleton) {
if (cached == null) cached = createInstance(classImpl)
cached!!
} else {
createInstance(classImpl)
}
}
}
fun mapInstances(vararg objs: Any) = run { for (obj in objs) mapInstance(obj) }
fun <T : Any> mapInstance(obj: T): T = mapInstance(obj, obj.javaClass)
fun <T : Any> mapInstance(obj: T, type: Class<T>): T = obj.apply { maps[type] = { obj } }
inline fun <reified TInt : Any, reified TImpl : TInt> mapImpl() = mapImplementation(TInt::class.java, TImpl::class.java)
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@JTranscKeepConstructors
annotation class Singleton()
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@JTranscKeepConstructors
annotation class Prototype()
| 59
| null |
66
| 619
|
6f9a2166f128c2ce5fb66f9af46fdbdbcbbe4ba4
| 2,900
|
jtransc
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/navigation/presentation/NavigationScreen.kt
|
FawnRescue
| 727,288,106
| false
|
{"Kotlin": 265110, "Swift": 594}
|
package navigation.presentation
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import dev.icerock.moko.mvvm.compose.getViewModel
import dev.icerock.moko.mvvm.compose.viewModelFactory
import friends.presentation.FriendListScreen
import friends.presentation.FriendListViewModel
import hangar.presentation.HangarScreen
import hangar.presentation.HangarViewModel
import hangar.presentation.discover.DiscoverScreen
import hangar.presentation.discover.DiscoverViewModel
import home.presentation.home.HomeScreen
import home.presentation.home.HomeViewModel
import login.presentation.LoginScreen
import login.presentation.LoginViewModel
import moe.tlaster.precompose.navigation.NavHost
import moe.tlaster.precompose.navigation.Navigator
import moe.tlaster.precompose.navigation.transition.NavTransition
import navigation.presentation.NAV.FLIGHT_DATE_EDITOR
import navigation.presentation.NAV.FLIGHT_PLAN_EDITOR
import navigation.presentation.NAV.FRIENDS
import navigation.presentation.NAV.GROUP
import navigation.presentation.NAV.HANGAR
import navigation.presentation.NAV.HANGAR_DISCOVER
import navigation.presentation.NAV.HOME
import navigation.presentation.NAV.LOGIN
import navigation.presentation.NAV.MISSION_EDITOR
import navigation.presentation.NAV.PILOT
import navigation.presentation.NAV.PLANNING
import navigation.presentation.NAV.PROFILE
import org.koin.compose.koinInject
import pilot.PilotScreen
import pilot.PilotViewModel
import planning.presentation.flightdate_editor.FlightDateEditorScreen
import planning.presentation.flightdate_editor.FlightDateEditorViewModel
import planning.presentation.flightdate_viewer.FlightDateViewerScreen
import planning.presentation.flightdate_viewer.FlightDateViewerViewModel
import planning.presentation.flightplan_editor.FlightPlanEditorScreen
import planning.presentation.flightplan_editor.FlightPlanEditorViewModel
import planning.presentation.mission_editor.MissionEditorScreen
import planning.presentation.mission_editor.MissionEditorViewModel
import planning.presentation.mission_list.MissionListScreen
import planning.presentation.mission_list.MissionListViewModel
import profile.ProfileEditorScreen
import profile.ProfileEditorViewModel
@Composable
fun NavigationScreen(
selectedItem: NAV,
onEvent: (NavigationEvent) -> Unit,
) {
val navigator = koinInject<Navigator>()
Scaffold(bottomBar = {
if (selectedItem.navBar) {
NavigationBar {
NAV.entries.filter { it.navItem }.forEach { item ->
NavigationBarItem(selected = selectedItem == item, onClick = {
onEvent(NavigationEvent.OnNavItemClicked(item))
}, icon = {
item.icon?.let {
Icon(
imageVector = it, contentDescription = item.label
)
}
}, label = { Text(text = item.label) })
}
}
}
}) { innerPadding ->
Box(modifier = Modifier.padding(innerPadding)) {
NavHost(
modifier = Modifier.fillMaxSize(),
navigator = navigator,
navTransition = NavTransition(),
initialRoute = NAV.entries.first().path
) {
NAV.entries.forEach {
when (it) {
HOME -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel =
getViewModel(key = "home-screen", factory = viewModelFactory {
HomeViewModel()
})
val stateHome by viewModel.state.collectAsState()
HomeScreen(
state = stateHome, onEvent = viewModel::onEvent
)
}
FRIENDS -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(
key = "friend-list-screen",
factory = viewModelFactory {
FriendListViewModel()
})
val stateFriend by viewModel.state.collectAsState()
FriendListScreen(
state = stateFriend, onEvent = viewModel::onEvent
)
}
LOGIN -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel =
getViewModel(key = "login-screen", factory = viewModelFactory {
LoginViewModel()
})
val stateLogin by viewModel.state.collectAsState()
LoginScreen(
state = stateLogin, onEvent = viewModel::onEvent
)
}
PLANNING -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(
key = "mission-list-screen",
factory = viewModelFactory {
MissionListViewModel()
})
val stateMissionList by viewModel.state.collectAsState()
MissionListScreen(
state = stateMissionList, onEvent = viewModel::onEvent
)
}
MISSION_EDITOR -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(
key = "mission-editor-screen",
factory = viewModelFactory {
MissionEditorViewModel()
})
val stateMissionEditor by viewModel.state.collectAsState()
MissionEditorScreen(
state = stateMissionEditor, onEvent = viewModel::onEvent
)
}
FLIGHT_PLAN_EDITOR -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(
key = "flight-plan-editor-screen",
factory = viewModelFactory {
FlightPlanEditorViewModel()
})
val stateFlightPlanEditor by viewModel.state.collectAsState()
FlightPlanEditorScreen(
state = stateFlightPlanEditor, onEvent = viewModel::onEvent
)
}
GROUP -> scene(
route = it.path, navTransition = NavTransition()
) {
}
HANGAR -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel =
getViewModel(key = "hangar-screen", factory = viewModelFactory {
HangarViewModel()
})
val stateHangar by viewModel.state.collectAsState()
HangarScreen(
state = stateHangar, onEvent = viewModel::onEvent
)
}
FLIGHT_DATE_EDITOR -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(
key = "flight-date-editor-screen",
factory = viewModelFactory {
FlightDateEditorViewModel()
})
val stateFlightDateEditor by viewModel.state.collectAsState()
FlightDateEditorScreen(
state = stateFlightDateEditor, onEvent = viewModel::onEvent
)
}
PROFILE -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel =
getViewModel(key = "profile-screen", factory = viewModelFactory {
ProfileEditorViewModel()
})
val stateProfile by viewModel.state.collectAsState()
ProfileEditorScreen(
state = stateProfile, onEvent = viewModel::onEvent
)
}
HANGAR_DISCOVER -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(key = "hangar-discover-screen",
factory = viewModelFactory {
DiscoverViewModel()
})
val stateHangarDiscover by viewModel.state.collectAsState()
DiscoverScreen(
state = stateHangarDiscover, onEvent = viewModel::onEvent
)
}
PILOT -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(key = "pilot-screen",
factory = viewModelFactory {
PilotViewModel()
})
val statePilot by viewModel.state.collectAsState()
PilotScreen(
state = statePilot, onEvent = viewModel::onEvent
)
}
NAV.FLIGHT_DATE_VIEWER -> scene(
route = it.path, navTransition = NavTransition()
) {
val viewModel = getViewModel(
key = "flight-date-viewer-screen",
factory = viewModelFactory {
FlightDateViewerViewModel()
})
val stateFlightDateViewer by viewModel.state.collectAsState()
FlightDateViewerScreen(
state = stateFlightDateViewer, onEvent = viewModel::onEvent
)
}
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
617413fdd26e153e23cc8476a31673668fcb7b37
| 12,265
|
frontend
|
MIT License
|
common/src/androidMain/kotlin/com/surrus/common/actual.kt
|
joreilly
| 222,286,745
| false
| null |
package com.surrus.common
import android.content.Context
lateinit var appContext: Context
actual fun getApplicationFilesDirectoryPath(): String =
appContext.filesDir.absolutePath
| 1
|
Kotlin
|
23
| 342
|
a95cf5c3b78157b95da2dd93fcec1e1f144d5c37
| 187
|
BikeShare
|
Apache License 2.0
|
core/common/src/main/kotlin/tachiyomi/core/common/preference/Preference.kt
|
mihonapp
| 743,704,912
| false
| null |
package tachiyomi.core.preference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
interface Preference<T> {
fun key(): String
fun get(): T
fun set(value: T)
fun isSet(): Boolean
fun delete()
fun defaultValue(): T
fun changes(): Flow<T>
fun stateIn(scope: CoroutineScope): StateFlow<T>
companion object {
/**
* A preference that should not be exposed in places like backups without user consent.
*/
fun isPrivate(key: String): Boolean {
return key.startsWith(PRIVATE_PREFIX)
}
fun privateKey(key: String): String {
return "${PRIVATE_PREFIX}$key"
}
/**
* A preference used for internal app state that isn't really a user preference
* and therefore should not be in places like backups.
*/
fun isAppState(key: String): Boolean {
return key.startsWith(APP_STATE_PREFIX)
}
fun appStateKey(key: String): String {
return "${APP_STATE_PREFIX}$key"
}
private const val APP_STATE_PREFIX = "__APP_STATE_"
private const val PRIVATE_PREFIX = "__PRIVATE_"
}
}
inline fun <reified T, R : T> Preference<T>.getAndSet(crossinline block: (T) -> R) = set(
block(get()),
)
operator fun <T> Preference<Set<T>>.plusAssign(item: T) {
set(get() + item)
}
operator fun <T> Preference<Set<T>>.minusAssign(item: T) {
set(get() - item)
}
fun Preference<Boolean>.toggle(): Boolean {
set(!get())
return get()
}
| 280
| null |
447
| 9,867
|
f3a2f566c8a09ab862758ae69b43da2a2cd8f1db
| 1,616
|
mihon
|
Apache License 2.0
|
src/main/kotlin/brreg/Miljø.kt
|
navikt
| 464,402,802
| false
| null |
package brreg
import org.apache.kafka.clients.CommonClientConfigs
import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.config.SslConfigs
import org.apache.kafka.common.serialization.StringSerializer
import java.io.Serializable
object Miljø {
val LAST_NED_ALLE_VIRKSOMHETER = getEnvVar("LAST_NED_ALLE_VIRKSOMHETER", "false")
val ANTALL_DAGER_SIDEN_OPPDATERING = getEnvVar(envVar = "ANTALL_DAGER_SIDEN_OPPDATERING", default = "1")
val BRREG_OPPDATERING_UNDERENHET_URL = getEnvVar(
envVar = "BRREG_OPPDATERING_UNDERENHET_URL",
default = "https://data.brreg.no/enhetsregisteret/api/oppdateringer/underenheter"
)
val BRREG_UNDERENHET_URL =
getEnvVar(envVar = "BRREG_UNDERENHET_URL", default = "https://data.brreg.no/enhetsregisteret/api/underenheter")
val FULL_EKSPORT_URL =
getEnvVar("FULL_EKSPORT_URL", default = "https://data.brreg.no/enhetsregisteret/api/underenheter/lastned")
val KAFKA_BROKERS = getEnvVar(envVar = "KAFKA_BROKERS", default = "")
val KAFKA_TRUSTSTORE_PATH = getEnvVar(envVar = "KAFKA_TRUSTSTORE_PATH", default = "")
val KAFKA_KEYSTORE_PATH = getEnvVar(envVar = "KAFKA_KEYSTORE_PATH", default = "")
val KAFKA_CREDSTORE_PASSWORD = getEnvVar(envVar = "KAFKA_CREDSTORE_PASSWORD", default = "")
const val KAFKA_TOPIC_OPPDATERINGER = "pia.brreg-oppdatering"
const val KAFKA_TOPIC_ALLE_VIRKSOMHETER = "pia.brreg-alle-virksomheter"
fun producerProperties(klientId: String): Map<String, Serializable> {
val producerConfigs = mutableMapOf(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG to KAFKA_BROKERS,
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG to StringSerializer::class.java,
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG to StringSerializer::class.java,
ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG to true, // Den sikrer rekkefølge
ProducerConfig.ACKS_CONFIG to "all", // Den sikrer at data ikke mistes
ProducerConfig.CLIENT_ID_CONFIG to klientId
)
if (KAFKA_TRUSTSTORE_PATH.isNotEmpty()) {
producerConfigs.putAll(securityConfigs())
}
return producerConfigs.toMap()
}
private fun securityConfigs() =
mapOf(
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG to "SSL",
SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG to "",
SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG to "JKS",
SslConfigs.SSL_KEYSTORE_TYPE_CONFIG to "PKCS12",
SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG to KAFKA_TRUSTSTORE_PATH,
SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG to KAFKA_CREDSTORE_PASSWORD,
SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG to KAFKA_KEYSTORE_PATH,
SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG to KAFKA_CREDSTORE_PASSWORD,
SslConfigs.SSL_KEY_PASSWORD_CONFIG to KAFKA_CREDSTORE_PASSWORD
)
}
private fun getEnvVar(envVar: String, default: String? = null) =
System.getenv(envVar) ?: default ?: throw IllegalStateException("Manglende kjøretidsvariabel: $envVar")
| 0
|
Kotlin
|
0
| 0
|
b775aa1d4bea6bd9d7472fae496beeecff3e0a6b
| 3,118
|
pia-brreg-oppdaterer
|
MIT License
|
src/main/kotlin/no/nav/syfo/util/XMLDateTimeAdapter.kt
|
navikt
| 145,608,534
| false
| null |
package no.nav.syfo
import com.migesok.jaxb.adapter.javatime.LocalDateTimeXmlAdapter
import com.migesok.jaxb.adapter.javatime.LocalDateXmlAdapter
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.xml.bind.DatatypeConverter
class XMLDateTimeAdapter : LocalDateTimeXmlAdapter() {
override fun unmarshal(stringValue: String?): LocalDateTime? = when (stringValue) {
null -> null
else -> DatatypeConverter.parseDateTime(stringValue).toInstant().atZone(ZoneOffset.UTC).toLocalDateTime()
}
}
class XMLDateAdapter : LocalDateXmlAdapter() {
override fun unmarshal(stringValue: String?): LocalDate? = when (stringValue) {
null -> null
else -> DatatypeConverter.parseDate(stringValue).toInstant().atZone(ZoneOffset.MAX).toLocalDate()
}
}
| 1
|
Kotlin
|
1
| 1
|
74ecceb3ad47819b789711f5520675a003caf63b
| 827
|
syfosmmottak
|
MIT License
|
work/workmanager-testing/src/androidTest/java/androidx/work/testing/TestWorkerBuilderTest.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work.testing
import android.content.Context
import android.net.Uri
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SmallTest
import androidx.work.ListenableWorker.Result
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import androidx.work.await
import androidx.work.testing.workers.TestListenableWorker
import androidx.work.testing.workers.TestWorker
import kotlinx.coroutines.runBlocking
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.hasItems
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.notNullValue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executor
import java.util.concurrent.Executors
@RunWith(AndroidJUnit4::class)
class TestWorkerBuilderTest {
private lateinit var context: Context
private lateinit var executor: Executor
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
executor = SynchronousExecutor()
}
@Test
@SmallTest
@Throws(InterruptedException::class, ExecutionException::class)
fun testListenableWorkerBuilder_buildsWorker() {
val request = OneTimeWorkRequestBuilder<TestWorker>().build()
val worker = TestListenableWorkerBuilder.from(context, request).build()
val result = worker.startWork().get()
assertThat(result, `is`(Result.success()))
}
@Test
@SmallTest
fun testWorkerBuilder_buildsWorker() {
val request = OneTimeWorkRequestBuilder<TestWorker>().build()
val worker = TestWorkerBuilder.from(context, request, executor).build()
val result = worker.doWork()
assertThat(result, `is`(Result.success()))
}
@Test(expected = IllegalArgumentException::class)
@SmallTest
fun testWorkerBuilder_invalidWorker() {
val request = OneTimeWorkRequestBuilder<TestListenableWorker>().build()
TestWorkerBuilder.from(context, request, executor).build()
}
@Test
@SmallTest
fun testBuilder() {
val request = OneTimeWorkRequestBuilder<TestWorker>()
.addTag("test")
.build()
val contentUris = arrayOf(Uri.parse("android.test://1"))
val authorities = arrayOf("android.test")
val worker = TestListenableWorkerBuilder.from(context, request)
.setRunAttemptCount(2)
.setTriggeredContentAuthorities(authorities.toList())
.setTriggeredContentUris(contentUris.toList())
.build()
assertThat(worker.tags, hasItems("test"))
assertThat(worker.id, `is`(request.id))
assertThat(worker.runAttemptCount, `is`(2))
assertThat(worker.triggeredContentAuthorities, containsInAnyOrder(*authorities))
assertThat(worker.triggeredContentUris, containsInAnyOrder(*contentUris))
}
@Test
@SmallTest
fun testWorkerBuilder_usesSingleThreadedExecutor() {
val request = OneTimeWorkRequestBuilder<TestWorker>().build()
val singleThreadedExecutor = Executors.newSingleThreadExecutor()
val worker = TestWorkerBuilder.from(context, request, singleThreadedExecutor).build()
val result = worker.doWork()
assertThat(result, `is`(Result.success()))
}
@Test
@SmallTest
fun testWorkerBuilder_returnsExpectedType() {
val listenableWorker: TestListenableWorker =
TestListenableWorkerBuilder.from(context, TestListenableWorker::class.java).build()
val worker: TestWorker =
TestWorkerBuilder.from(context, TestWorker::class.java, executor).build()
assertThat(listenableWorker, notNullValue())
assertThat(worker, notNullValue())
}
@Test
@SmallTest
fun testListenableWorkerBuilder_usesExtension() {
val worker = TestListenableWorkerBuilder<TestWorker>(context).build()
val result = worker.doWork()
assertThat(result, `is`(Result.success()))
}
@Test
@SmallTest
fun testWorkerBuilder_usesExtension() {
val singleThreadedExecutor = Executors.newSingleThreadExecutor()
val worker = TestWorkerBuilder<TestWorker>(context, singleThreadedExecutor).build()
val result = worker.doWork()
assertThat(result, `is`(Result.success()))
}
@Test
@MediumTest
fun testWorkerBuilder_usesWorkerFactory() {
val workerFactory = mock(WorkerFactory::class.java)
val worker = TestListenableWorkerBuilder<TestWorker>(context)
.setWorkerFactory(workerFactory)
.build()
runBlocking {
val result = worker.startWork().await()
verify(workerFactory, times(1))
.createWorker(
any(Context::class.java), anyString(), any(WorkerParameters::class.java)
)
assertThat(result, `is`(Result.success()))
}
}
}
| 23
| null |
843
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 5,996
|
androidx
|
Apache License 2.0
|
shared/src/commonMain/kotlin/feature_home/presentation/HomeScreenEvent.kt
|
tolgaprm
| 712,824,422
| false
|
{"Kotlin": 153117, "Swift": 657, "Shell": 228}
|
package feature_home.presentation
import core.domain.movie.Movie
import core.domain.tvseries.TvSeries
sealed interface HomeScreenEvent {
data class OnMovieSelected(val movie: Movie) : HomeScreenEvent
data class OnTvSeriesSelected(val tvSeries: TvSeries) : HomeScreenEvent
}
| 3
|
Kotlin
|
0
| 0
|
b5f393e09e4c99cc039627cde691a3de9245cc95
| 283
|
MovaApp-compose-multiplatform
|
Apache License 2.0
|
compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades/box.kt
|
msdgwzhy6
| 51,743,245
| true
|
{"Markdown": 33, "XML": 666, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 21040, "Java": 4546, "Protocol Buffer": 7, "Text": 4675, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 154, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1}
|
package test
fun box(): String = foo() + bar()
| 0
|
Java
|
0
| 1
|
ff00bde607d605c4eba2d98fbc9e99af932accb6
| 47
|
kotlin
|
Apache License 2.0
|
spring-simplicity-kotlin-sample/src/main/kotlin/org/pensatocode/simplicity/sample/mapper/CollegeMapper.kt
|
alexpensato
| 102,654,783
| false
| null |
/*
* Copyright 2017-2020 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pensatocode.simplicity.sample.mapper
import org.pensatocode.simplicity.jdbc.mapper.TransactionalRowMapper
import org.pensatocode.simplicity.sample.domain.College
import java.sql.ResultSet
import java.util.LinkedHashMap
object CollegeMapper: TransactionalRowMapper<College> {
override fun mapRow(rs: ResultSet, rowNum: Int): College {
val entity = College()
entity.id = rs.getLong("id")
entity.name = rs.getString("name")
entity.nameOfCity = rs.getString("name_of_city")
return entity
}
override fun mapColumns(entity: College): Map<String, Any> {
val mapping = LinkedHashMap<String, Any>()
mapping.put("id", entity.id)
mapping.put("name", entity.name)
mapping.put("name_of_city", entity.nameOfCity)
return mapping
}
}
| 0
|
Kotlin
|
0
| 0
|
df0f7e8c9e366f00ab3e686eb0bb457b37c5ed03
| 1,435
|
spring-boot-repositories-kotlin-samples
|
Apache License 2.0
|
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/dice/Dice.kt
|
InsanusMokrassar
| 163,152,024
| false
| null |
package dev.inmo.tgbotapi.types.dice
import dev.inmo.tgbotapi.types.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Dice(
@SerialName(valueField)
val value: DiceResult,
@SerialName(emojiField)
val animationType: DiceAnimationType
) : ReplyInfo.External.ContentVariant
| 9
|
Kotlin
|
29
| 99
|
8206aefbb661db936d4078a8ef7cc9cecb5384e4
| 347
|
TelegramBotAPI
|
Apache License 2.0
|
core/src/main/kotlin/cn/netdiscovery/command/extension/CommandExecutor+Extension.kt
|
fengzhizi715
| 183,575,200
| false
| null |
package cn.netdiscovery.command.extension
import cn.netdiscovery.command.*
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
/**
*
* @FileName:
* cn.netdiscovery.command.extension.`CommandExecutor+Extension`
* @author: <NAME>
* @date: 2020-10-07 22:23
* @since: V1.3 <描述当前版本功能>
*/
fun CommandExecutor.getCompletableFutureWithSync(cmd: Command, directory: File?=null, timeout:Long?=null, unit: TimeUnit?=null, charsetName:String = "UTF-8", appender: Appender): CompletableFuture<String>
= getCompletableFutureWithSyncOutputPrinter(cmd, directory, timeout, unit, ExecutionOutputPrinter(appender,charsetName))
fun CommandExecutor.getCompletableFutureWithSyncOutputPrinter(cmd: Command, directory: File?=null, timeout:Long?=null, unit: TimeUnit?=null, outputPrinter: ExecutionOutputPrinter = ExecutionOutputPrinter.DEFAULT_OUTPUT_PRINTER): CompletableFuture<String> {
return CompletableFuture<String>().apply {
val result = getStringWithSyncOutputPrinter(cmd,directory,timeout,unit,outputPrinter)
this.complete(result)
}
}
| 0
|
Kotlin
|
1
| 6
|
992da93f755be23b012d1fdff75e27fc1f962299
| 1,123
|
kcommand
|
Apache License 2.0
|
feature/feature_common/src/main/java/black/bracken/picsorter/feature_common/ext/TextEdit.kt
|
blackbracken
| 189,738,510
| false
| null |
package black.bracken.picsorter.feature_common.ext
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
fun EditText.setOnTextChanged(listener: (String) -> Unit) = this.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(seq: CharSequence, start: Int, count: Int, before: Int) {}
override fun onTextChanged(seq: CharSequence, start: Int, before: Int, count: Int) =
listener(seq.toString())
override fun afterTextChanged(editable: Editable) {}
}
)
| 14
|
Kotlin
|
0
| 4
|
f9f5cdd6e652f4f63e5c71ca1c533c6f176ebfc2
| 561
|
pic-sorter
|
MIT License
|
feature/feature_common/src/main/java/black/bracken/picsorter/feature_common/ext/TextEdit.kt
|
blackbracken
| 189,738,510
| false
| null |
package black.bracken.picsorter.feature_common.ext
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
fun EditText.setOnTextChanged(listener: (String) -> Unit) = this.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(seq: CharSequence, start: Int, count: Int, before: Int) {}
override fun onTextChanged(seq: CharSequence, start: Int, before: Int, count: Int) =
listener(seq.toString())
override fun afterTextChanged(editable: Editable) {}
}
)
| 14
|
Kotlin
|
0
| 4
|
f9f5cdd6e652f4f63e5c71ca1c533c6f176ebfc2
| 561
|
pic-sorter
|
MIT License
|
ui/src/main/java/com/gmail/bogumilmecel2/ui/components/base/SheetLayout.kt
|
BogumilMecel
| 499,018,800
| false
|
{"Kotlin": 808610}
|
package com.gmail.bogumilmecel2.ui.components.base
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.unit.dp
import com.gmail.bogumilmecel2.ui.theme.FitnessAppTheme
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SheetLayout(
sheetState: ModalBottomSheetState,
bottomSheetContent: @Composable () -> Unit,
onBottomSheetDismissed: () -> Unit,
content: @Composable () -> Unit
) {
if (sheetState.currentValue != ModalBottomSheetValue.Hidden) {
DisposableEffect(Unit) {
onDispose {
onBottomSheetDismissed()
}
}
}
ModalBottomSheetLayout(
sheetContent = {
bottomSheetContent()
},
sheetState = sheetState,
sheetShape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
sheetBackgroundColor = FitnessAppTheme.colors.BackgroundSecondary
) {
content()
}
}
| 0
|
Kotlin
|
0
| 0
|
f1036ca805dec913c5ca444d8efab87686442f39
| 1,262
|
FitnessAppV2
|
Apache License 2.0
|
test-app/src/androidTest/java/com/avito/android/ui/test/SwipeRefreshScreen.kt
|
avito-tech
| 120,176,958
| false
| null |
package com.avito.android.ui.test
import androidx.test.espresso.matcher.ViewMatchers.withId
import com.avito.android.test.page_object.ListElement
import com.avito.android.test.page_object.PageObject
import com.avito.android.test.page_object.SwipeRefreshElement
import com.avito.android.ui.R
class SwipeRefreshScreen : PageObject() {
val list: ListElement = element(withId(R.id.swipe_refresh))
val swipeRefreshElement: SwipeRefreshElement = element(withId(R.id.swipe_refresh))
}
| 0
|
Kotlin
|
14
| 38
|
3fa67bd425cb7ae38b2c4687e8e8ee9e6104ff2e
| 488
|
android-ui-testing
|
MIT License
|
kmqtt-broker/src/commonMain/kotlin/mqtt/broker/ClientConnection.kt
|
davidepianca98
| 235,132,697
| false
| null |
package mqtt.broker
import currentTimeMillis
import generateRandomClientId
import mqtt.*
import mqtt.broker.cluster.RemoteSession
import mqtt.broker.interfaces.EnhancedAuthenticationProvider
import mqtt.packets.ConnectAcknowledgeFlags
import mqtt.packets.MQTTPacket
import mqtt.packets.Qos
import mqtt.packets.mqtt.*
import mqtt.packets.mqttv4.*
import mqtt.packets.mqttv5.*
import socket.SocketInterface
import socket.streams.EOFException
import socket.tcp.IOException
import socket.tcp.TCPEventHandler
class ClientConnection(
private val client: SocketInterface,
private val broker: Broker
) : TCPEventHandler {
companion object {
private const val DEFAULT_MAX_SEND_QUOTA = 65535u
}
private var clientId: String? = null
private var session: Session? = null
// Client connection state
private val topicAliasesClient = mutableMapOf<UInt, String>()
private val topicAliasesServer = mutableMapOf<String, UInt>()
private var maxSendQuota: UInt =
DEFAULT_MAX_SEND_QUOTA // Client receive maximum
internal var sendQuota: UInt = DEFAULT_MAX_SEND_QUOTA
private var maximumPacketSize: UInt? = null
private var topicAliasMaximum = 0u
private var keepAlive = 0
private var connectHandled = false
private var connectCompleted = false
private var authenticationMethod: String? = null
private var connectPacket: MQTTConnect? = null
private var packetsReceivedBeforeConnack = mutableListOf<MQTTPacket>()
private val currentReceivedPacket = MQTTCurrentPacket(broker.maximumPacketSize)
private var lastReceivedMessageTimestamp = currentTimeMillis()
fun checkKeepAliveExpired() {
val timeout = ((keepAlive * 1000).toDouble() * 1.5).toInt()
val expired = currentTimeMillis() > lastReceivedMessageTimestamp + timeout
if (expired) {
if (connectHandled) {
if (keepAlive > 0) {
disconnect(ReasonCode.KEEP_ALIVE_TIMEOUT)
session?.connected = false
}
} else {
disconnect(ReasonCode.MAXIMUM_CONNECT_TIME)
}
}
}
override fun read(): UByteArray? {
return client.read()
}
override fun sendRemaining() {
client.sendRemaining()
}
override fun dataReceived(data: UByteArray) {
lastReceivedMessageTimestamp = currentTimeMillis()
try {
clientId?.let {
broker.bytesMetrics?.received(it, data.size.toLong())
}
currentReceivedPacket.addData(data).forEach {
handlePacket(it)
}
} catch (e: MQTTException) {
disconnect(e.reasonCode)
} catch (e: EOFException) {
println("EOF")
close()
} catch (e: IOException) {
println("IOException ${e.message}")
closedWithException()
} catch (e: Exception) {
println("Exception ${e.message} ${e.cause?.message}")
disconnect(ReasonCode.IMPLEMENTATION_SPECIFIC_ERROR)
}
}
internal fun writePacket(packet: MQTTPacket) {
try {
if (maximumPacketSize?.let { packet.resizeIfTooBig(it) } != false) {
val packetBytes = packet.toByteArray()
client.send(packetBytes)
clientId?.let {
broker.bytesMetrics?.sent(it, packetBytes.size.toLong())
}
}
} catch (e: IOException) {
closedWithException()
}
}
override fun closedWithException() {
close()
}
override fun closedGracefully() {
close()
}
private fun close() {
client.close()
(broker.getSession(clientId) as Session?)?.connected = false
}
fun disconnect(reasonCode: ReasonCode, serverReference: String? = null) {
if (currentReceivedPacket.mqttVersion == 5) {
if (!connectCompleted) {
val connack = MQTT5Connack(
ConnectAcknowledgeFlags(false),
reasonCode,
MQTT5Properties().apply { this.serverReference = serverReference })
writePacket(connack)
} else {
val disconnect =
MQTT5Disconnect(reasonCode, MQTT5Properties().apply { this.serverReference = serverReference })
writePacket(disconnect)
if (reasonCode in listOf(
ReasonCode.SUCCESS,
ReasonCode.SERVER_SHUTTING_DOWN,
ReasonCode.USE_ANOTHER_SERVER,
ReasonCode.SERVER_MOVED
)
) {
(broker.getSession(clientId) as Session?)?.will = null
}
}
}
close()
}
private fun handlePacket(packet: MQTTPacket) {
if (packet is MQTTConnect) {
if (!connectHandled) {
handleConnect(packet)
connectHandled = true
}
} else {
if (!connectHandled) // If first packet is not CONNECT, send Protocol Error
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
when (packet) {
is MQTTPublish -> handlePublish(packet)
is MQTTPuback -> handlePuback(packet)
is MQTTPubrec -> handlePubrec(packet)
is MQTTPubrel -> handlePubrel(packet)
is MQTTPubcomp -> handlePubcomp(packet)
is MQTTSubscribe -> handleSubscribe(packet)
is MQTTUnsubscribe -> handleUnsubscribe(packet)
is MQTTPingreq -> handlePingreq()
is MQTTDisconnect -> handleDisconnect(packet)
is MQTTAuth -> handleAuth(packet)
else -> throw MQTTException(ReasonCode.PROTOCOL_ERROR)
}
}
broker.packetInterceptor?.packetReceived(packet)
}
/**
* Either generates a new topic alias or uses an existing one, if they are enabled in the connection
* @param topicName to send the message to
* @param properties the publish properties, will get modified if topic aliases enabled
*/
internal fun getPublishTopicAlias(topicName: String, properties: MQTT5Properties): String {
var packetTopicName: String = topicName
if (topicAliasMaximum > 0u) {
topicAliasesServer[topicName]?.let {
packetTopicName = ""
properties.topicAlias = it
} ?: run {
if (topicAliasesServer.size < topicAliasMaximum.toInt()) {
topicAliasesServer[topicName] = topicAliasesServer.size.toUInt()
packetTopicName = topicName
properties.topicAlias = topicAliasesServer[topicName]
}
}
}
return packetTopicName
}
private fun generateClientId(): String {
var id: String
do {
id = generateRandomClientId()
} while (broker.getSession(id) != null)
return id
}
private fun incrementSendQuota() {
if (++sendQuota >= maxSendQuota)
sendQuota = maxSendQuota
session?.sendPending {
writePacket(it)
}
}
internal fun decrementSendQuota() {
if (sendQuota > 0u)
sendQuota--
}
private fun handleAuthentication(packet: MQTTConnect) {
if (broker.authentication != null) {
if (packet.userName != null || packet.password != null) {
if (!broker.authentication.authenticate(packet.userName, packet.password)) {
throw MQTTException(ReasonCode.NOT_AUTHORIZED)
}
} else {
throw MQTTException(ReasonCode.NOT_AUTHORIZED)
}
}
}
private fun sendAuth(reasonCode: ReasonCode, authenticationMethod: String, authenticationData: UByteArray?) {
val properties = MQTT5Properties()
properties.authenticationMethod = authenticationMethod
properties.authenticationData = authenticationData
val auth = MQTT5Auth(reasonCode, properties)
writePacket(auth)
}
private fun enhancedAuthenticationResult(
result: EnhancedAuthenticationProvider.Result,
authenticationMethod: String,
authenticationData: UByteArray?
) {
if (result == EnhancedAuthenticationProvider.Result.NEEDS_MORE) {
sendAuth(ReasonCode.CONTINUE_AUTHENTICATION, authenticationMethod, authenticationData)
} else if (result == EnhancedAuthenticationProvider.Result.SUCCESS) {
if (!connectCompleted) {
connectPacket?.let { initSessionAndSendConnack(it, authenticationData) }
?: throw MQTTException(ReasonCode.IMPLEMENTATION_SPECIFIC_ERROR)
} else {
sendAuth(ReasonCode.SUCCESS, authenticationMethod, authenticationData)
}
} else if (result == EnhancedAuthenticationProvider.Result.ERROR) {
throw MQTTException(ReasonCode.NOT_AUTHORIZED)
}
}
private fun handleEnhancedAuthentication(
clientId: String,
authenticationMethod: String,
authenticationData: UByteArray?
) {
val provider = broker.enhancedAuthenticationProviders[authenticationMethod]
if (provider == null) {
throw MQTTException(ReasonCode.BAD_AUTHENTICATION_METHOD)
} else {
this.authenticationMethod = authenticationMethod
provider.authReceived(clientId, authenticationData) { result, data ->
enhancedAuthenticationResult(result, authenticationMethod, data)
}
}
}
private fun handleConnect(packet: MQTTConnect) {
connectPacket = packet
handleAuthentication(packet)
val clientId = if (packet.clientID.isEmpty()) {
if (packet is MQTT4Connect && !packet.connectFlags.cleanStart) {
writePacket(MQTT4Connack(ConnectAcknowledgeFlags(false), ConnectReturnCode.IDENTIFIER_REJECTED))
return
}
generateClientId()
} else packet.clientID
this.clientId = clientId
if (packet is MQTT5Connect && packet.properties.authenticationMethod != null) {
packet.properties.authenticationMethod?.let { authenticationMethod ->
handleEnhancedAuthentication(clientId, authenticationMethod, packet.properties.authenticationData)
}
} else {
initSessionAndSendConnack(packet, null)
}
}
internal fun persistSession(clientId: String, session: Session) {
broker.persistence?.persistSession(clientId, session)
}
private fun newSession(packet: MQTTConnect): Session {
return Session(
this,
packet.clientID,
if (packet is MQTT5Connect) packet.properties.sessionExpiryInterval ?: 0u else 0xFFFFFFFFu,
Will.buildWill(packet),
this::persistSession,
broker::propagateSession
)
}
private fun initSessionAndSendConnack(packet: MQTTConnect, authenticationData: UByteArray?) {
var sessionPresent = false
val clientId = this.clientId ?: throw MQTTException(ReasonCode.IMPLEMENTATION_SPECIFIC_ERROR)
var session = broker.getSession(clientId)
if (session != null) {
if (session.connected) {
// Send disconnect to the old connection and close it
session.disconnectClientSessionTakenOver()
if (session is RemoteSession) {
session = session.toLocalSession(this, broker)
}
// Send old will if present
if ((session as Session).will?.willDelayInterval == 0u || packet.connectFlags.cleanStart) {
broker.sendWill(session)
}
} else {
if (session is RemoteSession) {
session = session.toLocalSession(this, broker)
}
}
if (packet.connectFlags.cleanStart) {
session = newSession(packet)
broker.addSession(clientId, session)
this.session = session
} else {
// Update the session with the new parameters
(session as Session).clientConnection = this
session.will = Will.buildWill(packet)
session.sessionExpiryInterval =
if (packet is MQTT5Connect) packet.properties.sessionExpiryInterval ?: 0u else 0xFFFFFFFFu
sessionPresent = true
this.session = session
}
} else {
session = newSession(packet)
broker.addSession(clientId, session)
this.session = session
}
session.mqttVersion = currentReceivedPacket.mqttVersion ?: 4
keepAlive = packet.keepAlive
val connack = if (packet is MQTT5Connect) {
sendQuota = packet.properties.receiveMaximum ?: DEFAULT_MAX_SEND_QUOTA
maxSendQuota = packet.properties.receiveMaximum ?: DEFAULT_MAX_SEND_QUOTA
maximumPacketSize = packet.properties.maximumPacketSize
topicAliasMaximum = packet.properties.topicAliasMaximum ?: 0u
//
// CONNACK properties
//
val connackProperties = MQTT5Properties()
if (session.sessionExpiryInterval > broker.maximumSessionExpiryInterval) {
session.sessionExpiryInterval = broker.maximumSessionExpiryInterval
connackProperties.sessionExpiryInterval = broker.maximumSessionExpiryInterval
}
broker.receiveMaximum?.toUInt()?.let {
connackProperties.receiveMaximum = it
}
broker.maximumQos?.let { maximumQos ->
if (maximumQos == Qos.AT_MOST_ONCE || maximumQos == Qos.AT_LEAST_ONCE)
connackProperties.maximumQos = maximumQos.value.toUInt()
session.will?.qos?.let {
if (it > maximumQos)
throw MQTTException(ReasonCode.QOS_NOT_SUPPORTED)
}
}
if (!broker.retainedAvailable) {
connackProperties.retainAvailable = 0u
if (session.will?.retain == true)
throw MQTTException(ReasonCode.RETAIN_NOT_SUPPORTED)
}
connackProperties.maximumPacketSize = broker.maximumPacketSize
if (packet.clientID.isEmpty())
connackProperties.assignedClientIdentifier = clientId
broker.maximumTopicAlias?.let {
connackProperties.topicAliasMaximum = it.toUInt()
}
if (!broker.wildcardSubscriptionAvailable)
connackProperties.wildcardSubscriptionAvailable = 0u
if (!broker.subscriptionIdentifiersAvailable)
connackProperties.subscriptionIdentifierAvailable = 0u
if (!broker.sharedSubscriptionsAvailable)
connackProperties.sharedSubscriptionAvailable = 0u
broker.serverKeepAlive?.let {
if (broker.serverKeepAlive < keepAlive) {
keepAlive = it
connackProperties.serverKeepAlive = it.toUInt()
}
}
packet.properties.requestResponseInformation?.let { requestResponseInformation ->
if (requestResponseInformation !in 0u..1u)
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
if (requestResponseInformation == 1u) {
broker.responseInformation?.let {
connackProperties.responseInformation = it
}
}
}
packet.properties.requestProblemInformation?.let { requestProblemInformation ->
if (requestProblemInformation !in 0u..1u)
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
// May send reason string here
}
this.authenticationMethod?.let {
connackProperties.authenticationMethod = it
}
authenticationData?.let {
connackProperties.authenticationData = it
}
MQTT5Connack(
ConnectAcknowledgeFlags(sessionPresent),
ReasonCode.SUCCESS,
connackProperties
)
} else {
MQTT4Connack(ConnectAcknowledgeFlags(sessionPresent), ConnectReturnCode.CONNECTION_ACCEPTED)
}
writePacket(connack)
connectCompleted = true
session.connected = true
session.resendPending {
writePacket(it)
}
handlePacketsReceivedBeforeConnack()
}
private fun handlePacketsReceivedBeforeConnack() {
packetsReceivedBeforeConnack.forEach { packet ->
if (packet is MQTTPublish) {
handlePublish(packet)
} else if (packet is MQTTSubscribe) {
handleSubscribe(packet)
}
}
packetsReceivedBeforeConnack.clear()
}
private fun checkAuthorization(topicName: String, isSubscription: Boolean): Boolean {
return broker.authorization?.authorize(clientId!!, topicName, isSubscription) != false
}
private fun handlePublish(packet: MQTTPublish) {
if (!connectCompleted) {
packetsReceivedBeforeConnack.add(packet)
return
}
// Handle topic alias
val topic = getTopicOrAlias(packet)
if (!checkAuthorization(topic, false))
throw MQTTException(ReasonCode.NOT_AUTHORIZED)
if (packet.qos > broker.maximumQos ?: Qos.EXACTLY_ONCE) {
throw MQTTException(ReasonCode.QOS_NOT_SUPPORTED)
}
if (!broker.retainedAvailable && packet.retain)
throw MQTTException(ReasonCode.RETAIN_NOT_SUPPORTED)
// Handle receive maximum
if (packet.qos > Qos.AT_MOST_ONCE && broker.receiveMaximum != null) {
if (session!!.qos2ListReceived.size + 1 > broker.receiveMaximum.toInt())
throw MQTTException(ReasonCode.RECEIVE_MAXIMUM_EXCEEDED)
}
val dontSend = if (packet.retain) {
broker.setRetained(packet.topicName, packet, session!!.clientId)
packet.payload == null || packet.payload.isEmpty()
} else false
when (packet.qos) {
Qos.AT_LEAST_ONCE -> {
val reasonCode = qos12ReasonCode(packet)
if (currentReceivedPacket.mqttVersion == 5) {
writePacket(MQTT5Puback(packet.packetId!!, reasonCode))
} else {
if (reasonCode == ReasonCode.SUCCESS) {
writePacket(MQTT4Puback(packet.packetId!!))
}
}
if (reasonCode != ReasonCode.SUCCESS)
return
}
Qos.EXACTLY_ONCE -> {
val reasonCode = qos12ReasonCode(packet)
if (currentReceivedPacket.mqttVersion == 5) {
writePacket(MQTT5Pubrec(packet.packetId!!, reasonCode))
} else {
if (reasonCode == ReasonCode.SUCCESS) {
writePacket(MQTT4Pubrec(packet.packetId!!))
}
}
if (reasonCode == ReasonCode.SUCCESS)
session!!.qos2ListReceived[packet.packetId!!] = packet
return // Don't send the PUBLISH to other clients until PUBCOMP
}
else -> {
}
}
if (!dontSend) {
broker.publish(
session!!.clientId,
packet.retain,
topic,
packet.qos,
false,
if (packet is MQTT5Publish) packet.properties else null,
packet.payload
)
}
}
private fun getTopicOrAlias(packet: MQTTPublish): String {
var topic = packet.topicName
if (packet is MQTT5Publish) {
packet.properties.topicAlias?.let {
if (it == 0u || it > broker.maximumTopicAlias?.toUInt() ?: 0u)
throw MQTTException(ReasonCode.TOPIC_ALIAS_INVALID)
if (packet.topicName.isNotEmpty()) {
topicAliasesClient[it] = packet.topicName
}
topic = topicAliasesClient[it] ?: throw MQTTException(ReasonCode.PROTOCOL_ERROR)
packet.properties.topicAlias = null
}
}
return topic
}
private fun qos12ReasonCode(packet: MQTTPublish): ReasonCode {
val payloadFormatValid = if (packet is MQTT5Publish) packet.validatePayloadFormat() else true
return if (!payloadFormatValid)
ReasonCode.PAYLOAD_FORMAT_INVALID
else if (session!!.isPacketIdInUse(packet.packetId!!))
ReasonCode.PACKET_IDENTIFIER_IN_USE
else
ReasonCode.SUCCESS
}
private fun handlePuback(packet: MQTTPuback) {
session!!.acknowledgePublish(packet.packetId)
incrementSendQuota()
}
private fun handlePubrec(packet: MQTTPubrec) {
if (packet is MQTT5Pubrec && packet.reasonCode >= ReasonCode.UNSPECIFIED_ERROR) {
session!!.acknowledgePublish(packet.packetId)
incrementSendQuota()
return
}
val reasonCode = if (session!!.hasPendingAcknowledgeMessage(packet.packetId)) {
ReasonCode.SUCCESS
} else {
ReasonCode.PACKET_IDENTIFIER_NOT_FOUND
}
val pubrel = if (packet is MQTT5Pubrec) {
MQTT5Pubrel(packet.packetId, reasonCode)
} else {
if (reasonCode == ReasonCode.SUCCESS) {
MQTT4Pubrel(packet.packetId)
} else {
null
}
}
pubrel?.let {
session!!.addPendingAcknowledgePubrel(pubrel)
writePacket(pubrel)
}
}
private fun handlePubrel(packet: MQTTPubrel) {
if (packet is MQTT5Pubrel && packet.reasonCode != ReasonCode.SUCCESS)
return
session!!.qos2ListReceived.remove(packet.packetId)?.let {
val pubcomp = if (packet is MQTT5Pubrel) {
MQTT5Pubcomp(
packet.packetId,
ReasonCode.SUCCESS,
packet.properties
)
} else {
MQTT4Pubcomp(packet.packetId)
}
writePacket(pubcomp)
if (it.retain && (it.payload == null || it.payload.isEmpty())) {
return
}
broker.publish(
session!!.clientId,
it.retain,
getTopicOrAlias(it),
Qos.EXACTLY_ONCE,
false,
if (it is MQTT5Publish) it.properties else null,
it.payload
)
} ?: run {
if (packet is MQTT5Pubrel) {
writePacket(
MQTT5Pubcomp(
packet.packetId,
ReasonCode.PACKET_IDENTIFIER_NOT_FOUND,
packet.properties
)
)
}
}
}
private fun handlePubcomp(packet: MQTTPubcomp) {
session!!.acknowledgePubrel(packet.packetId)
incrementSendQuota()
}
private fun prepareRetainedMessages(subscription: Subscription, replaced: Boolean): List<MQTTPublish> {
val retainedMessagesList = mutableListOf<MQTTPublish>()
if (!subscription.isShared() &&
((subscription.options.retainHandling == 0u) ||
(subscription.options.retainHandling == 1u && !replaced))
) {
broker.getRetained(subscription.topicFilter).forEach { pair ->
val retainedMessage = pair.first
val clientId = pair.second
if (!(subscription.options.noLocal && session!!.clientId == clientId)) {
val qos = Qos.min(retainedMessage.qos, subscription.options.qos)
if (currentReceivedPacket.mqttVersion == 5) {
retainedMessagesList += MQTT5Publish(
if (subscription.options.retainedAsPublished) retainedMessage.retain else false,
qos,
false,
retainedMessage.topicName,
if (qos > Qos.AT_MOST_ONCE) session!!.generatePacketId() else null,
if (retainedMessage is MQTT5Publish) retainedMessage.properties else MQTT5Properties(),
retainedMessage.payload
)
} else {
retainedMessagesList += MQTT4Publish(
if (subscription.options.retainedAsPublished) retainedMessage.retain else false,
qos,
false,
retainedMessage.topicName,
if (qos > Qos.AT_MOST_ONCE) session!!.generatePacketId() else null,
retainedMessage.payload
)
}
}
}
}
return retainedMessagesList
}
private fun handleSubscribe(packet: MQTTSubscribe) {
if (!connectCompleted) {
packetsReceivedBeforeConnack.add(packet)
return
}
val retainedMessagesList = mutableListOf<MQTTPublish>()
val reasonCodes = packet.subscriptions.map { subscription ->
if (!checkAuthorization(subscription.topicFilter, true))
return@map ReasonCode.NOT_AUTHORIZED
if (!subscription.matchTopicFilter.isValidTopic())
return@map ReasonCode.TOPIC_FILTER_INVALID
if (session!!.isPacketIdInUse(packet.packetIdentifier))
return@map ReasonCode.PACKET_IDENTIFIER_IN_USE
val isShared = subscription.isShared()
if (!broker.sharedSubscriptionsAvailable && isShared)
return@map ReasonCode.SHARED_SUBSCRIPTIONS_NOT_SUPPORTED
if (isShared && subscription.options.noLocal)
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
if (packet is MQTT5Subscribe) {
if (packet.properties.subscriptionIdentifier.getOrNull(0) != null && !broker.subscriptionIdentifiersAvailable)
return@map ReasonCode.SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED
}
if (!broker.wildcardSubscriptionAvailable && subscription.matchTopicFilter.containsWildcard())
return@map ReasonCode.WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED
val replaced = broker.addSubscription(clientId!!, subscription)
retainedMessagesList += prepareRetainedMessages(subscription, replaced)
when (subscription.options.qos) {
Qos.AT_MOST_ONCE -> ReasonCode.SUCCESS
Qos.AT_LEAST_ONCE -> ReasonCode.GRANTED_QOS1
Qos.EXACTLY_ONCE -> ReasonCode.GRANTED_QOS2
}
}
if (ReasonCode.SHARED_SUBSCRIPTIONS_NOT_SUPPORTED in reasonCodes) {
disconnect(ReasonCode.SHARED_SUBSCRIPTIONS_NOT_SUPPORTED)
return
}
if (ReasonCode.SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED in reasonCodes) {
disconnect(ReasonCode.SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED)
return
}
if (ReasonCode.WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED in reasonCodes) {
disconnect(ReasonCode.WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED)
return
}
val suback = if (packet is MQTT5Subscribe) {
MQTT5Suback(packet.packetIdentifier, reasonCodes)
} else {
MQTT4Suback(packet.packetIdentifier, reasonCodes.toSubackReturnCodes())
}
// Send SUBACK
writePacket(suback)
// Send retained messages
retainedMessagesList.forEach {
session?.publish(it)
}
}
private fun handleUnsubscribe(packet: MQTTUnsubscribe) {
val reasonCodes = packet.topicFilters.map { topicFilter ->
if (session!!.isPacketIdInUse(packet.packetIdentifier))
return@map ReasonCode.PACKET_IDENTIFIER_IN_USE
if (broker.removeSubscription(clientId!!, topicFilter)) {
return@map ReasonCode.SUCCESS
} else
return@map ReasonCode.NO_SUBSCRIPTION_EXISTED
}
val unsuback = if (packet is MQTT5Unsubscribe) {
MQTT5Unsuback(packet.packetIdentifier, reasonCodes)
} else {
MQTT4Unsuback(packet.packetIdentifier)
}
writePacket(unsuback)
}
private fun handlePingreq() {
val packet = if (currentReceivedPacket.mqttVersion == 5) {
MQTT5Pingresp()
} else {
MQTT4Pingresp()
}
writePacket(packet)
}
private fun handleDisconnect(packet: MQTTDisconnect) {
val session = try {
session
} catch (e: Exception) {
null
}
if (packet is MQTT5Disconnect && packet.properties.sessionExpiryInterval != null) {
if (session?.sessionExpiryInterval == 0u && packet.properties.sessionExpiryInterval != 0u) {
disconnect(ReasonCode.PROTOCOL_ERROR)
} else {
session?.sessionExpiryInterval = packet.properties.sessionExpiryInterval!!
close()
}
} else {
if ((packet is MQTT5Disconnect && packet.reasonCode == ReasonCode.SUCCESS) || packet is MQTT4Disconnect)
session?.will = null
close()
}
}
private fun handleAuth(packet: MQTTAuth) {
if (packet is MQTT5Auth) {
val authenticationMethod = packet.properties.authenticationMethod
val clientId = this.clientId ?: throw MQTTException(ReasonCode.IMPLEMENTATION_SPECIFIC_ERROR)
if (!connectCompleted && packet.authenticateReasonCode != ReasonCode.CONTINUE_AUTHENTICATION) {
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
} else if (authenticationMethod == null || authenticationMethod != this.authenticationMethod) {
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
} else {
handleEnhancedAuthentication(clientId, authenticationMethod, packet.properties.authenticationData)
}
} else {
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
}
}
}
| 1
| null |
8
| 82
|
c6d0587bedad9c003a08ff1dea3a8908b45a9552
| 31,080
|
KMQTT
|
MIT License
|
filekit-core/src/jvmMain/kotlin/io/github/vinceglb/filekit/core/platform/xdg/XdgFilePickerPortal.kt
|
vinceglb
| 782,211,616
| false
| null |
package io.github.vinceglb.filekit.core.platform.xdg
import com.sun.jna.Native
import io.github.vinceglb.filekit.core.platform.PlatformFilePicker
import kotlinx.coroutines.CompletableDeferred
import org.freedesktop.dbus.DBusMatchRule
import org.freedesktop.dbus.DBusPath
import org.freedesktop.dbus.Tuple
import org.freedesktop.dbus.annotations.DBusBoundProperty
import org.freedesktop.dbus.annotations.DBusInterfaceName
import org.freedesktop.dbus.annotations.DBusProperty.Access
import org.freedesktop.dbus.annotations.Position
import org.freedesktop.dbus.connections.impl.DBusConnection
import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder
import org.freedesktop.dbus.interfaces.DBusInterface
import org.freedesktop.dbus.interfaces.DBusSigHandler
import org.freedesktop.dbus.interfaces.Properties
import org.freedesktop.dbus.messages.DBusSignal
import org.freedesktop.dbus.types.UInt32
import org.freedesktop.dbus.types.Variant
import java.awt.Window
import java.io.File
import java.net.URI
import java.util.*
//https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.FileChooser.html
internal class XdgFilePickerPortal : PlatformFilePicker {
fun isAvailable(): Boolean {
try {
DBusConnectionBuilder.forSessionBus().build().use { connection ->
connection.getRemoteObject(
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
Properties::class.java
).Get<UInt32>("org.freedesktop.portal.FileChooser", "version")
return true
}
} catch (e: Exception) {
return false
}
}
override suspend fun pickFile(
initialDirectory: String?,
fileExtensions: List<String>?,
title: String?,
parentWindow: Window?
): File? {
return pickFiles(
initialDirectory = initialDirectory,
fileExtensions = fileExtensions,
title = title,
parentWindow = parentWindow,
multiple = false,
directory = false
)?.firstOrNull()
}
override suspend fun pickFiles(
initialDirectory: String?,
fileExtensions: List<String>?,
title: String?,
parentWindow: Window?
): List<File>? {
return pickFiles(
initialDirectory = initialDirectory,
fileExtensions = fileExtensions,
title = title,
parentWindow = parentWindow,
multiple = true,
directory = false
)
}
override suspend fun pickDirectory(
initialDirectory: String?,
title: String?,
parentWindow: Window?
): File? {
return pickFiles(
initialDirectory = initialDirectory,
fileExtensions = null,
title = title,
parentWindow = parentWindow,
multiple = false,
directory = true
)?.firstOrNull()
}
private suspend fun pickFiles(
initialDirectory: String?,
fileExtensions: List<String>?,
title: String?,
parentWindow: Window?,
multiple: Boolean,
directory: Boolean,
): List<File>? {
DBusConnectionBuilder.forSessionBus().build().use { connection ->
val handleToken = UUID.randomUUID().toString().replace("-", "")
val options: MutableMap<String, Variant<*>> = HashMap()
options["handle_token"] = Variant(handleToken)
options["multiple"] = Variant(multiple)
options["directory"] = Variant(directory)
fileExtensions?.let { options["filters"] = createFilterOption(it) }
initialDirectory?.let { options["current_folder"] = createCurrentFolderOption(it) }
val deferredResult = registerResponseHandler(connection, handleToken)
getFileChooserObject(connection).OpenFile(
parentWindow = getWindowIdentifier(parentWindow) ?: "",
title = title ?: "",
options = options
)
val files = deferredResult.await()?.map { File(it) }
return files
}
}
override suspend fun saveFile(
bytes: ByteArray?,
baseName: String,
extension: String,
initialDirectory: String?,
parentWindow: Window?,
): File? {
DBusConnectionBuilder.forSessionBus().build().use { connection ->
val handleToken = UUID.randomUUID().toString().replace("-", "")
val options: MutableMap<String, Variant<*>> = HashMap()
options["handle_token"] = Variant(handleToken)
options["current_name"] = Variant("$baseName.$extension")
initialDirectory?.let { options["current_folder"] = createCurrentFolderOption(it) }
val deferredResult = registerResponseHandler(connection, handleToken)
getFileChooserObject(connection).SaveFile(
parentWindow = getWindowIdentifier(parentWindow) ?: "",
title = "",
options = options
)
val file = deferredResult.await()?.first()?.let { File(it) }
if (bytes != null && file != null) file.writeBytes(bytes)
else file?.createNewFile()
return file
}
}
//https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html
private fun registerResponseHandler(
connection: DBusConnection,
handleToken: String
): CompletableDeferred<List<URI>?> {
val sender = connection.uniqueName.substring(1).replace('.', '_')
val path = "/org/freedesktop/portal/desktop/request/$sender/$handleToken"
val result = CompletableDeferred<List<URI>?>()
val matchRule = DBusMatchRule("signal", "org.freedesktop.portal.Request", "Response")
val handler = ResponseHandler(path) { uris, handler ->
connection.removeGenericSigHandler(matchRule, handler)
result.complete(uris)
}
connection.addGenericSigHandler(matchRule, handler)
return result;
}
private class ResponseHandler(
private val path: String,
private val onComplete: (result: List<URI>?, thisHandler: ResponseHandler) -> Unit
) : DBusSigHandler<DBusSignal> {
@Suppress("UNCHECKED_CAST")
override fun handle(signal: DBusSignal) {
if (path == signal.path) {
val params = signal.parameters
val response = params[0] as UInt32
val results = params[1] as Map<String, Variant<*>>
if (response.toInt() == 0) {
val uris = (results["uris"]!!.value as List<String>).map { URI(it) }
onComplete(uris, this)
} else {
onComplete(null, this)
}
}
}
}
// awt only supports X11
private fun getWindowIdentifier(parentWindow: Window?) = parentWindow?.let { "X11:${Native.getWindowID(it)}" }
private fun getFileChooserObject(connection: DBusConnection) = connection.getRemoteObject(
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
FileChooserDbusInterface::class.java
)
private fun createFilterOption(extensions: List<String>) = Variant(
extensions.map { extension -> Pair(extension, listOf(Pair(0, "*.$extension"))) },
"a(sa(us))"
)
private fun createCurrentFolderOption(currentFolder: String): Variant<*> {
val stringBytes = currentFolder.encodeToByteArray()
val nullTerminated = ByteArray(stringBytes.size + 1)
System.arraycopy(stringBytes, 0, nullTerminated, 0, stringBytes.size);
return Variant(nullTerminated)
}
}
@DBusInterfaceName(value = "org.freedesktop.portal.FileChooser")
@Suppress("FunctionName")
internal interface FileChooserDbusInterface : DBusInterface {
fun OpenFile(parentWindow: String, title: String, options: MutableMap<String, Variant<*>>): DBusPath
fun SaveFile(parentWindow: String, title: String, options: MutableMap<String, Variant<*>>): DBusPath
fun SaveFiles(parentWindow: String, title: String, options: MutableMap<String, Variant<*>>): DBusPath
@DBusBoundProperty(name = "version", access = Access.READ)
fun GetVersion(): UInt32
}
internal class Pair<A, B>(
@field:Position(0) val a: A,
@field:Position(1) val b: B
) : Tuple()
| 7
| null |
16
| 548
|
12c167d5bf53f99f76dba86bcab6a6c8b7306740
| 8,528
|
FileKit
|
MIT License
|
feature/listing/src/main/java/com/utsman/listing/di/provide.kt
|
irmansyah
| 317,537,024
| true
|
{"Kotlin": 124069}
|
/*
* Created by <NAME> on 28/11/20 3:54 PM
* Copyright (c) 2020 . All rights reserved.
*/
package com.utsman.listing.di
import com.utsman.data.repository.list.InstalledAppsRepository
import com.utsman.data.repository.list.PagingAppRepository
import com.utsman.listing.domain.InstalledAppUseCase
import com.utsman.listing.domain.PagingUseCase
import com.utsman.listing.viewmodel.InstalledAppsViewModel
import com.utsman.listing.viewmodel.PagingViewModel
import com.utsman.listing.viewmodel.SearchPagingViewModel
fun providePagingViewModel(pagingUseCase: PagingUseCase): PagingViewModel {
return PagingViewModel(pagingUseCase)
}
fun provideSearchPagingViewModel(pagingUseCase: PagingUseCase): SearchPagingViewModel {
return SearchPagingViewModel(pagingUseCase)
}
fun provideInstalledAppViewModel(installedAppUseCase: InstalledAppUseCase): InstalledAppsViewModel {
return InstalledAppsViewModel(installedAppUseCase)
}
fun providePagingUseCase(pagingAppRepository: PagingAppRepository, installedAppsRepository: InstalledAppsRepository): PagingUseCase {
return PagingUseCase(pagingAppRepository, installedAppsRepository)
}
fun provideInstalledAppUseCase(installedAppsRepository: InstalledAppsRepository): InstalledAppUseCase {
return InstalledAppUseCase(installedAppsRepository)
}
| 0
| null |
0
| 0
|
6e3ed614f5fcfb81a0c879e5aa96e4e4d2a63e68
| 1,305
|
store-apps-mvvm-clean-architecture
|
Apache License 2.0
|
app/src/main/java/br/fatec/miltonio/objetos/semestre_6/Governanca.kt
|
sleiph
| 281,927,072
| false
| null |
package br.fatec.miltonio.objetos.semestre_6
import br.fatec.miltonio.R
import br.fatec.miltonio.modelo.Materia
import br.fatec.miltonio.modelo.Pergunta
import br.fatec.miltonio.modelo.Resposta
class Governanca {
val materia = Materia(
53,
R.string.categ_sem6_ggt,
R.string.categ_sem6_ggt_prof,
6,
0,
R.color.colorAzul,
R.drawable.simb3eap,
R.drawable.fnd3eap,
true,
mutableListOf(
Pergunta(
R.string.sem6_ggt_p1, 1,53,
mutableListOf(
Resposta(R.string.sem6_ggt_p1r1, true, R.string.sem6_ggt_p1),
Resposta(R.string.sem6_ggt_p1r2, false, R.string.sem6_ggt_p1),
Resposta(R.string.sem6_ggt_p1r3, false, R.string.sem6_ggt_p1),
Resposta(R.string.sem6_ggt_p1r4, false, R.string.sem6_ggt_p1)
)
)
)
)
}
| 0
|
Kotlin
|
0
| 3
|
f82a4ae1c19fafc005cb14908ad6b53a0808a421
| 944
|
Miltonio
|
The Unlicense
|
src/main/kotlin/glsl/plugin/annotator/GlslHighlightingAnnotator.kt
|
walt-grace
| 529,402,279
| false
|
{"GLSL": 240725, "Kotlin": 195223, "HTML": 102021, "Lex": 65452, "Java": 50510, "JavaScript": 668}
|
package glsl.plugin.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import glsl.plugin.code.highlighting.GlslTextAttributes
import glsl.plugin.psi.GlslIdentifier
import glsl.plugin.psi.named.GlslNamedElement
import glsl.plugin.psi.named.types.builtins.GlslBuiltinType
import glsl.plugin.utils.GlslBuiltinUtils.isBuiltinConstant
import glsl.plugin.utils.GlslBuiltinUtils.isBuiltinFunction
import glsl.plugin.utils.GlslBuiltinUtils.isBuiltinShaderVariable
import glsl.psi.interfaces.GlslLayoutQualifierId
/**
*
*/
class GlslHighlightingAnnotator : Annotator {
/**
*
*/
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element !is GlslIdentifier || element is GlslBuiltinType) return
val extension = holder.currentAnnotationSession.file.virtualFile.extension
val elementName = element.getName()
if (isBuiltinFunction(elementName) || isBuiltinShaderVariable(elementName, extension)) {
createAnnotation(holder, GlslTextAttributes.BUILTIN_NAME_TEXT_ATTR)
} else if (isBuiltinConstant(elementName)) {
createAnnotation(holder, GlslTextAttributes.BUILTIN_GLOBAL_CONSTANTS)
} else {
val reference = element.reference?.resolve()
if (reference != null) {
setReferenceHighlighting(reference, holder)
} else {
setDeclarationHighlighting(element, holder)
}
}
}
/**
*
*/
private fun setReferenceHighlighting(element: GlslNamedElement, holder: AnnotationHolder) {
val textAttr = element.getHighlightTextAttr()
holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.textAttributes(textAttr)
.create()
}
/**
*
*/
private fun setDeclarationHighlighting(element: GlslIdentifier, holder: AnnotationHolder) {
if (element.parent is GlslLayoutQualifierId) {
createAnnotation(holder, GlslTextAttributes.VARIABLE_TEXT_ATTR)
return
}
val declaration = element.getDeclaration() ?: return
createAnnotation(holder, declaration.getHighlightTextAttr())
}
/**
*
*/
private fun createAnnotation(holder: AnnotationHolder, textAttr: TextAttributesKey?) {
if (textAttr == null) return
holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.textAttributes(textAttr)
.create()
}
}
| 4
|
GLSL
|
10
| 31
|
ccf570f25a39d030c48b39ea0997b646e3ba2846
| 2,679
|
glsl-plugin-idea
|
Apache License 2.0
|
app/src/main/java/ee/oyatl/ime/make/modifiers/ModifierKeyStateSet.kt
|
Lee0701
| 662,239,170
| false
|
{"Kotlin": 210510}
|
package ee.oyatl.ime.make.modifiers
import android.view.KeyEvent
data class ModifierKeyStateSet(
val shift: ModifierKeyState = ModifierKeyState(),
val alt: ModifierKeyState = ModifierKeyState(),
val control: ModifierKeyState = ModifierKeyState(),
val meta: ModifierKeyState = ModifierKeyState()
) {
fun asMetaState(): Int {
return if(shift.active) KeyEvent.META_SHIFT_ON else 0 or
if(alt.active) KeyEvent.META_ALT_ON else 0 or
if(control.active) KeyEvent.META_CTRL_ON else 0 or
if(meta.active) KeyEvent.META_META_ON else 0
}
companion object {
val MODIFIER_KEYS = setOf(
KeyEvent.KEYCODE_SHIFT_LEFT,
KeyEvent.KEYCODE_SHIFT_RIGHT,
KeyEvent.KEYCODE_ALT_LEFT,
KeyEvent.KEYCODE_ALT_RIGHT,
KeyEvent.KEYCODE_CTRL_LEFT,
KeyEvent.KEYCODE_CTRL_RIGHT,
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_META_RIGHT
)
}
}
| 6
|
Kotlin
|
1
| 1
|
e8b1f55203276c83555ed91a82095e16bb52470c
| 1,006
|
make-keyboard
|
Apache License 2.0
|
regex/Asterisk.kt
|
rudy3091
| 312,625,249
| false
| null |
// 정규식 탐색 결과 출력함수
fun walkThrough(matchResult: MatchResult?) {
var m = matchResult
if (m?.value != null) {
print("${m.value}, ")
}
while (m?.next() != null) {
m = m.next()
print("${m?.value}, ")
}
println()
}
// POSIX 표준 정규식
fun main(args: Array<String>) {
var str = "babaabaaabaaaab"
var regex = """a*b""".toRegex()
var matchResult = regex.find(str)
walkThrough(matchResult)
// b, ab, aab, aaab, aaaab
// *: 0회 이상 반복
regex = """a+b""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// ab, aab, aaab, aaaab
// +: 1회 이상 반복
regex = """a?b""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// b, ab, ab, ab, ab
// ?: 0회 또는 1회
regex = """a{2,3}b""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// aab, aaab, aaab
// ** 쉼표 다음에 공백이 있으면 안됨 **
// {m,n}: m회이상 n회 이하 반복
// {m,}: m회이상 반복
// {m}: 정확히 m회 반복
regex = """a.b""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// aab, aab, aab
// .: 문자 하나를 의미
// target string 변경
str = "Asd ASdf 1234"
regex = """[a-z]""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// s, d, d, f
// []: 문자 셋을 의미 -> [abcd]a 는 aa, ba, ca, da를 모두 포함
// 여기서는 a to z, 영어 소문자를 의미
regex = """[A-Za-z]""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// A, s, d, A, S, d, f
// 대문자, 소문자를 의미 - [A-z]와 같은 의미
regex = """[0-9]""".toRegex()
matchResult = regex.find(str)
walkThrough(matchResult)
// 1, 2, 3, 4
// 숫자를 의미
}
| 0
|
Kotlin
|
0
| 0
|
260977e937b3d22017dc96df8d72aa9212883d8b
| 1,508
|
kotlin-til
|
Apache License 2.0
|
repos/cache/src/commonMain/kotlin/dev/inmo/micro_utils/repos/cache/cache/KVCache.kt
|
InsanusMokrassar
| 295,712,640
| false
|
{"Kotlin": 1180314, "Python": 2464, "Shell": 1071}
|
package dev.inmo.micro_utils.repos.cache.cache
import dev.inmo.micro_utils.repos.*
interface KVCache<K, V> : KeyValueRepo<K, V> {
companion object
}
| 15
|
Kotlin
|
3
| 32
|
fecd719239c1aeec1e6454eb7b36645e7b594aff
| 155
|
MicroUtils
|
Apache License 2.0
|
reakt/web/src/main/kotlin/reakt/composites/ModuleSection.kt
|
aSoft-Ltd
| 314,091,136
| false
| null |
package reakt
import kotlinx.css.*
import react.RBuilder
import styled.css
import styled.styledDiv
import theme.clazz
import kotlinx.extensions.onDesktop
import kotlinx.extensions.onMobile
class ModuleSection(
val heading: String,
val modules: List<String>
)
fun RBuilder.ModuleSection(ms: ModuleSection) = Grid { theme ->
styledDiv {
css {
+theme.text.h2.clazz
textAlign = TextAlign.center
}
+ms.heading
}
Grid {
css {
onDesktop {
padding(horizontal = 20.pct)
gridTemplateColumns = GridTemplateColumns("1fr 1fr")
}
onMobile {
padding(0.5.em)
}
}
ms.modules.forEachIndexed { i, it -> styledDiv { +"${i + 1}. $it" } }
}
}
| 1
|
Kotlin
|
1
| 1
|
b6dd915deeea57e13e7977e4b7300c9021990d8b
| 816
|
reakt
|
MIT License
|
serenity-app/src/test/kotlin/us/nineworlds/serenity/ui/video/player/ExoplayerVideoActivityTest.kt
|
NineWorlds
| 7,139,471
| false
| null |
package us.nineworlds.serenity.ui.video.player
import android.net.Uri
import android.view.KeyEvent
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.trackselection.TrackSelectionArray
import com.google.android.exoplayer2.trackselection.TrackSelector
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.whenever
import org.assertj.android.api.Assertions
import org.assertj.core.api.Java6Assertions.assertThat
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.any
import org.mockito.Mockito.doNothing
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.never
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import org.mockito.quality.Strictness.LENIENT
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import toothpick.Scope
import toothpick.Toothpick
import toothpick.config.Module
import us.nineworlds.serenity.TestingModule
import us.nineworlds.serenity.common.annotations.InjectionConstants
import us.nineworlds.serenity.core.logger.Logger
import us.nineworlds.serenity.core.util.AndroidHelper
import us.nineworlds.serenity.core.util.TimeUtil
import us.nineworlds.serenity.injection.AppInjectionConstants
import us.nineworlds.serenity.test.InjectingTest
import us.nineworlds.serenity.test.ShadowSubtitleView
import javax.inject.Inject
@RunWith(RobolectricTestRunner::class)
@Config(shadows = [ShadowSubtitleView::class])
open class ExoplayerVideoActivityTest : InjectingTest() {
@Rule
@JvmField
var mockitoRule: MockitoRule = MockitoJUnit.rule().strictness(LENIENT)
@Mock
lateinit var mockExoPlayerPresenter: ExoplayerPresenter
@Mock
lateinit var mockDataSourceFactory: DataSource.Factory
@Mock
lateinit var mockMappingTrackSelector: TrackSelector
@Mock
lateinit var mockLogger: Logger
@Mock
lateinit var mockPlayer: SimpleExoPlayer
@Mock
lateinit var mockTimeUtil: TimeUtil
@Inject
lateinit var mockAndroidHelper: AndroidHelper
lateinit var activity: ExoplayerVideoActivity
override fun openScope(): Scope {
val scope = Toothpick.openScopes(InjectionConstants.APPLICATION_SCOPE, AppInjectionConstants.EXOPLAYER_SCOPE)
return scope
}
@Before
override fun setUp() {
super.setUp()
activity = Robolectric.buildActivity(ExoplayerVideoActivity::class.java).create().get()
activity.player = mockPlayer
}
@Test
fun bindsSimpleExoPlayerView() {
Assertions.assertThat(activity.playerView).isNotNull
}
@Test
fun onStartDoesNotCallsPresenterPlayBackFromVideoQueueWhenOnAPI19OrHigher() {
activity.onStart()
verify(mockExoPlayerPresenter, never()).playBackFromVideoQueue(anyOrNull())
}
@Test
fun onPauseCallsReleasePlayser() {
val spy = spy(activity)
doNothing().whenever(spy).releasePlayer()
spy.onPause()
verify(spy).releasePlayer()
}
@Test
fun onPauseDoesNotCallsReleasePlayser() {
doReturn(24).whenever(mockAndroidHelper).buildNumber()
val spy = spy(activity)
doNothing().whenever(spy).releasePlayer()
spy.onPause()
verify(spy, never()).releasePlayer()
}
@Test
fun onStopDCallsReleasePlayser() {
doReturn(24).whenever(mockAndroidHelper).buildNumber()
val spy = spy(activity)
doNothing().whenever(spy).releasePlayer()
spy.onStop()
verify(spy).releasePlayer()
}
@Test
fun onStopDoesNotCallsReleasePlayser() {
val spy = spy(activity)
doNothing().whenever(spy).releasePlayer()
spy.onStop()
verify(spy, never()).releasePlayer()
}
@Test
fun buildMediaSourceReturnsNonNullSource() {
assertThat(activity.buildMediaSource(Uri.parse("http://www.example.com/start.mkv"))).isNotNull()
}
@Test
@Ignore
fun initializePlayerSetABunchOfRequiredItems() {
val spy = spy(activity)
doReturn(mockPlayer).whenever(spy).createSimpleExoplayer()
doReturn(TrackSelectionArray()).whenever(mockPlayer).getCurrentTrackSelections()
spy.initializePlayer("http://www.example.com/start.mkv", 0)
assertThat(spy.player).isInstanceOf(SimpleExoPlayer::class.java)
verify(spy).createSimpleExoplayer()
verify(mockPlayer).addListener(any(Player.Listener::class.java))
verify(mockPlayer).prepare(any(MediaSource::class.java))
}
@Test
fun releasePlayerReleasesWhenPlayerIsNotNull() {
activity.releasePlayer()
verify(mockPlayer).release()
}
@Test
fun createSimpleExoplayer() {
assertThat(activity.createSimpleExoplayer()).isNotNull()
}
@Test
fun onBackPressedStopsAndReleasesVideoPlayer() {
doReturn(Player.STATE_READY).whenever(mockPlayer).playbackState
activity.onBackPressed()
verify(mockPlayer).playWhenReady = false
verify(mockExoPlayerPresenter).stopPlaying(anyOrNull())
verify(mockPlayer).clearVideoSurface()
verify(mockPlayer).release()
}
@Test
fun onBackPressedStopsAndReleasesVideoPlayerWhenBuffering() {
doReturn(Player.STATE_BUFFERING).whenever(mockPlayer).playbackState
activity.onBackPressed()
verify(mockPlayer).playWhenReady = false
verify(mockExoPlayerPresenter).stopPlaying(anyOrNull())
verify(mockPlayer).clearVideoSurface()
verify(mockPlayer).release()
}
@Test
fun onKeyCodeDownHandlesHomeEvent() {
doReturn(Player.STATE_BUFFERING).whenever(mockPlayer).playbackState
val result = activity.onKeyDown(KeyEvent.KEYCODE_HOME, null)
assertThat(result).isTrue()
verify(mockPlayer).playWhenReady = false
verify(mockExoPlayerPresenter).stopPlaying(anyOrNull())
verify(mockPlayer).clearVideoSurface()
verify(mockPlayer).release()
}
override fun installTestModules() {
scope.installTestModules(TestingModule(), TestModule())
}
inner class TestModule : Module() {
init {
bind(ExoplayerPresenter::class.java).toInstance(mockExoPlayerPresenter)
bind(DataSource.Factory::class.java).toInstance(mockDataSourceFactory)
bind(TrackSelector::class.java).toInstance(mockMappingTrackSelector)
bind(Logger::class.java).toInstance(mockLogger)
bind(TimeUtil::class.java).toInstance(mockTimeUtil)
}
}
}
| 25
| null |
65
| 177
|
155cfb76bb58f2f06ccac8e3e45151221c59560d
| 6,588
|
serenity-android
|
MIT License
|
compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/plugin/FirAbstractAnnotationResolveTransformer.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.
*/
package org.jetbrains.kotlin.fir.resolve.transformers.plugin
import org.jetbrains.kotlin.fir.FirAnnotationContainer
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.expressions.FirStatement
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.fir.scopes.FirScope
import org.jetbrains.kotlin.fir.scopes.createImportingScopes
import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.fir.visitors.FirDefaultTransformer
internal abstract class FirAbstractAnnotationResolveTransformer<D, S>(
protected val session: FirSession,
protected val scopeSession: ScopeSession
) : FirDefaultTransformer<D>() {
abstract override fun transformAnnotation(annotation: FirAnnotation, data: D): FirStatement
protected lateinit var scopes: List<FirScope>
inline fun <T> withFileScopes(file: FirFile, f: () -> T): T {
scopes = createImportingScopes(file, session, scopeSession, useCaching = false)
val state = beforeTransformingChildren(file)
try {
return f()
} finally {
afterTransformingChildren(state)
}
}
override fun transformFile(file: FirFile, data: D): FirFile {
withFileScopes(file) {
scopes = createImportingScopes(file, session, scopeSession, useCaching = false)
val state = beforeTransformingChildren(file)
file.transformDeclarations(this, data)
afterTransformingChildren(state)
}
return transformDeclaration(file, data) as FirFile
}
override fun transformProperty(property: FirProperty, data: D): FirProperty {
return transformDeclaration(property, data) as FirProperty
}
override fun transformRegularClass(
regularClass: FirRegularClass,
data: D
): FirStatement {
return transformDeclaration(regularClass, data).also {
val state = beforeTransformingChildren(regularClass)
regularClass.transformDeclarations(this, data)
regularClass.transformSuperTypeRefs(this, data)
afterTransformingChildren(state)
} as FirStatement
}
override fun transformSimpleFunction(
simpleFunction: FirSimpleFunction,
data: D
): FirSimpleFunction {
return transformDeclaration(simpleFunction, data).also {
val state = beforeTransformingChildren(simpleFunction)
simpleFunction.transformValueParameters(this, data)
afterTransformingChildren(state)
} as FirSimpleFunction
}
override fun transformConstructor(
constructor: FirConstructor,
data: D
): FirConstructor {
return transformDeclaration(constructor, data).also {
val state = beforeTransformingChildren(constructor)
constructor.transformValueParameters(this, data)
afterTransformingChildren(state)
} as FirConstructor
}
override fun transformValueParameter(
valueParameter: FirValueParameter,
data: D
): FirStatement {
return transformDeclaration(valueParameter, data) as FirStatement
}
override fun transformTypeAlias(typeAlias: FirTypeAlias, data: D): FirTypeAlias {
return transformDeclaration(typeAlias, data) as FirTypeAlias
}
override fun transformTypeRef(typeRef: FirTypeRef, data: D): FirTypeRef {
return transformAnnotationContainer(typeRef, data) as FirTypeRef
}
override fun transformDeclaration(declaration: FirDeclaration, data: D): FirDeclaration {
return transformAnnotationContainer(declaration, data) as FirDeclaration
}
override fun transformAnnotationContainer(
annotationContainer: FirAnnotationContainer,
data: D
): FirAnnotationContainer {
return annotationContainer.transformAnnotations(this, data)
}
override fun <E : FirElement> transformElement(element: E, data: D): E {
return element
}
/**
* Gets called before transforming [parentDeclaration]'s nested declarations (like in a class of a file).
*
* @param parentDeclaration A declaration whose nested declarations are about to be transformed.
* @return Some state of the transformer; when the nested declarations are transformed, this state will be
* passed to the [afterTransformingChildren].
*/
protected open fun beforeTransformingChildren(parentDeclaration: FirDeclaration): S? {
return null
}
/**
* Gets called after performing transformation of some declaration's nested declarations; can be used to restore the internal
* state of the transformer.
*
* @param state A state produced by the [beforeTransformingChildren] call before the transformation.
*/
protected open fun afterTransformingChildren(state: S?) {}
}
| 157
|
Kotlin
|
5209
| 42,102
|
65f712ab2d54e34c5b02ffa3ca8c659740277133
| 5,223
|
kotlin
|
Apache License 2.0
|
libraries/core/src/test/java/com/raxdenstudios/commons/ext/NumberExtensionTest.kt
|
raxden
| 32,153,256
| false
|
{"Kotlin": 182622, "Java": 14061, "Shell": 563}
|
package com.raxdenstudios.commons.core.ext
import org.junit.Assert.assertEquals
import org.junit.Test
internal class NumberExtensionTest {
@Test
fun `Given a Byte null, When orDefault is called Then return default value`() {
val nullValue: Byte? = null
assertEquals(Byte.ZERO, nullValue.orDefault())
assertEquals(1.toByte(), nullValue.orDefault(1.toByte()))
assertEquals(1.toByte(), 1.toByte().orDefault(2.toByte()))
}
@Test
fun `Given a Double null, When orDefault is called Then return default value`() {
val nullValue: Double? = null
assertEquals(Double.ZERO, Double.ZERO, nullValue.orDefault())
assertEquals(1.0, 1.0, nullValue.orDefault(1.0))
assertEquals(1.0, 1.0, 1.0.orDefault(2.0))
}
@Test
fun `Given a Float null, When orDefault is called Then return default value`() {
val nullValue: Float? = null
assertEquals(Float.ZERO, nullValue.orDefault())
assertEquals(1.0f, nullValue.orDefault(1.0f))
assertEquals(1.0f, 1.0f.orDefault(2.0f))
}
@Test
fun `Given a Int null, When orDefault is called Then return default value`() {
val nullValue: Int? = null
assertEquals(Int.ZERO, nullValue.orDefault())
assertEquals(1, nullValue.orDefault(1))
assertEquals(1, 1.orDefault(2))
}
@Test
fun `Given a Long null, When orDefault is called Then return default value`() {
val nullValue: Long? = null
assertEquals(Long.ZERO, nullValue.orDefault())
assertEquals(1, nullValue.orDefault(1))
assertEquals(1, 1.orDefault(2))
}
@Test
fun `Given a Short null, When orDefault is called Then return default value`() {
val nullValue: Short? = null
assertEquals(Short.ZERO, nullValue.orDefault())
assertEquals(1.toShort(), nullValue.orDefault(1.toShort()))
assertEquals(1.toShort(), 1.toShort().orDefault(2.toShort()))
}
}
| 1
|
Kotlin
|
2
| 3
|
957b6a7d6239d3fb75fae5c7d738a0c0f62de2aa
| 1,981
|
android-commons
|
Apache License 2.0
|
reaktive/src/commonMain/kotlin/com/badoo/reaktive/completable/Concat.kt
|
gotamafandy
| 234,538,666
| true
|
{"Kotlin": 805740, "Swift": 3813, "HTML": 1108, "Ruby": 150}
|
package com.badoo.reaktive.completable
import com.badoo.reaktive.base.subscribeSafe
import com.badoo.reaktive.disposable.Disposable
import com.badoo.reaktive.utils.atomic.AtomicInt
fun Iterable<Completable>.concat(): Completable =
completable { emitter ->
val sources = toList()
if (sources.isEmpty()) {
emitter.onComplete()
return@completable
}
val sourceIndex = AtomicInt()
val upstreamObserver =
object : CompletableObserver, CompletableCallbacks by emitter {
override fun onSubscribe(disposable: Disposable) {
emitter.setDisposable(disposable)
}
override fun onComplete() {
sourceIndex
.addAndGet(1)
.let(sources::getOrNull)
?.subscribeSafe(this)
?: emitter.onComplete()
}
}
sources[0].subscribeSafe(upstreamObserver)
}
fun concat(vararg sources: Completable): Completable =
sources
.asIterable()
.concat()
| 0
| null |
0
| 0
|
aec3e70186f91e38d9c411031b97b8acc220af75
| 1,143
|
Reaktive
|
Apache License 2.0
|
app/src/main/java/io/github/mcasper3/prep/recipeviewer/RecipeViewerView.kt
|
mcasper3
| 90,561,284
| false
| null |
package io.github.mcasper3.prep.recipeviewer
import io.github.mcasper3.prep.base.LceView
interface RecipeViewerView : LceView
| 15
|
Kotlin
|
0
| 0
|
397ba370ae5e71e245a60a0763cfb33c2b52a132
| 128
|
Prep
|
Apache License 2.0
|
extension/kotest-property-test/src/test/kotlin/io/github/serpro69/kfaker/tests/KotestPropertyArbsTest.kt
|
serpro69
| 174,969,439
| false
| null |
@file:FakerArb(Faker::class, BFaker::class, EduFaker::class)
package io.github.serpro69.kfaker.tests
import io.github.serpro69.kfaker.Faker
import io.github.serpro69.kfaker.arb
import io.github.serpro69.kfaker.books.BooksFaker
import io.github.serpro69.kfaker.books.arb
import io.github.serpro69.kfaker.books.booksFaker
import io.github.serpro69.kfaker.edu.EduFaker
import io.github.serpro69.kfaker.edu.arb
import io.github.serpro69.kfaker.faker
import io.github.serpro69.kfaker.kotest.FakerArb
import io.github.serpro69.kfaker.randomClass
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.property.Arb
import io.kotest.property.forAll
import io.github.serpro69.kfaker.books.Faker as BFaker
class KotestPropertyArbsTest : DescribeSpec({
describe("Custom kotlin-faker Arbs") {
it("should generate quotes from annotated local variable") {
val b = BooksFaker()
forAll(b.arb.bible.quote()) { q: String ->
q.isNotBlank()
}
val f = Faker()
forAll(f.arb.address.city()) { q ->
q.isNotBlank()
}
forAll(f.arb.address.city(), f.arb.address.streetName()) { city, street ->
city.isNotBlank()
street.isNotBlank()
}
// forAll(f.arb.randomClass.randomInstance<String>()) { q ->
// q.isNotBlank()
// }
// TODO support secondary providers via property, like educator.tertiary
val e = EduFaker()
forAll(e.arb.educator.campus()) { q ->
q.isNotBlank()
}
}
it("should generate quotes from companion object") {
forAll(Arb.booksFaker.bible.quote()) { q: String ->
q.isNotBlank()
}
}
it("should generate addresses from companion object") {
class Address(val city: String, val state: String) {
fun isValid() = city.isNotBlank() && state.isNotBlank()
}
forAll(Arb.faker.address.city(), Arb.faker.address.state()) { city, state ->
Address(city, state).isValid()
}
}
it("should generate random class instance") {
forAll(Arb.randomClass.instance()) { foo: Foo -> foo.bar.s.isNotBlank() }
forAll(
Arb.randomClass.instance<Foo> {
typeGenerator { "hello faker" }
},
) {
it.bar.s == "hello faker"
}
}
it("should generate person with address") {
val f = Faker()
val person: () -> Arb<Person> = {
Arb.randomClass.instance<Person> {
namedParameterGenerator("name") { f.name.name() }
namedParameterGenerator("age") { f.random.nextInt(20, 30) }
}
}
val address: () -> Arb<Address> = {
Arb.randomClass.instance<Address> {
namedParameterGenerator("city") { f.address.city() }
namedParameterGenerator("streetName") { f.address.streetName() }
namedParameterGenerator("streetAddress") { f.address.streetAddress() }
}
}
forAll(person(), address()) { p: Person, a: Address ->
p.name.isNotBlank()
p.age in 20..30
a.city.isNotBlank()
a.streetName.isNotBlank()
a.streetAddress.isNotBlank()
}
}
}
})
class Foo(val bar: Bar)
class Bar(val s: String)
class Person(val name: String, val age: Int)
class Address(val city: String, val streetName: String, val streetAddress: String)
/*
// pseudo-generated code below this line
// core faker
val Arb.Companion.faker get() = ArbFaker(Faker())
val Faker.arb: ArbFaker get() = ArbFaker(this)
class ArbFaker(faker: Faker) {
val address: ArbAddress by lazy { ArbAddress(faker.address) }
val name: ArbName by lazy { ArbName(faker.name) }
}
class ArbAddress(private val address: Address) {
fun city(): Arb<String> = arbitrary { address.city() }
}
class ArbName(private val name: Name) {
fun name(): Arb<String> = arbitrary { name.name() }
}
// books faker
val Arb.Companion.booksFaker get() = ArbBooks(BooksFaker())
val BooksFaker.arb: ArbBooks get() = ArbBooks(this)
class ArbBooks(booksFaker: BooksFaker) {
val bible: ArbBible by lazy { ArbBible(booksFaker.bible) }
}
class ArbBible(private val bible: Bible) {
fun character(): Arb<String> = arbitrary { bible.character() }
fun location(): Arb<String> = arbitrary { bible.location() }
fun quote(): Arb<String> = arbitrary { bible.quote() }
}
*/
| 23
| null |
42
| 452
|
20c85c54f4508ee633d2196ec4e43de591eeea60
| 4,759
|
kotlin-faker
|
MIT License
|
graphs/eacs/src/test/kotlin/com/anaplan/engineering/azuki/graphs/analysis/undirected/ShortestPath.kt
|
anaplan-engineering
| 458,253,960
| false
|
{"Kotlin": 390046, "Groovy": 6043, "Shell": 1385, "CSS": 957}
|
package com.anaplan.engineering.azuki.graphs.analysis.undirected
import com.anaplan.engineering.azuki.core.runner.AnalysisScenario
import com.anaplan.engineering.azuki.graphs.dsl.GraphScenario
import com.anaplan.engineering.azuki.graphs.graphA
class ShortestPath : GraphScenario() {
@AnalysisScenario
fun graphWithEdges() {
given {
thereIsAnUndirectedGraph(graphA) {
edge("a", "b")
edge("b", "c")
edge("a", "d")
edge("d", "e")
edge("e", "c")
}
}
then {
hasShortestPath(graphA, "a", "b", "c")
hasShortestPath(graphA, "e", "c")
}
}
@AnalysisScenario
fun graphWithLongerPath() {
given {
thereIsAnUndirectedGraph(graphA) {
edge("a", "b")
edge("b", "c")
edge("a", "d")
edge("d", "e")
}
}
then {
hasShortestPath(graphA, "e", "d", "a", "b", "c")
}
}
}
| 3
|
Kotlin
|
3
| 2
|
c5fc96c2edef276d1e7fd0077511094488dac663
| 1,066
|
azuki
|
MIT License
|
feature-product/api/src/commonMain/kotlin/apps/amo/paywall/feature/product/api/model/ProductChargeType.kt
|
amomama
| 754,027,977
| false
|
{"Kotlin": 173783, "Swift": 2049}
|
package apps.amo.paywall.feature.product.api.model
enum class ProductChargeType {
OneTimePayment,
Lifetime,
Subscription,
Unknown,
}
| 2
|
Kotlin
|
0
| 0
|
f66c7245f5e8644cac5c3185b60f10a99f4bce13
| 150
|
AmoPaywallBuilder
|
Apache License 2.0
|
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/Filter6TwoTone.kt
|
karakum-team
| 387,062,541
| false
|
{"Kotlin": 3060426, "TypeScript": 2249, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/Filter6TwoTone")
package mui.icons.material
@JsName("default")
external val Filter6TwoTone: SvgIconComponent
| 0
|
Kotlin
|
5
| 35
|
83952a79ffff62f5409461a2928102d0ff95d86b
| 192
|
mui-kotlin
|
Apache License 2.0
|
helperlib/src/main/java/com/itachi1706/helperlib/deprecation/TextViewDep.kt
|
itachi1706
| 230,937,973
| false
|
{"Kotlin": 44930}
|
package com.itachi1706.helperlib.deprecation
import android.content.Context
import android.os.Build
import android.widget.TextView
/**
* Created by Kenneth on 30/12/2019.
* for com.itachi1706.helperlib.deprecation in Helper Library
*/
@Suppress("DEPRECATION")
object TextViewDep {
@JvmStatic
fun setTextAppearance(textView: TextView, context: Context?, resId: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) textView.setTextAppearance(context, resId)
else textView.setTextAppearance(resId)
}
}
| 1
|
Kotlin
|
0
| 1
|
cdc21fa6bfa0486241a2d2a98d91bf2c6a0ec95a
| 536
|
AndroidHelperLib
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/ui/components/TopCard.kt
|
Trak-X
| 343,113,094
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.db.PetObj
import dev.chrisbanes.accompanist.coil.CoilImage
@Composable
fun TopCard(pet: PetObj) {
Column {
CoilImage(
fadeIn = true,
data = pet.pupImgLocation,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier =
Modifier
.height(250.dp)
.clip(
RoundedCornerShape(
topStart = CornerSize(0.dp),
topEnd = CornerSize(0.dp),
bottomEnd = CornerSize(20.dp),
bottomStart = CornerSize(20.dp)
)
)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
426fc10e1e304ce9959127b83193e09ff82fb5d4
| 1,812
|
Petoption
|
Apache License 2.0
|
ui/log/src/main/kotlin/me/gegenbauer/catspy/log/ui/customize/ParseOpParamsEditor.kt
|
Gegenbauer
| 609,809,576
| false
| null |
package me.gegenbauer.catspy.log.ui.customize
import me.gegenbauer.catspy.log.serialize.*
import me.gegenbauer.catspy.strings.STRINGS
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel
fun interface EditEventListener {
fun onEditDone(component: JComponent)
}
interface EditEventSource : Editor {
fun addEditEventListener(listener: EditEventListener)
fun removeEditEventListener(listener: EditEventListener) {}
}
abstract class ParseOpParamsEditor<T : ParseOp> : JPanel(), EditEventSource, Editor {
abstract val parseOp: T
private val editListeners = mutableListOf<EditEventListener>()
var partCount: Int = DEFAULT_MAX_PARTS
set(value) {
field = value
onPartCountChanged(value)
}
fun registerEditorEvents() {
getEditEventObservables().forEach { it.addEditEventListener { notifyEditListeners() } }
}
/**
* Set the maximum number of parts into which the input log line is split
*/
open fun onPartCountChanged(partCount: Int) {
// do nothing by default
}
private fun notifyEditListeners() {
editListeners.forEach { it.onEditDone(this) }
}
override fun addEditEventListener(listener: EditEventListener) {
editListeners.add(listener)
}
override fun startEditing() {
getEditEventObservables().forEach { it.startEditing() }
}
override fun stopEditing() {
getEditEventObservables().forEach { it.stopEditing() }
}
override fun isEditValid(): Boolean {
return getEditEventObservables().all { it.isEditValid() }
}
abstract fun getEditEventObservables(): List<EditEventSource>
companion object {
private const val DEFAULT_MAX_PARTS = 20
}
}
private class NumberParamEditor(tooltip: String? = null, min: Int, max: Int = Int.MAX_VALUE) : ParamEditor(tooltip) {
private var range: Range = Range(min, max)
init {
setRange(min, max)
}
fun setRange(min: Int, max: Int) {
range = Range(min, max)
setVerifier(IntVerifier(min, max))
reVerify()
}
data class Range(val min: Int, val max: Int)
}
private class CharParamEditor(tooltip: String? = null) : ParamEditor(tooltip) {
var value: Char?
get() = text.firstOrNull()
set(value) {
text = value?.toString() ?: ""
}
init {
setVerifier(CharVerifier())
}
}
class EmptyOpParamsEditor(override val parseOp: ParseOp) : ParseOpParamsEditor<ParseOp>() {
override fun getEditEventObservables(): List<EditEventSource> {
return emptyList()
}
}
class SplitByWordSeparatorOpParamsEditor(maxParts: Int) : ParseOpParamsEditor<SplitByWordSeparatorOp>() {
override val parseOp: SplitByWordSeparatorOp
get() = SplitByWordSeparatorOp(maxParts)
private var maxParts: Int = maxParts
get() = editor.text.toIntOrNull() ?: SplitByWordSeparatorOp.DEFAULT_MAX_PARTS
private set(value) {
editor.text = value.toString()
field = value
}
private val label = EditorLabel(STRINGS.ui.wordSeparatorMaxPartsLabel)
private val editor = NumberParamEditor(STRINGS.toolTip.wordSeparatorMaxParts, 0, maxParts)
init {
editor.maximumSize = Dimension(EDITOR_WIDTH, editor.preferredSize.height)
editor.minimumSize = Dimension(EDITOR_WIDTH, editor.preferredSize.height)
add(label)
add(editor)
this.maxParts = maxParts
editor.setRange(0, SplitByWordSeparatorOp.DEFAULT_MAX_PARTS + 1)
}
override fun getEditEventObservables(): List<EditEventSource> {
return listOf(editor)
}
companion object {
private const val EDITOR_WIDTH = 50
}
}
class SplitPartWithCharOpParamsEditor(
char: Char?,
targetPartIndex: Int,
partCount: Int
) : ParseOpParamsEditor<SplitPartWithCharOp>() {
override val parseOp: SplitPartWithCharOp
get() = SplitPartWithCharOp(char, targetPartIndex)
private var char: Char? = char
get() = charEditor.value
private set(value) {
charEditor.value = value
field = value
}
private var targetPartIndex: Int = targetPartIndex
get() = partIndexEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
partIndexEditor.text = value.toString()
field = value
}
private val charLabel = EditorLabel(STRINGS.ui.splitCharLabel)
private val charEditor = CharParamEditor(STRINGS.toolTip.splitChar)
private val targetPartIndexLabel = EditorLabel(STRINGS.ui.targetPartIndexLabel)
private val partIndexEditor = NumberParamEditor(STRINGS.toolTip.targetPartIndex, 0, partCount)
init {
val fieldWidth = 50
partIndexEditor.maximumSize = Dimension(fieldWidth, partIndexEditor.preferredSize.height)
partIndexEditor.minimumSize = Dimension(fieldWidth, partIndexEditor.preferredSize.height)
add(targetPartIndexLabel)
add(partIndexEditor)
charEditor.maximumSize = Dimension(fieldWidth, charEditor.preferredSize.height)
charEditor.minimumSize = Dimension(fieldWidth, charEditor.preferredSize.height)
add(charLabel)
add(charEditor)
this.char = char
this.targetPartIndex = targetPartIndex
}
override fun onPartCountChanged(partCount: Int) {
partIndexEditor.setRange(0, partCount)
}
override fun getEditEventObservables(): List<EditEventSource> {
return listOf(charEditor, partIndexEditor)
}
}
class MergeNearbyPartsOpParamsEditor(
from: Int,
to: Int,
partCount: Int
) : ParseOpParamsEditor<MergeNearbyPartsOp>() {
override val parseOp: MergeNearbyPartsOp
get() = MergeNearbyPartsOp(from, to)
private var from: Int = from
get() = fromEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
fromEditor.text = value.toString()
field = value
}
private var to: Int = to
get() = toEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
toEditor.text = value.toString()
field = value
}
private val fromLabel = EditorLabel(STRINGS.ui.mergeNearByPartsFromIndexLabel)
private val fromEditor = NumberParamEditor(STRINGS.toolTip.mergeNearByPartsFromIndex, 0, partCount)
private val toLabel = EditorLabel(STRINGS.ui.mergeNearByPartsToIndexLabel)
private val toEditor = NumberParamEditor(STRINGS.toolTip.mergeNearByPartsToIndex, 0, partCount)
init {
val fieldWidth = 50
fromEditor.maximumSize = Dimension(fieldWidth, fromEditor.preferredSize.height)
fromEditor.minimumSize = Dimension(fieldWidth, fromEditor.preferredSize.height)
add(fromLabel)
add(fromEditor)
toEditor.maximumSize = Dimension(fieldWidth, toEditor.preferredSize.height)
toEditor.minimumSize = Dimension(fieldWidth, toEditor.preferredSize.height)
add(toLabel)
add(toEditor)
this.from = from
this.to = to.takeIf { it > from } ?: (from + 1)
fromEditor.addEditEventListener {
toEditor.setRange(this.from, this.partCount)
}
toEditor.addEditEventListener {
fromEditor.setRange(0, this.to)
}
}
override fun onPartCountChanged(partCount: Int) {
fromEditor.setRange(0, this.to)
toEditor.setRange(this.from, this.partCount)
}
override fun getEditEventObservables(): List<EditEventSource> {
return listOf(fromEditor, toEditor)
}
}
class MergeUntilCharOpParamsEditor(
start: Int = 0,
partCount: Int,
targetChar: Char? = null,
) : ParseOpParamsEditor<MergeUntilCharOp>() {
override val parseOp: MergeUntilCharOp
get() = MergeUntilCharOp(start, targetChar)
private var start: Int = start
get() = startEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
startEditor.text = value.toString()
field = value
}
private var targetChar: Char? = targetChar
get() = targetCharEditor.value
private set(value) {
targetCharEditor.value = value
field = value
}
private val startLabel = EditorLabel(STRINGS.ui.mergeUntilCharStartIndexLabel)
private val startEditor = NumberParamEditor(STRINGS.toolTip.mergeUntilCharStartIndex, 0, partCount)
private val targetCharLabel = EditorLabel(STRINGS.ui.mergeUntilCharTargetCharLabel)
private val targetCharEditor = CharParamEditor(STRINGS.toolTip.mergeUntilCharTargetChar)
init {
val fieldWidth = 50
startEditor.maximumSize = Dimension(fieldWidth, startEditor.preferredSize.height)
startEditor.minimumSize = Dimension(fieldWidth, startEditor.preferredSize.height)
add(startLabel)
add(startEditor)
targetCharEditor.maximumSize = Dimension(fieldWidth, targetCharEditor.preferredSize.height)
targetCharEditor.minimumSize = Dimension(fieldWidth, targetCharEditor.preferredSize.height)
add(targetCharLabel)
add(targetCharEditor)
this.start = start
this.targetChar = targetChar
}
override fun onPartCountChanged(partCount: Int) {
startEditor.setRange(0, partCount)
}
override fun getEditEventObservables(): List<EditEventSource> {
return listOf(startEditor, targetCharEditor)
}
}
class TrimWithCharOpParamsEditor(
targetPartIndex: Int,
partCount: Int,
leadingChar: Char? = null,
trailingChar: Char? = null,
) : ParseOpParamsEditor<TrimWithCharOp>() {
override val parseOp: TrimWithCharOp
get() = TrimWithCharOp(targetPartIndex, leadingChar, trailingChar)
private var leadingChar: Char? = leadingChar
get() = leadingCharEditor.value
private set(value) {
leadingCharEditor.value = value
field = value
}
private var trailingChar: Char? = trailingChar
get() = trailingCharEditor.value
private set(value) {
trailingCharEditor.value = value
field = value
}
private var targetPartIndex: Int = targetPartIndex
get() = targetPartIndexEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
targetPartIndexEditor.text = value.toString()
field = value
}
private val leadingCharLabel = EditorLabel(STRINGS.ui.trimLeadingCharLabel)
private val leadingCharEditor = CharParamEditor(STRINGS.toolTip.trimLeadingChar)
private val tailingCharLabel = EditorLabel(STRINGS.ui.trimTrailingCharLabel)
private val trailingCharEditor = CharParamEditor(STRINGS.toolTip.trimTrailingChar)
private val targetPartIndexLabel = EditorLabel(STRINGS.ui.targetPartIndexLabel)
private val targetPartIndexEditor = NumberParamEditor(STRINGS.toolTip.targetPartIndex, 0, partCount)
init {
val fieldWidth = 50
targetPartIndexEditor.maximumSize = Dimension(fieldWidth, targetPartIndexEditor.preferredSize.height)
targetPartIndexEditor.minimumSize = Dimension(fieldWidth, targetPartIndexEditor.preferredSize.height)
add(targetPartIndexLabel)
add(targetPartIndexEditor)
leadingCharEditor.maximumSize = Dimension(fieldWidth, leadingCharEditor.preferredSize.height)
leadingCharEditor.minimumSize = Dimension(fieldWidth, leadingCharEditor.preferredSize.height)
add(leadingCharLabel)
add(leadingCharEditor)
trailingCharEditor.maximumSize = Dimension(fieldWidth, trailingCharEditor.preferredSize.height)
trailingCharEditor.minimumSize = Dimension(fieldWidth, trailingCharEditor.preferredSize.height)
add(tailingCharLabel)
add(trailingCharEditor)
this.targetPartIndex = targetPartIndex
this.leadingChar = leadingChar
this.trailingChar = trailingChar
}
override fun onPartCountChanged(partCount: Int) {
targetPartIndexEditor.setRange(0, partCount)
}
override fun getEditEventObservables(): List<EditEventSource> {
return listOf(leadingCharEditor, trailingCharEditor, targetPartIndexEditor)
}
}
class TrimWithIndexOpParamsEditor(
targetPartIndex: Int,
partCount: Int,
removedLeadingCharCount: Int,
removedTrailingCharCount: Int,
) : ParseOpParamsEditor<TrimWithIndexOp>() {
override val parseOp: TrimWithIndexOp
get() = TrimWithIndexOp(targetPartIndex, removedLeadingCharCount, removedTrailingCharCount)
private var targetPartIndex: Int = targetPartIndex
get() = targetPartIndexEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
targetPartIndexEditor.text = value.toString()
field = value
}
private var removedLeadingCharCount: Int = removedLeadingCharCount
get() = removedLeadingCharCountEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
removedLeadingCharCountEditor.text = value.toString()
field = value
}
private var removedTrailingCharCount: Int = removedTrailingCharCount
get() = removedTrailingCharCountEditor.text.toIntOrNull() ?: Int.MAX_VALUE
private set(value) {
removedTrailingCharCountEditor.text = value.toString()
field = value
}
private val targetPartIndexLabel = EditorLabel(STRINGS.ui.targetPartIndexLabel)
private val removedLeadingCharCountLabel = EditorLabel(STRINGS.ui.trimLeadingCharCountLabel)
private val removedTrailingCharCountLabel = EditorLabel(STRINGS.ui.trimTrailingCharCountLabel)
private val targetPartIndexEditor = NumberParamEditor(STRINGS.toolTip.targetPartIndex, 0, partCount)
private val removedLeadingCharCountEditor = NumberParamEditor(STRINGS.toolTip.trimLeadingCharCount, 0, partCount)
private val removedTrailingCharCountEditor = NumberParamEditor(STRINGS.toolTip.trimTrailingCharCount, 0, partCount)
init {
val fieldWidth = 50
targetPartIndexEditor.maximumSize = Dimension(fieldWidth, targetPartIndexEditor.preferredSize.height)
targetPartIndexEditor.minimumSize = Dimension(fieldWidth, targetPartIndexEditor.preferredSize.height)
add(targetPartIndexLabel)
add(targetPartIndexEditor)
removedLeadingCharCountEditor.maximumSize =
Dimension(fieldWidth, removedLeadingCharCountEditor.preferredSize.height)
removedLeadingCharCountEditor.minimumSize =
Dimension(fieldWidth, removedLeadingCharCountEditor.preferredSize.height)
add(removedLeadingCharCountLabel)
add(removedLeadingCharCountEditor)
removedTrailingCharCountEditor.maximumSize =
Dimension(fieldWidth, removedTrailingCharCountEditor.preferredSize.height)
removedTrailingCharCountEditor.minimumSize =
Dimension(fieldWidth, removedTrailingCharCountEditor.preferredSize.height)
add(removedTrailingCharCountLabel)
add(removedTrailingCharCountEditor)
this.targetPartIndex = targetPartIndex
this.removedLeadingCharCount = removedLeadingCharCount
this.removedTrailingCharCount = removedTrailingCharCount
removedLeadingCharCountEditor.addEditEventListener {
removedTrailingCharCountEditor.setRange(0, this.partCount - this.removedLeadingCharCount)
}
removedTrailingCharCountEditor.addEditEventListener {
removedLeadingCharCountEditor.setRange(0, this.partCount - this.removedTrailingCharCount)
}
}
override fun onPartCountChanged(partCount: Int) {
targetPartIndexEditor.setRange(0, partCount)
removedLeadingCharCountEditor.setRange(0, this.partCount - this.removedLeadingCharCount)
removedTrailingCharCountEditor.setRange(0, this.partCount - this.removedTrailingCharCount)
}
override fun getEditEventObservables(): List<EditEventSource> {
return listOf(targetPartIndexEditor, removedLeadingCharCountEditor, removedTrailingCharCountEditor)
}
}
| 3
| null |
4
| 23
|
a868d118c42a9ab0984bfd51ea845d3dcfd16449
| 16,150
|
CatSpy
|
Apache License 2.0
|
aws/sdk-codegen/src/test/kotlin/software/amazon/smithy/rustsdk/customize/IsTruncatedPaginatorTest.kt
|
smithy-lang
| 308,027,791
| false
|
{"Rust": 4428309, "Kotlin": 3842117, "Smithy": 151231, "Python": 62946, "Shell": 49728, "TypeScript": 30713, "Dockerfile": 9790, "JavaScript": 5975, "Harbour": 5848, "Makefile": 5633, "CSS": 982, "RenderScript": 116}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rustsdk.customize
import org.junit.jupiter.api.Test
import software.amazon.smithy.model.shapes.ShapeId
import software.amazon.smithy.model.shapes.StructureShape
import software.amazon.smithy.model.transform.ModelTransformer
import software.amazon.smithy.rust.codegen.client.smithy.traits.IsTruncatedPaginatorTrait
import software.amazon.smithy.rust.codegen.core.rustlang.CargoDependency
import software.amazon.smithy.rust.codegen.core.rustlang.rustTemplate
import software.amazon.smithy.rust.codegen.core.smithy.RuntimeType.Companion.preludeScope
import software.amazon.smithy.rust.codegen.core.testutil.asSmithyModel
import software.amazon.smithy.rust.codegen.core.testutil.integrationTest
import software.amazon.smithy.rust.codegen.core.util.letIf
import software.amazon.smithy.rustsdk.AwsRuntimeType
import software.amazon.smithy.rustsdk.awsSdkIntegrationTest
class IsTruncatedPaginatorTest {
private val model =
"""
namespace test
use aws.protocols#restXml
use aws.api#service
use smithy.rules#endpointRuleSet
@restXml
@service(sdkId: "fake")
@endpointRuleSet({
"version": "1.0",
"rules": [{ "type": "endpoint", "conditions": [], "endpoint": { "url": "https://example.com" } }],
"parameters": {
"Region": { "required": false, "type": "String", "builtIn": "AWS::Region" },
}
})
service TestService {
operations: [PaginatedList]
}
@readonly
@optionalAuth
@http(uri: "/PaginatedList", method: "POST")
@paginated(inputToken: "nextToken", outputToken: "nextToken",
pageSize: "maxResults", items: "items")
operation PaginatedList {
input: GetFoosInput,
output: GetFoosOutput
}
structure GetFoosInput {
maxResults: Integer,
nextToken: String
}
structure GetFoosOutput {
nextToken: String,
items: StringList,
isTruncated: Boolean,
}
list StringList {
member: String
}
""".asSmithyModel()
@Test
fun `isTruncated paginators work`() {
// Adding IsTruncated trait to the output shape
val modifiedModel =
ModelTransformer.create().mapShapes(model) { shape ->
shape.letIf(shape.isStructureShape && shape.toShapeId() == ShapeId.from("test#GetFoosOutput")) {
(it as StructureShape).toBuilder().addTrait(IsTruncatedPaginatorTrait()).build()
}
}
awsSdkIntegrationTest(modifiedModel) { context, rustCrate ->
val rc = context.runtimeConfig
val moduleName = context.moduleUseName()
rustCrate.integrationTest("is_truncated_paginator") {
rustTemplate(
"""
##![cfg(feature = "test-util")]
use $moduleName::Config;
use $moduleName::Client;
use #{Region};
use aws_smithy_runtime::client::http::test_util::{ReplayEvent, StaticReplayClient};
use aws_smithy_types::body::SdkBody;
fn mk_response(part_marker: u8) -> http::Response<SdkBody> {
let (part_num_marker, next_num_marker, is_truncated) = if part_marker < 3 {
(part_marker, part_marker + 1, true)
} else {
(part_marker, 0, false)
};
let body = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
<GetFoosOutput
xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">
<token>{part_num_marker}</token>
<nextToken>{next_num_marker}</nextToken>
<isTruncated>{is_truncated}</isTruncated>
</GetFoosOutput>"
);
http::Response::builder().body(SdkBody::from(body)).unwrap()
}
fn mk_request() -> http::Request<SdkBody> {
http::Request::builder()
.uri("https://some-test-bucket.s3.us-east-1.amazonaws.com/test.txt?part-number-marker=PartNumberMarker&uploadId=UploadId")
.body(SdkBody::empty())
.unwrap()
}
##[#{tokio}::test]
async fn is_truncated_pagination_does_not_loop() {
let http_client = StaticReplayClient::new(vec![
ReplayEvent::new(mk_request(), mk_response(0)),
ReplayEvent::new(mk_request(), mk_response(1)),
ReplayEvent::new(mk_request(), mk_response(2)),
ReplayEvent::new(mk_request(), mk_response(3)),
//The events below should never be called because the pagination should
//terminate with the event above
ReplayEvent::new(mk_request(), mk_response(0)),
ReplayEvent::new(mk_request(), mk_response(1)),
]);
let config = Config::builder()
.region(Region::new("fake"))
.http_client(http_client.clone())
.with_test_defaults()
.build();
let client = Client::from_conf(config);
let list_parts_res = client
.paginated_list()
.max_results(1)
.into_paginator()
.send()
.collect::<Vec<_>>()
.await;
// Confirm that the pagination stopped calling the http client after the
// first page with is_truncated = false
assert_eq!(list_parts_res.len(), 4)
}
""",
*preludeScope,
"tokio" to CargoDependency.Tokio.toType(),
"Region" to AwsRuntimeType.awsTypes(rc).resolve("region::Region"),
)
}
}
}
}
| 300
|
Rust
|
188
| 504
|
8d8e7ab7aa6c3b388ffb2365a29ab03f87c24507
| 6,718
|
smithy-rs
|
Apache License 2.0
|
feature/bestiary/domain/src/commonMain/kotlin/com/nesterov/veld/domain/FetchCreatureListUseCase.kt
|
anaesthez
| 793,406,212
| false
|
{"Kotlin": 213998, "Ruby": 1684, "Swift": 522, "HTML": 275}
|
package com.nesterov.veld.domain
import com.nesterov.veld.common.RequestResult
class FetchCreatureListUseCase(private val repository: BestiaryRepository) {
suspend operator fun invoke(): RequestResult<List<CreatureDomainModel>> =
repository.fetchCreatureList()
}
| 0
|
Kotlin
|
0
| 0
|
4273e340299452c008884a3634b6df1deb25b797
| 276
|
veld
|
MIT License
|
idea/src/org/jetbrains/jet/plugin/intentions/branchedTransformations/intentions/SafeAccessToIfThenIntention.kt
|
chashnikov
| 14,658,474
| 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 org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.intentions.JetSelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.convertToIfNotNullExpression
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceValueForCondition
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableVariable
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStatement
import org.jetbrains.kotlin.psi.*
public class SafeAccessToIfThenIntention : JetSelfTargetingOffsetIndependentIntention<JetSafeQualifiedExpression>("safe.access.to.if.then", javaClass()) {
override fun isApplicableTo(element: JetSafeQualifiedExpression): Boolean = true
override fun applyTo(element: JetSafeQualifiedExpression, editor: Editor) {
val receiver = JetPsiUtil.deparenthesize(element.getReceiverExpression())!!
val selector = JetPsiUtil.deparenthesize(element.getSelectorExpression())
val receiverIsStable = receiver.isStableVariable()
val receiverTemplate = if (receiver is JetBinaryExpression) "(%s)" else "%s"
val receiverAsString = receiverTemplate.format(receiver.getText())
val psiFactory = JetPsiFactory(element)
val dotQualifiedExpression = psiFactory.createExpression("${receiverAsString}.${selector!!.getText()}")
val elseClause = if (element.isStatement()) null else psiFactory.createExpression("null")
val ifExpression = element.convertToIfNotNullExpression(receiver, dotQualifiedExpression, elseClause)
if (!receiverIsStable) {
val valueToExtract = (ifExpression.getThen() as JetDotQualifiedExpression).getReceiverExpression()
ifExpression.introduceValueForCondition(valueToExtract, editor)
}
}
}
| 1
| null |
0
| 1
|
88a261234860ff0014e3c2dd8e64072c685d442d
| 2,521
|
kotlin
|
Apache License 2.0
|
androidsns/app/src/main/java/com/example/android_sns/User.kt
|
mwjng
| 568,067,280
| false
| null |
package com.example.android_sns
class User (
val image : Int, // 이미지
val writer: String, // 글쓴사람 이메일
val id : String, // 글마다 id 부여
val title : String, // 글 제목
val name : String, // 글쓴사람 닉네임
val content : String, // 글내용
val like : Int, // 좋아요 갯수
val date : String // 글 올린 시간
)
| 1
|
Kotlin
|
1
| 0
|
b40ebab3538bd5d31c31c56ea1090f2d3a490b68
| 355
|
Android_SNS
|
MIT License
|
app/src/main/java/io/j99/app/template/di/builder/MainActivityFragmentProvider.kt
|
henjue
| 224,099,805
| false
| null |
package io.j99.app.template.di.builder
import dagger.Module
import dagger.android.ContributesAndroidInjector
import io.j99.app.template.ui.main.view.HomePageFragment
/**
* activity对应的fragment
* 如果该activity有fragment的话
*/
@Module
abstract class MainActivityFragmentProvider {
@ContributesAndroidInjector
abstract fun provideHomePageFragment(): HomePageFragment
}
| 0
|
Kotlin
|
0
| 0
|
7d226ec0884b894865dea8b8bf33fcd6c7f18e3e
| 374
|
app-template
|
MIT License
|
runtime-android/10.2.x/kotlin-extensions/graphic-extensions/GraphicExt.kt
|
Esri
| 19,163,372
| false
| null |
/**
* A function that animates the movement of a marker graphic to provide a
* nice transition of a marker to a new location.
*/
fun Graphic.animatePointGraphic(handler: Handler, destination: Point) {
handler.removeCallbacksAndMessages(null)
val start = SystemClock.uptimeMillis()
val duration: Long = 1000
val graphic = this
val interpolator = LinearInterpolator()
handler.post(object : Runnable {
override fun run() {
val elapsed = SystemClock.uptimeMillis() - start
val t = interpolator.getInterpolation(elapsed.toFloat() / duration)
val lng = t * destination.x + (1 - t) * (graphic.geometry as Point).x
val lat = t * destination.y + (1 - t) * (graphic.geometry as Point).y
graphic.geometry = Point(lng, lat, graphic.geometry.spatialReference)
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16)
}
}
})
}
/**
* The puleGraphicSize method allows developers to pulse a graphic size to show the graphic
* changing and getting larger and smaller between a range.
*/
fun Graphic.pulseGraphicSize(period: Long, min: Float = 2.0f, max: Float = 20.0f) {
val timer = Timer("pulse", false)
timer.scheduleAtFixedRate(SizePulseTimer(this.symbol, min, max), 0, period)
}
/**
*
* This class is used exclusively with the pulseGraphicSize extension function. This allows
* developers to easily pulse a graphic size.
*
*/
private class SizePulseTimer(val symbol: Symbol, val min: Float = 2.0f, val max: Float = 20.0f) : TimerTask() {
var size = 5.0f
var goingDown = true
override fun run() {
when(symbol) {
is SimpleMarkerSymbol -> symbol.size += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.size }
is PictureMarkerSymbol -> {
symbol.height += (if (goingDown) (-.01f) else (.01f))
symbol.width += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.height }
}
is SimpleLineSymbol -> symbol.width += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.width }
is SimpleFillSymbol -> symbol.outline.width += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.outline.width }
}
if (size < min) {
goingDown = false
} else if (size > max) {
goingDown = true
}
}
}
| 8
| null |
164
| 266
|
4fcb1d5cc33de34cce3762d335290bc0356e2e2e
| 2,460
|
developer-support
|
Apache License 2.0
|
mediakit/src/main/java/com/jadyn/mediakit/function/CodeCFunction.kt
|
shanyaodan
| 186,106,040
| true
|
{"Kotlin": 143623, "Java": 16430}
|
package com.jadyn.mediakit.function
import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.util.Log
import android.util.Size
import java.nio.ByteBuffer
/**
*@version:
*@FileDescription:硬编码相关辅助类
*@Author:jing
*@Since:2019/2/12
*@ChangeList:
*/
/*
* 处理MediaCodeC输出队列数据
* */
fun MediaCodec.disposeOutput(bufferInfo: MediaCodec.BufferInfo, defTimeOut: Long,
endStream: () -> Unit = {},
formatChanged: () -> Unit = {},
render: (outputBufferId: Int) -> Unit) {
// 获取可用的输出缓存队列
val outputBufferId = dequeueOutputBuffer(bufferInfo, defTimeOut)
Log.d("disposeOutput", "output buffer id : $outputBufferId ")
if (outputBufferId >= 0) {
// 2019/2/12-22:55 and是位运算 &,转换为二进制进行“与”运算.位数不匹配则都为0
if ((bufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
// 2019/2/12-22:59 bufferInfo无可用缓存
endStream.invoke()
}
render.invoke(outputBufferId)
} else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
formatChanged.invoke()
}
}
/*
* 硬编码获得可用的输入队列
* */
fun MediaCodec.dequeueValidInputBuffer(timeOutUs: Long, input: (inputBufferId: Int, inputBuffer: ByteBuffer) -> Unit): Boolean {
val inputBufferId = dequeueInputBuffer(timeOutUs)
if (inputBufferId >= 0) {
input.invoke(inputBufferId, getInputBuffer(inputBufferId))
return true
}
return false
}
/**
*
* @param needEnd when bufferId is INFO_TRY_AGAIN_LATER, is need to break loop
* */
fun MediaCodec.handleOutputBuffer(bufferInfo: MediaCodec.BufferInfo, defTimeOut: Long,
formatChanged: () -> Unit = {},
render: (bufferId: Int) -> Unit,
needEnd: Boolean = true) {
loopOut@ while (true) {
// 获取可用的输出缓存队列
val outputBufferId = dequeueOutputBuffer(bufferInfo, defTimeOut)
Log.d("handleOutputBuffer", "output buffer id : $outputBufferId ")
if (outputBufferId == MediaCodec.INFO_TRY_AGAIN_LATER) {
if (needEnd) {
break@loopOut
}
} else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
formatChanged.invoke()
} else if (outputBufferId >= 0) {
render.invoke(outputBufferId)
if (bufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
break@loopOut
}
}
}
}
fun createVideoFormat(size: Size, colorFormat: Int = MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,
bitRate: Int, frameRate: Int, iFrameInterval: Int): MediaFormat {
return MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, size.width, size.height)
.apply {
setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat)
setInteger(MediaFormat.KEY_BIT_RATE, bitRate)
setInteger(MediaFormat.KEY_FRAME_RATE, frameRate)
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, iFrameInterval)
}
}
| 0
|
Kotlin
|
0
| 0
|
6e3229fff6bc1415c1c663166412acfaf84f4050
| 3,185
|
MediaLearn
|
Apache License 2.0
|
Novalles/src/main/java/com/flexeiprata/novalles/utils/writingtools/FunHeaderBuilder.kt
|
FlexeiPrata
| 512,871,297
| false
| null |
package com.flexeiprata.novalles.utils.writingtools
internal fun funHeaderBuilder(
extension: String? = null,
name: String,
returnType: String,
vararg args: String
): String {
return StringBuilder().apply {
append("fun ")
extension?.let { append("$extension.") }
append(name)
append(
args.joinToString(
separator = ", ",
prefix = "(",
postfix = ") "
)
)
append(": $returnType")
append(" {")
}.toString()
}
internal fun funHeaderBuilder(
name: String,
isOverridden: Boolean = false,
extension: String? = null,
modifier: String? = null,
returnType: String? = null,
tabs: String = "",
genericString: String = "",
args: List<String>
): String {
return StringBuilder().apply {
val sign = if (args.size > 2) "\n" else ""
if (isOverridden) append("override ")
modifier?.let {
append("$it ")
}
append("fun ")
if (genericString.isNotBlank()) {
append("$genericString ")
}
extension?.let { append("$extension.") }
append(name)
append(
args.joinToString(
separator = ",$sign ",
prefix = "($sign",
postfix = "$sign${tabs.dropLast(1)})"
) { if (args.size > 2) "$tabs$it" else it }
)
returnType?.let {
append(": $returnType")
}
append(" {")
}.toString()
}
internal fun dataClassConstructor(
name: String,
parent: String? = null,
vararg data: String
): String {
return StringBuilder().apply {
append("data class $name")
append(
data.joinToString(
prefix = "(",
separator = ", ",
postfix = ")"
) { "val $it" }
)
parent?.let {
append(": $parent")
}
}.toString()
}
| 0
|
Kotlin
|
0
| 4
|
d871e0e744a35f16c28f22ad9e9429b366e12466
| 2,006
|
Novalles
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/data/Note.kt
|
edsonDeCavalho
| 812,314,880
| false
|
{"Kotlin": 57707, "Swift": 721, "HTML": 305}
|
package data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Classe representant une note
*/
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id : Long =0,
@ColumnInfo(name = "title")
val title : String,
@ColumnInfo(name = "text")
val text :String,
@ColumnInfo(name = "image")
val image :String) {
}
| 0
|
Kotlin
|
0
| 1
|
d2d9d329068c2f326e23519f6327fefa3777d795
| 448
|
Demo_KMP_Room_database
|
MIT License
|
intellij-plugin/Edu-Python/src/com/jetbrains/edu/python/learning/PyCourseBuilder.kt
|
JetBrains
| 43,696,115
| false
|
{"Kotlin": 5014435, "Java": 42267, "Python": 19649, "HTML": 14893, "CSS": 10327, "JavaScript": 302, "Shell": 71}
|
package com.jetbrains.edu.python.learning
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.jetbrains.edu.learning.EduCourseBuilder
import com.jetbrains.edu.learning.LanguageSettings
import com.jetbrains.edu.learning.RefreshCause
import com.jetbrains.edu.learning.courseFormat.Course
import com.jetbrains.edu.learning.newproject.CourseProjectGenerator
import com.jetbrains.edu.python.learning.newproject.PyCourseProjectGenerator
import com.jetbrains.edu.python.learning.newproject.PyLanguageSettings
import com.jetbrains.edu.python.learning.newproject.PyProjectSettings
open class PyCourseBuilder : EduCourseBuilder<PyProjectSettings> {
override fun taskTemplateName(course: Course): String? = PyConfigurator.TASK_PY
override fun mainTemplateName(course: Course): String? = PyConfigurator.MAIN_PY
override fun testTemplateName(course: Course): String? = PyConfigurator.TESTS_PY
override fun getLanguageSettings(): LanguageSettings<PyProjectSettings> = PyLanguageSettings()
override fun getSupportedLanguageVersions(): List<String> = getSupportedVersions()
override fun getCourseProjectGenerator(course: Course): CourseProjectGenerator<PyProjectSettings>? =
PyCourseProjectGenerator(this, course)
override fun refreshProject(project: Project, cause: RefreshCause) {
if (cause == RefreshCause.DEPENDENCIES_UPDATED) {
val projectSdk = ProjectRootManager.getInstance(project).projectSdk ?: return
installRequiredPackages(project, projectSdk)
}
}
}
| 7
|
Kotlin
|
49
| 150
|
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
| 1,548
|
educational-plugin
|
Apache License 2.0
|
src/nl/hannahsten/texifyidea/psi/impl/LatexParameterTextImplMixin.kt
|
Hannah-Sten
| 62,398,769
| false
| null |
package nl.hannahsten.texifyidea.psi.impl
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import nl.hannahsten.texifyidea.lang.commands.LatexGlossariesCommand
import nl.hannahsten.texifyidea.psi.*
import nl.hannahsten.texifyidea.reference.BibtexIdReference
import nl.hannahsten.texifyidea.reference.LatexEnvironmentReference
import nl.hannahsten.texifyidea.reference.LatexGlossaryReference
import nl.hannahsten.texifyidea.reference.LatexLabelParameterReference
import nl.hannahsten.texifyidea.util.isFigureLabel
import nl.hannahsten.texifyidea.util.labels.extractLabelName
import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands
import nl.hannahsten.texifyidea.util.labels.getLabelReferenceCommands
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import nl.hannahsten.texifyidea.util.magic.EnvironmentMagic
import nl.hannahsten.texifyidea.util.parser.firstParentOfType
import nl.hannahsten.texifyidea.util.parser.parentOfType
import nl.hannahsten.texifyidea.util.parser.remove
abstract class LatexParameterTextImplMixin(node: ASTNode) : LatexParameterText, ASTWrapperPsiElement(node) {
/**
* If the normal text is the parameter of a \ref-like command, get the references to the label declaration.
*/
override fun getReferences(): Array<PsiReference> {
// If the command is a label reference
// NOTE When adding options here, also update getNameIdentifier below
return when {
this.project.getLabelReferenceCommands().contains(this.firstParentOfType(LatexCommands::class)?.name) -> {
arrayOf(LatexLabelParameterReference(this))
}
// If the command is a bibliography reference
CommandMagic.bibliographyReference.contains(this.firstParentOfType(LatexCommands::class)?.name) -> {
arrayOf(BibtexIdReference(this))
}
// If the command is an \end command (references to \begin)
this.firstParentOfType(LatexEndCommand::class) != null -> {
arrayOf(LatexEnvironmentReference(this))
}
// If the command is a glossary reference
CommandMagic.glossaryReference.contains(this.firstParentOfType(LatexCommands::class)?.name) -> {
arrayOf(LatexGlossaryReference(this))
}
else -> {
emptyArray<PsiReference>()
}
}
}
/**
* If [getReferences] returns one reference return that one, null otherwise.
*/
override fun getReference(): PsiReference? {
return references.firstOrNull()
}
override fun getNameIdentifier(): PsiElement? {
// Because we do not want to trigger the NonAsciiCharactersInspection when the LatexParameterText is not an identifier
// (think non-ASCII characters in a \section command), we return null here when the this is not an identifier
// It is important not to return null for any identifier, otherwise exceptions like "Throwable: null byMemberInplaceRenamer" may occur
val name = this.firstParentOfType(LatexCommands::class)?.name
val environmentName = this.firstParentOfType(LatexEnvironment::class)?.getEnvironmentName()
if (!CommandMagic.labelReferenceWithoutCustomCommands.contains(name) &&
!CommandMagic.labelDefinitionsWithoutCustomCommands.contains(name) &&
!CommandMagic.bibliographyReference.contains(name) &&
!CommandMagic.labelAsParameter.contains(name) &&
!CommandMagic.glossaryEntry.contains(name) &&
!EnvironmentMagic.labelAsParameter.contains(environmentName) &&
this.firstParentOfType(LatexEndCommand::class) == null &&
this.firstParentOfType(LatexBeginCommand::class) == null
) {
return null
}
return this
}
override fun setName(name: String): PsiElement {
/**
* Build a new PSI this where [old] is replaced with [new] and replace the old PSI this
*/
fun replaceInCommand(command: LatexCommands?, old: String, new: String) {
// This could go wrong in so many cases
val labelText = command?.text?.replaceFirst(old, new) ?: "${command?.name}{$new}"
val newElement = LatexPsiHelper(this.project).createFromText(labelText).firstChild
val oldNode = command?.node
val newNode = newElement.node
if (oldNode == null) {
command?.parent?.node?.addChild(newNode)
}
else {
command.parent.node.replaceChild(oldNode, newNode)
}
}
val command = this.firstParentOfType(LatexCommands::class)
val environment = this.firstParentOfType(LatexEnvironment::class)
// If we want to rename a label
if (
CommandMagic.reference.contains(command?.name) ||
this.project.getLabelDefinitionCommands().contains(command?.name)
) {
// Get a new psi this for the complete label command (\label included),
// because if we replace the complete command instead of just the normal text
// then the indices will be updated, which is necessary for the reference resolve to work
val oldLabel = this.extractLabelName()
replaceInCommand(command, oldLabel, name)
}
else if (CommandMagic.labelAsParameter.contains(command?.name) || EnvironmentMagic.labelAsParameter.contains(
environment?.getEnvironmentName()
)
) {
val helper = LatexPsiHelper(this.project)
// If the label name is inside a group, keep the group
val value = if (this.parentOfType(LatexParameterGroupText::class) != null) {
"{$name}"
}
else {
name
}
helper.setOptionalParameter(command ?: environment!!.beginCommand, "label", value)
}
else if (CommandMagic.glossaryReference.contains(command?.name) || CommandMagic.glossaryEntry.contains(command?.name)) {
// This assumes that glossary entry commands (e.g. \newglossaryentry) as well as glossary references (e.g. \gls)
// have the glossary label as their first required parameter. This is true for all currently supported glossary
// commands, but might change in the future.
if (command != null) {
val glossaryLabel = LatexGlossariesCommand.extractGlossaryLabel(command) ?: ""
replaceInCommand(command, glossaryLabel, name)
}
}
else if (this.firstParentOfType(LatexEndCommand::class) != null || this.firstParentOfType(LatexBeginCommand::class) != null) {
// We are renaming an environment, text in \begin or \end
val newElement = LatexPsiHelper(this.project).createFromText(name).firstChild
val oldNode = this.node
val newNode = newElement.node
this.parent.node.replaceChild(oldNode, newNode)
}
// Else, this is not renamable
return this
}
override fun getName(): String {
return this.text ?: ""
}
override fun delete() {
val cmd = this.parentOfType(LatexCommands::class) ?: return
if (cmd.isFigureLabel()) {
// Look for the NoMathContent that is around the environment, because that is the PsiElement that has the
// whitespace and other normal text as siblings.
cmd.parentOfType(LatexEnvironment::class)
?.parentOfType(LatexNoMathContent::class)
?.remove()
}
}
}
| 99
| null |
87
| 891
|
986550410e2fea91d1e93abfc683db1c8527c9d9
| 7,799
|
TeXiFy-IDEA
|
MIT License
|
core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsUnitTest.kt
|
Baeldung
| 260,481,121
| false
|
{"Kotlin": 1855665, "Java": 48276, "HTML": 4883, "Dockerfile": 292}
|
package com.baeldung.splitlist
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class SplitListIntoPartsUnitTest {
private val evenList = listOf(0, "a", 1, "b", 2, "c");
private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3);
private fun verifyList(resultList: List<List<Any>>) {
assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString())
}
private fun verifyPartialList(resultList: List<List<Any>>) {
assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString())
}
@Test
fun whenChunked_thenListIsSplit() {
val resultList = evenList.chunked(2)
verifyList(resultList)
}
@Test
fun whenUnevenChunked_thenListIsSplit() {
val resultList = unevenList.chunked(2)
verifyPartialList(resultList)
}
@Test
fun whenWindowed_thenListIsSplit() {
val resultList = evenList.windowed(2, 2)
verifyList(resultList)
}
@Test
fun whenUnevenPartialWindowed_thenListIsSplit() {
val resultList = unevenList.windowed(2, 2, partialWindows = true)
verifyPartialList(resultList)
}
@Test
fun whenUnevenWindowed_thenListIsSplit() {
val resultList = unevenList.windowed(2, 2, partialWindows = false)
verifyList(resultList)
}
@Test
fun whenGroupByWithAscendingNumbers_thenListIsSplit() {
val numberList = listOf(1, 2, 3, 4, 5, 6);
val resultList = numberList.groupBy { (it + 1) / 2 }
assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString())
assertEquals("[1, 2, 3]", resultList.keys.toString())
}
@Test
fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() {
val numberList = listOf(1, 2, 3, 4, 5, 6, 7);
val resultList = numberList.groupBy { (it + 1) / 2 }.values
assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString())
}
@Test
fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() {
val numberList = listOf(1, 3, 8, 20, 23, 30);
val resultList = numberList.groupBy { (it + 1) / 2 }
assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString())
assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString())
}
@Test
fun whenWithIndexGroupBy_thenListIsSplit() {
val resultList = evenList.withIndex()
.groupBy { it.index / 2 }
.map { it.value.map { it.value } }
verifyList(resultList)
}
@Test
fun whenWithIndexGroupByUneven_thenListIsSplit() {
val resultList = unevenList.withIndex()
.groupBy { it.index / 2 }
.map { it.value.map { it.value } }
verifyPartialList(resultList)
}
@Test
fun whenFoldIndexed_thenListIsSplit() {
val resultList = evenList.foldIndexed(ArrayList<ArrayList<Any>>(evenList.size / 2)) { index, acc, item ->
if (index % 2 == 0) {
acc.add(ArrayList(2))
}
acc.last().add(item)
acc
}
verifyList(resultList)
}
@Test
fun `when using partition() on a list then a pair of two lists`() {
val numbers = listOf(42, 1984, 1, 0, -4, 23, 100, 6, 8)
val aPairOfList = numbers.partition { it < 42 }
with(aPairOfList) {
assertEquals(listOf(1, 0, -4, 23, 6, 8), first)
assertEquals(listOf(42, 1984, 100), second)
}
val (lessThan42, greaterThanOrEq42) = numbers.partition { it < 42 }
assertEquals(listOf(1, 0, -4, 23, 6, 8), lessThan42)
assertEquals(listOf(42, 1984, 100), greaterThanOrEq42)
}
}
| 14
|
Kotlin
|
294
| 465
|
f1ef5d5ded3f7ddc647f1b6119f211068f704577
| 3,669
|
kotlin-tutorials
|
MIT License
|
kudoku/src/test/kotlin/io/github/ilikeyourhat/kudoku/integration/type/Square1x1Test.kt
|
ILikeYourHat
| 139,063,649
| false
| null |
package com.github.ilikeyourhat.kudoku.integration.type
class Square1x1Test: SudokuTypesTest() {
override val puzzle = """
square_1x1
_
""".trimIndent()
override val solution = """
square_1x1
1
""".trimIndent()
}
| 6
| null |
1
| 1
|
fa522856ed4dd07d5a49e2789fbc880494e83efd
| 288
|
SudokuSolver
|
Apache License 2.0
|
menus/AntKot/app/src/main/java/com/antkot/TopTabActivity.kt
|
themores
| 97,689,860
| false
| null |
package com.antkot
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import com.antkot.tabs.HomeFragment
import com.antkot.tabs.MessageFragment
import kotlinx.android.synthetic.main.activity_top_tab.*
class TopTabActivity : AppCompatActivity() {
var fragmentList: MutableList<BaseFragment> = mutableListOf(HomeFragment(), MessageFragment())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_top_tab)
viewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
override fun getCount(): Int {
return fragmentList.size
}
override fun getItem(position: Int): Fragment? {
return fragmentList[position]
}
override fun getPageTitle(position: Int): CharSequence {
if (position == 0) {
return "首页"
} else {
return "消息"
}
}
}
tablayout.setupWithViewPager(viewPager)
}
}
| 1
|
Kotlin
|
1
| 1
|
d519249de1d10a5f724eed192822e71f71f7510e
| 1,210
|
KotlinDemo
|
Apache License 2.0
|
src/main/kotlin/pl/alpheratzteam/obfuscator/util/StringUtil.kt
|
alpheratzteam
| 204,757,128
| false
| null |
package pl.alpheratzteam.deobfuscator.util
import java.lang.StringBuilder
import java.util.stream.Collectors
import java.util.stream.IntStream
import java.util.concurrent.ThreadLocalRandom
/**
* @author Unix
* @since 17.12.2020
*/
object StringUtil {
private val chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray()
private val javaKeywords = mutableListOf(
"abstract", "boolean", "break", "byte", "case", "catch", "char", "class",
"continue", "default", "do", "while", "for", "if",
"\u0000", "\u0001", "\u0002", "\u0004",
"double", "else", "new", "null", "return", "short",
"super", "static", "switch", "try", "void",
"while", "volatile"
)
// generate custom string
fun generateString(length: Int) = IntStream.range(0, length)
.mapToObj {
Character.toString(
chars[RandomUtil.int(chars.size)]
)
}.collect(Collectors.joining())
// generate unreadable string - Radon be like
fun makeUnreadable(string: String): String {
val stringBuilder = StringBuilder()
string.toCharArray().forEach { stringBuilder.append((it + '\u7159'.toInt())) }
return stringBuilder.toString()
}
fun getStringWithJavaKeywords(length: Int): String {
val stringBuilder = StringBuilder()
for (index in 0..length) {
val keyword = javaKeywords[ThreadLocalRandom.current().nextInt(0, javaKeywords.size)]
when {
index != 24 -> {
stringBuilder.append(keyword).append(" ")
}
else -> {
stringBuilder.append(keyword)
}
}
}
return stringBuilder.toString()
}
}
| 1
| null |
14
| 96
|
a03cc48293a7feb1826581fe5e175cf7ef3ce95c
| 1,827
|
obfuscator
|
MIT License
|
MapboxSearch/sdk/src/test/java/com/mapbox/search/utils/extension/BoundingBoxExtensionTest.kt
|
mapbox
| 438,355,708
| false
|
{"Kotlin": 2247142, "Java": 38877, "Python": 18980, "Shell": 17499}
|
package com.mapbox.search.utils.extension
import com.mapbox.geojson.BoundingBox
import com.mapbox.geojson.Point
import com.mapbox.search.base.utils.extension.mapToCore
import com.mapbox.test.dsl.TestCase
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.TestFactory
internal class BoundingBoxExtensionTest {
@TestFactory
fun `Check mapping BoundingBox to core`() = TestCase {
Given("BoundingBox extension") {
When("Convert <BoundingBox(Point($southwestLatitude, $southwestLongitude), Point($northeastLatitude, $northeastLongitude))> to platform") {
val actualValue = BoundingBox.fromPoints(
Point.fromLngLat(southwestLongitude, southwestLatitude),
Point.fromLngLat(northeastLongitude, northeastLatitude)
).mapToCore()
Then("BoundingBox should be <Point($southwestLongitude, $southwestLatitude, $northeastLongitude, $northeastLatitude)>") {
Assertions.assertEquals(southwestLatitude, actualValue.min.latitude())
Assertions.assertEquals(southwestLongitude, actualValue.min.longitude())
Assertions.assertEquals(northeastLatitude, actualValue.max.latitude())
Assertions.assertEquals(northeastLongitude, actualValue.max.longitude())
}
}
}
}
private companion object {
private const val southwestLatitude = 53.0
private const val southwestLongitude = 27.0
private const val northeastLatitude = 54.0
private const val northeastLongitude = 28.0
}
}
| 18
|
Kotlin
|
7
| 33
|
bbe22d4d17e8bab22b64c7327fafdd56be7a03e4
| 1,641
|
mapbox-search-android
|
Apache License 2.0
|
src/main/java/io/github/intellij/dlanguage/codeinsight/DCompletionContributor.kt
|
ErnyTech
| 146,434,208
| false
|
{"Gradle": 2, "Java Properties": 4, "Markdown": 4, "Shell": 1, "Text": 595, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "INI": 4, "Java": 667, "D": 948, "Makefile": 23, "DTrace": 5, "JSON": 3, "Kotlin": 117, "XML": 10, "JFlex": 2, "HTML": 11}
|
package io.github.intellij.dlanguage.codeinsight
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.Function
import com.intellij.util.ProcessingContext
import io.github.intellij.dlanguage.DLanguage
import io.github.intellij.dlanguage.codeinsight.dcd.DCDCompletionClient
import io.github.intellij.dlanguage.codeinsight.dcd.completions.DCDModel
import io.github.intellij.dlanguage.codeinsight.render.BasicRenderer
import io.github.intellij.dlanguage.icons.DlangIcons
class DCompletionContributor : CompletionContributor()
{
private val dcdCompletionClient = DCDCompletionClient()
init
{
extend(CompletionType.BASIC,
PlatformPatterns.psiElement().withLanguage(DLanguage),
object : CompletionProvider<CompletionParameters>()
{
public override fun addCompletions(parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet)
{
val position = parameters.editor.caretModel.offset
val file = parameters.originalFile
for (model in dcdCompletionClient.autoComplete(position, file))
{
result.addElement(BasicRenderer(model))
}
}
}
)
}
class DCDCompletionProvider : CompletionProvider<CompletionParameters>()
{
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet)
{
}
}
/**
* Adjust the error message when no lookup is found.
*/
override fun handleEmptyLookup(parameters: CompletionParameters, editor: Editor?): String?
{
return "DLanguage: no completion found."
}
companion object
{
fun createLookupElement(name: String, module: String, type: String): LookupElement
{
return LookupElementBuilder.create(name).withIcon(DlangIcons.FILE)
// .withTailText(" (" + module + ')', true)
.withTypeText(type)
}
val stringToLookupElement: Function<String, LookupElement> = Function { s -> LookupElementBuilder.create(s).withIcon(DlangIcons.FILE) }
}
}
| 1
| null |
1
| 1
|
b0fcc09ebe4287d60a1d35ba9e4387564e30a42d
| 2,778
|
intellij-dlanguage
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/BootstraplessSynthesizerDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 70198112}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.BootstraplessSynthesizer
/**
* Synthesizer that reuses bootstrap roles from a different region.
*
* A special synthesizer that behaves similarly to `DefaultStackSynthesizer`, but doesn't require
* bootstrapping the environment it operates in. Instead, it will re-use the Roles that were created
* for a different region (which is possible because IAM is a global service).
*
* However, it will not assume asset buckets or repositories have been created, and therefore does
* not support assets.
*
* The name is poorly chosen -- it does still require bootstrapping, it just does not support
* assets.
*
* Used by the CodePipeline construct for the support stacks needed for cross-region replication S3
* buckets. App builders do not need to use this synthesizer directly.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.*;
* BootstraplessSynthesizer bootstraplessSynthesizer = BootstraplessSynthesizer.Builder.create()
* .cloudFormationExecutionRoleArn("cloudFormationExecutionRoleArn")
* .deployRoleArn("deployRoleArn")
* .build();
* ```
*/
@CdkDslMarker
public class BootstraplessSynthesizerDsl {
private val cdkBuilder: BootstraplessSynthesizer.Builder =
BootstraplessSynthesizer.Builder.create()
/**
* The CFN execution Role ARN to use.
*
* Default: - No CloudFormation role (use CLI credentials)
*
* @param cloudFormationExecutionRoleArn The CFN execution Role ARN to use.
*/
public fun cloudFormationExecutionRoleArn(cloudFormationExecutionRoleArn: String) {
cdkBuilder.cloudFormationExecutionRoleArn(cloudFormationExecutionRoleArn)
}
/**
* The deploy Role ARN to use.
*
* Default: - No deploy role (use CLI credentials)
*
* @param deployRoleArn The deploy Role ARN to use.
*/
public fun deployRoleArn(deployRoleArn: String) {
cdkBuilder.deployRoleArn(deployRoleArn)
}
public fun build(): BootstraplessSynthesizer = cdkBuilder.build()
}
| 3
|
Kotlin
|
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 2,472
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
incubator.clients.kroviz/src/test/kotlin/org/apache/isis/client/kroviz/IconManagerTest.kt
|
joerg-rade
| 163,651,410
| false
| null |
package org.apache.isis.client.kroviz.ui
import org.apache.isis.client.kroviz.utils.IconManager
import kotlin.test.Test
import kotlin.test.assertEquals
class IconManagerTest {
@Test
fun testFind() {
//given
val name = "OK"
val expected = "fas fa-check"
//when
val actual = IconManager.find(name)
//
assertEquals(expected, actual)
}
}
| 20
| null |
1
| 10
|
07e7ed9aa6dabc7e8a9a0100451d89ae18e46950
| 406
|
kroviz
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/events/BasicAuthParametersPropertyDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.events
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.events.CfnConnection
@Generated
public fun buildBasicAuthParametersProperty(initializer: @AwsCdkDsl
CfnConnection.BasicAuthParametersProperty.Builder.() -> Unit):
CfnConnection.BasicAuthParametersProperty =
CfnConnection.BasicAuthParametersProperty.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
a1cf8fbfdfef9550b3936de2f864543edb76348b
| 487
|
aws-cdk-kt
|
Apache License 2.0
|
model/src/main/kotlin/org/digma/intellij/plugin/model/rest/insights/SpanScalingInsight.kt
|
digma-ai
| 472,408,329
| false
| null |
package org.digma.intellij.plugin.model.rest.insights
import com.fasterxml.jackson.annotation.JsonCreator
import org.digma.intellij.plugin.model.InsightType
import java.beans.ConstructorProperties
import java.util.*
import kotlin.collections.ArrayList
data class SpanScalingInsight
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
@ConstructorProperties(
"codeObjectId",
"environment",
"scope",
"importance",
"decorators",
"actualStartTime",
"customStartTime",
"prefixedCodeObjectId",
"shortDisplayInfo",
"spanName",
"spanInstrumentationLibrary",
"turningPointConcurrency",
"maxConcurrency",
"minDuration",
"maxDuration",
"rootCauseSpans"
)
constructor(
override val codeObjectId: String,
override val environment: String,
override val scope: String,
override val importance: Int,
override val decorators: List<CodeObjectDecorator>?,
override val actualStartTime: Date?,
override val customStartTime: Date?,
override val prefixedCodeObjectId: String?,
override val shortDisplayInfo: ShortDisplayInfo?,
val spanName: String,
val spanInstrumentationLibrary: String,
val turningPointConcurrency: Int,
val maxConcurrency: Int,
val minDuration: Duration,
val maxDuration: Duration,
val rootCauseSpans: List<RootCauseSpan> = ArrayList()
) : CodeObjectInsight {
override val type: InsightType = InsightType.SpanScaling
}
| 144
|
Kotlin
|
2
| 2
|
313aba39169fd1aca71955f3934c7260dd36c695
| 1,576
|
digma-intellij-plugin
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.