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
core/src/main/java/me/kwsk/odptlibrary/core/api/OdptTrainApiClient.kt
teracy
115,876,824
false
null
package me.kwsk.odptlibrary.core.api import io.reactivex.Single import me.kwsk.odptlibrary.core.api.train.* import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query import javax.inject.Inject import javax.inject.Singleton /** * 鉄道API */ @Singleton class OdptTrainApiClient @Inject constructor(private val consumerKey: String, private val odptTrainApiService: OdptTrainApiService) { /** * 駅別乗降人員取得 * @param odptId データに付与された固有識別子 * @param operator 事業者情報 odpt:Operatorを示すID(odpt:Operatorのowl:sameAs) * @param railway 路線情報 odpt:Railwayを示すID(odpt:Railwayのowl:sameAs) * @param station 駅情報 odpt:Stationを示すID(odpt:Stationのowl:sameAs) * @param surveyYear 調査年(西暦) * @param sameAs データに付与された固有識別子の別名 * @return 駅別乗降人員リスト */ fun getPassengerSurvey(odptId: String? = null, operator: String? = null, railway: String? = null, station: String? = null, surveyYear: Int? = null, sameAs: String? = null): Single<List<OdptPassengerSurveyResponse>> { return odptTrainApiService.getPassengerSurvey(consumerKey, odptId, operator, railway, station, surveyYear, sameAs) } /** * 路線情報取得 * @param odptId データに付与された固有識別子 * @param title 路線名(e.g. 小田原線、京王線、相模原線) * @param lineCode 路線コード、路線シンボル表記を格納(e.g. 小田原線 => OH、丸ノ内線=>M) * @param operator 事業者ID(e.g. 小田急電鉄: odpt.Operator:Odakyu) * @param sameAs データに付与された固有識別子の別名 * @return 路線情報リスト */ fun getRailway(odptId: String? = null, title: String? = null, lineCode: String? = null, operator: String? = null, sameAs: String? = null): Single<List<OdptRailwayResponse>> { return odptTrainApiService.getRailway(consumerKey, odptId, title, lineCode, operator, sameAs) } /** * 運賃情報取得 * @param odptId データに付与された固有識別子 * @param fromStation 起点となる駅のID * @param operator 事業者ID(e.g. 小田急電鉄: odpt.Operator:Odakyu) * @param toStation 着点となる駅のID * @param sameAs データに付与された固有識別子の別名 * @return 運賃情報リスト */ fun getRailwayFare(odptId: String? = null, fromStation: String? = null, operator: String? = null, toStation: String? = null, sameAs: String? = null): Single<List<OdptRailwayFareResponse>> { return odptTrainApiService.getRailwayFare(consumerKey, odptId, fromStation, operator, toStation, sameAs) } /** * 駅情報取得 * @param odptId データに付与された固有識別子 * @param title 駅名(e.g. 東京、新宿、上野) * @param operator 事業者ID(e.g. 小田急電鉄: odpt.Operator:Odakyu) * @param railway 駅が存在する路線ID(e.g. 小田急小田原線: odpt.Railway:Odakyu.Odawara) * @param stationCode 駅ナンバリング(e.g. OH01=小田急新宿駅) * @param sameAs データに付与された固有識別子の別名 * @return 駅情報リスト */ fun getStation(odptId: String? = null, title: String? = null, operator: String? = null, railway: String? = null, stationCode: String? = null, sameAs: String? = null): Single<List<OdptStationResponse>> { return odptTrainApiService.getStation(consumerKey, odptId, title, operator, railway, stationCode, sameAs) } /** * 駅時刻表取得 * @param odptId データに付与された固有識別子 * @param date 特定日付の時刻表を取得 * @param calendar 実施日 odpt:Calendarを示すID(odpt:Calendarのowl:sameAs) * @param operator 事業者情報 odpt:Operatorを示すID(odpt:Operatorのowl:sameAs) * @param railDirection 進行方向 odpt:RailDirectionを示すID(odpt:RailDirectionのowl:sameAs) * @param railway 路線情報 odpt:Railwayを示すID(odpt:Railwayのowl:sameAs) * @param station 駅情報 odpt:Stationを示すID(odpt:Stationのowl:sameAs) * @param sameAs データに付与された固有識別子の別名 * @return 駅時刻表リスト */ fun getStationTimetable(odptId: String? = null, date: String? = null, calendar: String? = null, operator: String? = null, railDirection: String? = null, railway: String? = null, station: String? = null, sameAs: String? = null): Single<List<OdptStationTimetableResponse>> { return odptTrainApiService.getStationTimetable(consumerKey, odptId, date, calendar, operator, railDirection, railway, station, sameAs) } // NOTE: sameAsはAPI仕様にはないが、応答に含まれている以上利用できると判断し、実際利用できたため追加した /** * 列車情報取得 * @param operator 列車情報を配信する事業者のID * @param railway 当該列車が運行している路線のID * @param sameAs データに付与された固有識別子の別名 * @return 列車情報リスト */ fun getTrain(operator: String? = null, railway: String? = null, sameAs: String? = null): Single<List<OdptTrainResponse>> { return odptTrainApiService.getTrain(consumerKey, operator, railway, sameAs) } /** * 運行情報取得 * @param operator 運行情報を配信する事業者のID * @param railway 運行情報が発生した路線のID * @return 運行情報リスト */ fun getTrainInformation(operator: String? = null, railway: String? = null): Single<List<OdptTrainInformationResponse>> { return odptTrainApiService.getTrainInformation(consumerKey, operator, railway) } // NOTE: optionalになっている項目でも極力強制(できれば列車IDだけでも)しないとUXに大きく影響するので注意 /** * 列車時刻表取得 * @param odptId 固有識別子 * @param calendar 特定のカレンダー情報ID * @param operator 運行事業者のID * @param railway 路線のID * @param train 該当する列車ID * @param trainNumber 列車番号、運行管理に用いられる運用番号 * @param trainType 列車種別ID * @param sameAs 固有識別子別名 * @return 列車時刻表リスト */ fun getTrainTimetable(odptId: String? = null, calendar: String? = null, operator: String? = null, railway: String? = null, train: String? = null, trainNumber: String? = null, trainType: String? = null, sameAs: String? = null): Single<List<OdptTrainTimetableResponse>> { return odptTrainApiService.getTrainTimetable(consumerKey, odptId, calendar, operator, railway, train, trainNumber, trainType, sameAs) } } interface OdptTrainApiService { /** * 駅別乗降人員取得 * @param consumerKey APIアクセス用のアクセストークン * @param odptId データに付与された固有識別子 * @param operator 事業者情報 odpt:Operatorを示すID(odpt:Operatorのowl:sameAs) * @param railway 路線情報 odpt:Railwayを示すID(odpt:Railwayのowl:sameAs) * @param station 駅情報 odpt:Stationを示すID(odpt:Stationのowl:sameAs) * @param surveyYear 調査年(西暦) * @param sameAs データに付与された固有識別子の別名 * @return 駅別乗降人員リスト */ @Headers("connection: close") @GET("/api/v4/odpt:PassengerSurvey") fun getPassengerSurvey(@Query("acl:consumerKey") consumerKey: String, @Query("@id") odptId: String?, @Query("odpt:operator") operator: String?, @Query("odpt:railway") railway: String?, @Query("odpt:station") station: String?, @Query("odpt:surveyYear") surveyYear: Int?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptPassengerSurveyResponse>> /** * 路線情報取得 * @param consumerKey APIアクセス用のアクセストークン * @param odptId データに付与された固有識別子 * @param title 路線名(e.g. 小田原線、京王線、相模原線) * @param lineCode 路線コード、路線シンボル表記を格納(e.g. 小田原線 => OH、丸ノ内線=>M) * @param operator 事業者ID(e.g. 小田急電鉄: odpt.Operator:Odakyu) * @param sameAs データに付与された固有識別子の別名 * @return 路線情報リスト */ @Headers("connection: close") @GET("/api/v4/odpt:Railway") fun getRailway(@Query("acl:consumerKey") consumerKey: String, @Query("@id") odptId: String?, @Query("dc:title") title: String?, @Query("odpt:lineCode") lineCode: String?, @Query("odpt:operator") operator: String?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptRailwayResponse>> /** * 運賃情報取得 * @param consumerKey APIアクセス用のアクセストークン * @param odptId データに付与された固有識別子 * @param fromStation 起点となる駅のID * @param operator 事業者ID(e.g. 小田急電鉄: odpt.Operator:Odakyu) * @param toStation 着点となる駅のID * @param sameAs データに付与された固有識別子の別名 * @return 運賃情報リスト */ @Headers("connection: close") @GET("/api/v4/odpt:RailwayFare") fun getRailwayFare(@Query("acl:consumerKey") consumerKey: String, @Query("@id") odptId: String?, @Query("odpt:fromStation") fromStation: String?, @Query("odpt:operator") operator: String?, @Query("odpt:toStation") toStation: String?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptRailwayFareResponse>> /** * 駅情報取得 * @param consumerKey APIアクセス用のアクセストークン * @param odptId データに付与された固有識別子 * @param title 駅名(e.g. 東京、新宿、上野) * @param operator 事業者ID(e.g. 小田急電鉄: odpt.Operator:Odakyu) * @param railway 駅が存在する路線ID(e.g. 小田急小田原線: odpt.Railway:Odakyu.Odawara) * @param stationCode 駅ナンバリング(e.g. OH01=小田急新宿駅) * @param sameAs データに付与された固有識別子の別名 * @return 駅情報リスト */ @Headers("connection: close") @GET("/api/v4/odpt:Station") fun getStation(@Query("acl:consumerKey") consumerKey: String, @Query("@id") odptId: String?, @Query("dc:title") title: String?, @Query("odpt:operator") operator: String?, @Query("odpt:railway") railway: String?, @Query("odpt:stationCode") stationCode: String?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptStationResponse>> /** * 駅時刻表取得 * @param consumerKey APIアクセス用のアクセストークン * @param odptId データに付与された固有識別子 * @param date 特定日付の時刻表を取得 * @param calendar 実施日 odpt:Calendarを示すID(odpt:Calendarのowl:sameAs) * @param operator 事業者情報 odpt:Operatorを示すID(odpt:Operatorのowl:sameAs) * @param railDirection 進行方向 odpt:RailDirectionを示すID(odpt:RailDirectionのowl:sameAs) * @param railway 路線情報 odpt:Railwayを示すID(odpt:Railwayのowl:sameAs) * @param station 駅情報 odpt:Stationを示すID(odpt:Stationのowl:sameAs) * @param sameAs データに付与された固有識別子の別名 * @return 駅時刻表リスト */ @Headers("connection: close") @GET("/api/v4/odpt:StationTimetable") fun getStationTimetable(@Query("acl:consumerKey") consumerKey: String, @Query("@id") odptId: String?, @Query("dc:date") date: String?, @Query("odpt:calendar") calendar: String?, @Query("odpt:operator") operator: String?, @Query("odpt:railDirection") railDirection: String?, @Query("odpt:railway") railway: String?, @Query("odpt:station") station: String?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptStationTimetableResponse>> // NOTE: sameAsはAPI仕様にはないが、応答に含まれている以上利用できると判断し、実際利用できたため追加した /** * 列車情報取得 * @param consumerKey APIアクセス用のアクセストークン * @param operator 列車情報を配信する事業者のID * @param railway 当該列車が運行している路線のID * @return 列車情報リスト */ @Headers("connection: close") @GET("/api/v4/odpt:Train") fun getTrain(@Query("acl:consumerKey") consumerKey: String, @Query("odpt:operator") operator: String?, @Query("odpt:railway") railway: String?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptTrainResponse>> /** * 運行情報取得 * @param consumerKey APIアクセス用のアクセストークン * @param operator 運行情報を配信する事業者のID * @param railway 運行情報が発生した路線のID * @return 運行情報リスト */ @Headers("connection: close") @GET("/api/v4/odpt:TrainInformation") fun getTrainInformation(@Query("acl:consumerKey") consumerKey: String, @Query("odpt:operator") operator: String?, @Query("odpt:railway") railway: String?): Single<List<OdptTrainInformationResponse>> /** * 列車時刻表取得 * @param odptId 固有識別子 * @param consumerKey APIアクセス用のアクセストークン * @param calendar 特定のカレンダー情報ID * @param operator 運行事業者のID * @param railway 路線のID * @param train 該当する列車ID * @param trainNumber 列車番号、運行管理に用いられる運用番号 * @param trainType 列車種別ID * @param sameAs 固有識別子別名 * @return 列車時刻表リスト */ @Headers("connection: close") @GET("/api/v4/odpt:TrainTimetable") fun getTrainTimetable(@Query("acl:consumerKey") consumerKey: String, @Query("@id") odptId: String?, @Query("odpt:calendar") calendar: String?, @Query("odpt:operator") operator: String?, @Query("odpt:railway") railway: String?, @Query("odpt:train") train: String?, @Query("odpt:trainNumber") trainNumber: String?, @Query("odpt:trainType") trainType: String?, @Query("owl:sameAs") sameAs: String?): Single<List<OdptTrainTimetableResponse>> }
0
null
0
5
b3fa9249598148fc9cca0574cb62998e42b538f9
12,812
OdptLibrary
Apache License 2.0
nebulosa-indi-protocol/src/main/kotlin/nebulosa/indi/protocol/DefNumber.kt
tiagohm
568,578,345
false
{"Kotlin": 2712371, "TypeScript": 513759, "HTML": 249483, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 445}
package nebulosa.indi.protocol import nebulosa.indi.protocol.INDIProtocol.Companion.writeXML import java.io.PrintStream data class DefNumber( override var name: String = "", override var label: String = name, override var value: Double = 0.0, var format: String = "", // TODO: Support sexagesimal format conversion. override var max: Double = 0.0, override var min: Double = 0.0, var step: Double = 0.0, ) : DefElement<Double>, NumberElement { override fun writeTo(stream: PrintStream) = stream.writeXML( "defNumber", value, "name", name, "label", label, "format", format, "min", min, "max", max, "step", step, ) }
26
Kotlin
2
4
4d398242b1ddf95b48fe95de47a2bcb01f6ff0a6
710
nebulosa
MIT License
src/test/java/de/fraunhofer/aisec/cpg/graph/QueryTest.kt
karthikswarna
339,977,118
true
{"Java": 1253578, "C++": 31052, "Kotlin": 27638, "C": 2181, "CMake": 204}
package de.fraunhofer.aisec.cpg.graph import de.fraunhofer.aisec.cpg.ExperimentalGraph import de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration import de.fraunhofer.aisec.cpg.graph.declarations.ParamVariableDeclaration import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge import de.fraunhofer.aisec.cpg.graph.types.UnknownType import de.fraunhofer.aisec.cpg.helpers.Benchmark import org.junit.jupiter.api.BeforeAll import org.opencypher.v9_0.ast.Query import org.opencypher.v9_0.parser.CypherParser import java.util.stream.Collector import java.util.stream.Collectors import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlin.time.ExperimentalTime import kotlin.time.milliseconds @ExperimentalGraph @ExperimentalTime class QueryTest { @Test fun testQueryExistenceOfEdge() { val query = parser.parse("MATCH (n:FunctionDeclaration)-[:PARAMETERS]->(m:ParamVariableDeclaration) RETURN n", null) as Query var nodes: List<Node> = db.executeQuery(query) assertEquals(2, nodes.size) var b: Benchmark = Benchmark(QueryTest::class.java, "something else - stream version") val variables: MutableMap<String, MutableList<Node>> = mutableMapOf() variables["n"] = mutableListOf() variables["m"] = mutableListOf() variables["n"] = db.nodes.parallelStream() .filter { it is FunctionDeclaration } .filter { val parameters = PropertyEdge.unwrap(it["parameters", "OUTGOING"] as List<PropertyEdge<Node>>) val params = parameters.parallelStream().filter { it is ParamVariableDeclaration }.collect(Collectors.toList()) variables["m"]?.addAll(params) params.isNotEmpty() } .collect(Collectors.toList()) nodes = variables["n"]!! assertEquals(2, nodes.size) b.stop() println("Experimental query2 took: ${b.duration.milliseconds}") b = Benchmark(QueryTest::class.java, "something else") variables["n"] = mutableListOf() variables["m"] = mutableListOf() for(node in db.nodes) { if(node is FunctionDeclaration) { val parameters = PropertyEdge.unwrap(node["parameters", "OUTGOING"] as List<PropertyEdge<Node>>) for(parameter in parameters) { if(parameter is ParamVariableDeclaration) { variables["m"]?.plusAssign(parameter) } } if(parameters.isNotEmpty()) { variables["n"]?.plusAssign(node) } } } nodes = variables["n"]!! assertEquals(2, nodes.size) b.stop() println("Experimental query2 took: ${b.duration.milliseconds}") } @Test fun testQueryExistenceOfEdgeOtherVar() { val query = parser.parse("MATCH (n:FunctionDeclaration)-[:PARAMETERS]->(m:ParamVariableDeclaration) RETURN m", null) as Query val nodes = db.executeQuery(query) assertEquals(2, nodes.size) } @Test fun testQueryExistenceOfEdgeWithEquals() { val query = parser.parse("MATCH (n:FunctionDeclaration)-[:PARAMETERS]->(m:ParamVariableDeclaration) WHERE m.name = 'paramB' RETURN n", null) as Query val nodes = db.executeQuery(query) assertEquals(1, nodes.size) assertEquals(func2, nodes[0]) } @Test fun testQueryWithSimpleProperty() { val query = parser.parse("MATCH (n:VariableDeclaration) WHERE n.name = 'myVar' RETURN n", null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(1, nodes.size) } @Test fun testQueryAllNodes() { // should return all nodes val query = parser.parse("MATCH (n) RETURN n", null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(db.size(), nodes.size) } @Test fun testQueryAllNodesWithEquals() { // should return all nodes val query = parser.parse("MATCH (n) WHERE 1=1 RETURN n", null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(db.size(), nodes.size) } @Test fun testQueryLimit() { // should return all nodes val query = parser.parse("MATCH (n) RETURN n LIMIT 25", null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(25, nodes.size) } @Test fun testQueryNoResult() { // should return no nodes val query = parser.parse("MATCH (n) WHERE 1='a' RETURN n", null) as Query println(query) val nodes = db.executeQuery(query) println(nodes) assertTrue(nodes.isEmpty()) } @Test fun testQueryLesser() { // should return no nodes val query = parser.parse("MATCH (n) WHERE 1<0 RETURN n", null) as Query println(query) val nodes = db.executeQuery(query) println(nodes) assertTrue(nodes.isEmpty()) } @Test fun testQueryGreaterThan() { // should return no nodes val query = parser.parse("MATCH (n) WHERE 0>1 RETURN n", null) as Query println(query) val nodes = db.executeQuery(query) println(nodes) assertTrue(nodes.isEmpty()) } companion object { lateinit var db: Graph val parser = CypherParser() lateinit var func1: FunctionDeclaration lateinit var func2: FunctionDeclaration lateinit var func3: FunctionDeclaration @ExperimentalGraph @BeforeAll @JvmStatic fun before() { db = Graph(mutableListOf()) db += NodeBuilder.newVariableDeclaration("myVar", UnknownType.getUnknownType(), "myVar", false) func1 = NodeBuilder.newFunctionDeclaration("func1", "private int func1() { return 1; }") func2 = NodeBuilder.newFunctionDeclaration("func2", "private int func2() { return 1; }") func3 = NodeBuilder.newFunctionDeclaration("func3", "private int func2() { return 1; }") val paramA = NodeBuilder.newMethodParameterIn("paramA", UnknownType.getUnknownType(), false, "paramA"); val paramB = NodeBuilder.newMethodParameterIn("paramB", UnknownType.getUnknownType(), false, "paramB"); func1.addParameter(paramA) func2.addParameter(paramB) // create some dummy nodes to make queries a little bit slower for (i in 0..10000) { db += NodeBuilder.newVariableDeclaration("var${i}", UnknownType.getUnknownType(), "var${i}", true) } db += func1 db += func2 db += func3 db += paramA db += paramB } } }
0
Java
0
0
c578f6db6693fe0f78f47ff0757b6bb5ae24bac4
6,919
cpg
Apache License 2.0
embrace-test-fakes/src/main/kotlin/io/embrace/android/embracesdk/fakes/injection/FakeMomentsModule.kt
embrace-io
704,537,857
false
{"Kotlin": 2981564, "C": 189341, "Java": 150268, "C++": 13140, "CMake": 4261}
package io.embrace.android.embracesdk.fakes.injection import io.embrace.android.embracesdk.fakes.FakeEventService import io.embrace.android.embracesdk.internal.event.EventService import io.embrace.android.embracesdk.internal.injection.MomentsModule public class FakeMomentsModule( override val eventService: EventService = FakeEventService() ) : MomentsModule
20
Kotlin
8
134
896e9aadf568ba527c76ec66f6f440baed29d1ee
366
embrace-android-sdk
Apache License 2.0
app/src/main/java/me/devsaki/hentoid/viewmodels/QueueViewModel.kt
avluis
37,775,708
false
null
package me.devsaki.hentoid.viewmodels import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import com.annimon.stream.Optional import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import me.devsaki.hentoid.R import me.devsaki.hentoid.database.CollectionDAO import me.devsaki.hentoid.database.domains.Content import me.devsaki.hentoid.database.domains.ErrorRecord import me.devsaki.hentoid.database.domains.QueueRecord import me.devsaki.hentoid.enums.ErrorType import me.devsaki.hentoid.enums.StatusContent import me.devsaki.hentoid.events.DownloadCommandEvent import me.devsaki.hentoid.events.DownloadEvent import me.devsaki.hentoid.events.ProcessEvent import me.devsaki.hentoid.util.ContentHelper import me.devsaki.hentoid.util.Preferences import me.devsaki.hentoid.util.download.ContentQueueManager import me.devsaki.hentoid.util.exception.EmptyResultException import me.devsaki.hentoid.workers.DeleteWorker import me.devsaki.hentoid.workers.PurgeWorker import me.devsaki.hentoid.workers.data.DeleteData import org.apache.commons.lang3.tuple.ImmutablePair import org.greenrobot.eventbus.EventBus import org.threeten.bp.Instant import timber.log.Timber import java.util.concurrent.atomic.AtomicInteger class QueueViewModel( application: Application, private val dao: CollectionDAO ) : AndroidViewModel(application) { // Collection data for queue private var currentQueueSource: LiveData<List<QueueRecord>>? = null private val queue = MediatorLiveData<List<QueueRecord>>() // Collection data for errors private var currentErrorsSource: LiveData<List<Content>>? = null private val errors = MediatorLiveData<List<Content>>() // ID of the content to show at 1st display private val contentHashToShowFirst = MutableLiveData<Long>() // Updated whenever a new search is performed private val newSearch = MediatorLiveData<Boolean>() init { refresh() } override fun onCleared() { super.onCleared() dao.cleanup() } fun getQueue(): LiveData<List<QueueRecord>> { return queue } fun getErrors(): LiveData<List<Content>> { return errors } fun getNewSearch(): LiveData<Boolean> { return newSearch } fun getContentHashToShowFirst(): LiveData<Long> { return contentHashToShowFirst } // ========================= // =========== QUEUE ACTIONS // ========================= /** * Perform a new search */ fun refresh() { searchQueueUniversal() searchErrorContentUniversal() } fun searchQueueUniversal(query: String? = null) { if (currentQueueSource != null) queue.removeSource(currentQueueSource!!) currentQueueSource = if (query.isNullOrEmpty()) dao.selectQueueLive() else dao.selectQueueLive(query) queue.addSource(currentQueueSource!!) { value -> queue.setValue(value) } newSearch.value = true } fun searchErrorContentUniversal(query: String? = null) { if (currentErrorsSource != null) errors.removeSource(currentErrorsSource!!) currentErrorsSource = if (query.isNullOrEmpty()) dao.selectErrorContentLive() else dao.selectErrorContentLive(query) errors.addSource(currentErrorsSource!!) { value -> errors.setValue(value) } newSearch.value = true } // ========================= // ========= CONTENT ACTIONS // ========================= fun moveAbsolute(oldPosition: Int, newPosition: Int) { if (oldPosition == newPosition) return Timber.d(">> move %s to %s", oldPosition, newPosition) // Get unpaged data to be sure we have everything in one collection val localQueue = dao.selectQueue() if (oldPosition < 0 || oldPosition >= localQueue.size) return // Move the item val fromValue = localQueue[oldPosition] val delta = if (oldPosition < newPosition) 1 else -1 var i = oldPosition while (i != newPosition) { localQueue[i] = localQueue[i + delta] i += delta } localQueue[newPosition] = fromValue // Renumber everything var index = 1 for (qr in localQueue) qr.rank = index++ // Update queue in DB dao.updateQueue(localQueue) // If the 1st item is involved, signal it being skipped if (0 == newPosition || 0 == oldPosition) EventBus.getDefault() .post(DownloadCommandEvent(DownloadCommandEvent.Type.EV_SKIP)) } /** * Move all items at given positions to top of the list * * @param relativePositions Adapter positions of the items to move */ fun moveTop(relativePositions: List<Int>) { val absolutePositions = relativeToAbsolutePositions(relativePositions) for ((processed, oldPos) in absolutePositions.withIndex()) { moveAbsolute(oldPos, processed) } } /** * Move all items at given positions to bottom of the list * * @param relativePositions Adapter positions of the items to move */ fun moveBottom(relativePositions: List<Int>) { val absolutePositions = relativeToAbsolutePositions(relativePositions) val dbQueue = dao.selectQueue() ?: return val endPos = dbQueue.size - 1 for ((processed, oldPos) in absolutePositions.withIndex()) { moveAbsolute(oldPos - processed, endPos) } } private fun relativeToAbsolutePositions(relativePositions: List<Int>): List<Int> { val result: MutableList<Int> = ArrayList() val currentQueue = queue.value val dbQueue = dao.selectQueue() if (null == currentQueue || null == dbQueue) return relativePositions for (position in relativePositions) { for (i in dbQueue.indices) if (dbQueue[i].id == currentQueue[position].id) { result.add(i) break } } return result } fun unpauseQueue() { dao.updateContentStatus(StatusContent.PAUSED, StatusContent.DOWNLOADING) ContentQueueManager.unpauseQueue() ContentQueueManager.resumeQueue(getApplication()) EventBus.getDefault().post(DownloadEvent(DownloadEvent.Type.EV_UNPAUSED)) } fun invertQueue() { // Get unpaged data to be sure we have everything in one collection val localQueue = dao.selectQueue() if (localQueue.size < 2) return // Renumber everything in reverse order var index = 1 for (i in localQueue.indices.reversed()) { localQueue[i].rank = index++ } // Update queue and signal skipping the 1st item dao.updateQueue(localQueue) EventBus.getDefault().post(DownloadCommandEvent(DownloadCommandEvent.Type.EV_SKIP)) } /** * Cancel download of designated Content * NB : Contrary to Pause command, Cancel removes the Content from the download queue * * @param contents Contents whose download has to be canceled */ fun cancel(contents: List<Content>) { remove(contents) } fun removeAll() { val errorsLocal = dao.selectErrorContent() if (errorsLocal.isEmpty()) return remove(errorsLocal) } fun remove(contentList: List<Content>) { val builder = DeleteData.Builder() if (contentList.isNotEmpty()) builder.setQueueIds( contentList.map { c -> c.id }.filter { id -> id > 0 } ) val workManager = WorkManager.getInstance(getApplication()) workManager.enqueueUniqueWork( R.id.delete_service_delete.toString(), ExistingWorkPolicy.APPEND_OR_REPLACE, OneTimeWorkRequest.Builder(DeleteWorker::class.java).setInputData(builder.data).build() ) } private fun purgeItem(content: Content) { val builder = DeleteData.Builder() builder.setContentPurgeIds(listOf(content.id)) val workManager = WorkManager.getInstance(getApplication()) workManager.enqueueUniqueWork( R.id.delete_service_purge.toString(), ExistingWorkPolicy.APPEND_OR_REPLACE, OneTimeWorkRequest.Builder(PurgeWorker::class.java).setInputData(builder.data).build() ) } fun cancelAll() { val localQueue = dao.selectQueue() if (localQueue.isEmpty()) return val contentIdList = localQueue.map { qr -> qr.content.targetId }.filter { id -> id > 0 } EventBus.getDefault().post(DownloadCommandEvent(DownloadCommandEvent.Type.EV_PAUSE)) val builder = DeleteData.Builder() if (contentIdList.isNotEmpty()) builder.setQueueIds(contentIdList) builder.setDeleteAllQueueRecords(true) val workManager = WorkManager.getInstance(getApplication()) workManager.enqueueUniqueWork( R.id.delete_service_delete.toString(), ExistingWorkPolicy.APPEND_OR_REPLACE, OneTimeWorkRequest.Builder(DeleteWorker::class.java).setInputData(builder.data).build() ) } /** * Redownload the given list of Content according to the given parameters * NB : Used by both the regular redownload and redownload from scratch * * @param contentList List of content to be redownloaded * @param reparseContent True if the content (general metadata) has to be re-parsed from the site; false to keep * @param reparseImages True if the images have to be re-detected and redownloaded from the site; false to keep * @param position Position of the new item to redownload, either QUEUE_NEW_DOWNLOADS_POSITION_TOP or QUEUE_NEW_DOWNLOADS_POSITION_BOTTOM * @param onSuccess Handler for process success; consumes the number of books successfuly redownloaded * @param onError Handler for process error; consumes the exception */ fun redownloadContent( contentList: List<Content>, reparseContent: Boolean, reparseImages: Boolean, position: Int, onSuccess: (Int) -> Unit, onError: (Throwable) -> Unit ) { val targetImageStatus = if (reparseImages) StatusContent.ERROR else null val errorCount = AtomicInteger(0) val okCount = AtomicInteger(0) viewModelScope.launch { withContext(Dispatchers.IO) { contentList.forEach { val res = if (reparseContent) ContentHelper.reparseFromScratch(it) else ImmutablePair(it, Optional.of(it)) if (res.right.isPresent) { val content = res.right.get() // Non-blocking performance bottleneck; run in a dedicated worker if (reparseImages) purgeItem(content) okCount.incrementAndGet() dao.addContentToQueue( content, targetImageStatus, position, -1, content.replacementTitle, ContentQueueManager.isQueueActive(getApplication()) ) } else { // As we're in the download queue, an item whose content is unreachable should directly get to the error queue val c = dao.selectContent(res.left.id) if (c != null) { // Remove the content from the regular queue ContentHelper.removeQueuedContent( getApplication(), dao, c, false ) // Put it in the error queue c.status = StatusContent.ERROR val errors: MutableList<ErrorRecord> = ArrayList() errors.add( ErrorRecord( c.id, ErrorType.PARSING, c.galleryUrl, "Book", "Redownload from scratch -> Content unreachable", Instant.now() ) ) c.setErrorLog(errors) dao.insertContent(c) // Save the regular queue ContentHelper.updateQueueJson(getApplication(), dao) } errorCount.incrementAndGet() onError.invoke(EmptyResultException("Redownload from scratch -> Content unreachable")) } EventBus.getDefault().post( ProcessEvent( ProcessEvent.EventType.PROGRESS, R.id.generic_progress, 0, okCount.get(), errorCount.get(), contentList.size ) ) } // For each content if (Preferences.isQueueAutostart()) ContentQueueManager.resumeQueue(getApplication()) EventBus.getDefault().postSticky( ProcessEvent( ProcessEvent.EventType.COMPLETE, R.id.generic_progress, 0, okCount.get(), errorCount.get(), contentList.size ) ) } onSuccess.invoke(contentList.size - errorCount.get()) } } fun setContentToShowFirst(hash: Long) { contentHashToShowFirst.value = hash } fun setDownloadMode(contentIds: List<Long>, downloadMode: Int) { viewModelScope.launch { withContext(Dispatchers.IO) { contentIds.forEach { val theContent = dao.selectContent(it) if (theContent != null && !theContent.isBeingDeleted) { theContent.downloadMode = downloadMode dao.insertContent(theContent) } } ContentHelper.updateQueueJson(getApplication(), dao) // Force display by updating queue dao.updateQueue(dao.selectQueue()) } } } fun toogleFreeze(recordId: List<Long>) { viewModelScope.launch { launch(Dispatchers.IO) { val queue = dao.selectQueue() queue.forEach { if (recordId.contains(it.id)) it.isFrozen = !it.isFrozen } dao.updateQueue(queue) // Update queue JSON ContentHelper.updateQueueJson(getApplication(), dao) } } } }
4
null
85
992
f54df07b79da4147951bc9902ab0dbd70edb50f1
15,461
Hentoid
Apache License 2.0
app/src/main/java/com/joshuatz/nfceinkwriter/Constants.kt
joshuatz
364,138,857
false
null
package com.joshuatz.nfceinkwriter const val PackageName = "com.joshuatz.nfceinkwriter" const val WaveShareUID = "WSDZ10m" // Order matches WS SDK Enum (except off by 1, due to zero-index) // @see https://www.waveshare.com/wiki/Android_SDK_for_NFC-Powered_e-Paper // @see https://github.com/RfidResearchGroup/proxmark3/blob/0d1f8ca957c0ae6f3039237889cdabe5921afe2d/client/src/cmdhfwaveshare.c#L81-L90 val ScreenSizes = arrayOf( "2.13\"", "2.9\"", "4.2\"", "7.5\"", "7.5\" HD", "2.7\"", "2.9\" v.B", ) val DefaultScreenSize = ScreenSizes[1] val ScreenSizesInPixels = mapOf( // The true resolution for 2.13" is 250x122, but there is a (likely) typo in the SDK // @see https://github.com/joshuatz/nfc-epaper-writer/issues/2 "2.13\"" to Pair(250, 128), "2.9\"" to Pair(296, 128), "4.2\"" to Pair(400, 300), "7.5\"" to Pair(800, 480), "7.5\" HD" to Pair(880, 528), "2.7\"" to Pair(264, 176), "2.9\" v.B" to Pair(296, 128), ) object Constants { var Preference_File_Key = "Preferences" var PreferenceKeys = PrefKeys } object PrefKeys { var DisplaySize = "Display_Size" var GeneratedImgPath = "Generated_Image_Path" } object IntentKeys { var GeneratedImgPath = "$PackageName.imgUri" var GeneratedImgMime = "$PackageName.imgMime" } val GeneratedImageFilename = "generated.png"
1
Kotlin
2
8
2fe5b01a48dddd5beba2d96cb858a1b927feb45c
1,364
nfc-epaper-writer
MIT License
src/main/kotlin/com/github/juzraai/cordis/crawler/model/openaire/sygma/Publication.kt
juzraai
14,644,476
false
{"Kotlin": 60620, "HTML": 2201}
package com.github.juzraai.cordis.crawler.model.openaire.sygma import org.simpleframework.xml.* import java.util.* /** * @author <NAME> */ @Default(required = false) data class Publication( @field:ElementList(name = "authors", entry = "author", required = false) var authors: List<String>? = null, @field:Element(name = "bestlicense", required = false) var bestLicense: String? = null, @field:Element(name = "dateofacceptance", required = false) var dateOfAcceptance: Date? = null, var description: String? = null, var doi: String? = null, @field:Element(name = "openaireid", required = false) var openAireId: String? = null, @field:Element(name = "publicationtype", required = false) var publicationType: String? = null, @field:ElementList(entry = "sourcejournal", inline = true, required = false) var sourceJournals: Set<String>? = null, var title: String? = null, @field:ElementList(entry = "webresource", inline = true, required = false) var webResources: Set<String>? = null )
4
Kotlin
0
1
62bfd6ef3423954782689dccde153518c2ea4245
1,029
cordis-projects-crawler
MIT License
annotation/annotation/src/jvmMain/kotlin/androidx/annotation/WorkerThread.jvm.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright (C) 2015 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.annotation /** * Denotes that the annotated method should only be called on a worker thread. * If the annotated element is a class, then all methods in the class should be called * on a worker thread. * * Example: * ``` * @WorkerThread * protected abstract FilterResults performFiltering(CharSequence constraint); * ``` */ @MustBeDocumented @Retention(AnnotationRetention.BINARY) @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR, AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS, AnnotationTarget.VALUE_PARAMETER ) public annotation class WorkerThread
29
Kotlin
778
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
1,320
androidx
Apache License 2.0
app/src/main/kotlin/edu/stanford/bdh/engagehf/bluetooth/data/mapper/BluetoothUiStateMapper.kt
StanfordSpezi
787,513,636
false
{"Kotlin": 333238, "Ruby": 1659, "Shell": 212}
package edu.stanford.spezi.app.bluetooth.data.mapper import edu.stanford.spezi.app.bluetooth.data.models.BluetoothUiState import edu.stanford.spezi.app.bluetooth.data.models.DeviceUiModel import edu.stanford.spezi.core.bluetooth.data.model.BLEServiceState import edu.stanford.spezi.core.bluetooth.data.model.Measurement import java.util.Locale import javax.inject.Inject class BluetoothUiStateMapper @Inject constructor() { fun map(state: BLEServiceState.Scanning): BluetoothUiState.Ready { val devices = state.sessions.map { val summary = when (val lastMeasurement = it.measurements.lastOrNull()) { is Measurement.BloodPressure -> "Blood Pressure: ${format(lastMeasurement.systolic)} / ${format(lastMeasurement.diastolic)}" is Measurement.Weight -> "Weight: ${format(lastMeasurement.weight)}" else -> "No measurement received yet" } DeviceUiModel( address = it.device.address, measurementsCount = it.measurements.size, summary = summary, ) } val header = if (devices.isEmpty()) "No devices connected yet" else "Connected devices (${devices.size})" return BluetoothUiState.Ready( header = header, devices = devices ) } private fun format(value: Number?): String = String.format(Locale.US, "%.2f", value) }
8
Kotlin
1
7
b77e6eacbcb464bf454f3f566642d4f3c6e0b3d3
1,430
SpeziKt
MIT License
decoder/wasm/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/section/export/ExportSectionDecoder.kt
CharlieTap
743,980,037
false
{"Kotlin": 898736, "WebAssembly": 7119}
package io.github.charlietap.chasm.decoder.section.export import com.github.michaelbull.result.Result import io.github.charlietap.chasm.error.WasmDecodeError import io.github.charlietap.chasm.reader.WasmBinaryReader import io.github.charlietap.chasm.section.ExportSection import io.github.charlietap.chasm.section.SectionSize fun interface ExportSectionDecoder : (WasmBinaryReader, SectionSize) -> Result<ExportSection, WasmDecodeError>
2
Kotlin
1
16
1566c1b504b4e0a31ae5008f5ada463c47de71c5
439
chasm
Apache License 2.0
orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProviderIntTest.kt
ArcadeData
170,271,274
false
null
/*- * #%L * Arcade Connectors * %% * Copyright (C) 2018 - 2019 ArcadeAnalytics * %% * 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. * #L% */ package com.arcadeanalytics.provider.orient3 import com.arcadeanalytics.data.Sprite import com.arcadeanalytics.data.SpritePlayer import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import java.util.* /** * NOTE: tests are ignored because on our Jenkins the test containers isn't working * enable tests on local machine */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class OrientDB3DataSourceGraphProviderIntTest { private val provider: OrientDB3DataSourceGraphProvider = OrientDB3DataSourceGraphProvider() @Test fun shouldFetchAllVerticesAndEdges() { val docs = ArrayList<Sprite>() val indexer = object : SpritePlayer { override fun begin() { } override fun end() { } override fun play(document: Sprite) { docs.add(document) assertThat(document.valuesOf("@class")).doesNotContain("V", "E") } } provider.provideTo(OrientDB3Container.dataSource, indexer) assertThat(docs).hasSize(8) } }
9
null
4
6
731917fa365abc6112c70d464baa40841382e0f8
1,803
arcade-connectors
Apache License 2.0
project-system-gradle/testSrc/com/android/tools/idea/gradle/project/build/output/JavaLanguageLevelDeprecationOutputParserTest.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.project.build.output import com.google.common.truth.Truth.assertThat import com.intellij.build.events.MessageEvent import com.intellij.pom.java.LanguageLevel import org.junit.Test class JavaLanguageLevelDeprecationOutputParserTest { private val parser = JavaLanguageLevelDeprecationOutputParser() private val lineAfterWarning = "line after the warning" @Test fun testUnrelatedLineNotParsed() { val reader = TestBuildOutputInstantReader( lines = listOf( "warning: someOtherWarning", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isNull() assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testWarning() { val reader = TestBuildOutputInstantReader( lines = listOf( "warning: [options] source value 8 is obsolete and will be removed in a future release", "warning: [options] target value 8 is obsolete and will be removed in a future release", "warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.WARNING, title = "Java compiler has deprecated support for compiling with source/target compatibility version 8.", suggestedToolchainVersion = 17, suggestedLanguageLevel = LanguageLevel.JDK_11, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testWarningWithDifferentVersions() { // This seems to be unreal for now but maybe they will deprecate several versions at once in the future. val reader = TestBuildOutputInstantReader( lines = listOf( "warning: [options] source value 7 is obsolete and will be removed in a future release", "warning: [options] target value 8 is obsolete and will be removed in a future release", "warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.WARNING, title = "Java compiler has deprecated support for compiling with source/target compatibility version 7.", suggestedToolchainVersion = 11, suggestedLanguageLevel = LanguageLevel.JDK_11, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testWarningSingleLine() { val reader = TestBuildOutputInstantReader( lines = listOf( "warning: [options] source value 8 is obsolete and will be removed in a future release", "warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.WARNING, title = "Java compiler has deprecated support for compiling with source/target compatibility version 8.", suggestedToolchainVersion = 17, suggestedLanguageLevel = LanguageLevel.JDK_11, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testError() { val reader = TestBuildOutputInstantReader( lines = listOf( "error: Source option 7 is no longer supported. Use 8 or later.", "error: Target option 7 is no longer supported. Use 8 or later.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.ERROR, title = "Java compiler has removed support for compiling with source/target compatibility version 7.", suggestedToolchainVersion = 11, suggestedLanguageLevel = LanguageLevel.JDK_1_8, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testOnlySourceError() { val reader = TestBuildOutputInstantReader( lines = listOf( "error: Source option 7 is no longer supported. Use 8 or later.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.ERROR, title = "Java compiler has removed support for compiling with source/target compatibility version 7.", suggestedToolchainVersion = 11, suggestedLanguageLevel = LanguageLevel.JDK_1_8, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } //TODO is it possible to have two warnings for different versions? @Test fun testErrorWithDifferentVersions() { val reader = TestBuildOutputInstantReader( lines = listOf( "error: Source option 7 is no longer supported. Use 11 or later.", "error: Target option 8 is no longer supported. Use 11 or later.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.ERROR, title = "Java compiler has removed support for compiling with source/target compatibility version 7.", suggestedToolchainVersion = 11, suggestedLanguageLevel = LanguageLevel.JDK_11, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testErrorWithDifferentOlderVersions() { val reader = TestBuildOutputInstantReader( lines = listOf( "error: Source option 5 is no longer supported. Use 11 or later.", "error: Target option 6 is no longer supported. Use 11 or later.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.ERROR, title = "Java compiler has removed support for compiling with source/target compatibility version 5.", suggestedToolchainVersion = null, suggestedLanguageLevel = LanguageLevel.JDK_11, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } @Test fun testMixedErrorAndWarning() { val reader = TestBuildOutputInstantReader( lines = listOf( "error: Source option 7 is no longer supported. Use 8 or later.", "warning: [options] target value 8 is obsolete and will be removed in a future release", "warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.", lineAfterWarning ), parentEventId = "[root build id] > [Task :app:compileDebugAndroidTestJavaWithJavac]" ) assertThat(parser.parseLines(reader.readLine()!!, reader)).isEqualTo(JavaLanguageLevelDeprecationOutputParser.ParsingResult( kind = MessageEvent.Kind.ERROR, title = "Java compiler has removed support for compiling with source/target compatibility version 7.", suggestedToolchainVersion = 11, suggestedLanguageLevel = LanguageLevel.JDK_11, modulePath = ":app" )) assertThat(reader.readLine()).isEqualTo(lineAfterWarning) } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
8,872
android
Apache License 2.0
app/src/main/java/xyz/teamgravity/swipetodeleteedit/MainViewModel.kt
raheemadamboev
767,473,692
false
{"Kotlin": 18500}
package xyz.teamgravity.swipetodeleteedit import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class MainViewModel : ViewModel() { private val _names = MutableStateFlow(NameProvider.VALUE) val names: StateFlow<List<NameModel>> = _names.asStateFlow() /////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////// fun onDelete(position: Int) { _names.update { data -> val processedData = data.toMutableList() processedData.removeAt(position) return@update processedData } } }
0
Kotlin
0
0
f2bbfa293e44d01a0732dbb0e020027042d892e9
808
swipe-to-delete-edit
Apache License 2.0
android/src/main/kotlin/fr/pointcheval/native_crypto/Cipher.kt
Overlord21
464,856,812
true
{"Dart": 51754, "Swift": 16236, "Kotlin": 12906, "Ruby": 4346, "Objective-C": 717}
package fr.pointcheval.native_crypto import java.lang.Exception import javax.crypto.Cipher import javax.crypto.SecretKey import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec enum class CipherAlgorithm(val spec: String) { AES("AES"), } enum class BlockCipherMode(val instance: String) { CBC("CBC"), GCM("GCM"), } enum class Padding(val instance: String) { PKCS5("PKCS5Padding"), None("NoPadding") } class CipherParameters(private val mode: BlockCipherMode, private val padding: Padding) { override fun toString(): String { return mode.instance + "/" + padding.instance } } class Cipher { fun getCipherAlgorithm(dartAlgorithm: String) : CipherAlgorithm { return when (dartAlgorithm) { "aes" -> CipherAlgorithm.AES else -> CipherAlgorithm.AES } } fun getInstance(mode : String, padding : String) : CipherParameters { val m = when (mode) { "cbc" -> BlockCipherMode.CBC "gcm" -> BlockCipherMode.GCM else -> throw Exception() } val p = when (padding) { "pkcs5" -> Padding.PKCS5 else -> Padding.None } return CipherParameters(m,p) } fun encrypt(data: ByteArray, key: ByteArray, algorithm: String, mode: String, padding: String) : List<ByteArray> { val algo = getCipherAlgorithm(algorithm) val params = getInstance(mode, padding) val keySpecification = algo.spec + "/" + params.toString() val mac = Hash().digest(key + data) val sk: SecretKey = SecretKeySpec(key, algo.spec) val cipher = Cipher.getInstance(keySpecification) cipher.init(Cipher.ENCRYPT_MODE, sk) val encryptedBytes = cipher.doFinal(mac + data) val iv = cipher.iv return listOf(encryptedBytes, iv); } fun decrypt(payload: Collection<ByteArray>, key: ByteArray, algorithm: String, mode: String, padding: String) : ByteArray? { val algo = getCipherAlgorithm(algorithm) val params = getInstance(mode, padding) val keySpecification = algo.spec + "/" + params.toString() val sk: SecretKey = SecretKeySpec(key, algo.spec) val cipher = Cipher.getInstance(keySpecification); val iv = payload.last(); val ivSpec = IvParameterSpec(iv) cipher.init(Cipher.DECRYPT_MODE, sk, ivSpec); val decryptedBytes = cipher.doFinal(payload.first()); val mac = decryptedBytes.copyOfRange(0, 32) val decryptedContent : ByteArray = decryptedBytes.copyOfRange(32, decryptedBytes.size) val verificationMac = Hash().digest(key + decryptedContent) return if (mac.contentEquals(verificationMac)) { decryptedContent } else { null; } } }
0
null
0
0
9790be4a5c44504dba347ff41b1f65c4f67642dc
2,838
native-crypto-flutter
MIT License
openapi-processor-core/src/testInt/kotlin/io/openapiprocessor/core/ProcessorTestSets.kt
openapi-processor
547,758,502
false
{"Kotlin": 739922, "Groovy": 216443, "Java": 108438, "ANTLR": 2555, "TypeScript": 1166}
/* * Copyright 2022 https://github.com/openapi-processor/openapi-processor-core * PDX-License-Identifier: Apache-2.0 */ package io.openapiprocessor.core import io.openapiprocessor.test.* val ALL_30: List<TestParams> = listOf( test30_DR("annotation-mapping-class"), test30_DR("bean-validation"), test30_DR("bean-validation-allof-required"), test30_DR("bean-validation-iterable"), test30_DR("bean-validation-jakarta"), test30_D_("bean-validation-list-item-import"), test30_D_("bean-validation-requestbody"), test30_D_("bean-validation-requestbody-mapping"), test30_DR("components-requestbodies"), test30_DR("deprecated"), test30_D_("endpoint-exclude"), test30_D_("endpoint-http-mapping"), // framework specific test30_DR("generated"), test30_DR("javadoc"), test30_DR("javadoc-with-mapping"), test30_DR("keyword-identifier"), test30_D_("map-from-additional-properties"), test30_DR("map-from-additional-properties-with-package-name"), test30_DR("map-to-primitive-data-types"), test30_D_("method-operation-id"), test30_DR("model-name-suffix"), test30_DR("model-name-suffix-with-package-name"), test30_D_("object-empty"), test30_DR("object-nullable-properties"), test30_DR("object-read-write-properties"), test30_DR("object-without-properties"), test30_D_("params-additional"), test30_D_("params-additional-global"), test30_DR("params-complex-data-types"), // framework specific test30_D_("params-endpoint"), test30_D_("params-enum"), test30_D_("params-enum-string"), test30_D_("params-path-simple-data-types"), // framework specific test30_DR("params-request-body"), // framework specific test30_D_("params-request-body-multipart-form-data"), // framework specific test30_D_("params-simple-data-types"), // framework specific test30_DR("ref-array-items-nested"), test30_DR("ref-chain-spring-124.1"), test30_DR("ref-chain-spring-124.2"), test30_DR("ref-into-another-file"), test30_DR("ref-into-another-file-path"), test30_DR("ref-is-relative-to-current-file"), test30_DR("ref-loop"), test30_DR("ref-loop-array"), test30_D_("ref-parameter"), test30_D_("ref-parameter-with-primitive-mapping"), test30_DR("ref-to-escaped-path-name"), test30_D_("response-array-data-type-mapping"), test30_DR("response-complex-data-types"), test30_DR("response-content-multiple-no-content"), test30_DR("response-content-multiple-style-all"), test30_DR("response-content-multiple-style-success"), test30_D_("response-content-single"), test30_DR("response-multi-mapping-with-array-type-mapping"), test30_D_("response-result-mapping"), test30_D_("response-simple-data-types"), test30_DR("response-single-multi-mapping"), test30_DR("schema-composed"), test30_DR("schema-composed-allof"), test30_DR("schema-composed-allof-notype"), test30_DR("schema-composed-allof-properties"), test30_DR("schema-composed-allof-ref-sibling"), test30_DR("schema-composed-nested"), test30_DR("schema-composed-oneof-interface"), test30_DR("swagger-parsing-error") ) val ALL_31: List<TestParams> = listOf( test31_DR("annotation-mapping-class"), test31_DR("bean-validation"), test31_DR("bean-validation-allof-required"), test31_DR("bean-validation-iterable"), test31_DR("bean-validation-jakarta"), test31_D_("bean-validation-list-item-import"), test31_D_("bean-validation-requestbody"), test31_D_("bean-validation-requestbody-mapping"), test31_DR("components-requestbodies"), test31_DR("deprecated"), test31_D_("endpoint-exclude"), test31_D_("endpoint-http-mapping"), // framework specific test31_DR("generated"), test31_DR("javadoc"), test31_DR("javadoc-with-mapping"), test31_DR("keyword-identifier"), test31_D_("map-from-additional-properties"), test31_DR("map-from-additional-properties-with-package-name"), test31_DR("map-to-primitive-data-types"), test31_D_("method-operation-id"), test31_DR("model-name-suffix"), test31_DR("model-name-suffix-with-package-name"), test31_D_("object-empty"), test31_DR("object-nullable-properties"), test31_DR("object-read-write-properties"), test31_DR("object-without-properties"), test31_D_("params-additional"), test31_D_("params-additional-global"), test31_DR("params-complex-data-types"), // framework specific test31_D_("params-endpoint"), test31_D_("params-enum"), test31_D_("params-enum-string"), test31_D_("params-path-simple-data-types"), // framework specific test31_DR("params-request-body"), // framework specific test31_D_("params-request-body-multipart-form-data"), // framework specific test31_D_("params-simple-data-types"), // framework specific test31_DR("ref-array-items-nested"), test31_DR("ref-chain-spring-124.1"), test31_DR("ref-chain-spring-124.2"), test31_DR("ref-into-another-file"), test31_DR("ref-into-another-file-path"), test31_DR("ref-is-relative-to-current-file"), test31_DR("ref-loop"), test31_DR("ref-loop-array"), test31_D_("ref-parameter"), test31_D_("ref-parameter-with-primitive-mapping"), test31_DR("ref-to-escaped-path-name"), test31_D_("response-array-data-type-mapping"), test31_DR("response-complex-data-types"), test31_DR("response-content-multiple-no-content"), test31_DR("response-content-multiple-style-all"), test31_DR("response-content-multiple-style-success"), test31_D_("response-content-single"), test31_DR("response-multi-mapping-with-array-type-mapping"), test31_D_("response-result-mapping"), test31_D_("response-simple-data-types"), test31_DR("response-single-multi-mapping"), test31_DR("schema-composed"), test31_DR("schema-composed-allof"), test31_DR("schema-composed-allof-notype"), test31_DR("schema-composed-allof-properties"), test31_DR("schema-composed-allof-ref-sibling"), test31_DR("schema-composed-nested"), test31_DR("schema-composed-oneof-interface"), test31_DR("swagger-parsing-error") )
9
Kotlin
3
2
ffbb239a493a96cb2f291365fd974fd6bfcf56a0
6,170
openapi-processor-base
Apache License 2.0
adaptive-core/src/commonMain/kotlin/fun/adaptive/foundation/testing/entry.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2431816, "Java": 25628, "HTML": 8024, "JavaScript": 3880, "Shell": 687}
/* * Copyright © 2020-2024, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package `fun`.adaptive.foundation.testing import `fun`.adaptive.backend.BackendAdapter import `fun`.adaptive.foundation.Adaptive import `fun`.adaptive.foundation.AdaptiveAdapter import `fun`.adaptive.foundation.AdaptiveEntry import `fun`.adaptive.service.testing.TestServiceTransport import kotlinx.coroutines.Dispatchers /** * The general entry point of an Adaptive test component tree. * * **IMPORTANT** variables declared outside the block are **NOT** reactive */ @AdaptiveEntry fun test( backendAdapter: BackendAdapter = BackendAdapter(transport = TestServiceTransport(), dispatcher = Dispatchers.Default), printTrace: Boolean = false, @Adaptive block: (adapter: AdaptiveAdapter) -> Unit ): AdaptiveTestAdapter = AdaptiveTestAdapter(printTrace, backendAdapter).also { block(it) it.mounted() }
34
Kotlin
0
3
590e01b857c9c759a69ece62f11ed8822fa4ee59
959
adaptive
Apache License 2.0
app/src/main/java/com/example/careerboast/domain/use_cases/GetInterviewsListUseCase.kt
Ev4esem
771,869,351
false
{"Kotlin": 90779}
package com.example.careerboast.domain.use_cases import com.example.careerboast.domain.model.interviews.Question import com.example.careerboast.domain.repositories.interview.InterviewRepository class GetInterviewsListUseCase(val repository : InterviewRepository) { }
0
Kotlin
0
0
1239403f5ae15e7ab81e3e48a01b083b73284582
270
CareerBoast
Apache License 2.0
clients/fossid-webapp/src/main/kotlin/model/Scan.kt
oss-review-toolkit
107,540,288
false
null
/* * Copyright (C) 2020 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.clients.fossid.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.databind.annotation.JsonDeserialize @JsonIgnoreProperties(ignoreUnknown = true) data class Scan( val id: Int, val created: String?, val updated: String?, val userId: Int?, val projectId: Int?, val name: String?, val code: String?, val description: String?, val comment: String?, @JsonDeserialize(using = IntBooleanDeserializer::class) val isArchived: Boolean?, /** * Used when the files are available on the FossID server prior to the api call creating the scan. * This property and [gitRepoUrl] are exclusive and should never be used at the same time. */ val targetPath: String?, @JsonDeserialize(using = IntBooleanDeserializer::class) val isBlindAudit: Boolean?, val filesNotScanned: String?, val pendingItems: String?, val isFromReport: String?, val gitRepoUrl: String?, val gitBranch: String?, val importedMetadata: String?, @JsonDeserialize(using = IntBooleanDeserializer::class) val hasFileExtension: Boolean?, val jarExtraction: String?, val anyArchivesExpanded: String?, val uploadedFiles: String? )
304
null
309
873
0546d450d3082cff0c685897bef4c23e56a3d73a
2,036
ort
Apache License 2.0
marketkit/src/main/java/io/horizontalsystems/marketkit/providers/HsProvider.kt
horizontalsystems
408,718,031
false
null
package io.horizontalsystems.marketkit.providers import com.google.gson.annotations.SerializedName import io.horizontalsystems.marketkit.models.* import io.reactivex.Single import retrofit2.Response import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Headers import retrofit2.http.POST import retrofit2.http.Path import retrofit2.http.Query import retrofit2.http.QueryMap import java.math.BigDecimal class HsProvider(baseUrl: String, apiKey: String) { private val service by lazy { RetrofitUtils.build("${baseUrl}/v1/", mapOf("apikey" to apiKey)) .create(MarketService::class.java) } fun marketInfosSingle( top: Int, currencyCode: String, defi: Boolean, ): Single<List<MarketInfoRaw>> { return service.getMarketInfos( top = top, currencyCode = currencyCode, defi = defi ) } fun advancedMarketInfosSingle( top: Int, currencyCode: String, ): Single<List<MarketInfoRaw>> { return service.getAdvancedMarketInfos( top = top, currencyCode = currencyCode ) } fun marketInfosSingle( coinUids: List<String>, currencyCode: String, ): Single<List<MarketInfoRaw>> { return service.getMarketInfos( uids = coinUids.joinToString(","), currencyCode = currencyCode ) } fun topCoinsMarketInfosSingle( top: Int, currencyCode: String, ): Single<List<MarketInfoRaw>> { return service.getTopCoinsMarketInfos( top = top, currencyCode = currencyCode, ) } fun marketInfosSingle( categoryUid: String, currencyCode: String, ): Single<List<MarketInfoRaw>> { return service.getMarketInfosByCategory( categoryUid = categoryUid, currencyCode = currencyCode ) } fun getCoinCategories(currencyCode: String): Single<List<CoinCategory>> { return service.getCategories(currencyCode) } fun coinCategoryMarketPointsSingle( categoryUid: String, timePeriod: HsTimePeriod, currencyCode: String, ): Single<List<CoinCategoryMarketPoint>> { return service.coinCategoryMarketPoints(categoryUid, timePeriod.value, currencyCode) } fun getCoinPrices( coinUids: List<String>, walletCoinUids: List<String>, currencyCode: String ): Single<List<CoinPrice>> { val additionalParams = mutableMapOf<String, String>() if (walletCoinUids.isNotEmpty()) { additionalParams["enabled_uids"] = walletCoinUids.joinToString(separator = ",") } return service.getCoinPrices( uids = coinUids.joinToString(separator = ","), currencyCode = currencyCode, additionalParams = additionalParams ) .map { coinPrices -> coinPrices.mapNotNull { coinPriceResponse -> coinPriceResponse.coinPrice(currencyCode) } } } fun historicalCoinPriceSingle( coinUid: String, currencyCode: String, timestamp: Long ): Single<HistoricalCoinPriceResponse> { return service.getHistoricalCoinPrice(coinUid, currencyCode, timestamp) } fun coinPriceChartSingle( coinUid: String, currencyCode: String, periodType: HsPointTimePeriod, fromTimestamp: Long? ): Single<List<ChartCoinPriceResponse>> { return service.getCoinPriceChart(coinUid, currencyCode, fromTimestamp, periodType.value) } fun coinPriceChartStartTime(coinUid: String): Single<Long> { return service.getCoinPriceChartStart(coinUid).map { it.timestamp } } fun topPlatformMarketCapStartTime(platform: String): Single<Long> { return service.getTopPlatformMarketCapStart(platform).map { it.timestamp } } fun getMarketInfoOverview( coinUid: String, currencyCode: String, language: String, ): Single<MarketInfoOverviewRaw> { return service.getMarketInfoOverview( coinUid = coinUid, currencyCode = currencyCode, language = language ) } fun getGlobalMarketPointsSingle( currencyCode: String, timePeriod: HsTimePeriod, ): Single<List<GlobalMarketPoint>> { return service.globalMarketPoints(timePeriod.value, currencyCode) } fun defiMarketInfosSingle(currencyCode: String): Single<List<DefiMarketInfoResponse>> { return service.getDefiMarketInfos(currencyCode = currencyCode) } fun marketInfoTvlSingle( coinUid: String, currencyCode: String, timePeriod: HsTimePeriod ): Single<List<ChartPoint>> { return service.getMarketInfoTvl(coinUid, currencyCode, timePeriod.value) .map { responseList -> responseList.mapNotNull { it.tvl?.let { tvl -> ChartPoint(tvl, it.timestamp, null) } } } } fun marketInfoGlobalTvlSingle( chain: String, currencyCode: String, timePeriod: HsTimePeriod ): Single<List<ChartPoint>> { return service.getMarketInfoGlobalTvl( currencyCode, timePeriod.value, blockchain = if (chain.isNotBlank()) chain else null ).map { responseList -> responseList.mapNotNull { it.tvl?.let { tvl -> ChartPoint(tvl, it.timestamp, null) } } } } fun tokenHoldersSingle( authToken: String, coinUid: String, blockchainUid: String ): Single<TokenHolders> { return service.getTokenHolders(authToken, coinUid, blockchainUid) } fun coinTreasuriesSingle(coinUid: String, currencyCode: String): Single<List<CoinTreasury>> { return service.getCoinTreasuries(coinUid, currencyCode).map { responseList -> responseList.mapNotNull { try { CoinTreasury( type = CoinTreasury.TreasuryType.fromString(it.type)!!, fund = it.fund, fundUid = it.fundUid, amount = it.amount, amountInCurrency = it.amountInCurrency, countryCode = it.countryCode ) } catch (exception: Exception) { null } } } } fun investmentsSingle(coinUid: String): Single<List<CoinInvestment>> { return service.getInvestments(coinUid) } fun coinReportsSingle(coinUid: String): Single<List<CoinReport>> { return service.getCoinReports(coinUid) } fun topPlatformsSingle(currencyCode: String): Single<List<TopPlatformResponse>> { return service.getTopPlatforms(currencyCode = currencyCode) } fun topPlatformMarketCapPointsSingle( chain: String, currencyCode: String, periodType: HsPointTimePeriod, fromTimestamp: Long? ): Single<List<TopPlatformMarketCapPoint>> { return service.getTopPlatformMarketCapPoints(chain, currencyCode, fromTimestamp, periodType.value) } fun topPlatformCoinListSingle( chain: String, currencyCode: String ): Single<List<MarketInfoRaw>> { return service.getTopPlatformCoinList( chain = chain, currencyCode = currencyCode ) } fun dexLiquiditySingle( authToken: String, coinUid: String, currencyCode: String, timePeriod: HsTimePeriod ): Single<List<Analytics.VolumePoint>> { return service.getDexLiquidities(authToken, coinUid, currencyCode, timePeriod.value) } fun dexVolumesSingle( authToken: String, coinUid: String, currencyCode: String, timePeriod: HsTimePeriod ): Single<List<Analytics.VolumePoint>> { return service.getDexVolumes(authToken, coinUid, currencyCode, timePeriod.value) } fun transactionDataSingle( authToken: String, coinUid: String, timePeriod: HsTimePeriod, platform: String? ): Single<List<Analytics.CountVolumePoint>> { return service.getTransactions(authToken, coinUid, timePeriod.value, platform) } fun activeAddressesSingle( authToken: String, coinUid: String, timePeriod: HsTimePeriod ): Single<List<Analytics.CountPoint>> { return service.getActiveAddresses(authToken, coinUid, timePeriod.value) } fun marketOverviewSingle(currencyCode: String): Single<MarketOverviewResponse> { return service.getMarketOverview(currencyCode) } fun marketGlobalSingle(currencyCode: String): Single<MarketGlobal> { return service.getMarketGlobal(currencyCode) } fun marketTickers(coinUid: String, currencyCode: String): Single<List<MarketTicker>> { return service.getMarketTickers(coinUid, currencyCode) } fun topMoversRawSingle(currencyCode: String): Single<TopMoversRaw> { return service.getTopMovers(currencyCode) } fun statusSingle(): Single<HsStatus> { return service.getStatus() } fun allCoinsSingle(): Single<List<CoinResponse>> { return service.getAllCoins() } fun allBlockchainsSingle(): Single<List<BlockchainResponse>> { return service.getAllBlockchains() } fun allTokensSingle(): Single<List<TokenResponse>> { return service.getAllTokens() } fun analyticsPreviewSingle(coinUid: String, addresses: List<String>): Single<AnalyticsPreview> { return service.getAnalyticsPreview( coinUid = coinUid, address = if (addresses.isEmpty()) null else addresses.joinToString(",") ) } fun analyticsSingle( authToken: String, coinUid: String, currencyCode: String, ): Single<Analytics> { return service.getAnalyticsData( authToken = authToken, coinUid = coinUid, currencyCode = currencyCode ) } fun rankValueSingle( authToken: String, type: String, currencyCode: String ): Single<List<RankValue>> { return service.getRankValue(authToken, type, currencyCode) } fun rankMultiValueSingle( authToken: String, type: String, currencyCode: String ): Single<List<RankMultiValue>> { return service.getRankMultiValue(authToken, type, currencyCode) } fun subscriptionsSingle( addresses: List<String> ): Single<List<SubscriptionResponse>> { return service.getSubscriptions(addresses.joinToString(separator = ",")) } fun authGetSignMessage(address: String): Single<String> { return service.authGetSignMessage(address) .map { it["message"] } } fun authenticate(signature: String, address: String): Single<String> { return service.authenticate(signature, address) .map { it["token"] } } fun requestPersonalSupport(authToken: String, username: String): Single<Response<Void>> { return service.requestPersonalSupport(authToken, username) } fun verifiedExchangeUids(): Single<List<String>> { return service.verifiedExchangeUids() } fun topPairsSingle(currencyCode: String, page: Int, limit: Int): Single<List<TopPair>> { return service.getTopPairs(currencyCode, page, limit) } fun sendStats(statsJson: String, appVersion: String, appId: String?): Single<Unit> { return service.sendStats( appPlatform = "android", appVersion = appVersion, appId = appId, stats = statsJson ) } fun coinsSignalsSingle(uids: List<String>): Single<List<SignalResponse>> { return service.getCoinsSignals(uids.joinToString(separator = ",")) } fun etfsSingle(currencyCode: String): Single<List<EtfResponse>> { return service.getEtfs(currencyCode) } fun etfPointsSingle(currencyCode: String): Single<List<EtfPointResponse>> { return service.getEtfPoints(currencyCode) } private interface MarketService { @GET("coins") fun getMarketInfos( @Query("limit") top: Int, @Query("currency") currencyCode: String, @Query("defi") defi: Boolean, @Query("order_by_rank") orderByRank: Boolean = true, @Query("fields") fields: String = marketInfoFields, ): Single<List<MarketInfoRaw>> @GET("coins") fun getTopCoinsMarketInfos( @Query("limit") top: Int, @Query("currency") currencyCode: String, @Query("order_by_rank") orderByRank: Boolean = true, @Query("fields") fields: String = topCoinsMarketInfoFields, ): Single<List<MarketInfoRaw>> @GET("coins/filter") fun getAdvancedMarketInfos( @Query("limit") top: Int, @Query("currency") currencyCode: String, @Query("order_by_rank") orderByRank: Boolean = true, @Query("page") page: Int = 1, ): Single<List<MarketInfoRaw>> @GET("coins") fun getMarketInfos( @Query("uids") uids: String, @Query("currency") currencyCode: String, @Query("fields") fields: String = marketInfoFields, ): Single<List<MarketInfoRaw>> @GET("categories/{categoryUid}/coins") fun getMarketInfosByCategory( @Path("categoryUid") categoryUid: String, @Query("currency") currencyCode: String, ): Single<List<MarketInfoRaw>> @GET("categories") fun getCategories( @Query("currency") currencyCode: String ): Single<List<CoinCategory>> @GET("categories/{categoryUid}/market_cap") fun coinCategoryMarketPoints( @Path("categoryUid") categoryUid: String, @Query("interval") interval: String, @Query("currency") currencyCode: String, ): Single<List<CoinCategoryMarketPoint>> @GET("coins") fun getCoinPrices( @Query("uids") uids: String, @Query("currency") currencyCode: String, @Query("fields") fields: String = coinPriceFields, @QueryMap additionalParams: Map<String, String>, ): Single<List<CoinPriceResponse>> @GET("coins/{coinUid}/price_history") fun getHistoricalCoinPrice( @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, @Query("timestamp") timestamp: Long, ): Single<HistoricalCoinPriceResponse> @GET("coins/{coinUid}/price_chart") fun getCoinPriceChart( @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, @Query("from_timestamp") timestamp: Long?, @Query("interval") interval: String, ): Single<List<ChartCoinPriceResponse>> @GET("coins/{coinUid}/price_chart_start") fun getCoinPriceChartStart( @Path("coinUid") coinUid: String ): Single<ChartStart> @GET("coins/{coinUid}") fun getMarketInfoOverview( @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, @Query("language") language: String, ): Single<MarketInfoOverviewRaw> @GET("defi-protocols") fun getDefiMarketInfos( @Query("currency") currencyCode: String ): Single<List<DefiMarketInfoResponse>> @GET("coins/{coinUid}/details") fun getMarketInfoDetails( @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String ): Single<MarketInfoDetailsResponse> @GET("analytics/{coinUid}/preview") fun getAnalyticsPreview( @Path("coinUid") coinUid: String, @Query("address") address: String?, ): Single<AnalyticsPreview> @GET("analytics/{coinUid}") fun getAnalyticsData( @Header("authorization") authToken: String, @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, ): Single<Analytics> @GET("analytics/{coinUid}/dex-liquidity") fun getDexLiquidities( @Header("authorization") auth: String, @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, @Query("interval") interval: String, ): Single<List<Analytics.VolumePoint>> @GET("analytics/{coinUid}/dex-volumes") fun getDexVolumes( @Header("authorization") auth: String, @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, @Query("interval") interval: String ): Single<List<Analytics.VolumePoint>> @GET("analytics/{coinUid}/transactions") fun getTransactions( @Header("authorization") auth: String, @Path("coinUid") coinUid: String, @Query("interval") interval: String, @Query("platform") platform: String? ): Single<List<Analytics.CountVolumePoint>> @GET("analytics/{coinUid}/addresses") fun getActiveAddresses( @Header("authorization") auth: String, @Path("coinUid") coinUid: String, @Query("interval") interval: String ): Single<List<Analytics.CountPoint>> @GET("analytics/{coinUid}/holders") fun getTokenHolders( @Header("authorization") authToken: String, @Path("coinUid") coinUid: String, @Query("blockchain_uid") blockchainUid: String ): Single<TokenHolders> @GET("analytics/ranks") fun getRankValue( @Header("authorization") authToken: String, @Query("type") type: String, @Query("currency") currencyCode: String, ): Single<List<RankValue>> @GET("analytics/ranks") fun getRankMultiValue( @Header("authorization") authToken: String, @Query("type") type: String, @Query("currency") currencyCode: String, ): Single<List<RankMultiValue>> @GET("analytics/subscriptions") fun getSubscriptions( @Query("address") addresses: String ): Single<List<SubscriptionResponse>> @GET("defi-protocols/{coinUid}/tvls") fun getMarketInfoTvl( @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, @Query("interval") interval: String ): Single<List<MarketInfoTvlResponse>> @GET("global-markets/tvls") fun getMarketInfoGlobalTvl( @Query("currency") currencyCode: String, @Query("interval") interval: String, @Query("blockchain") blockchain: String? ): Single<List<MarketInfoTvlResponse>> @GET("funds/treasuries") fun getCoinTreasuries( @Query("coin_uid") coinUid: String, @Query("currency") currencyCode: String ): Single<List<CoinTreasuryResponse>> @GET("funds/investments") fun getInvestments( @Query("coin_uid") coinUid: String, ): Single<List<CoinInvestment>> @GET("reports") fun getCoinReports( @Query("coin_uid") coinUid: String ): Single<List<CoinReport>> @GET("global-markets") fun globalMarketPoints( @Query("interval") timePeriod: String, @Query("currency") currencyCode: String, ): Single<List<GlobalMarketPoint>> @GET("top-platforms") fun getTopPlatforms( @Query("currency") currencyCode: String ): Single<List<TopPlatformResponse>> @GET("top-platforms/{platform}/market_chart_start") fun getTopPlatformMarketCapStart( @Path("platform") platform: String ): Single<ChartStart> @GET("top-platforms/{platform}/market_chart") fun getTopPlatformMarketCapPoints( @Path("platform") platform: String, @Query("currency") currencyCode: String, @Query("from_timestamp") timestamp: Long?, @Query("interval") interval: String ): Single<List<TopPlatformMarketCapPoint>> @GET("top-platforms/{chain}/list") fun getTopPlatformCoinList( @Path("chain") chain: String, @Query("currency") currencyCode: String, ): Single<List<MarketInfoRaw>> @GET("markets/overview") fun getMarketOverview( @Query("currency") currencyCode: String, @Query("simplified") simplified: Boolean = true ): Single<MarketOverviewResponse> @GET("markets/overview-simple") fun getMarketGlobal( @Query("currency") currencyCode: String ): Single<MarketGlobal> @GET("exchanges/tickers/{coinUid}") fun getMarketTickers( @Path("coinUid") coinUid: String, @Query("currency") currencyCode: String, ): Single<List<MarketTicker>> @GET("coins/top-movers") fun getTopMovers( @Query("currency") currencyCode: String ): Single<TopMoversRaw> @GET("status/updates") fun getStatus(): Single<HsStatus> @GET("coins/list") fun getAllCoins(): Single<List<CoinResponse>> @GET("blockchains/list") fun getAllBlockchains(): Single<List<BlockchainResponse>> @GET("tokens/list") fun getAllTokens(): Single<List<TokenResponse>> @GET("auth/get-sign-message") fun authGetSignMessage( @Query("address") address: String ): Single<Map<String, String>> @FormUrlEncoded @POST("auth/authenticate") fun authenticate( @Field("signature") signature: String, @Field("address") address: String ): Single<Map<String, String>> @FormUrlEncoded @POST("support/start-chat") fun requestPersonalSupport( @Header("authorization") auth: String, @Field("username") username: String, ): Single<Response<Void>> @GET("exchanges/whitelist") fun verifiedExchangeUids(): Single<List<String>> @GET("exchanges/top-market-pairs") fun getTopPairs( @Query("currency") currencyCode: String, @Query("page") page: Int, @Query("limit") limit: Int ): Single<List<TopPair>> @POST("stats") @Headers("Content-Type: application/json") fun sendStats( @Header("app_platform") appPlatform: String, @Header("app_version") appVersion: String, @Header("app_id") appId: String?, @Body stats: String, ): Single<Unit> @GET("coins/signals") fun getCoinsSignals( @Query("uids") uids: String, ): Single<List<SignalResponse>> @GET("etfs") fun getEtfs( @Query("currency") currencyCode: String ): Single<List<EtfResponse>> @GET("etfs/total") fun getEtfPoints( @Query("currency") currencyCode: String ): Single<List<EtfPointResponse>> companion object { private const val marketInfoFields = "name,code,price,price_change_1d,price_change_24h,price_change_7d,price_change_30d,price_change_90d,market_cap_rank,coingecko_id,market_cap,market_cap_rank,total_volume" private const val topCoinsMarketInfoFields = "price,price_change_1d,price_change_24h,price_change_7d,price_change_30d,price_change_90d,market_cap_rank,market_cap,total_volume" private const val coinPriceFields = "price,price_change_1d,price_change_24h,last_updated" private const val advancedMarketFields = "all_platforms,price,market_cap,total_volume,price_change_1d,price_change_24h,price_change_7d,price_change_14d,price_change_30d,price_change_200d,price_change_1y,ath_percentage,atl_percentage" } } } data class HistoricalCoinPriceResponse( val timestamp: Long, val price: BigDecimal, ) data class SignalResponse( val uid: String, val signal: Analytics.TechnicalAdvice.Advice? ) data class ChartStart(val timestamp: Long) data class ChartCoinPriceResponse( val timestamp: Long, val price: BigDecimal, @SerializedName("volume") val totalVolume: BigDecimal? ) { val chartPoint: ChartPoint get() { return ChartPoint( price, timestamp, totalVolume ) } }
1
null
24
9
872cb042bdd6eb9063ecb3a2e3954f3954b501bf
25,066
market-kit-android
MIT License
core-verification/src/main/kotlin/io/vibrantnet/ryp/core/verification/configuration/SecurityConfig.kt
nilscodes
769,729,247
false
{"Kotlin": 901616, "TypeScript": 887764, "Dockerfile": 8250, "Shell": 7536, "JavaScript": 1867}
package io.vibrantnet.ryp.core.subscription.configuration import io.vibrantnet.ryp.core.subscription.CoreSubscriptionConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity import org.springframework.security.config.web.server.SecurityWebFiltersOrder import org.springframework.security.config.web.server.ServerHttpSecurity import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.context.ReactiveSecurityContextHolder import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.web.server.ServerWebExchange import org.springframework.web.server.WebFilter import org.springframework.web.server.WebFilterChain import reactor.core.publisher.Mono @EnableWebFluxSecurity @Configuration class SecurityConfig( private val config: CoreSubscriptionConfiguration, ) { @Bean fun filterChain(http: ServerHttpSecurity): SecurityWebFilterChain { http .csrf { it.disable() } .authorizeExchange { it.pathMatchers("/actuator/health").permitAll() if (!config.security.apiKey.isNullOrBlank()) { it.anyExchange().authenticated() } else { it.anyExchange().permitAll() } } if (!config.security.apiKey.isNullOrBlank()) { http.addFilterAt(tokenAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION) } return http.build() } @Bean fun tokenAuthenticationFilter() = TokenAuthenticationFilter(config.security.apiKey) } class TokenAuthenticationFilter( private val authToken: String? ) : WebFilter { override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> { val token = exchange.request.headers.getFirst("Authorization") if (authToken == token) { val authentication = PreAuthenticatedAuthenticationToken(token, null, listOf(SimpleGrantedAuthority("INTERNAL_API"))) return chain.filter(exchange).contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)) } return chain.filter(exchange) } }
0
Kotlin
0
0
a03ddb79eb7a71d0c440584c758cb5600c29c15e
2,452
reach-your-people
Apache License 2.0
core-verification/src/main/kotlin/io/vibrantnet/ryp/core/verification/configuration/SecurityConfig.kt
nilscodes
769,729,247
false
{"Kotlin": 901616, "TypeScript": 887764, "Dockerfile": 8250, "Shell": 7536, "JavaScript": 1867}
package io.vibrantnet.ryp.core.subscription.configuration import io.vibrantnet.ryp.core.subscription.CoreSubscriptionConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity import org.springframework.security.config.web.server.SecurityWebFiltersOrder import org.springframework.security.config.web.server.ServerHttpSecurity import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.context.ReactiveSecurityContextHolder import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.web.server.ServerWebExchange import org.springframework.web.server.WebFilter import org.springframework.web.server.WebFilterChain import reactor.core.publisher.Mono @EnableWebFluxSecurity @Configuration class SecurityConfig( private val config: CoreSubscriptionConfiguration, ) { @Bean fun filterChain(http: ServerHttpSecurity): SecurityWebFilterChain { http .csrf { it.disable() } .authorizeExchange { it.pathMatchers("/actuator/health").permitAll() if (!config.security.apiKey.isNullOrBlank()) { it.anyExchange().authenticated() } else { it.anyExchange().permitAll() } } if (!config.security.apiKey.isNullOrBlank()) { http.addFilterAt(tokenAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION) } return http.build() } @Bean fun tokenAuthenticationFilter() = TokenAuthenticationFilter(config.security.apiKey) } class TokenAuthenticationFilter( private val authToken: String? ) : WebFilter { override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> { val token = exchange.request.headers.getFirst("Authorization") if (authToken == token) { val authentication = PreAuthenticatedAuthenticationToken(token, null, listOf(SimpleGrantedAuthority("INTERNAL_API"))) return chain.filter(exchange).contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)) } return chain.filter(exchange) } }
0
Kotlin
0
0
a03ddb79eb7a71d0c440584c758cb5600c29c15e
2,452
reach-your-people
Apache License 2.0
apps/etterlatte-testdata/src/main/kotlin/no/nav/etterlatte/testdata/dolly/Model.kt
navikt
417,041,535
false
{"Kotlin": 5821854, "TypeScript": 1522353, "Handlebars": 24856, "Shell": 12214, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556}
package no.nav.etterlatte.testdata.dolly import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class Bruker(val brukerId: String?, val brukerType: String?, val navIdent: String?, val epost: String?) @JsonIgnoreProperties(ignoreUnknown = true) data class Gruppe(val id: Long, val navn: String, val hensikt: String) data class HentGruppeResponse( val antallPages: Int, val pageNo: Int, val pageSize: Int, val antallElementer: Int, val contents: List<Gruppe> ) data class OpprettGruppeRequest(val navn: String, val hensikt: String) @JsonIgnoreProperties(ignoreUnknown = true) data class DollyIBrukResponse(val ident: String, val ibruk: Boolean, val beskrivelse: String, val gruppeId: Long) @JsonIgnoreProperties(ignoreUnknown = true) data class BestillingStatus(val id: Long, val ferdig: Boolean) @JsonIgnoreProperties(ignoreUnknown = true) data class TestGruppeBestillinger(val identer: List<TestGruppeBestilling>) @JsonIgnoreProperties(ignoreUnknown = true) data class TestGruppeBestilling(val ident: String, val bestillingId: List<Long>, val ibruk: Boolean) @JsonIgnoreProperties(ignoreUnknown = true) data class DollyPersonResponse(val ident: String, val person: DollyPerson) @JsonIgnoreProperties(ignoreUnknown = true) data class DollyPerson( val doedsfall: List<Doedsfall>, val foedsel: List<Foedsel>, val navn: List<Navn>, val forelderBarnRelasjon: List<ForelderBarnRelasjon>, val sivilstand: List<Sivilstand> ) data class ForelderBarnRelasjon( val relatertPersonsIdent: String, val relatertPersonsRolle: String ) data class Sivilstand(val type: String, val relatertVedSivilstand: String?) @JsonIgnoreProperties(ignoreUnknown = true) data class Doedsfall(val doedsdato: String) @JsonIgnoreProperties(ignoreUnknown = true) data class Foedsel(val foedselsdato: String, val foedselsaar: Int) @JsonIgnoreProperties(ignoreUnknown = true) data class Navn(val fornavn: String, val etternavn: String) data class ForenkletFamilieModell( val ibruk: Boolean, val avdoed: String, val gjenlevende: String, val barn: List<String> ) data class BestillingRequest( val helsoesken: Int, val halvsoeskenAvdoed: Int, val halvsoeskenGjenlevende: Int, val gruppeId: Long )
8
Kotlin
0
6
6d96a550ab22a95e2964ff6cb7dc14b028963dcf
2,308
pensjon-etterlatte-saksbehandling
MIT License
apps/etterlatte-testdata/src/main/kotlin/no/nav/etterlatte/testdata/dolly/Model.kt
navikt
417,041,535
false
{"Kotlin": 5821854, "TypeScript": 1522353, "Handlebars": 24856, "Shell": 12214, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556}
package no.nav.etterlatte.testdata.dolly import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class Bruker(val brukerId: String?, val brukerType: String?, val navIdent: String?, val epost: String?) @JsonIgnoreProperties(ignoreUnknown = true) data class Gruppe(val id: Long, val navn: String, val hensikt: String) data class HentGruppeResponse( val antallPages: Int, val pageNo: Int, val pageSize: Int, val antallElementer: Int, val contents: List<Gruppe> ) data class OpprettGruppeRequest(val navn: String, val hensikt: String) @JsonIgnoreProperties(ignoreUnknown = true) data class DollyIBrukResponse(val ident: String, val ibruk: Boolean, val beskrivelse: String, val gruppeId: Long) @JsonIgnoreProperties(ignoreUnknown = true) data class BestillingStatus(val id: Long, val ferdig: Boolean) @JsonIgnoreProperties(ignoreUnknown = true) data class TestGruppeBestillinger(val identer: List<TestGruppeBestilling>) @JsonIgnoreProperties(ignoreUnknown = true) data class TestGruppeBestilling(val ident: String, val bestillingId: List<Long>, val ibruk: Boolean) @JsonIgnoreProperties(ignoreUnknown = true) data class DollyPersonResponse(val ident: String, val person: DollyPerson) @JsonIgnoreProperties(ignoreUnknown = true) data class DollyPerson( val doedsfall: List<Doedsfall>, val foedsel: List<Foedsel>, val navn: List<Navn>, val forelderBarnRelasjon: List<ForelderBarnRelasjon>, val sivilstand: List<Sivilstand> ) data class ForelderBarnRelasjon( val relatertPersonsIdent: String, val relatertPersonsRolle: String ) data class Sivilstand(val type: String, val relatertVedSivilstand: String?) @JsonIgnoreProperties(ignoreUnknown = true) data class Doedsfall(val doedsdato: String) @JsonIgnoreProperties(ignoreUnknown = true) data class Foedsel(val foedselsdato: String, val foedselsaar: Int) @JsonIgnoreProperties(ignoreUnknown = true) data class Navn(val fornavn: String, val etternavn: String) data class ForenkletFamilieModell( val ibruk: Boolean, val avdoed: String, val gjenlevende: String, val barn: List<String> ) data class BestillingRequest( val helsoesken: Int, val halvsoeskenAvdoed: Int, val halvsoeskenGjenlevende: Int, val gruppeId: Long )
8
Kotlin
0
6
6d96a550ab22a95e2964ff6cb7dc14b028963dcf
2,308
pensjon-etterlatte-saksbehandling
MIT License
3ds2/src/main/java/com/adyen/checkout/adyen3ds2/Adyen3DS2Component.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2019 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by caiof on 7/5/2019. */ package com.adyen.checkout.adyen3ds2 import android.app.Activity import android.content.Intent import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.adyen.checkout.adyen3ds2.internal.provider.Adyen3DS2ComponentProvider import com.adyen.checkout.adyen3ds2.internal.ui.Adyen3DS2Delegate import com.adyen.checkout.components.core.RedirectableActionComponent import com.adyen.checkout.components.core.action.Action import com.adyen.checkout.components.core.internal.ActionComponent import com.adyen.checkout.components.core.internal.ActionComponentEvent import com.adyen.checkout.components.core.internal.ActionComponentEventHandler import com.adyen.checkout.components.core.internal.IntentHandlingComponent import com.adyen.checkout.components.core.internal.provider.ActionComponentProvider import com.adyen.checkout.core.internal.util.LogUtil import com.adyen.checkout.core.internal.util.Logger import com.adyen.checkout.ui.core.internal.ui.ComponentViewType import com.adyen.checkout.ui.core.internal.ui.ViewableComponent import kotlinx.coroutines.flow.Flow /** * An [ActionComponent] that is able to handle 3DS2 related actions. */ class Adyen3DS2Component internal constructor( override val delegate: Adyen3DS2Delegate, internal val actionComponentEventHandler: ActionComponentEventHandler, ) : ViewModel(), ActionComponent, IntentHandlingComponent, ViewableComponent, RedirectableActionComponent { override val viewFlow: Flow<ComponentViewType?> = delegate.viewFlow init { delegate.initialize(viewModelScope) } internal fun observe(lifecycleOwner: LifecycleOwner, callback: (ActionComponentEvent) -> Unit) { delegate.observe(lifecycleOwner, viewModelScope, callback) } internal fun removeObserver() { delegate.removeObserver() } override fun handleAction(action: Action, activity: Activity) { delegate.handleAction(action, activity) } /** * Call this method when receiving the return URL from the 3DS redirect with the result data. * This result will be in the [Intent.getData] and begins with the returnUrl you specified on the payments/ call. * * @param intent The received [Intent]. */ override fun handleIntent(intent: Intent) { delegate.handleIntent(intent) } override fun canHandleAction(action: Action): Boolean { return PROVIDER.canHandleAction(action) } override fun setOnRedirectListener(listener: () -> Unit) { delegate.setOnRedirectListener(listener) } override fun onCleared() { super.onCleared() Logger.d(TAG, "onCleared") delegate.onCleared() } companion object { private val TAG = LogUtil.getTag() @JvmField val PROVIDER: ActionComponentProvider<Adyen3DS2Component, Adyen3DS2Configuration, Adyen3DS2Delegate> = Adyen3DS2ComponentProvider() } }
28
Kotlin
66
96
1f000e27e07467f3a30bb3a786a43de62be003b2
3,174
adyen-android
MIT License
android/src/main/java/com/reactnativeonespanorchestration/utils/Status.kt
arthuraraujo
514,345,590
false
null
package com.reactnativeonespanorchestration.utils enum class Status { DEFAULT, LOADING, SUCCESS, ERROR }
0
Kotlin
0
0
0fab31050bc99f96710551cf6a34f67254e94513
122
rn
MIT License
testapp/src/test/java/uk/ac/bmth/aprog/testapp/PlainCoroutineTest.kt
LouisCAD
112,741,364
true
{"Kotlin": 66470}
package nl.adaptivity.android.test import com.esotericsoftware.kryo.Kryo import com.esotericsoftware.kryo.io.Input import com.esotericsoftware.kryo.io.Output import kotlinx.coroutines.experimental.* import nl.adaptivity.android.kryo.kryoAndroid import org.junit.Test import org.junit.Assert.* import org.objenesis.strategy.StdInstantiatorStrategy import java.io.ByteArrayOutputStream import kotlin.coroutines.experimental.Continuation import kotlin.coroutines.experimental.suspendCoroutine /** * Example local unit test, which will execute on the development machine (host). * * @see [Testing documentation](http://d.android.com/tools/testing) */ class PlainCoroutineTestAndroid { private suspend fun foo(): String { yield() return "2" } @Test fun testClosureSerialization() { // val kryo = Kryo().apply { instantiatorStrategy = Kryo.DefaultInstantiatorStrategy(StdInstantiatorStrategy()) } val kryo = kryoAndroid var coroutine: Continuation<Unit>? = null async<String>(start = CoroutineStart.UNDISPATCHED) { val s = "Hello" suspendCoroutine<Unit> { cont -> coroutine = cont } s } val baos = ByteArrayOutputStream() Output(baos).use { output -> kryo.writeClassAndObject(output, coroutine) } val serialized = baos.toByteArray() // val deserializedCoroutine = coroutine!! val deserializedCoroutine = kryo.readClassAndObject(Input(serialized)) as Continuation<Unit> val resultField = deserializedCoroutine::class.java.getDeclaredField("result").apply { isAccessible=true } resultField.set(deserializedCoroutine, kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED) deserializedCoroutine.resume(Unit) // is not guaranteed to run here val deferred = deserializedCoroutine.context[Job] as Deferred<String> val result = runBlocking { System.out.println("5") deferred.await().apply { System.out.println("6") } } System.out.println("5") assertEquals("Hello", result) } }
0
Kotlin
0
1
8ad2156808b689fe1755e0c7214ae9e4e9afda88
2,174
android-coroutines
Apache License 2.0
subprojects/persistence/src/main/kotlin/com/gradle/dependencymanagement/persistence/BeansRepository.kt
britter
215,755,504
false
null
package com.gradle.dependencymanagement.persistence import com.gradle.dependencymanagement.model.Beans interface BeansRepository { fun getAll(): List<Beans> fun save(beans: Beans) }
0
Kotlin
0
0
3ad7bdf26198bcf64968e9d63e792e72d501c060
194
dependency-management-with-gradle
Apache License 2.0
src/main/kotlin/com/ahmed/schedulebot/models/DayInSchedule.kt
Ahmed-no-oil
637,725,671
false
null
package com.ahmed.schedulebot.models import java.time.DayOfWeek import java.time.LocalTime class DayInSchedule() { var day: DayOfWeek = DayOfWeek.MONDAY var timeComment: String = "" var timeData: LocalTime = LocalTime.MIN var isGoingToStream: Boolean = false var comment: String = "" var authorName: String = "" constructor(dayOfWeek: DayOfWeek) : this() { day = dayOfWeek } override fun toString(): String { val s = if (isGoingToStream) "Stream" else "No Stream" return "${day.name}: $s $timeComment $comment -by $authorName" } }
0
Kotlin
0
0
3c84ffd6a98058fda0b63ba51d75f75e1dbadbf0
600
Schedule-Bot
MIT No Attribution
libraries/stdlib/src/kotlin/properties/Properties.kt
chirino
3,596,099
false
null
package kotlin.properties import java.util.HashMap import java.util.ArrayList public class ChangeEvent(val source: Any, val name: String, val oldValue: Any?, val newValue: Any?) { var propogationId: Any? = null public fun toString() : String = "ChangeEvent($name, $oldValue, $newValue)" } public trait ChangeListener { public fun onPropertyChange(event: ChangeEvent): Unit } /** * Represents an object where properties can be listened to and notified on * updates for easier binding to user interfaces, undo/redo command stacks and * change tracking mechanisms for persistence or distributed change notifications. */ public abstract class ChangeSupport { private var allListeners: MutableList<ChangeListener>? = null private var nameListeners: MutableMap<String, MutableList<ChangeListener>>? = null public fun addChangeListener(listener: ChangeListener) { if (allListeners == null) { allListeners = ArrayList<ChangeListener>() } allListeners?.add(listener) } public fun addChangeListener(name: String, listener: ChangeListener) { if (nameListeners == null) { nameListeners = HashMap<String, MutableList<ChangeListener>>() } var listeners = nameListeners?.get(name) if (listeners == null) { listeners = arrayList<ChangeListener>() nameListeners?.put(name, listeners!!) } listeners?.add(listener) } protected fun <T> changeProperty(name: String, oldValue: T?, newValue: T?): Unit { if (oldValue != newValue) { firePropertyChanged(ChangeEvent(this, name, oldValue, newValue)) } } protected fun firePropertyChanged(event: ChangeEvent): Unit { if (nameListeners != null) { val listeners = nameListeners?.get(event.name) if (listeners != null) { for (listener in listeners) { listener.onPropertyChange(event) } } } if (allListeners != null) { for (listener in allListeners!!) { listener.onPropertyChange(event) } } } protected fun property<T>(init: T): ReadWriteProperty<Any?, T> { return Delegates.observable(init) { desc, oldValue, newValue -> changeProperty(desc.name, oldValue, newValue) } } public fun onPropertyChange(fn: (ChangeEvent) -> Unit) { // TODO //addChangeListener(DelegateChangeListener(fn)) } public fun onPropertyChange(name: String, fn: (ChangeEvent) -> Unit) { // TODO //addChangeListener(name, DelegateChangeListener(fn)) } } /* TODO this seems to generate a compiler barf! see http://youtrack.jetbrains.com/issue/KT-1362 protected fun createChangeListener(fn: (ChangeEvent) -> Unit): ChangeListener { return DelegateChangeListener(fn) } protected fun createChangeListener(fn: (ChangeEvent) -> Unit): ChangeListener { return ChangeListener { public override fun onPropertyChange(event: ChangeEvent): Unit { fn(event) } } } } class DelegateChangeListener(val f: (ChangeEvent) -> Unit) : ChangeListener { public override fun onPropertyChange(event: ChangeEvent): Unit { f(event) } }
2
null
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
3,343
kotlin
Apache License 2.0
core/src/main/kotlin/com/exactpro/th2/read/db/impl/grpc/ExecuteBodyData.kt
th2-net
522,950,261
false
{"Kotlin": 211275, "Python": 4581, "Dockerfile": 115}
/* * Copyright 2023 Exactpro (Exactpro Systems Limited) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exactpro.th2.read.db.impl.grpc import com.exactpro.th2.common.event.IBodyData import com.exactpro.th2.read.db.app.ExecuteQueryRequest import com.exactpro.th2.read.db.core.DataSourceConfiguration import com.exactpro.th2.read.db.core.QueryConfiguration import com.fasterxml.jackson.annotation.JsonInclude @JsonInclude(JsonInclude.Include.NON_EMPTY) data class ExecuteBodyData( val executionId: Long, val dataSource: DataSourceConfiguration, val beforeQueries: List<QueryConfiguration> = emptyList(), val query: QueryConfiguration, val afterQueries: List<QueryConfiguration> = emptyList(), val request: ExecuteQueryRequest, ) : IBodyData
1
Kotlin
0
1
c21fc32b2c750cfedeef6869c2e06b9af02df201
1,292
th2-read-db
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ec2/AclPortRange.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.ec2 import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Number import kotlin.Unit /** * Properties to create PortRange. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.ec2.*; * AclPortRange aclPortRange = AclPortRange.builder() * .from(123) * .to(123) * .build(); * ``` */ public interface AclPortRange { /** * The first port in the range. * * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ public fun from(): Number? = unwrap(this).getFrom() /** * The last port in the range. * * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ public fun to(): Number? = unwrap(this).getTo() /** * A builder for [AclPortRange] */ @CdkDslMarker public interface Builder { /** * @param from The first port in the range. * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ public fun from(from: Number) /** * @param to The last port in the range. * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ public fun to(to: Number) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.ec2.AclPortRange.Builder = software.amazon.awscdk.services.ec2.AclPortRange.builder() /** * @param from The first port in the range. * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ override fun from(from: Number) { cdkBuilder.from(from) } /** * @param to The last port in the range. * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ override fun to(to: Number) { cdkBuilder.to(to) } public fun build(): software.amazon.awscdk.services.ec2.AclPortRange = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.ec2.AclPortRange, ) : CdkObject(cdkObject), AclPortRange { /** * The first port in the range. * * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ override fun from(): Number? = unwrap(this).getFrom() /** * The last port in the range. * * Required if you specify 6 (TCP) or 17 (UDP) for the protocol parameter. */ override fun to(): Number? = unwrap(this).getTo() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): AclPortRange { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.ec2.AclPortRange): AclPortRange = CdkObjectWrappers.wrap(cdkObject) as? AclPortRange ?: Wrapper(cdkObject) internal fun unwrap(wrapped: AclPortRange): software.amazon.awscdk.services.ec2.AclPortRange = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.ec2.AclPortRange } }
1
Kotlin
0
4
e15f2e27e08adeb755ad44b2424c195521a6f5ba
3,425
kotlin-cdk-wrapper
Apache License 2.0
backend/api/src/main/kotlin/io/tolgee/api/v2/controllers/V2LanguagesController.kt
tolgee
303,766,501
false
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
/* * Copyright (c) 2020. Tolgee */ package io.tolgee.api.v2.controllers import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.tags.Tag import io.tolgee.activity.RequestActivity import io.tolgee.activity.data.ActivityType import io.tolgee.component.LanguageValidator import io.tolgee.constants.Message import io.tolgee.dtos.cacheable.LanguageDto import io.tolgee.dtos.request.LanguageRequest import io.tolgee.exceptions.BadRequestException import io.tolgee.hateoas.language.LanguageModel import io.tolgee.hateoas.language.LanguageModelAssembler import io.tolgee.model.enums.Scope import io.tolgee.openApiDocs.OpenApiOrderExtension import io.tolgee.security.ProjectHolder import io.tolgee.security.authentication.AllowApiAccess import io.tolgee.security.authorization.RequiresProjectPermissions import io.tolgee.security.authorization.UseDefaultPermissions import io.tolgee.service.language.LanguageService import io.tolgee.service.project.ProjectService import jakarta.validation.Valid import org.springdoc.core.annotations.ParameterObject import org.springframework.data.domain.Pageable import org.springframework.data.web.PagedResourcesAssembler import org.springframework.data.web.SortDefault import org.springframework.hateoas.PagedModel import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @Suppress("MVCPathVariableInspection", "SpringJavaInjectionPointsAutowiringInspection") @RestController @CrossOrigin(origins = ["*"]) @RequestMapping( value = [ "/v2/projects/{projectId:[0-9]+}/languages", "/v2/projects/languages", ], ) @Tag(name = "Languages", description = "Languages") @OpenApiOrderExtension(2) class V2LanguagesController( private val languageService: LanguageService, private val projectService: ProjectService, private val languageValidator: LanguageValidator, private val languageModelAssembler: LanguageModelAssembler, private val pagedAssembler: PagedResourcesAssembler<LanguageDto>, private val projectHolder: ProjectHolder, ) : IController { @PostMapping(value = [""]) @Operation(summary = "Create language") @RequestActivity(ActivityType.CREATE_LANGUAGE) @RequiresProjectPermissions([Scope.LANGUAGES_EDIT]) @AllowApiAccess @OpenApiOrderExtension(1) fun createLanguage( @PathVariable("projectId") projectId: Long, @RequestBody @Valid dto: LanguageRequest, ): LanguageModel { val project = projectService.get(projectId) languageValidator.validateCreate(dto, project) val language = languageService.createLanguage(dto, project) return languageModelAssembler.toModel(LanguageDto.fromEntity(language, project.baseLanguage?.id)) } @GetMapping(value = ["/{languageId}"]) @Operation(summary = "Get one language") @UseDefaultPermissions @AllowApiAccess @OpenApiOrderExtension(2) fun get( @PathVariable("languageId") id: Long, ): LanguageModel { val languageView = languageService.get(id, projectHolder.project.id) return languageModelAssembler.toModel(languageView) } @GetMapping(value = [""]) @Operation(summary = "Get all languages", tags = ["Languages"]) @UseDefaultPermissions @AllowApiAccess @OpenApiOrderExtension(3) fun getAll( @PathVariable("projectId") pathProjectId: Long?, @ParameterObject @SortDefault("tag") pageable: Pageable, ): PagedModel<LanguageModel> { val data = languageService.getPaged(projectHolder.project.id, pageable) return pagedAssembler.toModel(data, languageModelAssembler) } @Operation(summary = "Update language") @PutMapping(value = ["/{languageId}"]) @RequestActivity(ActivityType.EDIT_LANGUAGE) @RequiresProjectPermissions([Scope.LANGUAGES_EDIT]) @AllowApiAccess @OpenApiOrderExtension(4) fun editLanguage( @RequestBody @Valid dto: LanguageRequest, @PathVariable("languageId") languageId: Long, ): LanguageModel { languageValidator.validateEdit(languageId, dto) languageService.editLanguage(languageId, projectHolder.project.id, dto) return languageModelAssembler.toModel(languageService.get(languageId, projectHolder.project.id)) } @Operation(summary = "Delete specific language") @DeleteMapping(value = ["/{languageId}"]) @RequestActivity(ActivityType.DELETE_LANGUAGE) @RequiresProjectPermissions([Scope.LANGUAGES_EDIT]) @AllowApiAccess @OpenApiOrderExtension(5) fun deleteLanguage( @PathVariable languageId: Long, ) { val isBaseLanguage = languageService.getProjectLanguages(projectHolder.project.id).any { it.base && it.id == languageId } if (isBaseLanguage) { throw BadRequestException(Message.CANNOT_DELETE_BASE_LANGUAGE) } languageService.deleteLanguage(languageId, projectHolder.project.id) } }
170
TypeScript
96
1,837
6e01eec3a19c151a6e0aca49e187e2d0deef3082
5,200
tolgee-platform
Apache License 2.0
libs/hiltLib041/src/main/java/hilt/benchmark/hiltLib041/HiltLib041ViewModel.kt
RBusarow
415,108,675
false
null
package hilt.benchmark.hiltLib041 import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class HiltLib041ViewModel @Inject constructor() : ViewModel()
0
Kotlin
0
1
b271faeb36f8f57977dd2b43d276098e1932f4eb
227
tangle-benchmark-project
Apache License 2.0
src/main/kotlin/org/move/ide/utils/FunctionSignature.kt
pontem-network
279,299,159
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.move.ide.utils import com.intellij.openapi.util.Key import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import org.move.lang.core.psi.* import org.move.lang.core.psi.ext.ability import org.move.lang.core.psi.ext.abilityBounds import org.move.lang.core.psi.ext.bounds import org.move.lang.core.psi.ext.name import org.move.lang.core.types.ty.Ability import org.move.utils.cache import org.move.utils.cacheManager data class FunctionSignature( val typeParameters: List<TypeParameter>, val parameters: List<Parameter>, val returnType: String? ) { data class TypeParameter(val name: String, val bounds: List<Ability>) { override fun hashCode(): Int { return 31 * name.hashCode() } override fun equals(other: Any?): Boolean { return other is TypeParameter && name == other.name } override fun toString(): String { val bounds = if (bounds.isNotEmpty()) bounds.joinToString(" + ", prefix = ": ") else "" return "$name$bounds" } } data class Parameter(val name: String, val type: String) { override fun toString(): String { return "$name: $type" } } companion object { fun resolve(callExpr: MvCallExpr): FunctionSignature? { val function = callExpr.path.reference?.resolveWithAliases() as? MvFunction return function?.signature } fun fromFunction(function: MvFunction): FunctionSignature? { val typeParameters = function.typeParameters .map { typeParam -> val paramName = typeParam.name ?: return null val bounds = typeParam.abilityBounds.mapNotNull { it.ability } TypeParameter(paramName, bounds) } val parameters = function.parameters .map { param -> val paramType = param.type ?: return null Parameter(param.name, paramType.text) } val returnType = function.returnType?.type?.text val signature = FunctionSignature(typeParameters, parameters, returnType) return signature } fun fromItemSpecSignature(specSignature: MvItemSpecSignature): FunctionSignature { val paramList = specSignature.itemSpecFunctionParameterList val specParameters = paramList.itemSpecFunctionParameterList val signatureParams = specParameters.map { specParam -> val paramName = specParam.referenceName val paramType = specParam.typeAnnotation?.type?.text ?: "" Parameter(paramName, paramType) } val specTypeParameters = specSignature.itemSpecTypeParameterList?.itemSpecTypeParameterList.orEmpty() val signatureTypeParams = specTypeParameters .map { specTypeParam -> TypeParameter(specTypeParam.referenceName, specTypeParam.bounds.mapNotNull { it.ability }) } val returnType = specSignature.returnType?.type?.text return FunctionSignature(signatureTypeParams, signatureParams, returnType) } } } private val SIGNATURE_KEY: Key<CachedValue<FunctionSignature?>> = Key.create("SIGNATURE_KEY") val MvFunction.signature: FunctionSignature? get() = project.cacheManager.cache(this, SIGNATURE_KEY) { val signature = FunctionSignature.fromFunction(this) CachedValueProvider.Result.create( signature, project.moveStructureModificationTracker ) } val MvItemSpecSignature.functionSignature: FunctionSignature get() = FunctionSignature.fromItemSpecSignature(this)
4
null
29
69
51a5703d064a4b016ff2a19c2f00fe8f8407d473
3,915
intellij-move
MIT License
compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalScopeImpl.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.resolve.scopes import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.utils.Printer class LexicalScopeImpl @JvmOverloads constructor( parent: HierarchicalScope, override val ownerDescriptor: DeclarationDescriptor, override val isOwnerDescriptorAccessibleByLabel: Boolean, override val implicitReceivers: List<ReceiverParameterDescriptor>, override val kind: LexicalScopeKind, redeclarationChecker: LocalRedeclarationChecker = LocalRedeclarationChecker.DO_NOTHING, initialize: LexicalScopeImpl.InitializeHandler.() -> Unit = {} ) : LexicalScope, LexicalScopeStorage(parent, redeclarationChecker) { init { InitializeHandler().initialize() } override fun toString(): String = kind.toString() override fun printStructure(p: Printer) { p.println( this::class.java.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, " with implicitReceiver: ", if (implicitReceivers.isEmpty()) "NONE" else implicitReceivers.joinToString { it.value.toString() }, " {" ) p.pushIndent() p.print("parent = ") parent.printStructure(p.withholdIndentOnce()) p.popIndent() p.println("}") } inner class InitializeHandler { fun addVariableDescriptor(variableDescriptor: VariableDescriptor): Unit = [email protected](variableDescriptor) fun addFunctionDescriptor(functionDescriptor: FunctionDescriptor): Unit = [email protected](functionDescriptor) fun addClassifierDescriptor(classifierDescriptor: ClassifierDescriptor): Unit = [email protected](classifierDescriptor) } }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
2,490
kotlin
Apache License 2.0
cams-component-network/src/main/java/com/linwei/cams/component/network/utils/LaunchBuilder.kt
WeiShuaiDev
390,640,743
false
null
package com.linwei.cams.component.network.utils class LaunchBuilder<T> { lateinit var onRequest: (suspend () -> T) var onSuccess: ((data: T) -> Unit)? = null var onError: ((Throwable) -> Unit)? = null }
1
Kotlin
1
3
37ffb7142ce1141c7b09ef69664c535150d25aaa
215
CamsModular
Apache License 2.0
sample/src/main/java/com/tyganeutronics/activator/KotlinActivity.kt
richard-muvirimi
354,964,607
false
{"Kotlin": 6864}
package com.tyganeutronics.activator import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.CompoundButton import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatCheckBox import androidx.appcompat.widget.AppCompatSpinner import androidx.appcompat.widget.AppCompatTextView import androidx.core.widget.addTextChangedListener import com.google.android.material.textfield.TextInputEditText import com.tyganeutronics.numbershortener.shorten import java.math.RoundingMode class KotlinActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener, CompoundButton.OnCheckedChangeListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Precision findViewById<AppCompatSpinner>(R.id.as_precision).apply { adapter = ArrayAdapter( this@KotlinActivity, android.R.layout.simple_list_item_1, //https://www.nist.gov/pml/weights-and-measures/metric-si-prefixes (0..24).map { it.toString() }) setSelection(resources.getInteger(R.integer.default_precision)) onItemSelectedListener = this@KotlinActivity } //Round findViewById<AppCompatSpinner>(R.id.as_round).apply { adapter = ArrayAdapter( this@KotlinActivity, android.R.layout.simple_list_item_1, resources.getStringArray(R.array.round) ) onItemSelectedListener = this@KotlinActivity } findViewById<AppCompatCheckBox>(R.id.cb_round).apply { setOnCheckedChangeListener(this@KotlinActivity) } listOf(R.id.ed_suffix, R.id.ed_input).forEach { id -> findViewById<TextInputEditText>(id).apply { addTextChangedListener { shorten() } } } } override fun onStart() { super.onStart() shorten() } /** * The magic happens here */ private fun shorten() { val number = findViewById<TextInputEditText>(R.id.ed_input) .text .toString() .ifEmpty { "0" } .toBigDecimal() val round = findViewById<AppCompatCheckBox>(R.id.cb_round) .isChecked //precision val precision = findViewById<AppCompatSpinner>(R.id.as_precision) .selectedItem .toString() .toInt() //round val roundingMode = findViewById<AppCompatSpinner>(R.id.as_round) .selectedItemPosition //suffix val suffix = findViewById<TextInputEditText>(R.id.ed_suffix) .text .toString() findViewById<AppCompatTextView>(R.id.txt_output).text = number .shorten( round = round, precision = precision, suffix = suffix, roundMode = RoundingMode.valueOf(roundingMode) ) } override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) { shorten() } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { shorten() } override fun onNothingSelected(parent: AdapterView<*>?) { } }
0
Kotlin
1
5
23bca3262a98a8048a66b8b995dc2cdaf3fcf83b
3,441
android-number-shortener
Apache License 2.0
compiler/test/src/org/jetbrains/dukat/compiler/tests/extended/DescriptorTests.kt
posix-dev
285,553,214
true
{"Kotlin": 2740097, "WebIDL": 323303, "TypeScript": 132241, "JavaScript": 18587, "ANTLR": 11333}
package org.jetbrains.dukat.compiler.tests.extended import org.jetbrains.dukat.astModel.SourceFileModel import org.jetbrains.dukat.astModel.flattenDeclarations import org.jetbrains.dukat.cli.compileUnits import org.jetbrains.dukat.compiler.tests.MethodSourceSourceFiles import org.jetbrains.dukat.compiler.tests.createStandardCliTranslator import org.jetbrains.dukat.compiler.tests.descriptors.DescriptorValidator import org.jetbrains.dukat.compiler.tests.descriptors.DescriptorValidator.validate import org.jetbrains.dukat.compiler.tests.descriptors.RecursiveDescriptorComparator import org.jetbrains.dukat.compiler.tests.descriptors.generateModuleDescriptor import org.jetbrains.dukat.descriptors.translateToDescriptors import org.jetbrains.dukat.translatorString.D_TS_DECLARATION_EXTENSION import org.jetbrains.dukat.translatorString.translateModule import org.jetbrains.kotlin.name.FqName import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.condition.EnabledIfSystemProperty import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import java.io.File import kotlin.test.assertEquals @ExtendWith(CliTestsStarted::class, CliTestsEnded::class) class DescriptorTests { @DisplayName("descriptors test set") @ParameterizedTest(name = "{0}") @MethodSource("descriptorsTestSet") fun withValueSource(name: String, tsPath: String, ktPath: String) { assertDescriptorEquals(name, tsPath, ktPath) } @Suppress("UNUSED_PARAMETER") private fun assertDescriptorEquals(name: String, tsPath: String, ktPath: String) { val sourceSet = translator.translate(tsPath) val targetPath = "./build/test/data/descriptors/$name" File(targetPath).deleteRecursively() compileUnits(translateModule(sourceSet), "./build/test/data/descriptors/$name", null) val flattenedSourceSet = sourceSet.copy(sources = sourceSet.sources.flatMap { sourceFile -> sourceFile.root.flattenDeclarations().map { SourceFileModel( sourceFile.name, sourceFile.fileName, it, sourceFile.referencedFiles ) } }) val outputModuleDescriptor = flattenedSourceSet.translateToDescriptors() val expectedModuleDescriptor = generateModuleDescriptor(File(targetPath).walk().filter { it.isFile }.toList()) validate( DescriptorValidator.ValidationVisitor.errorTypesAllowed(), outputModuleDescriptor.getPackage(FqName.ROOT) ) assertEquals( RecursiveDescriptorComparator(RecursiveDescriptorComparator.RECURSIVE_ALL) .serializeRecursively( outputModuleDescriptor.getPackage(FqName.ROOT) ), RecursiveDescriptorComparator(RecursiveDescriptorComparator.RECURSIVE_ALL) .serializeRecursively(expectedModuleDescriptor.getPackage(FqName.ROOT)) ) } companion object { private val translator = createStandardCliTranslator() private val skippedDescriptorTests = setOf( "class/inheritance/overrides", "class/inheritance/overridesFromReferencedFile", "class/inheritance/overridingStdLib", "class/inheritance/simple", "escaping/escaping", "interface/inheritance/simple", "interface/inheritance/withQualifiedParent", "mergeDeclarations/moduleWith/functionAndSecondaryWithTrait", "misc/missedOverloads", "misc/stringTypeInAlias", "qualifiedNames/extendingEntityFromParentModule", "stdlib/convertTsStdlib", "typePredicate/simple" ) @JvmStatic fun descriptorsTestSet(): Array<Array<String>> { return MethodSourceSourceFiles("./test/data/typescript/", D_TS_DECLARATION_EXTENSION) .fileSetWithDescriptors().filter { !skippedDescriptorTests.contains(it.first()) }.toTypedArray() } } }
0
null
0
0
4313a4924dea968bc4198bdd18346958b5fbf534
4,286
dukat
Apache License 2.0
macos-app/src/macosX64Main/kotlin/ru/tetraquark/kotlin/playground/macos/Main.kt
Tetraquark
378,612,246
false
null
package ru.tetraquark.kotlin.playground.macos fun main() { val branches = sequenceOf<ProgramBranch>( CinteropMultiply, ) branches.forEach(ProgramBranch::execute) }
0
Kotlin
0
0
bd86209874d438233cc5383cec2e705d5e7d9f83
186
KotlinPlayground
Apache License 2.0
kex-z3/src/main/kotlin/org/jetbrains/research/kex/smt/z3/Z3Engine.kt
vorpal-research
204,454,367
false
null
package org.jetbrains.research.kex.smt.z3 import com.microsoft.z3.* import org.jetbrains.research.kex.smt.SMTEngine import org.jetbrains.research.kthelper.assert.unreachable import org.jetbrains.research.kthelper.logging.log @Suppress("UNCHECKED_CAST") object Z3Engine : SMTEngine<Context, Expr<*>, Sort, FuncDecl<*>, Pattern>() { private var trueExpr: Expr<BoolSort>? = null private var falseExpr: Expr<BoolSort>? = null private val bvSortCache = mutableMapOf<Int, Sort>() private val bv32Sort get() = bvSortCache[32] private val bv64Sort get() = bvSortCache[64] private var array32to32Sort: Sort? = null private var array32to64Sort: Sort? = null private var array64to64Sort: Sort? = null override fun initialize() { trueExpr = null falseExpr = null array32to32Sort = null array32to64Sort = null array64to64Sort = null bvSortCache.clear() } override fun makeBound(ctx: Context, size: Int, sort: Sort): Expr<*> = ctx.mkBound(size, sort) override fun makePattern(ctx: Context, expr: Expr<*>): Pattern = ctx.mkPattern(expr) override fun getSort(ctx: Context, expr: Expr<*>): Sort = expr.sort override fun getBoolSort(ctx: Context): Sort = ctx.boolSort override fun getBVSort(ctx: Context, size: Int): Sort = bvSortCache.getOrPut(size) { ctx.mkBitVecSort(size) } override fun getFloatSort(ctx: Context): Sort = ctx.mkFPSort32() override fun getDoubleSort(ctx: Context): Sort = ctx.mkFPSort64() override fun getArraySort(ctx: Context, domain: Sort, range: Sort): Sort = when { domain === bv32Sort && range === bv32Sort -> { if (array32to32Sort == null) { array32to32Sort = ctx.mkArraySort(bv32Sort, bv32Sort) } array32to32Sort!! } domain === bv32Sort && range === bv64Sort -> { if (array32to64Sort == null) { array32to64Sort = ctx.mkArraySort(bv32Sort, bv64Sort) } array32to64Sort!! } domain === bv64Sort && range === bv64Sort -> { if (array64to64Sort == null) { array64to64Sort = ctx.mkArraySort(bv64Sort, bv64Sort) } array64to64Sort!! } else -> ctx.mkArraySort(domain, range) } override fun isBoolSort(ctx: Context, sort: Sort): Boolean = sort is BoolSort override fun isBVSort(ctx: Context, sort: Sort): Boolean = sort is BitVecSort override fun isArraySort(ctx: Context, sort: Sort): Boolean = sort is ArraySort<*, *> override fun isFloatSort(ctx: Context, sort: Sort): Boolean = sort is FPSort && sort == ctx.mkFPSort32() override fun isDoubleSort(ctx: Context, sort: Sort): Boolean = sort is FPSort && sort == ctx.mkFPSort64() override fun bvBitSize(ctx: Context, sort: Sort): Int = (sort as BitVecSort).size override fun floatEBitSize(ctx: Context, sort: Sort): Int = (sort as FPSort).eBits override fun floatSBitSize(ctx: Context, sort: Sort): Int = (sort as FPSort).sBits override fun bool2bv(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ite(ctx, expr, makeNumericConst(ctx, sort, 1), makeNumericConst(ctx, sort, 0)) override fun bv2bool(ctx: Context, expr: Expr<*>): Expr<*> = binary(ctx, Opcode.NEQ, expr, makeNumericConst(ctx, getSort(ctx, expr), 0)) override fun bv2bv(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> { val curSize = (getSort(ctx, expr) as BitVecSort).size val castSize = (sort as BitVecSort).size return when { curSize == castSize -> expr curSize < castSize -> sext(ctx, castSize, expr) else -> extract(ctx, expr, high = castSize - 1, low = 0) } } override fun bv2float(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ctx.mkFPToFP(ctx.mkFPRTZ(), expr as BitVecExpr, sort as FPSort, true) override fun float2bv(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ctx.mkFPToBV(ctx.mkFPRTZ(), expr as FPExpr, (sort as BitVecSort).size, true) override fun bvIEEE2float(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ctx.mkFPToFP(expr as BitVecExpr, sort as FPSort) override fun float2IEEEbv(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ctx.mkFPToIEEEBV(expr as FPExpr) override fun float2float(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ctx.mkFPToFP(ctx.mkFPRTZ(), expr as FPExpr, sort as FPSort) override fun hash(ctx: Context, expr: Expr<*>) = expr.hashCode() override fun name(ctx: Context, expr: Expr<*>) = expr.toString() override fun toString(ctx: Context, expr: Expr<*>) = expr.toString() override fun simplify(ctx: Context, expr: Expr<*>): Expr<*> = expr.simplify() override fun equality(ctx: Context, lhv: Expr<*>, rhv: Expr<*>) = lhv == rhv override fun makeVar(ctx: Context, sort: Sort, name: String, fresh: Boolean): Expr<*> = when { fresh -> ctx.mkFreshConst(name, sort) else -> ctx.mkConst(name, sort) } fun makeTrue(ctx: Context) = trueExpr ?: run { trueExpr = ctx.mkTrue() trueExpr!! } fun makeFalse(ctx: Context) = falseExpr ?: run { falseExpr = ctx.mkFalse() falseExpr!! } override fun makeBooleanConst(ctx: Context, value: Boolean): Expr<*> = when { value -> makeTrue(ctx) else -> makeFalse(ctx) } override fun makeIntConst(ctx: Context, value: Short): Expr<*> = ctx.mkNumeral(value.toInt(), getBVSort(ctx, WORD)) override fun makeIntConst(ctx: Context, value: Int): Expr<*> = ctx.mkNumeral(value, getBVSort(ctx, WORD)) override fun makeLongConst(ctx: Context, value: Long): Expr<*> = ctx.mkNumeral(value, getBVSort(ctx, DWORD)) override fun makeNumericConst(ctx: Context, sort: Sort, value: Long): Expr<*> = ctx.mkNumeral(value, sort) override fun makeFloatConst(ctx: Context, value: Float): Expr<*> = ctx.mkFPNumeral(value, getFloatSort(ctx) as FPSort) override fun makeDoubleConst(ctx: Context, value: Double): Expr<*> = ctx.mkFPNumeral(value, getDoubleSort(ctx) as FPSort) override fun makeConstArray(ctx: Context, sort: Sort, expr: Expr<*>): Expr<*> = ctx.mkConstArray(sort, expr) override fun makeFunction(ctx: Context, name: String, retSort: Sort, args: List<Sort>): FuncDecl<*> = ctx.mkFuncDecl(name, args.toTypedArray(), retSort) override fun apply(ctx: Context, f: FuncDecl<*>, args: List<Expr<*>>): Expr<*> = f.apply(*args.toTypedArray()) override fun negate(ctx: Context, expr: Expr<*>): Expr<*> = when (expr) { is BoolExpr -> ctx.mkNot(expr) is BitVecExpr -> ctx.mkBVNeg(expr) is FPExpr -> ctx.mkFPNeg(expr) else -> unreachable { log.error("Unimplemented operation negate") } } override fun binary(ctx: Context, opcode: Opcode, lhv: Expr<*>, rhv: Expr<*>): Expr<*> = when (opcode) { Opcode.EQ -> eq(ctx, lhv, rhv) Opcode.NEQ -> neq(ctx, lhv, rhv) Opcode.ADD -> when { lhv is BitVecExpr && rhv is BitVecExpr -> add(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> add(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.SUB -> when { lhv is BitVecExpr && rhv is BitVecExpr -> sub(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> sub(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.MUL -> when { lhv is BitVecExpr && rhv is BitVecExpr -> mul(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> mul(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.DIVIDE -> when { lhv is BitVecExpr && rhv is BitVecExpr -> sdiv(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> sdiv(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.MOD -> when { lhv is BitVecExpr && rhv is BitVecExpr -> smod(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> fmod(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected mod arguments: $lhv and $rhv") } } Opcode.GT -> when { lhv is BitVecExpr && rhv is BitVecExpr -> gt(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> gt(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.GE -> when { lhv is BitVecExpr && rhv is BitVecExpr -> ge(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> ge(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.LT -> when { lhv is BitVecExpr && rhv is BitVecExpr -> lt(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> lt(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.LE -> when { lhv is BitVecExpr && rhv is BitVecExpr -> le(ctx, lhv, rhv) lhv is FPExpr && rhv is FPExpr -> le(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.SHL -> shl(ctx, lhv as BitVecExpr, rhv as BitVecExpr) Opcode.SHR -> lshr(ctx, lhv as BitVecExpr, rhv as BitVecExpr) Opcode.ASHR -> ashr(ctx, lhv as BitVecExpr, rhv as BitVecExpr) Opcode.AND -> when { lhv is BoolExpr && rhv is BoolExpr -> and(ctx, lhv, rhv) lhv is BitVecExpr && rhv is BitVecExpr -> and(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected and arguments: $lhv and $rhv") } } Opcode.OR -> when { lhv is BoolExpr && rhv is BoolExpr -> or(ctx, lhv, rhv) lhv is BitVecExpr && rhv is BitVecExpr -> or(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected or arguments: $lhv or $rhv") } } Opcode.XOR -> when { lhv is BoolExpr && rhv is BoolExpr -> xor(ctx, lhv, rhv) lhv is BitVecExpr && rhv is BitVecExpr -> xor(ctx, lhv, rhv) else -> unreachable { log.error("Unexpected xor arguments: $lhv xor $rhv") } } Opcode.IMPLIES -> implies(ctx, lhv as BoolExpr, rhv as BoolExpr) Opcode.IFF -> iff(ctx, lhv as BoolExpr, rhv as BoolExpr) Opcode.CONCAT -> concat(ctx, lhv as BitVecExpr, rhv as BitVecExpr) } private fun eq(ctx: Context, lhv: Expr<*>, rhv: Expr<*>) = ctx.mkEq(lhv, rhv) private fun neq(ctx: Context, lhv: Expr<*>, rhv: Expr<*>) = ctx.mkNot(eq(ctx, lhv, rhv)) private fun add(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVAdd(lhv, rhv) private fun add(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPAdd(ctx.mkFPRNA(), lhv, rhv) private fun sub(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSub(lhv, rhv) private fun sub(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPSub(ctx.mkFPRNA(), lhv, rhv) private fun mul(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVMul(lhv, rhv) private fun mul(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPMul(ctx.mkFPRNA(), lhv, rhv) private fun sdiv(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSDiv(lhv, rhv) private fun sdiv(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPDiv(ctx.mkFPRNA(), lhv, rhv) private fun udiv(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVUDiv(lhv, rhv) private fun smod(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSMod(lhv, rhv) private fun umod(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVURem(lhv, rhv) private fun fmod(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPRem(lhv, rhv) private fun gt(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSGT(lhv, rhv) private fun gt(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPGt(lhv, rhv) private fun ge(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSGE(lhv, rhv) private fun ge(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPGEq(lhv, rhv) private fun lt(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSLT(lhv, rhv) private fun lt(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPLt(lhv, rhv) private fun le(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSLE(lhv, rhv) private fun le(ctx: Context, lhv: FPExpr, rhv: FPExpr) = ctx.mkFPLEq(lhv, rhv) private fun shl(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVSHL(lhv, rhv) private fun lshr(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVLSHR(lhv, rhv) private fun ashr(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVASHR(lhv, rhv) private fun and(ctx: Context, lhv: BoolExpr, rhv: BoolExpr) = ctx.mkAnd(lhv, rhv) private fun or(ctx: Context, lhv: BoolExpr, rhv: BoolExpr) = ctx.mkOr(lhv, rhv) private fun xor(ctx: Context, lhv: BoolExpr, rhv: BoolExpr) = ctx.mkXor(lhv, rhv) private fun and(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVAND(lhv, rhv) private fun or(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVOR(lhv, rhv) private fun xor(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkBVXOR(lhv, rhv) private fun implies(ctx: Context, lhv: BoolExpr, rhv: BoolExpr) = ctx.mkImplies(lhv, rhv) private fun iff(ctx: Context, lhv: BoolExpr, rhv: BoolExpr) = ctx.mkIff(lhv, rhv) private fun concat(ctx: Context, lhv: BitVecExpr, rhv: BitVecExpr) = ctx.mkConcat(lhv, rhv) override fun conjunction(ctx: Context, vararg exprs: Expr<*>): Expr<*> { val boolExprs = exprs.map { it as BoolExpr }.toTypedArray() return ctx.mkAnd(*boolExprs) } override fun conjunction(ctx: Context, exprs: Collection<Expr<*>>): Expr<*> { val boolExprs = exprs.map { it as BoolExpr }.toTypedArray() return ctx.mkAnd(*boolExprs) } override fun sext(ctx: Context, n: Int, expr: Expr<*>): Expr<*> { val exprBitSize = bvBitSize(ctx, getSort(ctx, expr)) return if (exprBitSize < n) ctx.mkSignExt(n - exprBitSize, expr as BitVecExpr) else expr } override fun zext(ctx: Context, n: Int, expr: Expr<*>): Expr<*> { val exprBitSize = bvBitSize(ctx, getSort(ctx, expr)) return if (exprBitSize < n) ctx.mkZeroExt(n - exprBitSize, expr as BitVecExpr) else expr } fun <T : Sort, R : Sort> ld(ctx: Context, array: Expr<*>, index: Expr<T>): Expr<*> = ctx.mkSelect(array as ArrayExpr<T, R>, index) fun <T : Sort, R : Sort> st(ctx: Context, array: Expr<*>, index: Expr<T>, value: Expr<R>): Expr<*> = ctx.mkStore(array as ArrayExpr<T, R>, index, value) override fun load(ctx: Context, array: Expr<*>, index: Expr<*>): Expr<*> = ld<Sort, Sort>(ctx, array, index as Expr<Sort>) override fun store(ctx: Context, array: Expr<*>, index: Expr<*>, value: Expr<*>): Expr<*> = st<Sort, Sort>(ctx, array, index as Expr<Sort>, value as Expr<Sort>) override fun ite(ctx: Context, cond: Expr<*>, lhv: Expr<*>, rhv: Expr<*>): Expr<*> = ctx.mkITE(cond as BoolExpr, lhv, rhv) override fun extract(ctx: Context, bv: Expr<*>, high: Int, low: Int): Expr<*> = ctx.mkExtract(high, low, bv as BitVecExpr) override fun forAll(ctx: Context, sorts: List<Sort>, body: (List<Expr<*>>) -> Expr<*>): Expr<*> { val numArgs = sorts.lastIndex val bounds = sorts.asSequence().withIndex().map { (index, sort) -> makeBound(ctx, index, sort) }.toList() val realBody = body(bounds) val names = (0..numArgs).map { "forall_bound_${numArgs - it}" }.map { ctx.mkSymbol(it) }.toTypedArray() val sortsRaw = sorts.toTypedArray() return ctx.mkForall(sortsRaw, names, realBody as BoolExpr, 0, arrayOf(), arrayOf(), null, null) } override fun forAll( ctx: Context, sorts: List<Sort>, body: (List<Expr<*>>) -> Expr<*>, patternGenerator: (List<Expr<*>>) -> List<Pattern> ): Expr<*> { val numArgs = sorts.lastIndex val bounds = sorts.asSequence().withIndex().map { (index, sort) -> makeBound(ctx, index, sort) }.toList() val realBody = body(bounds) val names = (0..numArgs).map { "forall_bound_${numArgs - it - 1}" }.map { ctx.mkSymbol(it) }.toTypedArray() val sortsRaw = sorts.toTypedArray() val patterns = patternGenerator(bounds).toTypedArray() return ctx.mkForall(sortsRaw, names, realBody as BoolExpr, 0, patterns, arrayOf(), null, null) } override fun exists(ctx: Context, sorts: List<Sort>, body: (List<Expr<*>>) -> Expr<*>): Expr<*> { val numArgs = sorts.lastIndex val bounds = sorts.asSequence().withIndex().map { (index, sort) -> makeBound(ctx, index, sort) }.toList() val realBody = body(bounds) val names = (0..numArgs).map { "exists_bound_${numArgs - it}" }.map { ctx.mkSymbol(it) }.toTypedArray() val sortsRaw = sorts.toTypedArray() return ctx.mkExists(sortsRaw, names, realBody as BoolExpr, 0, arrayOf(), arrayOf(), null, null) } override fun exists( ctx: Context, sorts: List<Sort>, body: (List<Expr<*>>) -> Expr<*>, patternGenerator: (List<Expr<*>>) -> List<Pattern> ): Expr<*> { val numArgs = sorts.lastIndex val bounds = sorts.asSequence().withIndex().map { (index, sort) -> makeBound(ctx, index, sort) }.toList() val realBody = body(bounds) val names = (0..numArgs).map { "forall_bound_${numArgs - it - 1}" }.map { ctx.mkSymbol(it) }.toTypedArray() val sortsRaw = sorts.toTypedArray() val patterns = patternGenerator(bounds).toTypedArray() return ctx.mkExists(sortsRaw, names, realBody as BoolExpr, 0, patterns, arrayOf(), null, null) } override fun lambda( ctx: Context, elementSort: Sort, sorts: List<Sort>, body: (List<Expr<*>>) -> Expr<*> ): Expr<*> { val numArgs = sorts.lastIndex val bounds = sorts.asSequence().withIndex().map { (index, sort) -> makeBound(ctx, index, sort) }.toList() val realBody = body(bounds) val names = (0..numArgs).map { "lambda_bound_${numArgs - it}" }.map { ctx.mkSymbol(it) }.toTypedArray() val sortsRaw = sorts.toTypedArray() return ctx.mkLambda(sortsRaw, names, realBody) } override fun getStringSort(ctx: Context): Sort = ctx.stringSort override fun isStringSort(ctx: Context, sort: Sort): Boolean = sort == ctx.stringSort override fun bv2string(ctx: Context, expr: Expr<*>): Expr<*> = ctx.intToString(ctx.mkBV2Int(expr as BitVecExpr, true)) override fun float2string(ctx: Context, expr: Expr<*>): Expr<*> = ctx.intToString(ctx.mkBV2Int(ctx.mkFPToBV(ctx.mkFPRTZ(), expr as Expr<FPSort>, WORD, true), true)) override fun double2string(ctx: Context, expr: Expr<*>): Expr<*> = ctx.intToString(ctx.mkBV2Int(ctx.mkFPToBV(ctx.mkFPRTZ(), expr as Expr<FPSort>, DWORD, true), true)) override fun string2bv(ctx: Context, expr: Expr<*>, sort: Sort): Expr<*> = ctx.mkInt2BV(getSortBitSize(ctx, sort), ctx.stringToInt(expr as Expr<SeqSort<BitVecSort>>)) override fun string2float(ctx: Context, expr: Expr<*>): Expr<*> = bv2float(ctx, string2bv(ctx, expr, getBVSort(ctx, WORD)), getFloatSort(ctx)) override fun string2double(ctx: Context, expr: Expr<*>): Expr<*> = bv2float(ctx, string2bv(ctx, expr, getBVSort(ctx, DWORD)), getDoubleSort(ctx)) override fun makeStringConst(ctx: Context, value: String): Expr<*> = ctx.mkString(value) override fun contains(ctx: Context, seq: Expr<*>, value: Expr<*>): Expr<*> = ctx.mkContains<BoolSort>(seq as Expr<SeqSort<BitVecSort>>, value as Expr<SeqSort<BitVecSort>>) override fun nths(ctx: Context, seq: Expr<*>, index: Expr<*>): Expr<*> { // val char2Int = ctx.mkFuncDecl("char.to_int", ctx.mkBitVecSort(), ctx.mkIntSort()) // val nth = ctx.MkNth(seq as Expr<SeqSort<BitVecSort>>, ctx.mkBV2Int(index as Expr<BitVecSort>, true)) // val nthInt = ctx.mkApp(char2Int, nth) // return ctx.mkInt2BV(WORD, nthInt) return ctx.MkNth<BitVecSort>(seq as Expr<SeqSort<BitVecSort>>, ctx.mkBV2Int(index as Expr<BitVecSort>, true)) } override fun length(ctx: Context, seq: Expr<*>): Expr<*> = ctx.mkInt2BV(WORD, ctx.mkLength<IntSort>(seq as Expr<SeqSort<BitVecSort>>)) override fun prefixOf(ctx: Context, seq: Expr<*>, prefix: Expr<*>): Expr<*> = ctx.mkPrefixOf<BoolSort>(prefix as Expr<SeqSort<BitVecSort>>, seq as Expr<SeqSort<BitVecSort>>) override fun suffixOf(ctx: Context, seq: Expr<*>, suffix: Expr<*>): Expr<*> = ctx.mkSuffixOf<BoolSort>(suffix as Expr<SeqSort<BitVecSort>>, seq as Expr<SeqSort<BitVecSort>>) override fun at(ctx: Context, seq: Expr<*>, index: Expr<*>): Expr<*> = ctx.mkAt<SeqSort<BitVecSort>>(seq as Expr<SeqSort<BitVecSort>>, ctx.mkBV2Int(index as Expr<BitVecSort>, true)) override fun extract(ctx: Context, seq: Expr<*>, from: Expr<*>, to: Expr<*>): Expr<*> = ctx.mkExtract<SeqSort<BitVecSort>>( seq as Expr<SeqSort<BitVecSort>>, ctx.mkBV2Int(from as Expr<BitVecSort>, true), ctx.mkBV2Int(to as Expr<BitVecSort>, true) ) override fun indexOf(ctx: Context, seq: Expr<*>, subSeq: Expr<*>, offset: Expr<*>): Expr<*> = ctx.mkInt2BV(WORD, ctx.mkIndexOf<SeqSort<BitVecSort>>( seq as Expr<SeqSort<BitVecSort>>, subSeq as Expr<SeqSort<BitVecSort>>, ctx.mkBV2Int(offset as Expr<BitVecSort>, true) )) override fun concat(ctx: Context, lhv: Expr<*>, rhv: Expr<*>): Expr<*> = ctx.mkConcat(lhv as Expr<SeqSort<BitVecSort>>, rhv as Expr<SeqSort<BitVecSort>>) override fun char2string(ctx: Context, expr: Expr<*>): Expr<*> = ctx.mkUnit(bv2bv(ctx, expr, getBVSort(ctx, 8))) }
6
null
11
7
3bd61388117e635f568a19bd6f871c30d2184bd3
22,164
kex
Apache License 2.0
sample/inbox/src/main/java/com/walletconnect/sample/web3inbox/ui/routes/W3ISampleNavGraph.kt
WalletConnect
435,951,419
false
null
@file:OptIn(ExperimentalMaterialNavigationApi::class) package com.walletconnect.sample.web3inbox.ui.routes import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp import androidx.navigation.* import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.google.accompanist.navigation.material.BottomSheetNavigator import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi import com.google.accompanist.navigation.material.ModalBottomSheetLayout import com.walletconnect.sample.web3inbox.ui.routes.select_account.AccountRoute import com.walletconnect.sample.web3inbox.ui.routes.home.HomeRoute import com.walletconnect.wcmodal.ui.theme.WalletConnectModalTheme import com.walletconnect.wcmodal.ui.walletConnectModalGraph @OptIn(ExperimentalMaterialNavigationApi::class) @Composable fun W3ISampleNavGraph( bottomSheetNavigator: BottomSheetNavigator, navController: NavHostController, ) { WalletConnectModalTheme( accentColor = MaterialTheme.colors.primary, onAccentColor = MaterialTheme.colors.onPrimary ) { ModalBottomSheetLayout( bottomSheetNavigator = bottomSheetNavigator, sheetShape = RoundedCornerShape(topEnd = 12.dp, topStart = 12.dp) ) { NavHost( navController = navController, startDestination = Route.SelectAccount.path ) { composable(Route.SelectAccount.path) { AccountRoute(navController) } composable(Route.Home.path + "/{$accountArg}", arguments = listOf(navArgument(accountArg) { type = NavType.StringType })) { navBackStackEntry -> HomeRoute(navController, navBackStackEntry.arguments?.getString(accountArg)!!) } walletConnectModalGraph(navController) } } } } const val accountArg = "accountArg" fun NavController.navigateToW3I(selectedAccount: String) { navigate(Route.Home.path + "/$selectedAccount") } fun NavController.navigateToSelectAccount() { navigate(Route.SelectAccount.path) { popUpTo(Route.SelectAccount.path) { inclusive = true } } }
147
Kotlin
59
157
e34c0e716ca68021602463773403d8d7fd558b34
2,351
WalletConnectKotlinV2
Apache License 2.0
node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/kryo/ArrayListItrConcurrentModificationException.kt
corda
70,137,417
false
{"Kotlin": 10675960, "Java": 275115, "C++": 239894, "Python": 37811, "Shell": 28324, "CSS": 23544, "Groovy": 14725, "CMake": 5393, "Dockerfile": 2574, "Batchfile": 1777, "PowerShell": 660, "C": 454}
package net.corda.nodeapi.internal.serialization.kryo import org.mockito.kotlin.doReturn import org.mockito.kotlin.whenever import net.corda.core.serialization.EncodingWhitelist import net.corda.core.serialization.internal.CheckpointSerializationContext import net.corda.core.serialization.internal.checkpointDeserialize import net.corda.core.serialization.internal.checkpointSerialize import net.corda.coretesting.internal.rigorousMock import net.corda.serialization.internal.AllWhitelist import net.corda.serialization.internal.CheckpointSerializationContextImpl import net.corda.serialization.internal.CordaSerializationEncoding import net.corda.testing.core.internal.CheckpointSerializationEnvironmentRule import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.collections.LinkedHashMap import kotlin.collections.LinkedHashSet @RunWith(Parameterized::class) class ArrayListItrConcurrentModificationException(private val compression: CordaSerializationEncoding?) { companion object { @Parameters(name = "{0}") @JvmStatic fun compression() = arrayOf<CordaSerializationEncoding?>(null) + CordaSerializationEncoding.values() } @get:Rule val serializationRule = CheckpointSerializationEnvironmentRule(inheritable = true) private lateinit var context: CheckpointSerializationContext @Before fun setup() { context = CheckpointSerializationContextImpl( deserializationClassLoader = javaClass.classLoader, whitelist = AllWhitelist, properties = emptyMap(), objectReferencesEnabled = true, encoding = compression, encodingWhitelist = rigorousMock<EncodingWhitelist>().also { if (compression != null) doReturn(true).whenever(it).acceptEncoding(compression) }) } @Test(timeout=300_000) fun `ArrayList iterator can checkpoint without error`() { runTestWithCollection(ArrayList()) } @Test(timeout=300_000) fun `HashSet iterator can checkpoint without error`() { runTestWithCollection(HashSet()) } @Test(timeout=300_000) fun `LinkedHashSet iterator can checkpoint without error`() { runTestWithCollection(LinkedHashSet()) } @Test(timeout=300_000) fun `HashMap iterator can checkpoint without error`() { runTestWithCollection(HashMap()) } @Test(timeout=300_000) fun `LinkedHashMap iterator can checkpoint without error`() { runTestWithCollection(LinkedHashMap()) } @Test(timeout=300_000) fun `LinkedList iterator can checkpoint without error`() { runTestWithCollection(LinkedList()) } private data class TestCheckpoint<C,I>(val list: C, val iterator: I) private fun runTestWithCollection(collection: MutableCollection<Int>) { for (i in 1..100) { collection.add(i) } val iterator = collection.iterator() iterator.next() val checkpoint = TestCheckpoint(collection, iterator) val serializedBytes = checkpoint.checkpointSerialize(context) val deserializedCheckpoint = serializedBytes.checkpointDeserialize(context) assertThat(deserializedCheckpoint.list).isEqualTo(collection) assertThat(deserializedCheckpoint.iterator.next()).isEqualTo(2) assertThat(deserializedCheckpoint.iterator.hasNext()).isTrue() } private fun runTestWithCollection(collection: MutableMap<Int, Int>) { for (i in 1..100) { collection[i] = i } val iterator = collection.iterator() iterator.next() val checkpoint = TestCheckpoint(collection, iterator) val serializedBytes = checkpoint.checkpointSerialize(context) val deserializedCheckpoint = serializedBytes.checkpointDeserialize(context) assertThat(deserializedCheckpoint.list).isEqualTo(collection) assertThat(deserializedCheckpoint.iterator.next().key).isEqualTo(2) assertThat(deserializedCheckpoint.iterator.hasNext()).isTrue() } }
62
Kotlin
1088
3,989
d27aa0e6850d3804d0982024054376d452e7073a
4,406
corda
Apache License 2.0
src/ii_collections/n16FlatMap.kt
samuelpisa
101,820,858
false
null
package ii_collections fun example() { val result = listOf("abc", "12").flatMap { it.toCharList() } result == listOf('a', 'b', 'c', '1', '2') } val Customer.orderedProducts: Set<Product> get() { // Return all products ordered by customer return orders.flatMap { it.products }.toSet() } val Shop.allOrderedProducts: Set<Product> get() { // Return all products that were ordered by at least one customer return this.customers.flatMap { it.orderedProducts }.toSet() }
37
null
27
6
424e1795fd807d8cec42b2ede5c4c8928d5283c3
494
kotlin-koans-resolved
MIT License
src/main/kotlin/de/derniklaas/buildbugs/BugCreator.kt
derNiklaas
737,881,211
false
null
package de.derniklaas.buildbugs import com.noxcrew.noxesium.network.clientbound.ClientboundMccServerPacket import de.derniklaas.buildbugs.utils.ServerState import de.derniklaas.buildbugs.utils.Utils import net.minecraft.client.MinecraftClient import net.minecraft.client.util.Clipboard import net.minecraft.util.math.BlockPos object BugCreator { var gameState: ServerState = ServerState.UNKNOWN private set private val clipboard: Clipboard = Clipboard() /** * Gathers information to more easily create a build bug report. */ fun report() { val client = MinecraftClient.getInstance() val server = client.currentServerEntry ?: return val player = client.player ?: return // Check if the player is connected to a server if (server.isLocal) { Utils.sendErrorMessage("You are not connected to a server.") return } // Check if the player is connected to a MCC related server if (!Utils.isOnMCCServer()) { Utils.sendErrorMessage("You are not connected to a MCC related server.") return } // Get the "area" of the player val area = gameState.getFancyName() val blockPos = player.blockPos val map = gameState.mapName val minecraftMessage = getCopyMessage(area, map, blockPos).trim() val discordMessage = getCopyMessage(area, map, blockPos, true) Utils.sendMiniMessage( "<click:copy_to_clipboard:'${ discordMessage.replace( "'", "\\\'" ) }'>$minecraftMessage <yellow><bold>[CLICK TO COPY]</bold></yellow></click>", true ) if (BuildBugsClientEntrypoint.config.copyToClipboard) { setClipboard(client, discordMessage) } } /** * Updates [gameState] when a new packet is received. */ fun handleServerStatePacket(packet: ClientboundMccServerPacket, printState: Boolean) { gameState = ServerState.fromPacket(packet) if (printState) { printCurrentGameState() } } /** * Updates the map saved in [gameState] with the given [name]. */ fun updateMap(name: String) { gameState = gameState.withMapName(name) printCurrentGameState() } private fun getCopyMessage(area: String, map: String, position: BlockPos, discord: Boolean = false): String { val start = if (area.isNotBlank()) "$area, " else "" val codeBlock = if (!discord) "" else "`" return "[$start${if (map.isNotBlank() && map != Constants.UNKNOWN) map else "$codeBlock${position.x} ${position.y} ${position.z}$codeBlock"}] " } /** * Prints the current [gameState] to the chat. */ fun printCurrentGameState() { Utils.sendDebugMessage("Current gameState: ${gameState.miniMessageString()}") } /** * Sets the content of the Clipboard to [text]. */ fun setClipboard(client: MinecraftClient, text: String) { clipboard.setClipboard(client.window.handle, text) Utils.sendMiniMessage("<i>Copied </i>${if (BuildBugsClientEntrypoint.config.debugMode) "<green>${text.trim()}</green> " else ""}<i>to clipboard.</i>") } /** * Resets the [gameState] to [ServerState.UNKNOWN]. */ fun resetGameState() { gameState = ServerState.UNKNOWN Utils.sendDebugMessage("Reset gameState.") } /** * Forces the [gameState] to the given [type], [subType] and [map]. */ fun forceGameState(type: String, subType: String, map: String) { gameState = ServerState(type, subType, map) Utils.sendDebugMessage("Forced gameState to ${gameState.miniMessageString()}") } }
1
null
0
2
494cbf9feb8c6dc97e9587a2bd22397d9967f542
3,798
build-bugs
MIT License
operations-karma/src/main/kotlin/com/enigmastation/nevet/karma/operation/GetKarmaOperation.kt
jottinger
842,021,834
false
{"Kotlin": 151168, "Dockerfile": 286, "Just": 148}
/* Joseph B. Ottinger (C)2024 */ package com.enigmastation.nevet.karma.operation import com.enigmastation.nevet.extensions.compress import com.enigmastation.nevet.karma.service.KarmaEntryService import com.enigmastation.nevet.whiteboard.model.MessageSource import com.enigmastation.nevet.whiteboard.model.RouterMessage import com.enigmastation.nevet.whiteboard.model.RouterOperation import org.springframework.stereotype.Service @Service class GetKarmaOperation(val karmaEntryService: KarmaEntryService) : RouterOperation(), KarmaOperation { override fun canHandle(message: RouterMessage): Boolean { return message.messageSource == MessageSource.IRC && message.content.compress().removePrefix("~").startsWith("karma ") } override fun handleMessage(message: RouterMessage): RouterMessage? { if (!canHandle(message)) { return null } val selector = message.content.compress().removePrefix("~").removePrefix("karma ") val karma = karmaEntryService.getKarma(selector) return if (karmaEntryService.hasKarma(selector)) { val karmaExpression = if (karma == 0) { "neutral karma" } else { "karma of $karma" } if (message.source.equals(selector, true)) { message.respondWith("$selector, you have $karmaExpression.") } else { message.respondWith("$selector has $karmaExpression.") } } else { if (message.source.equals(selector, true)) { message.respondWith("$selector, you have no karma data.") } else { message.respondWith("$selector has no karma data.") } } } }
11
Kotlin
0
1
6093b1c76058396aaf2bc781c1d1beea8c7be060
1,799
nevet
MIT License
infra/nats/src/test/kotlin/io/nats/examples/jetstream/JetStreamTestUtils.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.nats.examples.jetstream import io.bluetape4k.logging.KotlinLogging import io.bluetape4k.logging.debug import io.bluetape4k.nats.client.natsMessageOf import io.bluetape4k.support.toUtf8Bytes import io.nats.client.JetStream private val log = KotlinLogging.logger { } fun JetStream.publish(subject: String, prefix: String = "data", times: Int = 1, msgSize: Int, verbose: Boolean) { if (verbose) { log.debug { "Publish ->" } } repeat(times) { index -> val data = makeData(prefix, msgSize, verbose, index) val msg = natsMessageOf(subject, data) publish(msg) } if (verbose) { log.debug { " <-" } } } fun makeData(prefix: String, msgSize: Int, verbose: Boolean, index: Int): ByteArray? { if (msgSize == 0) { return null } val text = "$prefix-$index." if (verbose) { log.debug { " $text" } } var data = text.toUtf8Bytes() if (data.size < msgSize) { val larger = ByteArray(msgSize) data.copyInto(larger, 0, 0, data.size) data = larger } return data }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
1,099
bluetape4k
MIT License
core/model/src/main/java/app/tsampa/model/Food.kt
stefanosansone
601,827,249
false
null
package app.tsampa.model data class Food( var name: String = "", var description: String = "", var carbohydrates: Int = 0, var proteins: Int = 0, var fats: Int = 0, )
2
Kotlin
0
1
e12996a6e52c1575acb5955896823a6708f44f3c
187
tsampa
Apache License 2.0
http4k-core/src/main/kotlin/org/http4k/core/http.kt
http4k
86,003,479
false
null
@file:Suppress("UNCHECKED_CAST") package org.http4k.core import org.http4k.asString import org.http4k.core.Body.Companion.EMPTY import org.http4k.core.HttpMessage.Companion.HTTP_1_1 import java.io.Closeable import java.io.InputStream import java.nio.ByteBuffer typealias Headers = Parameters /** * If this Body is NOT being returned to the caller (via a Server implementation or otherwise), close() should be * called. */ interface Body : Closeable { val stream: InputStream val payload: ByteBuffer /** * Will be `null` for bodies where it's impossible to a priori determine - e.g. StreamBody */ val length: Long? companion object { operator fun invoke(body: String): Body = MemoryBody(body) operator fun invoke(body: ByteBuffer): Body = MemoryBody(body) operator fun invoke(body: InputStream, length: Long? = null): Body = StreamBody(body, length) val EMPTY: Body = MemoryBody("") } } /** * Represents a body that is backed by an in-memory ByteBuffer. Closing this has no effect. **/ data class MemoryBody(override val payload: ByteBuffer) : Body { constructor(payload: String) : this(ByteBuffer.wrap(payload.toByteArray())) override val length: Long by lazy { payload.array().size.toLong() } override fun close() {} override val stream: InputStream get() = payload.array().inputStream() override fun toString(): String = payload.asString() } /** * Represents a body that is backed by a (lazy) InputStream. Operating with StreamBody has a number of potential * gotchas: * 1. Attempts to consume the stream will pull all of the contents into memory, and should thus be avoided. * This includes calling `equals()` and `payload` * 2. If this Body is NOT being returned to the caller (via a Server implementation or otherwise), close() should be called. * 3. Depending on the source of the stream, this body may or may not contain a known length. */ class StreamBody(override val stream: InputStream, override val length: Long? = null) : Body { override val payload: ByteBuffer by lazy { stream.use { ByteBuffer.wrap(it.readBytes()) } } override fun close() { stream.close() } override fun toString(): String = "<<stream>>" override fun equals(other: Any?): Boolean = when { this === other -> true other !is Body? -> false else -> payload == other?.payload } override fun hashCode(): Int = payload.hashCode() } interface HttpMessage : Closeable { val headers: Headers val body: Body val version: String fun toMessage(): String fun header(name: String): String? = headers.headerValue(name) fun header(name: String, value: String?): HttpMessage fun headers(headers: Headers): HttpMessage fun replaceHeader(name: String, value: String?): HttpMessage fun removeHeader(name: String): HttpMessage fun body(body: Body): HttpMessage fun body(body: String): HttpMessage fun body(body: InputStream, length: Long? = null): HttpMessage fun headerValues(name: String): List<String?> = headers.headerValues(name) /** * This will realise any underlying stream */ fun bodyString(): String = String(body.payload.array()) companion object { const val HTTP_1_1 = "HTTP/1.1" const val HTTP_2 = "HTTP/2" } override fun close() = body.close() } enum class Method { GET, POST, PUT, DELETE, OPTIONS, TRACE, PATCH, PURGE, HEAD } interface Request : HttpMessage { val method: Method val uri: Uri fun method(method: Method): Request fun uri(uri: Uri): Request fun query(name: String, value: String): Request fun query(name: String): String? fun queries(name: String): List<String?> override fun header(name: String, value: String?): Request override fun headers(headers: Headers): Request override fun replaceHeader(name: String, value: String?): Request override fun removeHeader(name: String): Request override fun body(body: Body): Request override fun body(body: String): Request override fun body(body: InputStream, length: Long?): Request override fun toMessage() = listOf("$method $uri $version", headers.toHeaderMessage(), bodyString()).joinToString("\r\n") companion object { operator fun invoke(method: Method, uri: Uri, version: String = HTTP_1_1): Request = MemoryRequest(method, uri, listOf(), EMPTY, version) operator fun invoke(method: Method, uri: String, version: String = HTTP_1_1): Request = MemoryRequest(method, Uri.of(uri), listOf(), EMPTY, version) } } @Suppress("EqualsOrHashCode") data class MemoryRequest(override val method: Method, override val uri: Uri, override val headers: Headers = listOf(), override val body: Body = EMPTY, override val version: String = HTTP_1_1) : Request { override fun method(method: Method): Request = copy(method = method) override fun uri(uri: Uri) = copy(uri = uri) override fun query(name: String, value: String) = copy(uri = uri.query(name, value)) override fun query(name: String): String? = uri.queries().findSingle(name) override fun queries(name: String): List<String?> = uri.queries().findMultiple(name) override fun header(name: String, value: String?) = copy(headers = headers.plus(name to value)) override fun headers(headers: Headers) = copy(headers = this.headers.plus(headers)) override fun replaceHeader(name: String, value: String?) = copy(headers = headers.replaceHeader(name, value)) override fun removeHeader(name: String) = copy(headers = headers.removeHeader(name)) override fun body(body: Body) = copy(body = body) override fun body(body: String) = copy(body = Body(body)) override fun body(body: InputStream, length: Long?) = copy(body = Body(body, length)) override fun toString(): String = toMessage() override fun equals(other: Any?) = (other is Request && headers.areSameHeadersAs(other.headers) && method == other.method && uri == other.uri && body == other.body) } @Suppress("EqualsOrHashCode") interface Response : HttpMessage { val status: Status override fun header(name: String, value: String?): Response override fun headers(headers: Headers): Response override fun replaceHeader(name: String, value: String?): Response override fun removeHeader(name: String): Response override fun body(body: Body): Response override fun body(body: String): Response override fun body(body: InputStream, length: Long?): Response override fun toMessage(): String = listOf("$version $status", headers.toHeaderMessage(), bodyString()).joinToString("\r\n") companion object { operator fun invoke(status: Status, version: String = HTTP_1_1): Response = MemoryResponse(status, listOf(), EMPTY, version) } } @Suppress("EqualsOrHashCode") data class MemoryResponse(override val status: Status, override val headers: Headers = listOf(), override val body: Body = EMPTY, override val version: String = HTTP_1_1) : Response { override fun header(name: String, value: String?) = copy(headers = headers.plus(name to value)) override fun headers(headers: Headers) = copy(headers = this.headers.plus(headers)) override fun replaceHeader(name: String, value: String?) = copy(headers = headers.replaceHeader(name, value)) override fun removeHeader(name: String) = copy(headers = headers.removeHeader(name)) override fun body(body: Body) = copy(body = body) override fun body(body: String) = copy(body = Body(body)) override fun body(body: InputStream, length: Long?) = copy(body = Body(body, length)) override fun toString(): String = toMessage() override fun equals(other: Any?) = (other is Response && headers.areSameHeadersAs(other.headers) && status == other.status && body == other.body) } fun <T> T.with(vararg modifiers: (T) -> T): T = modifiers.fold(this) { memo, next -> next(memo) } @Deprecated("Removed in favour of explicit body creation", ReplaceWith("Body(this)", "org.http4k.core.Body")) fun String.toBody(): Body = Body(this)
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
8,264
http4k
Apache License 2.0
spot-client-android/app/src/main/java/com/example/spotTv/di/HomeComponent.kt
tmoldovan8x8
250,230,979
true
{"JavaScript": 1321801, "CSS": 53677, "Kotlin": 31539, "TypeScript": 27120, "Objective-C": 8445, "Java": 6322, "Ruby": 4820, "Shell": 3591, "HTML": 2528, "Starlark": 2068, "Dockerfile": 295}
package com.example.spotTv.di import com.example.spotTv.presentation.view.MainActivity import dagger.Subcomponent @Subcomponent(modules = [HomeModule::class]) interface HomeComponent { fun inject(mainActivity: MainActivity) }
0
JavaScript
0
0
348cccba951f335e474cb395ed14f037ff9c473c
231
jitsi-meet-spot
Apache License 2.0
GrowthBook/src/commonTest/kotlin/com/sdk/growthbook/tests/GBTestCases.kt
growthbook
445,362,249
false
null
package com.sdk.growthbook.tests val gbTestCases = """ { "evalCondition": [ [ "${"$"}not - pass", { "${"$"}not": { "name": "hello" } }, { "name": "world" }, true ], [ "${"$"}not - fail", { "${"$"}not": { "name": "hello" } }, { "name": "hello" }, false ], [ "${"$"}and /${"$"}or - all true", { "${"$"}and": [ { "father.age": { "${"$"}gt": 65 } }, { "${"$"}or": [ { "bday": { "${"$"}regex": "-12-25${'$'}" } }, { "name": "santa" } ] } ] }, { "name": "santa", "bday": "1980-12-25", "father": { "age": 70 } }, true ], [ "${"$"}and /${"$"}or - first or true", { "${"$"}and": [ { "father.age": { "${"$"}gt": 65 } }, { "${"$"}or": [ { "bday": { "${"$"}regex": "-12-25${'$'}" } }, { "name": "santa" } ] } ] }, { "name": "santa", "bday": "1980-12-20", "father": { "age": 70 } }, true ], [ "${"$"}and /${"$"}or - second or true", { "${"$"}and": [ { "father.age": { "${"$"}gt": 65 } }, { "${"$"}or": [ { "bday": { "${"$"}regex": "-12-25${'$'}" } }, { "name": "santa" } ] } ] }, { "name": "barbara", "bday": "1980-12-25", "father": { "age": 70 } }, true ], [ "${"$"}and /${"$"}or - first and false", { "${"$"}and": [ { "father.age": { "${"$"}gt": 65 } }, { "${"$"}or": [ { "bday": { "${"$"}regex": "-12-25${'$'}" } }, { "name": "santa" } ] } ] }, { "name": "santa", "bday": "1980-12-25", "father": { "age": 65 } }, false ], [ "${"$"}and /${"$"}or - both or false", { "${"$"}and": [ { "father.age": { "${"$"}gt": 65 } }, { "${"$"}or": [ { "bday": { "${"$"}regex": "-12-25${'$'}" } }, { "name": "santa" } ] } ] }, { "name": "barbara", "bday": "1980-11-25", "father": { "age": 70 } }, false ], [ "${"$"}and /${"$"}or - both and false", { "${"$"}and": [ { "father.age": { "${"$"}gt": 65 } }, { "${"$"}or": [ { "bday": { "${"$"}regex": "-12-25${'$'}" } }, { "name": "santa" } ] } ] }, { "name": "john smith", "bday": "1956-12-20", "father": { "age": 40 } }, false ], [ "${"$"}exists - false pass", { "pets.dog.name": { "${"$"}exists": false } }, { "hello": "world" }, true ], [ "${"$"}exists - false fail", { "pets.dog.name": { "${"$"}exists": false } }, { "pets": { "dog": { "name": "fido" } } }, false ], [ "${"$"}exists - true fail", { "pets.dog.name": { "${"$"}exists": true } }, { "hello": "world" }, false ], [ "${"$"}exists - true pass", { "pets.dog.name": { "${"$"}exists": true } }, { "pets": { "dog": { "name": "fido" } } }, true ], [ "equals - multiple datatypes", { "str": "str", "num": 10, "flag": false }, { "str": "str", "num": 10, "flag": false }, true ], [ "${'$'}in - pass", { "num": { "${'$'}in": [ 1, 2, 3 ] } }, { "num": 2 }, true ], [ "${'$'}in - fail", { "num": { "${'$'}in": [ 1, 2, 3 ] } }, { "num": 4 }, false ], [ "${"$"}nin - pass", { "num": { "${"$"}nin": [ 1, 2, 3 ] } }, { "num": 4 }, true ], [ "${"$"}nin - fail", { "num": { "${"$"}nin": [ 1, 2, 3 ] } }, { "num": 2 }, false ], [ "${"$"}elemMatch - pass - flat arrays", { "nums": { "${"$"}elemMatch": { "${"$"}gt": 10 } } }, { "nums": [ 0, 5, -20, 15 ] }, true ], [ "${"$"}elemMatch - fail - flat arrays", { "nums": { "${"$"}elemMatch": { "${"$"}gt": 10 } } }, { "nums": [ 0, 5, -20, 8 ] }, false ], [ "missing attribute - fail", { "pets.dog.name": { "${'$'}in": [ "fido" ] } }, { "hello": "world" }, false ], [ "empty ${"$"}or - pass", { "${"$"}or": [ ] }, { "hello": "world" }, true ], [ "empty ${"$"}and - pass", { "${"$"}and": [ ] }, { "hello": "world" }, true ], [ "empty - pass", { }, { "hello": "world" }, true ], [ "${"$"}eq - pass", { "occupation": { "${"$"}eq": "engineer" } }, { "occupation": "engineer" }, true ], [ "${"$"}veq - fail", { "version": { "${"$"}veq": "v1.2.3-rc.1+build123" } }, { "version": "1- 2- 3-rc- 2" }, false ], [ "${"$"}vne - pass", { "version": { "${"$"}vne": "v1.2.3-rc.1+build123" } }, { "version": "1.3.4-rc.3" }, true ], [ "${"$"}vne - fail", { "version": { "${"$"}vne": "v1.2.3-rc.1+build123" } }, { "version": "1.2.3-rc.1" }, false ], [ "${"$"}vgt - pass", { "version": { "${"$"}vgt": "v1.2.3-rc.1+build123" } }, { "version": "1.2.4-rc.0" }, true ], [ "${"$"}vgt - fail", { "version": { "${"$"}vgt": "v1.2.3-rc.1+build123" } }, { "version": "1.2.2-rc.0" }, false ], [ "${"$"}vgte - pass", { "version": { "${"$"}vgte": "v1.2.3-rc.1+build123" } }, { "version": "1.2.3-rc.1" }, true ], [ "${"$"}vgte - fail", { "version": { "${"$"}vgte": "v1.2.3-rc.1+build123" } }, { "version": "1.2.2-rc.1" }, false ], [ "${"$"}vlt - pass", { "version": { "${"$"}vlt": "v1.2.3-rc.1+build123" } }, { "version": "1.2.2-rc.1" }, true ], [ "${"$"}vlt - fail", { "version": { "${"$"}vlt": "v1.2.3-rc.1+build123" } }, { "version": "1.2.4-rc.1" }, false ], [ "${"$"}vlte - pass", { "version": { "${"$"}vlte": "v1.2.3-rc.1+build123" } }, { "version": "1.2.3-rc.1" }, true ], [ "${"$"}vlte - fail", { "version": { "${"$"}vlte": "v1.2.3-rc.1+build123" } }, { "version": "1.2.4-rc.1" }, false ], [ "${"$"}eq - fail", { "occupation": { "${"$"}eq": "engineer" } }, { "occupation": "civil engineer" }, false ], [ "${"$"}ne - pass", { "level": { "${"$"}ne": "senior" } }, { "level": "junior" }, true ], [ "${"$"}ne - fail", { "level": { "${"$"}ne": "senior" } }, { "level": "senior" }, false ], [ "${"$"}regex - pass", { "userAgent": { "${"$"}regex": "(Mobile|Tablet)" } }, { "userAgent": "Android Mobile Browser" }, true ], [ "${"$"}regex - fail", { "userAgent": { "${"$"}regex": "(Mobile|Tablet)" } }, { "userAgent": "Chrome Desktop Browser" }, false ], [ "${"$"}gt /${"$"}lt numbers - pass", { "age": { "${"$"}gt": 30, "${"$"}lt": 60 } }, { "age": 50 }, true ], [ "${"$"}gt /${"$"}lt numbers - fail ${"$"}lt ", { "age": { "${"$"}gt": 30, "${"$"}lt": 60 } }, { "age": 60 }, false ], [ "${"$"}gt /${"$"}lt numbers - fail ${"$"}gt ", { "age": { "${"$"}gt": 30, "${"$"}lt": 60 } }, { "age": 30 }, false ], [ "${"$"}gte /${"$"}lte numbers - pass", { "age": { "${"$"}gte": 30, "${"$"}lte": 60 } }, { "age": 50 }, true ], [ "${"$"}gte /${"$"}lte numbers - pass ${"$"}gte ", { "age": { "${"$"}gte": 30, "${"$"}lte": 60 } }, { "age": 30 }, true ], [ "${"$"}gte /${"$"}lte numbers - pass ${"$"}lte ", { "age": { "${"$"}gte": 30, "${"$"}lte": 60 } }, { "age": 60 }, true ], [ "${"$"}gte /${"$"}lte numbers - fail ${"$"}lte ", { "age": { "${"$"}gte": 30, "${"$"}lte": 60 } }, { "age": 61 }, false ], [ "${"$"}gte /${"$"}lte numbers - fail ${"$"}gte ", { "age": { "${"$"}gt": 30, "${"$"}lt": 60 } }, { "age": 29 }, false ], [ "${"$"}gt /${"$"}lt strings - fail ${"$"}gt ", { "word": { "${"$"}gt": "alphabet", "${"$"}lt": "zebra" } }, { "word": "alphabet" }, false ], [ "${"$"}gt /${"$"}lt strings - fail ${"$"}lt ", { "word": { "${"$"}gt": "alphabet", "${"$"}lt": "zebra" } }, { "word": "zebra" }, false ], [ "${"$"}gt /${"$"}lt strings - pass", { "word": { "${"$"}gt": "alphabet", "${"$"}lt": "zebra" } }, { "word": "always" }, true ], [ "${"$"}gt /${"$"}lt strings - fail uppercase", { "word": { "${"$"}gt": "alphabet", "${"$"}lt": "zebra" } }, { "word": "AZL" }, false ], [ "${"$"}type string - pass", { "a": { "${"$"}type": "string" } }, { "a": "a" }, true ], [ "${"$"}type string - fail", { "a": { "${"$"}type": "string" } }, { "a": 1 }, false ], [ "${"$"}type null - pass", { "a": { "${"$"}type": "null" } }, { "a": null }, true ], [ "${"$"}type null - fail", { "a": { "${"$"}type": "null" } }, { "a": 1 }, false ], [ "${"$"}type boolean - pass", { "a": { "${"$"}type": "boolean" } }, { "a": false }, true ], [ "${"$"}type boolean - fail", { "a": { "${"$"}type": "boolean" } }, { "a": 1 }, false ], [ "${"$"}type number - pass", { "a": { "${"$"}type": "number" } }, { "a": 1 }, true ], [ "${"$"}type number - fail", { "a": { "${"$"}type": "number" } }, { "a": "a" }, false ], [ "${"$"}type object - pass", { "a": { "${"$"}type": "object" } }, { "a": { "a": "b" } }, true ], [ "${"$"}type object - fail", { "a": { "${"$"}type": "object" } }, { "a": 1 }, false ], [ "${"$"}type array - pass", { "a": { "${"$"}type": "array" } }, { "a": [ 1, 2 ] }, true ], [ "${"$"}type array - fail", { "a": { "${"$"}type": "array" } }, { "a": 1 }, false ], [ "unknown operator - pass", { "name": { "${"$"}regx": "hello" } }, { "name": "hello" }, false ], [ "${"$"}regex invalid - pass", { "name": { "${"$"}regex": "/???***[)" } }, { "name": "hello" }, false ], [ "${"$"}regex invalid - fail", { "name": { "${"$"}regex": "/???***[)" } }, { "hello": "hello" }, false ], [ "${"$"}size number - pass", { "tags": { "${"$"}size": 3 } }, { "tags": [ "a", "b", "c" ] }, true ], [ "${"$"}size number - fail small", { "tags": { "${"$"}size": 3 } }, { "tags": [ "a", "b" ] }, false ], [ "${"$"}size number - fail large", { "tags": { "${"$"}size": 3 } }, { "tags": [ "a", "b", "c", "d" ] }, false ], [ "${"$"}size number - fail not array", { "tags": { "${"$"}size": 3 } }, { "tags": "abc" }, false ], [ "${"$"}size nested - pass", { "tags": { "${"$"}size": { "${"$"}gt": 2 } } }, { "tags": [ 0, 1, 2 ] }, true ], [ "${"$"}size nested - fail equal", { "tags": { "${"$"}size": { "${"$"}gt": 2 } } }, { "tags": [ 0, 1 ] }, false ], [ "${"$"}size nested - fail less than", { "tags": { "${"$"}size": { "${"$"}gt": 2 } } }, { "tags": [ 0 ] }, false ], [ "${"$"}elemMatch nested - pass", { "hobbies": { "${"$"}elemMatch": { "name": { "${"$"}regex": "^ping" } } } }, { "hobbies": [ { "name": "bowling" }, { "name": "pingpong" }, { "name": "tennis" } ] }, true ], [ "${"$"}elemMatch nested - fail", { "hobbies": { "${"$"}elemMatch": { "name": { "${"$"}regex": "^ping" } } } }, { "hobbies": [ { "name": "bowling" }, { "name": "tennis" } ] }, false ], [ "${"$"}elemMatch nested - fail not array", { "hobbies": { "${"$"}elemMatch": { "name": { "${"$"}regex": "^ping" } } } }, { "hobbies": "all" }, false ], [ "${"$"}not - pass", { "name": { "${"$"}not": { "${"$"}regex": "^hello" } } }, { "name": "world" }, true ], [ "${"$"}not - fail", { "name": { "${"$"}not": { "${"$"}regex": "^hello" } } }, { "name": "hello world" }, false ], [ "${"$"}all - pass", { "tags": { "${"$"}all": [ "one", "three" ] } }, { "tags": [ "one", "two", "three" ] }, true ], [ "${"$"}all - fail", { "tags": { "${"$"}all": [ "one", "three" ] } }, { "tags": [ "one", "two", "four" ] }, false ], [ "${"$"}all - fail not array", { "tags": { "${"$"}all": [ "one", "three" ] } }, { "tags": "hello" }, false ], [ "${"$"}nor - pass", { "${"$"}nor": [ { "name": "john" }, { "age": { "${"$"}lt": 30 } } ] }, { "name": "jim", "age": 40 }, true ], [ "${"$"}nor - fail both", { "${"$"}nor": [ { "name": "john" }, { "age": { "${"$"}lt": 30 } } ] }, { "name": "john", "age": 20 }, false ], [ "${"$"}nor - fail first", { "${"$"}nor": [ { "name": "john" }, { "age": { "${"$"}lt": 30 } } ] }, { "name": "john", "age": 40 }, false ], [ "${"$"}nor - fail second", { "${"$"}nor": [ { "name": "john" }, { "age": { "${"$"}lt": 30 } } ] }, { "name": "jim", "age": 20 }, false ], [ "equals array - pass", { "tags": [ "hello", "world" ] }, { "tags": [ "hello", "world" ] }, true ], [ "equals array - fail order", { "tags": [ "hello", "world" ] }, { "tags": [ "world", "hello" ] }, false ], [ "equals array - fail missing item", { "tags": [ "hello", "world" ] }, { "tags": [ "hello" ] }, false ], [ "equals array - fail extra item", { "tags": [ "hello", "world" ] }, { "tags": [ "hello", "world", "foo" ] }, false ], [ "equals array - fail type mismatch", { "tags": [ "hello", "world" ] }, { "tags": "hello world" }, false ], [ "equals object - pass", { "tags": { "hello": "world" } }, { "tags": { "hello": "world" } }, true ], [ "equals object - fail extra property", { "tags": { "hello": "world" } }, { "tags": { "hello": "world", "yes": "please" } }, false ], [ "equals object - fail missing property", { "tags": { "hello": "world" } }, { "tags": { } }, false ], [ "equals object - fail type mismatch", { "tags": { "hello": "world" } }, { "tags": "hello world" }, false ] ], "hash": [ [ "a", 0.22 ], [ "b", 0.077 ], [ "ab", 0.946 ], [ "def", 0.652 ], [ "8952klfjas09ujkasdf", 0.549 ], [ "123", 0.011 ], [ "___)((*\":&", 0.563 ] ], "getBucketRange": [ [ "normal 50/50", [ 2, 1, null ], [ [ 0, 0.5 ], [ 0.5, 1 ] ] ], [ "reduced coverage", [ 2, 0.5, null ], [ [ 0, 0.25 ], [ 0.5, 0.75 ] ] ], [ "zero coverage", [ 2, 0, null ], [ [ 0, 0 ], [ 0.5, 0.5 ] ] ], [ "4 variations", [ 4, 1, null ], [ [ 0, 0.25 ], [ 0.25, 0.5 ], [ 0.5, 0.75 ], [ 0.75, 1 ] ] ], [ "uneven weights", [ 2, 1, [ 0.4, 0.6 ] ], [ [ 0, 0.4 ], [ 0.4, 1 ] ] ], [ "uneven weights, 3 variations", [ 3, 1, [ 0.2, 0.3, 0.5 ] ], [ [ 0, 0.2 ], [ 0.2, 0.5 ], [ 0.5, 1 ] ] ], [ "uneven weights, reduced coverage, 3 variations", [ 3, 0.2, [ 0.2, 0.3, 0.5 ] ], [ [ 0, 0.04 ], [ 0.2, 0.26 ], [ 0.5, 0.6 ] ] ], [ "negative coverage", [ 2, -0.2, null ], [ [ 0, 0 ], [ 0.5, 0.5 ] ] ], [ "coverage above 1", [ 2, 1.5, null ], [ [ 0, 0.5 ], [ 0.5, 1 ] ] ], [ "weights sum below 1", [ 2, 1, [ 0.4, 0.1 ] ], [ [ 0, 0.5 ], [ 0.5, 1 ] ] ], [ "weights sum above 1", [ 2, 1, [ 0.7, 0.6 ] ], [ [ 0, 0.5 ], [ 0.5, 1 ] ] ], [ "weights.length not equal to num variations", [ 4, 1, [ 0.4, 0.4, 0.2 ] ], [ [ 0, 0.25 ], [ 0.25, 0.5 ], [ 0.5, 0.75 ], [ 0.75, 1 ] ] ], [ "weights sum almost equals 1", [ 2, 1, [ 0.4, 0.5999 ] ], [ [ 0, 0.4 ], [ 0.4, 0.9999 ] ] ] ], "feature": [ [ "unknown feature key", { }, "my-feature", { "value": null, "on": false, "off": true, "source": "unknownFeature" } ], [ "defaults when empty", { "features": { "feature": { } } }, "feature", { "value": null, "on": false, "off": true, "source": "defaultValue" } ], [ "uses defaultValue - number", { "features": { "feature": { "defaultValue": 1 } } }, "feature", { "value": 1, "on": true, "off": false, "source": "defaultValue" } ], [ "uses custom values - string", { "features": { "feature": { "defaultValue": "yes" } } }, "feature", { "value": "yes", "on": true, "off": false, "source": "defaultValue" } ], [ "force rules", { "features": { "feature": { "defaultValue": 2, "rules": [ { "force": 1 } ] } } }, "feature", { "value": 1, "on": true, "off": false, "source": "force" } ], [ "force rules - coverage included", { "attributes": { "id": "3" }, "features": { "feature": { "defaultValue": 2, "rules": [ { "force": 1, "coverage": 0.5 } ] } } }, "feature", { "value": 1, "on": true, "off": false, "source": "force" } ], [ "force rules - coverage excluded", { "attributes": { "id": "1" }, "features": { "feature": { "defaultValue": 2, "rules": [ { "force": 1, "coverage": 0.5 } ] } } }, "feature", { "value": 2, "on": true, "off": false, "source": "defaultValue" } ], [ "force rules - coverage missing hashAttribute", { "attributes": { }, "features": { "feature": { "defaultValue": 2, "rules": [ { "force": 1, "coverage": 0.5 } ] } } }, "feature", { "value": 2, "on": true, "off": false, "source": "defaultValue" } ], [ "force rules - condition pass", { "attributes": { "country": "US", "browser": "firefox" }, "features": { "feature": { "defaultValue": 2, "rules": [ { "force": 1, "condition": { "country": { "${'$'}in": [ "US", "CA" ] }, "browser": "firefox" } } ] } } }, "feature", { "value": 1, "on": true, "off": false, "source": "force" } ], [ "force rules - condition fail", { "attributes": { "country": "US", "browser": "chrome" }, "features": { "feature": { "defaultValue": 2, "rules": [ { "force": 1, "condition": { "country": { "${'$'}in": [ "US", "CA" ] }, "browser": "firefox" } } ] } } }, "feature", { "value": 2, "on": true, "off": false, "source": "defaultValue" } ], [ "ignores empty rules", { "features": { "feature": { "rules": [ { } ] } } }, "feature", { "value": null, "on": false, "off": true, "source": "defaultValue" } ], [ "empty experiment rule - c", { "attributes": { "id": "123" }, "features": { "feature": { "rules": [ { "variations": [ "a", "b", "c" ] } ] } } }, "feature", { "value": "c", "on": true, "off": false, "experiment": { "key": "feature", "variations": [ "a", "b", "c" ] }, "experimentResult": { "value": "c", "variationId": 2, "inExperiment": true, "hashAttribute": "id", "hashValue": "123" }, "source": "experiment" } ], [ "empty experiment rule - a", { "attributes": { "id": "456" }, "features": { "feature": { "rules": [ { "variations": [ "a", "b", "c" ] } ] } } }, "feature", { "value": "a", "on": true, "off": false, "experiment": { "key": "feature", "variations": [ "a", "b", "c" ] }, "experimentResult": { "value": "a", "variationId": 0, "inExperiment": true, "hashAttribute": "id", "hashValue": "456" }, "source": "experiment" } ], [ "empty experiment rule - b", { "attributes": { "id": "fds" }, "features": { "feature": { "rules": [ { "variations": [ "a", "b", "c" ] } ] } } }, "feature", { "value": "b", "on": true, "off": false, "experiment": { "key": "feature", "variations": [ "a", "b", "c" ] }, "experimentResult": { "value": "b", "variationId": 1, "inExperiment": true, "hashAttribute": "id", "hashValue": "fds" }, "source": "experiment" } ], [ "creates experiments properly", { "attributes": { "anonId": "123", "premium": true }, "features": { "feature": { "rules": [ { "coverage": 0.99, "hashAttribute": "anonId", "namespace": [ "pricing", 0, 1 ], "key": "hello", "variations": [ true, false ], "weights": [ 0.1, 0.9 ], "condition": { "premium": true } } ] } } }, "feature", { "value": false, "on": false, "off": true, "source": "experiment", "experiment": { "coverage": 0.99, "hashAttribute": "anonId", "namespace": [ "pricing", 0, 1 ], "key": "hello", "variations": [ true, false ], "weights": [ 0.1, 0.9 ] }, "experimentResult": { "value": false, "variationId": 1, "inExperiment": true, "hashAttribute": "anonId", "hashValue": "123" } } ], [ "rule orders - skip 1", { "attributes": { "browser": "firefox" }, "features": { "feature": { "defaultValue": 0, "rules": [ { "force": 1, "condition": { "browser": "chrome" } }, { "force": 2, "condition": { "browser": "firefox" } }, { "force": 3, "condition": { "browser": "safari" } } ] } } }, "feature", { "value": 2, "on": true, "off": false, "source": "force" } ], [ "rule orders - skip 1,2", { "attributes": { "browser": "safari" }, "features": { "feature": { "defaultValue": 0, "rules": [ { "force": 1, "condition": { "browser": "chrome" } }, { "force": 2, "condition": { "browser": "firefox" } }, { "force": 3, "condition": { "browser": "safari" } } ] } } }, "feature", { "value": 3, "on": true, "off": false, "source": "force" } ], [ "rule orders - skip all", { "attributes": { "browser": "ie" }, "features": { "feature": { "defaultValue": 0, "rules": [ { "force": 1, "condition": { "browser": "chrome" } }, { "force": 2, "condition": { "browser": "firefox" } }, { "force": 3, "condition": { "browser": "safari" } } ] } } }, "feature", { "value": 0, "on": false, "off": true, "source": "defaultValue" } ], [ "skips experiment on coverage", { "attributes": { "id": "123" }, "features": { "feature": { "defaultValue": 0, "rules": [ { "variations": [ 0, 1, 2, 3 ], "coverage": 0.01 }, { "force": 3 } ] } } }, "feature", { "value": 3, "on": true, "off": false, "source": "force" } ], [ "skips experiment on namespace", { "attributes": { "id": "123" }, "features": { "feature": { "defaultValue": 0, "rules": [ { "variations": [ 0, 1, 2, 3 ], "namespace": [ "pricing", 0, 0.01 ] }, { "force": 3 } ] } } }, "feature", { "value": 3, "on": true, "off": false, "source": "force" } ], [ "skip experiment on missing hashAttribute", { "attributes": { "id": "123" }, "features": { "feature": { "defaultValue": 0, "rules": [ { "variations": [ 0, 1, 2, 3 ], "hashAttribute": "company" }, { "force": 3 } ] } } }, "feature", { "value": 3, "on": true, "off": false, "source": "force" } ] ], "run": [ [ "default weights - 1", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, true ], [ "default weights - 2", { "attributes": { "id": "2" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, true ], [ "default weights - 3", { "attributes": { "id": "3" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, true ], [ "default weights - 4", { "attributes": { "id": "4" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, true ], [ "default weights - 5", { "attributes": { "id": "5" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, true ], [ "default weights - 6", { "attributes": { "id": "6" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, true ], [ "default weights - 7", { "attributes": { "id": "7" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, true ], [ "default weights - 8", { "attributes": { "id": "8" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, true ], [ "default weights - 9", { "attributes": { "id": "9" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, true ], [ "uneven weights - 1", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "uneven weights - 2", { "attributes": { "id": "2" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "uneven weights - 3", { "attributes": { "id": "3" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 0, true ], [ "uneven weights - 4", { "attributes": { "id": "4" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "uneven weights - 5", { "attributes": { "id": "5" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "uneven weights - 6", { "attributes": { "id": "6" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "uneven weights - 7", { "attributes": { "id": "7" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 0, true ], [ "uneven weights - 8", { "attributes": { "id": "8" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "uneven weights - 9", { "attributes": { "id": "9" } }, { "key": "my-test", "variations": [ 0, 1 ], "weights": [ 0.1, 0.9 ] }, 1, true ], [ "coverage - 1", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, false ], [ "coverage - 2", { "attributes": { "id": "2" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, true ], [ "coverage - 3", { "attributes": { "id": "3" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, true ], [ "coverage - 4", { "attributes": { "id": "4" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, false ], [ "coverage - 5", { "attributes": { "id": "5" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 1, true ], [ "coverage - 6", { "attributes": { "id": "6" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, false ], [ "coverage - 7", { "attributes": { "id": "7" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, true ], [ "coverage - 8", { "attributes": { "id": "8" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 1, true ], [ "coverage - 9", { "attributes": { "id": "9" } }, { "key": "my-test", "variations": [ 0, 1 ], "coverage": 0.4 }, 0, false ], [ "three way test - 1", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 2, true ], [ "three way test - 2", { "attributes": { "id": "2" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 0, true ], [ "three way test - 3", { "attributes": { "id": "3" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 0, true ], [ "three way test - 4", { "attributes": { "id": "4" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 2, true ], [ "three way test - 5", { "attributes": { "id": "5" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 1, true ], [ "three way test - 6", { "attributes": { "id": "6" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 2, true ], [ "three way test - 7", { "attributes": { "id": "7" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 0, true ], [ "three way test - 8", { "attributes": { "id": "8" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 1, true ], [ "three way test - 9", { "attributes": { "id": "9" } }, { "key": "my-test", "variations": [ 0, 1, 2 ] }, 0, true ], [ "test name - my-test", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, true ], [ "test name - my-test-3", { "attributes": { "id": "1" } }, { "key": "my-test-3", "variations": [ 0, 1 ] }, 0, true ], [ "empty id", { "attributes": { "id": "" } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, false ], [ "missing id", { "attributes": { } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, false ], [ "missing attributes", { }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, false ], [ "single variation", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0 ] }, 0, false ], [ "negative forced variation", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "force": -8 }, 0, false ], [ "high forced variation", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "force": 25 }, 0, false ], [ "evaluates conditions - pass", { "attributes": { "id": "1", "browser": "firefox" } }, { "key": "my-test", "variations": [ 0, 1 ], "condition": { "browser": "firefox" } }, 1, true ], [ "evaluates conditions - fail", { "attributes": { "id": "1", "browser": "chrome" } }, { "key": "my-test", "variations": [ 0, 1 ], "condition": { "browser": "firefox" } }, 0, false ], [ "custom hashAttribute", { "attributes": { "id": "2", "companyId": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "hashAttribute": "companyId" }, 1, true ], [ "globally disabled", { "attributes": { "id": "1" }, "enabled": false }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, false ], [ "run active experiments", { "attributes": { "id": "1" } }, { "key": "my-test", "active": true, "variations": [ 0, 1 ] }, 1, true ], [ "skip inactive experiments", { "attributes": { "id": "1" } }, { "key": "my-test", "active": false, "variations": [ 0, 1 ] }, 0, false ], [ "coverage take precendence over forced", { "attributes": { "id": "1" } }, { "key": "my-test", "force": 1, "coverage": 0.01, "variations": [ 0, 1 ] }, 0, false ], [ "JSON values for experiments", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ { "color": "blue", "size": "small" }, { "color": "green", "size": "large" } ] }, { "color": "green", "size": "large" }, true ], [ "Force variation from context", { "attributes": { "id": "1" }, "forcedVariations": { "my-test": 0 } }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, false ], [ "Skips experiments in QA mode", { "attributes": { "id": "1" }, "qaMode": true }, { "key": "my-test", "variations": [ 0, 1 ] }, 0, false ], [ "Works in QA mode if forced in context", { "attributes": { "id": "1" }, "qaMode": true, "forcedVariations": { "my-test": 1 } }, { "key": "my-test", "variations": [ 0, 1 ] }, 1, false ], [ "Works in QA mode if forced in experiment", { "attributes": { "id": "1" }, "qaMode": true }, { "key": "my-test", "variations": [ 0, 1 ], "force": 1 }, 1, false ], [ "Experiment namespace - pass", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "namespace": [ "namespace", 0.1, 1 ] }, 1, true ], [ "Experiment namespace - fail", { "attributes": { "id": "1" } }, { "key": "my-test", "variations": [ 0, 1 ], "namespace": [ "namespace", 0, 0.1 ] }, 0, false ] ], "chooseVariation": [ [ "even range, 0.2", 0.2, [ [ 0, 0.5 ], [ 0.5, 1 ] ], 0 ], [ "even range, 0.4", 0.4, [ [ 0, 0.5 ], [ 0.5, 1 ] ], 0 ], [ "even range, 0.6", 0.6, [ [ 0, 0.5 ], [ 0.5, 1 ] ], 1 ], [ "even range, 0.8", 0.8, [ [ 0, 0.5 ], [ 0.5, 1 ] ], 1 ], [ "even range, 0", 0, [ [ 0, 0.5 ], [ 0.5, 1 ] ], 0 ], [ "even range, 0.5", 0.5, [ [ 0, 0.5 ], [ 0.5, 1 ] ], 1 ], [ "reduced range, 0.2", 0.2, [ [ 0, 0.25 ], [ 0.5, 0.75 ] ], 0 ], [ "reduced range, 0.4", 0.4, [ [ 0, 0.25 ], [ 0.5, 0.75 ] ], -1 ], [ "reduced range, 0.6", 0.6, [ [ 0, 0.25 ], [ 0.5, 0.75 ] ], 1 ], [ "reduced range, 0.8", 0.8, [ [ 0, 0.25 ], [ 0.5, 0.75 ] ], -1 ], [ "reduced range, 0.25", 0.25, [ [ 0, 0.25 ], [ 0.5, 0.75 ] ], -1 ], [ "reduced range, 0.5", 0.5, [ [ 0, 0.25 ], [ 0.5, 0.75 ] ], 1 ], [ "zero range", 0.5, [ [ 0, 0.5 ], [ 0.5, 0.5 ], [ 0.5, 1 ] ], 2 ] ], "inNamespace": [ [ "user 1, namespace1, 1", "1", [ "namespace1", 0, 0.4 ], false ], [ "user 1, namespace1, 2", "1", [ "namespace1", 0.4, 1 ], true ], [ "user 1, namespace2, 1", "1", [ "namespace2", 0, 0.4 ], false ], [ "user 1, namespace2, 2", "1", [ "namespace2", 0.4, 1 ], true ], [ "user 2, namespace1, 1", "2", [ "namespace1", 0, 0.4 ], false ], [ "user 2, namespace1, 2", "2", [ "namespace1", 0.4, 1 ], true ], [ "user 2, namespace2, 1", "2", [ "namespace2", 0, 0.4 ], false ], [ "user 2, namespace2, 2", "2", [ "namespace2", 0.4, 1 ], true ], [ "user 3, namespace1, 1", "3", [ "namespace1", 0, 0.4 ], false ], [ "user 3, namespace1, 2", "3", [ "namespace1", 0.4, 1 ], true ], [ "user 3, namespace2, 1", "3", [ "namespace2", 0, 0.4 ], true ], [ "user 3, namespace2, 2", "3", [ "namespace2", 0.4, 1 ], false ], [ "user 4, namespace1, 1", "4", [ "namespace1", 0, 0.4 ], false ], [ "user 4, namespace1, 2", "4", [ "namespace1", 0.4, 1 ], true ], [ "user 4, namespace2, 1", "4", [ "namespace2", 0, 0.4 ], true ], [ "user 4, namespace2, 2", "4", [ "namespace2", 0.4, 1 ], false ] ], "getEqualWeights": [ [ -1, [ ] ], [ 0, [ ] ], [ 1, [ 1 ] ], [ 2, [ 0.5, 0.5 ] ], [ 3, [ 0.33333333, 0.33333333, 0.33333333 ] ], [ 4, [ 0.25, 0.25, 0.25, 0.25 ] ] ] } """.trimIndent()
8
null
16
19
40be0415b275d6717df6194f2356c339505a440f
75,856
growthbook-kotlin
MIT License
modules/contracts-for-testing/src/main/kotlin/com/r3/corda/lib/tokens/testing/states/DiamondGradingReport.kt
corda
160,397,060
false
{"Kotlin": 673352, "Java": 18696, "Dockerfile": 2031}
package com.r3.corda.lib.tokens.testing.states import com.r3.corda.lib.tokens.contracts.states.EvolvableTokenType import com.r3.corda.lib.tokens.testing.contracts.DiamondGradingReportContract import net.corda.core.contracts.BelongsToContract import net.corda.core.contracts.UniqueIdentifier import net.corda.core.identity.Party import net.corda.core.serialization.CordaSerializable import java.math.BigDecimal /** * The [DiamondGradingReport] is inspired by the grading reports issued by the Gemological Institute of America * (GIA). For more excellent information on diamond grading, please see the (GIA's website)[http://www.gia.edu]. */ @BelongsToContract(DiamondGradingReportContract::class) data class DiamondGradingReport( val caratWeight: BigDecimal, val color: ColorScale, val clarity: ClarityScale, val cut: CutScale, val assessor: Party, val requester: Party, override val linearId: UniqueIdentifier = UniqueIdentifier() ) : EvolvableTokenType() { constructor( caratWeight: String, color: ColorScale, clarity: ClarityScale, cut: CutScale, assessor: Party, requester: Party, linearId: UniqueIdentifier = UniqueIdentifier()) : this(BigDecimal(caratWeight), color, clarity, cut, assessor, requester, linearId) @CordaSerializable enum class ColorScale { A, B, C, D, E, F } @CordaSerializable enum class ClarityScale { A, B, C, D, E, F } @CordaSerializable enum class CutScale { A, B, C, D, E, F } override val maintainers get() = listOf(assessor) override val participants get() = setOf(assessor, requester).toList() override val fractionDigits: Int get() = 0 }
38
Kotlin
77
80
749483f691c2c6ca56d9caacdd73a9e6319a969e
1,758
token-sdk
Apache License 2.0
src/main/kotlin/com/wsl/symlinks/vfs/WslVirtualFileSystem.kt
patricklx
781,426,990
false
{"Kotlin": 10886, "Shell": 286}
package com.wsl.symlinks.vfs import ai.grazie.utils.WeakHashMap import com.intellij.ide.AppLifecycleListener import com.intellij.idea.IdeaLogger import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.DefaultLogger import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileAttributes import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.VirtualFileSystem import com.intellij.openapi.vfs.impl.VirtualFileManagerImpl import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl import com.intellij.platform.workspace.storage.url.VirtualFileUrl import com.intellij.util.io.URLUtil import com.jetbrains.rd.util.collections.SynchronizedMap import java.io.* import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.thread import kotlin.concurrent.withLock class StartupListener: AppLifecycleListener { override fun appFrameCreated(commandLineArgs: MutableList<String>) { MyLogger.setup() } } class MyLogger(category: String): DefaultLogger(category) { override fun error(message: String?) { if (message?.contains(">1 file system registered for protocol") == true) { return } super.error(message) } override fun error(message: String?, t: Throwable?, vararg details: String?) { if (message?.contains(">1 file system registered for protocol") == true) { return } super.error(message, t, *details) } companion object { fun setup() { //IdeaLogger.setFactory { category -> MyLogger(category) } //Logger.setFactory { category -> MyLogger(category) } } // val logger = setup() } } val myResourceLock = ReentrantLock() class WslSymlinksProvider(distro: String) { val LOGGER = Logger.getInstance(WslSymlinksProvider::class.java) private var process: Process? = null private var processReader: BufferedReader? = null private var processWriter: BufferedWriter? = null private val queue: LinkedBlockingQueue<AsyncValue> = LinkedBlockingQueue() private val mapped: SynchronizedMap<String, AsyncValue> = SynchronizedMap() class AsyncValue { public val id = this.hashCode().toString() public var request: String? = null internal var value: String? = null internal val condition = myResourceLock.newCondition() fun getValue(): String? { var elapsed = 0 while (value == null && elapsed < 5000) { if (myResourceLock.tryLock(10, TimeUnit.MILLISECONDS)) { condition.await(10, TimeUnit.MILLISECONDS) myResourceLock.unlock() } elapsed += 10 } // if (this.value == null) { // throw Error("failed to obtain file info for $request") // } return this.value } } init { val bash = {}.javaClass.getResource("/files.sh")?.readText()!! val location = "\\\\wsl.localhost\\$distro\\var\\tmp\\intellij-idea-wsl-symlinks.sh" File(location).writeText(bash) val builder = ProcessBuilder("wsl.exe", "-d", distro, "-e", "bash", "//var/tmp/intellij-idea-wsl-symlinks.sh") fun setupProcess() { val process = builder.start() this.process = process this.processReader = BufferedReader(InputStreamReader(process.inputStream)) this.processWriter = BufferedWriter(OutputStreamWriter(process.outputStream)); process.onExit().whenComplete { t, u -> LOGGER.error("process did exit ${u?.message ?: "no-reason"}") setupProcess() } } setupProcess() thread { while (true) { try { if (this.processReader == null) { Thread.sleep(100) } val line = this.processReader!!.readLine() val (id, answer) = line.split(";") val a = mapped[id]!! a.value = answer myResourceLock.withLock { a.condition.signalAll() } mapped.remove(id) } catch (e: Exception) { LOGGER.error("failed to write", e) } } } thread { while (true) { try { if (this.processWriter == null) { Thread.sleep(100) } val a = this.queue.take() if (a.value != null) continue mapped[a.id] = a this.processWriter!!.write(a.request!!) this.processWriter!!.flush() } catch (e: Exception) { LOGGER.error("failed to write", e) } } } } fun getWSLCanonicalPath(file: VirtualFile): String? { if (!file.isFromWSL()) { return null } if (file.cachedWSLCanonicalPath == null) { try { val wslPath = file.getWSLPath() val a = AsyncValue() a.request = "${a.id};read-symlink;${wslPath}\n" this.queue.add(a) while (a.getValue() == null) { if (!queue.contains(a)) { this.queue.add(a) } } val link = a.getValue() file.cachedWSLCanonicalPath = file.path.split("/").subList(0, 4).joinToString("/") + link } catch (e: IOException) { LOGGER.error("failed to getWSLCanonicalPath", e) } } return file.cachedWSLCanonicalPath } fun isWslSymlink(file: VirtualFile): Boolean { if (file.isSymlink != null) { return file.isSymlink!! } if (file.isFromWSL() && file.parent != null) { try { val path: String = file.path.replace("^//wsl\\$/[^/]+".toRegex(), "").replace("""^//wsl.localhost/[^/]+""".toRegex(), "") val a = AsyncValue() a.request = "${a.id};is-symlink;${path}\n" this.queue.add(a) while (a.getValue() == null) { if (!queue.contains(a)) { this.queue.add(a) } } val isSymLink = a.getValue() file.isSymlink = isSymLink.equals("true") return isSymLink.equals("true") } catch (e: Exception) { LOGGER.error("failed isWslSymlink", e) return false } } return false } } class WslVirtualFileSystem: LocalFileSystemImpl() { private var wslSymlinksProviders: MutableMap<String, WslSymlinksProvider> = HashMap() private var reentry: VirtualFile? = null val lock = ReentrantLock() override fun getProtocol(): String { return "file" } fun getWslSymlinksProviders(file: VirtualFile): WslSymlinksProvider { val distro = file.getWSLDistribution()!! if (!this.wslSymlinksProviders.containsKey(distro)) { this.wslSymlinksProviders[distro] = WslSymlinksProvider(distro) } return this.wslSymlinksProviders[distro]!! } fun getRealVirtualFile(file: VirtualFile): VirtualFile { lock.withLock { if (reentry == file) { throw Error("error") } reentry = file val symlkinkWsl = file.parents.find { it.isFromWSL() && this.getWslSymlinksProviders(file).isWslSymlink(it) } val relative = symlkinkWsl?.path?.let { file.path.replace(it, "") } val resolved = symlkinkWsl?.let { virtualFile -> this.resolveSymLink(virtualFile)?.let { this.findFileByPath(it) } } val r = relative?.let { resolved?.findFileByRelativePath(it) } ?: file reentry = null return r } } override fun contentsToByteArray(vfile: VirtualFile): ByteArray { val file = this.getRealVirtualFile(vfile) return super.contentsToByteArray(file) } override fun getOutputStream(vfile: VirtualFile, requestor: Any?, modStamp: Long, timeStamp: Long): OutputStream { val file = this.getRealVirtualFile(vfile) return super.getOutputStream(file, requestor, modStamp, timeStamp) } override fun getAttributes(vfile: VirtualFile): FileAttributes? { val file = getRealVirtualFile(vfile) var attributes = super.getAttributes(file) if (attributes != null && attributes.type == null && this.getWslSymlinksProviders(file).isWslSymlink(file)) { val resolved = this.resolveSymLink(file)?.let { this.findFileByPath(it) } if (resolved != null) { val resolvedAttrs = super.getAttributes(resolved) attributes = FileAttributes(resolvedAttrs?.isDirectory ?: false, false, true, attributes.isHidden, attributes.length, attributes.lastModified, attributes.isWritable, FileAttributes.CaseSensitivity.SENSITIVE) } } return attributes } override fun resolveSymLink(file: VirtualFile): String? { if (file.isFromWSL()) { return this.getWslSymlinksProviders(file).getWSLCanonicalPath(file); } return super.resolveSymLink(file) } companion object { const val PROTOCOL = "\\wsl.localhost" fun getInstance() = service<VirtualFileManager>().getFileSystem(PROTOCOL) as WslVirtualFileSystem } override fun list(vfile: VirtualFile): Array<String> { val file = getRealVirtualFile(vfile) if (file.isFromWSL() && this.getWslSymlinksProviders(file).isWslSymlink(file)) { val f = this.resolveSymLink(file)?.let { this.findFileByPath(it) } return f?.let { super.list(it) } ?: emptyArray() } return super.list(file) } } val weakMap = WeakHashMap<VirtualFile, String?>() val weakMapSymlink = WeakHashMap<VirtualFile, Boolean?>() private var VirtualFile.cachedWSLCanonicalPath: String? get() { return weakMap[this] } set(value) { weakMap[this] = value } private var VirtualFile.isSymlink: Boolean? get() { return weakMapSymlink[this] } set(value) { weakMapSymlink[this] = value } private fun VirtualFile.isFromWSL(): Boolean { return this.path.startsWith("//wsl$/") || path.startsWith("//wsl.localhost"); } private fun VirtualFile.getWSLDistribution(): String? { if (!isFromWSL()) { return null; } return path.replace("""^//wsl\$/""".toRegex(), "") .replace("""^//wsl.localhost/""".toRegex(), "").split("/")[0] } private fun VirtualFile.getWSLPath(): String { return path.replace("""^//wsl\$/[^/]+""".toRegex(), "") .replace("""^//wsl.localhost/[^/]+""".toRegex(), "") } public val VirtualFileUrl.getVirtualFile: VirtualFile? get() { if (url.startsWith(WslVirtualFileSystem.PROTOCOL)) { val protocolSepIndex = url.indexOf(URLUtil.SCHEME_SEPARATOR) val fileSystem: VirtualFileSystem? = if (protocolSepIndex < 0) null else WslVirtualFileSystem.getInstance() if (fileSystem == null) return null val path = url.substring(protocolSepIndex + URLUtil.SCHEME_SEPARATOR.length) return fileSystem.findFileByPath(path) } return null } val VirtualFile.parents: Iterable<VirtualFile> get() = object : Iterable<VirtualFile> { override fun iterator(): Iterator<VirtualFile> { var file = this@parents return object : Iterator<VirtualFile> { override fun hasNext() = file.parent != null override fun next(): VirtualFile { file = file.parent return file } } } }
1
Kotlin
0
1
b31d09a059e50dc518aa668399e71b3906f87466
12,382
intellij-wsl-symlinks
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/JumpListSettings.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package electron typealias JumpListSettings = electron.core.JumpListSettings
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
79
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/example/androidweather/db/CityDao.kt
KwunHeiChan
328,347,388
false
null
package com.example.androidweather.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import io.reactivex.rxjava3.core.Single @Dao interface CityDao { @Query("SELECT * FROM city ORDER BY last_searched_at DESC LIMIT 1") fun getLastSearchedCity(): Single<City> @Query("SELECT * FROM city ORDER BY name DESC") fun getAll(): Single<List<City>> @Query("DELETE FROM city WHERE id = :id") fun deleteCityById(id: Int): Single<Int> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(city: City) }
0
Kotlin
1
0
aaf1753e16aaa0bbf844323d317b752ca9582444
590
android-weather
Apache License 2.0
src/main/kotlin/example/component/Backdrop.kt
aerialist7
388,885,791
false
null
package kz.beigam.component.showcase import csstype.Color import csstype.ZIndex import kotlinx.js.jso import mui.material.Backdrop import mui.material.Button import mui.material.CircularProgress import mui.material.CircularProgressColor import react.FC import react.Props import react.useState val BackdropShowcase = FC<Props> { var isOpen by useState(false) Button { onClick = { isOpen = !isOpen } +"Show backdrop" } Backdrop { open = isOpen onClick = { isOpen = false } sx = jso { color = Color("#FFFFFF") zIndex = ZIndex(1000) } CircularProgress { color = CircularProgressColor.inherit } } }
2
null
5
7
e79c483de06738da9a58df6c4151952ab7a54eed
720
kotlin-material-ui-sample
Apache License 2.0
app/src/main/java/com/marknkamau/justjava/utils/NotificationHelper.kt
MarkNjunge
86,477,705
false
null
package com.thuylinhtran.FoodKotlin.utils import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import com.marknjunge.core.data.model.OrderStatus import com.thuylinhtran.FoodKotlin.R import kotlin.random.Random /** * Created by Mark Njung'e. * [email protected] * https://github.com/MarkNjunge */ interface NotificationHelper { val defaultChannelId: String val ordersChannelId: String val paymentsChannelId: String fun showCompletedOrderNotification() fun showPaymentNotification(body: String) fun showOrderStatusNotification(id: String, status: OrderStatus) fun showNotification(title: String, body: String, channelId: String = defaultChannelId) } class NotificationHelperImpl(private val context: Context) : NotificationHelper { override val defaultChannelId = "defaultNotificationChannel" override val ordersChannelId = "ordersNotificationChannel" override val paymentsChannelId = "paymentsNotificationChannel" private val notificationManager by lazy { context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createChannel(defaultChannelId, "Default channel", "Notifications") createChannel(ordersChannelId, "Orders channel", "Notifications for orders") createChannel(paymentsChannelId, "Payments channel", "Notifications for payments") } } @RequiresApi(Build.VERSION_CODES.O) private fun createChannel(id: String, name: String, description: String) { val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT) channel.description = description channel.enableLights(true) channel.enableVibration(true) notificationManager.createNotificationChannel(channel) } override fun showCompletedOrderNotification() { showNotification("Completed Order", "Your order has been completed.", ordersChannelId) } override fun showPaymentNotification(body: String) { showNotification("Order Payment", body, paymentsChannelId) } override fun showOrderStatusNotification(id: String, orderStatus: OrderStatus) { val body = when (orderStatus) { OrderStatus.PENDING -> "Your order is now pending." OrderStatus.CONFIRMED -> "Your order has been confirmed!" OrderStatus.IN_PROGRESS -> "Your order is now in progress." OrderStatus.COMPLETED -> "Your order has been completed!" OrderStatus.CANCELLED -> "Your order has been cancelled." } showNotification("Order updated", body, ordersChannelId) } override fun showNotification(title: String, body: String, channelId: String) { val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_just_java_logo_black) .setContentTitle(title) .setContentText(body) .setColor(ContextCompat.getColor(context, R.color.colorAccent)) .build() notificationManager.notify(Random.nextInt(), notification) } }
1
null
36
74
e3811f064797d50fadef4033bf1532b3c2ceef8d
3,366
JustJava-Android
Apache License 2.0
heart-rate-app/central/src/main/java/titsch/guilherme/heartratemonitor/central/usecases/measurements/GetLastHeartRateMeasurementFlowUseCase.kt
titsch-guilherme
568,068,598
false
{"Kotlin": 134173, "JavaScript": 16582}
package titsch.guilherme.heartratemonitor.central.usecases.measurements import titsch.guilherme.heartratemonitor.core.db.repositories.HeartRateMeasurementRepository class GetLastHeartRateMeasurementFlowUseCase( private val heartRateMeasurementRepository: HeartRateMeasurementRepository ) { suspend operator fun invoke() = heartRateMeasurementRepository.lastMeasurementFlow() }
0
Kotlin
0
0
7647c459186696b3b0675aeb289b5a59e1864cf5
386
heart-rate-monitor-android
MIT License
ulid/src/commonTest/kotlin/ulid/TestULIDFactory.kt
aallam
496,579,439
false
null
package ulid import ulid.utils.* import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue class TestULIDFactory { @Test fun test_randomULID() { val result = ULID.randomULID() assertEquals(26, result.length) val (timePart, randomPart) = partsOf(result) assertTrue { PastTimestampPart < timePart } assertTrue { MaxTimestampPart >= timePart } assertTrue { MinRandomPart <= randomPart } assertTrue { MaxRandomPart >= randomPart } } @Test fun test_randomULID_with_random_0() { val random = MockRandom(0) val factory = ULID.Factory(random) val result = factory.randomULID() assertEquals(0, random.nextLong()) assertEquals(26, result.length) val (timePart, randomPart) = partsOf(result) assertTrue { PastTimestampPart < timePart } assertTrue { MaxTimestampPart >= timePart } assertEquals(MinRandomPart, randomPart) } @Test fun test_randomULID_with_random_minus_1() { val random = MockRandom(-1) val factory = ULID.Factory(random) val result = factory.randomULID() assertEquals(-1, random.nextLong()) assertEquals(26, result.length) val (timePart, randomPart) = partsOf(result) assertTrue { PastTimestampPart < timePart } assertTrue { MaxTimestampPart >= timePart } assertEquals(MaxRandomPart, randomPart) } @Test fun test_randomULID_invalid_timestamp() { assertFailsWith<IllegalArgumentException> { ULID.randomULID(0x0001000000000000L) } } @Test fun test_nextULID() { val result = ULID.nextULID().toString() assertEquals(26, result.length) val (timePart, randomPart) = partsOf(result) assertTrue { PastTimestampPart < timePart } assertTrue { MaxTimestampPart >= timePart } assertTrue { MinRandomPart <= randomPart } assertTrue { MaxRandomPart >= randomPart } } @Test fun test_nextULID_with_random_0() { val random = MockRandom(0) val factory = ULID.Factory(random) val result = factory.nextULID().toString() assertEquals(0, random.nextLong()) assertEquals(26, result.length) val (timePart, randomPart) = partsOf(result) assertTrue { PastTimestampPart < timePart } assertTrue { MaxTimestampPart >= timePart } assertEquals(MinRandomPart, randomPart) } @Test fun test_nextValue_with_random_minus_1() { val random = MockRandom(-1) val factory = ULID.Factory(random) val result = factory.nextULID().toString() assertEquals(-1, random.nextLong()) assertEquals(26, result.length) val (timePart, randomPart) = partsOf(result) assertTrue { PastTimestampPart < timePart } assertTrue { MaxTimestampPart >= timePart } assertEquals(MaxRandomPart, randomPart) } @Test fun test_nextValue_invalid_timestamp() { assertFailsWith<IllegalArgumentException> { ULID.nextULID(0x0001000000000000L) } } @Test fun test_fromBytes() { class Input( val data: ByteArray, val mostSignificantBits: Long, val leastSignificantBits: Long, ) val inputs = listOf( Input(ZeroBytes, 0L, 0L), Input(FullBytes, AllBitsSet, AllBitsSet), Input(PatternBytes, PatternMostSignificantBits, PatternLeastSignificantBits), ) for (input in inputs) { input.run { val ulid = ULID.fromBytes(data) assertEquals(ulid.mostSignificantBits, mostSignificantBits) assertEquals(ulid.leastSignificantBits, leastSignificantBits) } } } @Test fun test_fromBytes_fails() { assertFailsWith<IllegalArgumentException> { ULID.fromBytes(ByteArray(15)) } assertFailsWith<IllegalArgumentException> { ULID.fromBytes(ByteArray(17)) } } @Test fun test_parseULID_and_toString() { class Input( val ulidString: String, val expectedTimestamp: Long ) val inputs = listOf( Input(PastTimestampPart + "0000000000000000", PastTimestamp), Input(PastTimestampPart + "ZZZZZZZZZZZZZZZZ", PastTimestamp), Input(PastTimestampPart + "123456789ABCDEFG", PastTimestamp), Input(PastTimestampPart + "1000000000000000", PastTimestamp), Input(PastTimestampPart + "1000000000000001", PastTimestamp), Input(PastTimestampPart + "0001000000000001", PastTimestamp), Input(PastTimestampPart + "0100000000000001", PastTimestamp), Input(PastTimestampPart + "0000000000000001", PastTimestamp), Input(MinTimestampPart + "123456789ABCDEFG", MinTimestamp), Input(MaxTimestampPart + "123456789ABCDEFG", MaxTimestamp), ) for (input in inputs) { input.run { val ulid = ULID.parseULID(ulidString) assertEquals(ulidString, ulid.toString()) assertEquals(expectedTimestamp, ulid.timestamp) } } } @Test fun test_parseULID_toString_invalid() { class Input( val ulidString: String, val expectedString: String, val expectedTimestamp: Long, ) val inputs = listOf( Input(PastTimestampPart + "0l00000000000000", PastTimestampPart + "0100000000000000", PastTimestamp), Input(PastTimestampPart + "0L00000000000000", PastTimestampPart + "0100000000000000", PastTimestamp), Input(PastTimestampPart + "0i00000000000000", PastTimestampPart + "0100000000000000", PastTimestamp), Input(PastTimestampPart + "0I00000000000000", PastTimestampPart + "0100000000000000", PastTimestamp), Input(PastTimestampPart + "0o00000000000000", PastTimestampPart + "0000000000000000", PastTimestamp), Input(PastTimestampPart + "0O00000000000000", PastTimestampPart + "0000000000000000", PastTimestamp), ) for (input in inputs) { input.run { val ulid = ULID.parseULID(ulidString) assertEquals(expectedString, ulid.toString()) assertEquals(expectedTimestamp, ulid.timestamp) } } } @Test fun test_parseULID_fails() { val inputs = listOf( "0000000000000000000000000", "000000000000000000000000000", "80000000000000000000000000", ) for (input in inputs) { assertFailsWith<IllegalArgumentException> { ULID.parseULID(input) } } } }
3
Kotlin
1
8
9cde1020a87df200ee3f25c26a9e1ea19ff47d59
6,844
ulid-kotlin
MIT License
vector/src/main/java/im/vector/riotx/features/crypto/verification/qrconfirmation/VerificationQrScannedByOtherFragment.kt
ginnyTheCat
310,769,850
false
{"Gradle": 8, "Markdown": 16, "Java Properties": 2, "Shell": 19, "Text": 43, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "YAML": 2, "INI": 2, "Proguard": 5, "XML": 768, "Kotlin": 2184, "Java": 12, "JavaScript": 4, "JSON": 5, "HTML": 2, "Python": 2, "FreeMarker": 2, "Fluent": 7}
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.riotx.features.crypto.verification.conclusion import android.os.Bundle import android.os.Parcelable import android.view.View import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.parentFragmentViewModel import com.airbnb.mvrx.withState import im.vector.riotx.R import im.vector.riotx.core.extensions.cleanup import im.vector.riotx.core.extensions.configureWith import im.vector.riotx.core.platform.VectorBaseFragment import im.vector.riotx.features.crypto.verification.VerificationAction import im.vector.riotx.features.crypto.verification.VerificationBottomSheetViewModel import kotlinx.android.parcel.Parcelize import kotlinx.android.synthetic.main.bottom_sheet_verification_child_fragment.* import javax.inject.Inject class VerificationConclusionFragment @Inject constructor( val controller: VerificationConclusionController ) : VectorBaseFragment(), VerificationConclusionController.Listener { @Parcelize data class Args( val isSuccessFull: Boolean, val cancelReason: String?, val isMe: Boolean ) : Parcelable private val sharedViewModel by parentFragmentViewModel(VerificationBottomSheetViewModel::class) private val viewModel by fragmentViewModel(VerificationConclusionViewModel::class) override fun getLayoutResId() = R.layout.bottom_sheet_verification_child_fragment override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() } override fun onDestroyView() { bottomSheetVerificationRecyclerView.cleanup() controller.listener = null super.onDestroyView() } private fun setupRecyclerView() { bottomSheetVerificationRecyclerView.configureWith(controller, hasFixedSize = false, disableItemAnimation = true) controller.listener = this } override fun invalidate() = withState(viewModel) { state -> controller.update(state) } override fun onButtonTapped() { sharedViewModel.handle(VerificationAction.GotItConclusion) } }
1
null
1
1
ee1d5faf0d59f9cc1c058d45fae3e811d97740fd
2,717
element-android
Apache License 2.0
core/resources/src/main/java/com/sapiest/vaultspace/core/resources/ResourcesProvider.kt
sapiest
703,269,182
false
{"Kotlin": 84168}
package com.sapiest.vaultspace.core.resources import android.graphics.drawable.Drawable import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes interface ResourcesProvider { fun getString(@StringRes resId: Int): String fun getColor(@ColorRes resId: Int): Int fun getDrawable(@DrawableRes resId: Int): Drawable? }
0
Kotlin
0
0
1a0639bec80b5d18dcd88761543aadf517260e1c
382
VaultSpace
MIT License
core/resources/src/main/java/com/sapiest/vaultspace/core/resources/ResourcesProvider.kt
sapiest
703,269,182
false
{"Kotlin": 84168}
package com.sapiest.vaultspace.core.resources import android.graphics.drawable.Drawable import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes interface ResourcesProvider { fun getString(@StringRes resId: Int): String fun getColor(@ColorRes resId: Int): Int fun getDrawable(@DrawableRes resId: Int): Drawable? }
0
Kotlin
0
0
1a0639bec80b5d18dcd88761543aadf517260e1c
382
VaultSpace
MIT License
src/main/kotlin/no/nav/klage/dokument/repositories/OpplastetDokumentUnderArbeidAsHoveddokumentRepository.kt
navikt
297,650,936
false
null
package no.nav.klage.dokument.repositories import no.nav.klage.dokument.domain.dokumenterunderarbeid.OpplastetDokumentUnderArbeidAsHoveddokument import org.springframework.data.jpa.repository.JpaRepository import org.springframework.transaction.annotation.Transactional import java.util.* @Transactional interface OpplastetDokumentUnderArbeidAsHoveddokumentRepository : JpaRepository<OpplastetDokumentUnderArbeidAsHoveddokument, UUID> { fun findByBehandlingIdAndDokarkivReferencesIsNotEmpty(behandlingId: UUID): Set<OpplastetDokumentUnderArbeidAsHoveddokument> fun findByMarkertFerdigNotNullAndFerdigstiltNull(): Set<OpplastetDokumentUnderArbeidAsHoveddokument> fun findByBehandlingIdAndMarkertFerdigNotNull(behandlingId: UUID): Set<OpplastetDokumentUnderArbeidAsHoveddokument> }
4
null
4
1
73fdef1da6d11c8ab19dd0c9b12c143877b85680
796
kabal-api
MIT License
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/wrapWithCollectionLiteral/toList.kt
ingokegel
72,937,917
true
null
// "Wrap element with 'listOf()' call" "true" // WITH_STDLIB fun foo(a: String) { bar(a<caret>) } fun bar(a: List<String>) {} // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.WrapWithCollectionLiteralCallFix
233
null
4912
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
222
intellij-community
Apache License 2.0
src/test/java/uk/gov/justice/hmpps/prison/service/AgencyPrisonerPayProfileServiceTest.kt
ministryofjustice
156,829,108
false
null
package uk.gov.justice.hmpps.prison.service import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.reset import org.mockito.kotlin.whenever import org.springframework.dao.DataAccessException import org.springframework.dao.QueryTimeoutException import uk.gov.justice.hmpps.prison.repository.jpa.model.AgyPrisonerPayProfile import uk.gov.justice.hmpps.prison.repository.jpa.repository.AgencyPrisonerPayProfileRepository import java.math.BigDecimal import java.time.LocalDate class AgencyPrisonerPayProfileServiceTest { val repository: AgencyPrisonerPayProfileRepository = mock() val service = AgencyPrisonerPayProfileService(repository) @BeforeEach fun setUp() { reset(repository) } @Test fun shouldReturnTheActiveAgencyPayProfile() { val today = LocalDate.now() whenever( repository.findAgencyPrisonerPayProfileByAgyLocId("MDI"), ).thenReturn( // Active listOf(getFakeEntity("MDI", today.minusDays(1), today.plusDays(1))), ) val payProfile = service.getAgencyPrisonerPayProfile("MDI") with(payProfile) { assertThat(agencyId).isEqualTo("MDI") assertThat(startDate).isEqualTo(today.minusDays(1)) assertThat(endDate).isEqualTo(today.plusDays(1)) assertThat(autoPayFlag).isTrue assertThat(minHalfDayRate).isEqualTo(BigDecimal("1.25")) assertThat(maxHalfDayRate).isEqualTo(BigDecimal("5.25")) assertThat(maxBonusRate).isEqualTo(BigDecimal("4.00")) assertThat(maxPieceWorkRate).isEqualTo(BigDecimal("8.00")) assertThat(payFrequency).isEqualTo(1) assertThat(backdateDays).isEqualTo(7) assertThat(defaultPayBandCode).isEqualTo("1") assertThat(weeklyAbsenceLimit).isEqualTo(12) } } @Test fun shouldChooseTheActiveProfileWhenOthersExist() { val today = LocalDate.now() whenever( repository.findAgencyPrisonerPayProfileByAgyLocId("MDI"), ).thenReturn( listOf( // Expired getFakeEntity("MDI", today.minusDays(10), today.minusDays(8)), // Active today getFakeEntity("MDI", today.minusDays(8), today), // Active today getFakeEntity("MDI", today.plusDays(1), null), ), ) val payProfile = service.getAgencyPrisonerPayProfile("MDI") with(payProfile) { assertThat(agencyId).isEqualTo("MDI") assertThat(startDate).isEqualTo(today.minusDays(8)) assertThat(endDate).isEqualTo(today) } } @Test fun notFoundExceptionForAgencyPayProfile() { whenever(repository.findAgencyPrisonerPayProfileByAgyLocId("XXX")).thenReturn(emptyList()) assertThatThrownBy { service.getAgencyPrisonerPayProfile("XXX") } .isInstanceOf(EntityNotFoundException::class.java) .hasMessage("Resource with id [XXX] not found.") } @Test fun dataAccessExceptionForAgencyPayProfile() { whenever( repository.findAgencyPrisonerPayProfileByAgyLocId("XXX"), ).thenThrow(QueryTimeoutException("Error")) assertThatThrownBy { service.getAgencyPrisonerPayProfile("XXX") } .isInstanceOf(DataAccessException::class.java) .hasMessage("Error") } private fun getFakeEntity(agencyId: String, startDate: LocalDate, endDate: LocalDate?) = AgyPrisonerPayProfile( agyLocId = agencyId, startDate = startDate, endDate = endDate, autoPayFlag = "Y", minHalfDayRate = BigDecimal("1.25"), maxHalfDayRate = BigDecimal("5.25"), maxBonusRate = BigDecimal("4.00"), maxPieceWorkRate = BigDecimal("8.00"), payFrequency = 1, backdateDays = 7, defaultPayBandCode = "1", weeklyAbsenceLimit = 12, ) }
5
null
6
6
c3d08a4c67f24e3c3bea9af8f9f8cfc16f787b6d
3,805
prison-api
MIT License
app/src/main/java/jp/gr/aqua/dropbox/provider/MainActivity.kt
jiro-aqua
184,567,108
false
null
package jp.gr.aqua.dropbox.provider import android.os.Bundle import android.provider.DocumentsContract import androidx.appcompat.app.AppCompatActivity import com.dropbox.core.android.Auth import jp.gr.aqua.dropbox.provider.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private val pref by lazy { Preference(this) } private lateinit var binding : ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.buttonLogin.setOnClickListener { if (pref.hasCredential()) { // Log out pref.putCredential() // BEGIN_INCLUDE(notify_change) // Notify the system that the status of our roots has changed. This will trigger // a call to DropboxProvider.queryRoots() and force a refresh of the system // picker UI. It's important to call this or stale results may persist. this.contentResolver.notifyChange(DocumentsContract.buildRootsUri(AUTHORITY), null) // END_INCLUDE(notify_change) showStatus() } else { // Login Auth.startOAuth2PKCE(this, BuildConfig.DROPBOX_APPID, DropboxClientFactory.requestConfig, SCOPES); } } showStatus() } override fun onResume() { super.onResume() val credential = Auth.getDbxCredential() credential?.let { pref.putCredential(credential.toString()) // BEGIN_INCLUDE(notify_change) // Notify the system that the status of our roots has changed. This will trigger // a call to DropboxProvider.queryRoots() and force a refresh of the system // picker UI. It's important to call this or stale results may persist. contentResolver.notifyChange(DocumentsContract.buildRootsUri(AUTHORITY), null) // END_INCLUDE(notify_change) showStatus() } } private fun showStatus() { if (pref.hasCredential()) { binding.sampleOutput.setText(R.string.logout_message) binding.buttonLogin.setText(R.string.log_out) } else { binding.sampleOutput.setText(R.string.intro_message) binding.buttonLogin.setText(R.string.log_in) } } companion object { private const val AUTHORITY = "${BuildConfig.APPLICATION_ID}.documents" private val SCOPES = arrayListOf("files.metadata.write", "files.metadata.read", "files.content.write", "files.content.read", "account_info.read") } }
0
Kotlin
1
6
c040be1df4472a43499bdce946f23fad6416f100
2,764
document-provider-dropbox-android
Apache License 2.0
src/main/kotlin/net/papierkorb2292/command_crafter/parser/Language.kt
Papierkorb2292
584,879,864
false
{"Kotlin": 714339, "Java": 422878, "TypeScript": 32500, "JavaScript": 2311, "SCSS": 1936}
package net.papierkorb2292.command_crafter.parser import net.minecraft.command.CommandSource import net.minecraft.server.command.ServerCommandSource import net.minecraft.server.function.FunctionBuilder import net.papierkorb2292.command_crafter.editor.debugger.server.functions.FunctionDebugInformation import net.papierkorb2292.command_crafter.editor.processing.AnalyzingResourceCreator import net.papierkorb2292.command_crafter.editor.processing.helper.AnalyzingResult import net.papierkorb2292.command_crafter.parser.helper.RawResource interface Language { fun parseToVanilla( reader: DirectiveStringReader<RawZipResourceCreator>, source: ServerCommandSource, resource: RawResource ) fun analyze( reader: DirectiveStringReader<AnalyzingResourceCreator>, source: CommandSource, result: AnalyzingResult ) fun parseToCommands( reader: DirectiveStringReader<ParsedResourceCreator?>, source: ServerCommandSource, builder: FunctionBuilder<ServerCommandSource> ): FunctionDebugInformation? interface LanguageClosure { val startLanguage: Language fun endsClosure(reader: DirectiveStringReader<*>): Boolean fun skipClosureEnd(reader: DirectiveStringReader<*>) } class TopLevelClosure(override val startLanguage: Language) : LanguageClosure { override fun endsClosure(reader: DirectiveStringReader<*>): Boolean { return !reader.canRead() } override fun skipClosureEnd(reader: DirectiveStringReader<*>) { } } }
1
Kotlin
0
7
ae01c01e8c69a1930d87557c0eefa7b76dd39c52
1,580
CommandCrafter
MIT License
src/com/hxz/mpxjs/lang/expr/psi/VueJSElementVisitor.kt
wuxianqiang
508,329,768
false
{"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338}
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.hxz.mpxjs.lang.expr.psi import com.intellij.lang.javascript.psi.JSElementVisitor class VueJSElementVisitor : JSElementVisitor() { fun visitVueJSFilterExpression(filter: VueJSFilterExpression) { visitJSCallExpression(filter) } }
2
Kotlin
0
4
e069e8b340ab04780ac13eab375d900f21bc7613
393
intellij-plugin-mpx
Apache License 2.0
serialization/src/test/kotlin/net/corda/serialization/internal/amqp/GenericsTests.kt
corda
70,137,417
false
null
package net.corda.nodeapi.internal.serialization.amqp import net.corda.core.contracts.* import net.corda.core.serialization.SerializedBytes import net.corda.nodeapi.internal.serialization.AllWhitelist import net.corda.testing.common.internal.ProjectStructure.projectRootDir import org.junit.Test import net.corda.core.identity.AbstractParty import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.transactions.WireTransaction import net.corda.testing.core.TestIdentity import org.hibernate.Transaction import java.io.File import java.net.URI import java.util.* import java.util.concurrent.ConcurrentHashMap import kotlin.test.assertEquals data class TestContractState( override val participants: List<AbstractParty> ) : ContractState class TestAttachmentConstraint : AttachmentConstraint { override fun isSatisfiedBy(attachment: Attachment) = true } class GenericsTests { companion object { val VERBOSE = true @Suppress("UNUSED") var localPath = projectRootDir.toUri().resolve( "node-api/src/test/resources/net/corda/nodeapi/internal/serialization/amqp") val miniCorp = TestIdentity(CordaX500Name("MiniCorp", "London", "GB")) } private fun printSeparator() = if (VERBOSE) println("\n\n-------------------------------------------\n\n") else Unit private fun <T : Any> BytesAndSchemas<T>.printSchema() = if (VERBOSE) println("${this.schema}\n") else Unit private fun ConcurrentHashMap<Any, AMQPSerializer<Any>>.printKeyToType() { if (!VERBOSE) return forEach { println("Key = ${it.key} - ${it.value.type.typeName}") } println() } @Test fun twoDifferentTypesSameParameterizedOuter() { data class G<A>(val a: A) val factory = testDefaultFactoryNoEvolution() val bytes1 = SerializationOutput(factory).serializeAndReturnSchema(G("hi")).apply { printSchema() } factory.getSerializersByDescriptor().printKeyToType() val bytes2 = SerializationOutput(factory).serializeAndReturnSchema(G(121)).apply { printSchema() } factory.getSerializersByDescriptor().printKeyToType() listOf(factory, testDefaultFactory()).forEach { f -> DeserializationInput(f).deserialize(bytes1.obj).apply { assertEquals("hi", this.a) } DeserializationInput(f).deserialize(bytes2.obj).apply { assertEquals(121, this.a) } } } @Test fun doWeIgnoreMultipleParams() { data class G1<out T>(val a: T) data class G2<out T>(val a: T) data class Wrapper<out T>(val a: Int, val b: G1<T>, val c: G2<T>) val factory = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactoryNoEvolution() val bytes = SerializationOutput(factory).serializeAndReturnSchema(Wrapper(1, G1("hi"), G2("poop"))).apply { printSchema() } printSeparator() DeserializationInput(factory2).deserialize(bytes.obj) } @Test fun nestedSerializationOfGenerics() { data class G<out T>(val a: T) data class Wrapper<out T>(val a: Int, val b: G<T>) val factory = testDefaultFactoryNoEvolution() val altContextFactory = testDefaultFactoryNoEvolution() val ser = SerializationOutput(factory) val bytes = ser.serializeAndReturnSchema(G("hi")).apply { printSchema() } factory.getSerializersByDescriptor().printKeyToType() assertEquals("hi", DeserializationInput(factory).deserialize(bytes.obj).a) assertEquals("hi", DeserializationInput(altContextFactory).deserialize(bytes.obj).a) val bytes2 = ser.serializeAndReturnSchema(Wrapper(1, G("hi"))).apply { printSchema() } factory.getSerializersByDescriptor().printKeyToType() printSeparator() DeserializationInput(factory).deserialize(bytes2.obj).apply { assertEquals(1, a) assertEquals("hi", b.a) } DeserializationInput(altContextFactory).deserialize(bytes2.obj).apply { assertEquals(1, a) assertEquals("hi", b.a) } } @Test fun nestedGenericsReferencesByteArrayViaSerializedBytes() { data class G(val a: Int) data class Wrapper<T : Any>(val a: Int, val b: SerializedBytes<T>) val factory = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()) val factory2 = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()) val ser = SerializationOutput(factory) val gBytes = ser.serialize(G(1)) val bytes2 = ser.serializeAndReturnSchema(Wrapper<G>(1, gBytes)) DeserializationInput(factory).deserialize(bytes2.obj).apply { assertEquals(1, a) assertEquals(1, DeserializationInput(factory).deserialize(b).a) } DeserializationInput(factory2).deserialize(bytes2.obj).apply { assertEquals(1, a) assertEquals(1, DeserializationInput(factory).deserialize(b).a) } } @Test fun nestedSerializationInMultipleContextsDoesntColideGenericTypes() { data class InnerA(val a_a: Int) data class InnerB(val a_b: Int) data class InnerC(val a_c: String) data class Container<T>(val b: T) data class Wrapper<T : Any>(val c: Container<T>) val factory = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()) val factories = listOf(factory, SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())) val ser = SerializationOutput(factory) ser.serialize(Wrapper(Container(InnerA(1)))).apply { factories.forEach { DeserializationInput(it).deserialize(this).apply { assertEquals(1, c.b.a_a) } it.getSerializersByDescriptor().printKeyToType(); printSeparator() } } ser.serialize(Wrapper(Container(InnerB(1)))).apply { factories.forEach { DeserializationInput(it).deserialize(this).apply { assertEquals(1, c.b.a_b) } it.getSerializersByDescriptor().printKeyToType(); printSeparator() } } ser.serialize(Wrapper(Container(InnerC("Ho ho ho")))).apply { factories.forEach { DeserializationInput(it).deserialize(this).apply { assertEquals("Ho ho ho", c.b.a_c) } it.getSerializersByDescriptor().printKeyToType(); printSeparator() } } } @Test fun nestedSerializationWhereGenericDoesntImpactFingerprint() { data class Inner(val a: Int) data class Container<T : Any>(val b: Inner) data class Wrapper<T : Any>(val c: Container<T>) val factorys = listOf( SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()), SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())) val ser = SerializationOutput(factorys[0]) ser.serialize(Wrapper<Int>(Container(Inner(1)))).apply { factorys.forEach { assertEquals(1, DeserializationInput(it).deserialize(this).c.b.a) } } ser.serialize(Wrapper<String>(Container(Inner(1)))).apply { factorys.forEach { assertEquals(1, DeserializationInput(it).deserialize(this).c.b.a) } } } data class ForceWildcard<out T>(val t: T) private fun forceWildcardSerialize( a: ForceWildcard<*>, factory: SerializerFactory = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())): SerializedBytes<*> { val bytes = SerializationOutput(factory).serializeAndReturnSchema(a) factory.getSerializersByDescriptor().printKeyToType() bytes.printSchema() return bytes.obj } @Suppress("UNCHECKED_CAST") private fun forceWildcardDeserializeString( bytes: SerializedBytes<*>, factory: SerializerFactory = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())) { DeserializationInput(factory).deserialize(bytes as SerializedBytes<ForceWildcard<String>>) } @Suppress("UNCHECKED_CAST") private fun forceWildcardDeserializeDouble( bytes: SerializedBytes<*>, factory: SerializerFactory = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())) { DeserializationInput(factory).deserialize(bytes as SerializedBytes<ForceWildcard<Double>>) } @Suppress("UNCHECKED_CAST") private fun forceWildcardDeserialize( bytes: SerializedBytes<*>, factory: SerializerFactory = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())) { DeserializationInput(factory).deserialize(bytes as SerializedBytes<ForceWildcard<*>>) } @Test fun forceWildcard() { forceWildcardDeserializeString(forceWildcardSerialize(ForceWildcard("hello"))) forceWildcardDeserializeDouble(forceWildcardSerialize(ForceWildcard(3.0))) } @Test fun forceWildcardSharedFactory() { val f = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()) forceWildcardDeserializeString(forceWildcardSerialize(ForceWildcard("hello"), f), f) forceWildcardDeserializeDouble(forceWildcardSerialize(ForceWildcard(3.0), f), f) } @Test fun forceWildcardDeserialize() { forceWildcardDeserialize(forceWildcardSerialize(ForceWildcard("hello"))) forceWildcardDeserialize(forceWildcardSerialize(ForceWildcard(10))) forceWildcardDeserialize(forceWildcardSerialize(ForceWildcard(20.0))) } @Test fun forceWildcardDeserializeSharedFactory() { val f = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()) forceWildcardDeserialize(forceWildcardSerialize(ForceWildcard("hello"), f), f) forceWildcardDeserialize(forceWildcardSerialize(ForceWildcard(10), f), f) forceWildcardDeserialize(forceWildcardSerialize(ForceWildcard(20.0), f), f) } @Test fun loadGenericFromFile() { val resource = "${javaClass.simpleName}.${testName()}" val sf = testDefaultFactory() // Uncomment to re-generate test files, needs to be done in three stages // File(URI("$localPath/$resource")).writeBytes(forceWildcardSerialize(ForceWildcard("wibble")).bytes) assertEquals("wibble", DeserializationInput(sf).deserialize(SerializedBytes<ForceWildcard<*>>( GenericsTests::class.java.getResource(resource).readBytes())).t) } data class StateAndString(val state: TransactionState<*>, val ref: String) data class GenericStateAndString<out T: ContractState>(val state: TransactionState<T>, val ref: String) // // If this doesn't blow up all is fine private fun fingerprintingDiffersStrip(state: Any) { class cl : ClassLoader() val m = ClassLoader::class.java.getDeclaredMethod("findLoadedClass", *arrayOf<Class<*>>(String::class.java)) m.isAccessible = true val factory1 = testDefaultFactory() factory1.register(net.corda.nodeapi.internal.serialization.amqp.custom.PublicKeySerializer) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(state) // attempt at having a class loader without some of the derived non core types loaded and thus // possibly altering how we serialise things val altClassLoader = cl() val factory2 = SerializerFactory(AllWhitelist, altClassLoader) factory2.register(net.corda.nodeapi.internal.serialization.amqp.custom.PublicKeySerializer) val ser2 = TestSerializationOutput(VERBOSE, factory2).serializeAndReturnSchema(state) // now deserialise those objects val factory3 = testDefaultFactory() factory3.register(net.corda.nodeapi.internal.serialization.amqp.custom.PublicKeySerializer) val des1 = DeserializationInput(factory3).deserializeAndReturnEnvelope(ser1.obj) val factory4 = SerializerFactory(AllWhitelist, cl()) factory4.register(net.corda.nodeapi.internal.serialization.amqp.custom.PublicKeySerializer) val des2 = DeserializationInput(factory4).deserializeAndReturnEnvelope(ser2.obj) } @Test fun fingerprintingDiffers() { val state = TransactionState<TestContractState> ( TestContractState(listOf(miniCorp.party)), "wibble", miniCorp.party, encumbrance = null, constraint = TestAttachmentConstraint()) val sas = StateAndString(state, "wibble") fingerprintingDiffersStrip(sas) } @Test fun fingerprintingDiffersList() { val state = TransactionState<TestContractState> ( TestContractState(listOf(miniCorp.party)), "wibble", miniCorp.party, encumbrance = null, constraint = TestAttachmentConstraint()) val sas = StateAndString(state, "wibble") fingerprintingDiffersStrip(Collections.singletonList(sas)) } // // Force object to be serialised as Example<T> and deserialized as Example<?> // @Test fun fingerprintingDiffersListLoaded() { // // using this wrapper class we force the object to be serialised as // net.corda.core.contracts.TransactionState<T> // data class TransactionStateWrapper<out T : ContractState> (val o: List<GenericStateAndString<T>>) val state = TransactionState<TestContractState> ( TestContractState(listOf(miniCorp.party)), "wibble", miniCorp.party, encumbrance = null, constraint = TestAttachmentConstraint()) val sas = GenericStateAndString(state, "wibble") val factory1 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() factory1.register(net.corda.nodeapi.internal.serialization.amqp.custom.PublicKeySerializer) factory2.register(net.corda.nodeapi.internal.serialization.amqp.custom.PublicKeySerializer) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema( TransactionStateWrapper(Collections.singletonList(sas))) val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(sas.ref, des1.obj.o.firstOrNull()?.ref ?: "WILL NOT MATCH") } @Test fun nestedGenericsWithBound() { open class BaseState(val a : Int) class DState(a: Int) : BaseState(a) data class LTransactionState<out T : BaseState> constructor(val data: T) data class StateWrapper<out T : BaseState>(val state: LTransactionState<T>) val factory1 = testDefaultFactoryNoEvolution() val state = LTransactionState(DState(1020304)) val stateAndString = StateWrapper(state) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(stateAndString) //val factory2 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(state.data.a, des1.obj.state.data.a) } @Test fun nestedMultiGenericsWithBound() { open class BaseState(val a : Int) class DState(a: Int) : BaseState(a) class EState(a: Int, val msg: String) : BaseState(a) data class LTransactionState<out T1 : BaseState, out T2: BaseState> (val data: T1, val context: T2) data class StateWrapper<out T1 : BaseState, out T2: BaseState>(val state: LTransactionState<T1, T2>) val factory1 = testDefaultFactoryNoEvolution() val state = LTransactionState(DState(1020304), EState(5060708, msg = "thigns")) val stateAndString = StateWrapper(state) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(stateAndString) //val factory2 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(state.data.a, des1.obj.state.data.a) assertEquals(state.context.a, des1.obj.state.context.a) } @Test fun nestedMultiGenericsNoBound() { open class BaseState(val a : Int) class DState(a: Int) : BaseState(a) class EState(a: Int, val msg: String) : BaseState(a) data class LTransactionState<out T1, out T2> (val data: T1, val context: T2) data class StateWrapper<out T1, out T2>(val state: LTransactionState<T1, T2>) val factory1 = testDefaultFactoryNoEvolution() val state = LTransactionState(DState(1020304), EState(5060708, msg = "things")) val stateAndString = StateWrapper(state) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(stateAndString) //val factory2 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(state.data.a, des1.obj.state.data.a) assertEquals(state.context.a, des1.obj.state.context.a) assertEquals(state.context.msg, des1.obj.state.context.msg) } @Test fun baseClassInheritedButNotOverriden() { val factory1 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() open class BaseState<T1, T2>(open val a : T1, open val b: T2) class DState<T1, T2>(a: T1, b: T2) : BaseState<T1, T2>(a, b) val state = DState(100, "hello") val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(state) val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(state.a, des1.obj.a) assertEquals(state.b, des1.obj.b) class DState2<T1, T2, T3>(a: T1, b: T2, val c: T3) : BaseState<T1, T2>(a, b) val state2 = DState2(100, "hello", 100L) val ser2 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(state2) val des2 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser2.obj) assertEquals(state2.a, des2.obj.a) assertEquals(state2.b, des2.obj.b) assertEquals(state2.c, des2.obj.c) } @Test fun baseClassInheritedButNotOverridenBounded() { val factory1 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() open class Bound(val a: Int) open class BaseState<out T1 : Bound>(open val a: T1) class DState<out T1: Bound>(a: T1) : BaseState<T1>(a) val state = DState(Bound(100)) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(state) val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(state.a.a, des1.obj.a.a) } @Test fun nestedMultiGenericsAtBottomWithBound() { open class BaseState<T1, T2>(val a : T1, val b: T2) class DState<T1, T2>(a: T1, b: T2) : BaseState<T1, T2>(a, b) class EState<T1, T2>(a: T1, b: T2, val c: Long) : BaseState<T1, T2>(a, b) data class LTransactionState<T1, T2, T3 : BaseState<T1, T2>, out T4: BaseState<T1, T2>> (val data: T3, val context: T4) data class StateWrapper<T1, T2, T3 : BaseState<T1, T2>, out T4: BaseState<T1, T2>>(val state: LTransactionState<T1, T2, T3, T4>) val factory1 = testDefaultFactoryNoEvolution() val state = LTransactionState(DState(1020304, "Hello"), EState(5060708, "thins", 100L)) val stateAndString = StateWrapper(state) val ser1 = TestSerializationOutput(VERBOSE, factory1).serializeAndReturnSchema(stateAndString) //val factory2 = testDefaultFactoryNoEvolution() val factory2 = testDefaultFactory() val des1 = DeserializationInput(factory2).deserializeAndReturnEnvelope(ser1.obj) assertEquals(state.data.a, des1.obj.state.data.a) assertEquals(state.context.a, des1.obj.state.context.a) } fun implemntsGeneric() { open class B<out T>(open val a: T) class D(override val a: String) : B<String>(a) val factory = testDefaultFactoryNoEvolution() val bytes = SerializationOutput(factory).serialize(D("Test")) DeserializationInput(factory).deserialize(bytes).apply { assertEquals("Test", this.a) } } interface implementsGenericInterfaceI<out T> { val a: T } @Test fun implemntsGenericInterface() { class D(override val a: String) : implementsGenericInterfaceI<String> val factory = testDefaultFactoryNoEvolution() val bytes = SerializationOutput(factory).serialize(D("Test")) DeserializationInput(factory).deserialize(bytes).apply { assertEquals("Test", this.a) } } }
62
null
1077
3,989
d27aa0e6850d3804d0982024054376d452e7073a
21,072
corda
Apache License 2.0
PhoenixPenNG/libgame/src/main/java/com/phoenixpen/game/input/EnumKeyComboMapping.kt
nshcat
182,317,693
false
{"Text": 2, "Ignore List": 4, "Markdown": 1, "Gradle": 5, "INI": 1, "Shell": 6, "Batchfile": 1, "GLSL": 12, "JSON": 28, "Java Properties": 1, "XML": 15, "Kotlin": 213, "Java": 6, "C": 2}
package com.phoenixpen.game.input /** * A key combo input mapping that emits a [EnumEvent] with a given constant enumeration value. */ class EnumKeyComboMapping<E>(private val eventValue: E, vararg components: Any): KeyComboMapping(*components) { /** * Create event instance * * @return New event instance */ override fun createEvent(): InputEvent { return EnumEvent(this.eventValue) } }
0
Kotlin
0
1
8e29e78b8f3d1ff7bdfedfd7c872b1ac69dd665d
438
phoenixpen_ng
MIT License
backend/src/jvmBackMain/kotlin/com/example/backend/util/jwt/JwtUtil.kt
DeNyWho
584,003,645
false
{"Kotlin": 511314}
package com.example.backend.util.jwt import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import io.jsonwebtoken.security.Keys import org.springframework.beans.factory.annotation.Value import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import java.util.* import javax.crypto.SecretKey @Component class JwtTokenUtil( @Value("\${jwt.expiration.access}") private val accessExpiration: Long, @Value("\${jwt.expiration.refresh}") private val refreshExpiration: Long ) { private val key: SecretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256) val secret: ByteArray = key.encoded fun generateAccessToken(userDetails: UserDetails): String { val claims = Jwts.claims().setSubject(userDetails.username) claims["roles"] = userDetails.authorities.map { it.authority } val now = Date() val validity = Date(now.time + accessExpiration * 1000) return Jwts.builder() .setClaims(claims) .setIssuedAt(now) .setExpiration(validity) .signWith(SignatureAlgorithm.HS256, secret) .compact() } fun generateRefreshToken(): String { val now = Date() val validity = Date(now.time + refreshExpiration * 1000) return Jwts.builder() .setIssuedAt(now) .setExpiration(validity) .signWith(SignatureAlgorithm.HS256, secret) .compact() } fun validateToken(token: String, userDetails: UserDetails): Boolean { val username = getUsernameFromToken(token) return username == userDetails.username && !isTokenExpired(token) } private fun getUsernameFromToken(token: String): String { return Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .body .subject } fun getExpirationDateFromToken(token: String): Date { return Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .body .expiration } private fun isTokenExpired(token: String): Boolean { val expiration = getExpirationDateFromToken(token) return expiration.before(Date()) } }
0
Kotlin
0
0
4388d4eb1f0c3e52929077ba3939b7f4124d1d5b
2,283
AniFoxKMP
Apache License 2.0
j2k/old/tests/testData/fileOrElement/newClassExpression/fullQualifiedName.kt
JetBrains
278,369,660
false
null
// ERROR: Not enough information to infer type variable E package test internal class User { fun main() { val list = java.util.ArrayList() } }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
159
intellij-kotlin
Apache License 2.0
demo/src/main/java/otpview/demo/ToggleController.kt
stoyicker
252,207,155
false
null
package otpview.demo import android.widget.Checkable internal abstract class ToggleController(private val checkable: Checkable) { fun setActive(newActive: Boolean) { checkable.isChecked = newActive if (newActive) { onActive() } else { onInactive() } } abstract fun onActive() abstract fun onInactive() }
0
Java
2
26
2eeaf16647859e318315ed13f8db178a675af919
344
otpview
MIT License
app/src/test/java/com/joel/jlibtemplate/MainViewModelTest.kt
jogcaetano13
524,525,946
false
null
package com.joel.jlibtemplate import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import com.joel.communication_android.dispatchers.CommunicationDispatcher import com.joel.communication_android.states.ResultState import com.joel.jlibtemplate.respositories.ChallengeRepository import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.given @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class MainViewModelTest { @Mock private lateinit var dispatcher: CommunicationDispatcher @Mock private lateinit var repository: ChallengeRepository private lateinit var viewModel: MainViewModel @Before fun setup() { viewModel = MainViewModel(dispatcher, repository) given(dispatcher.main()).willReturn(UnconfinedTestDispatcher()) given(dispatcher.default()).willReturn(UnconfinedTestDispatcher()) given(dispatcher.io()).willReturn(UnconfinedTestDispatcher()) } @Test fun `given challenges, then return success`() = runTest { given(repository.getChallenges(dispatcher)).willReturn(flowOf(ResultState.Success(listOf()))) viewModel.getChallenges().test { val state = awaitItem() awaitComplete() assertThat(state is ResultState.Success).isTrue() } } }
0
null
0
1
491d46c1925a1ffb8120b91a5f2c8e9e701ad4df
1,620
communication
MIT License
src/test/kotlin/dev/fastmc/common/BoxedIntArrayUtil.kt
FastMinecraft
576,040,289
false
null
package dev.fastmc.common import it.unimi.dsi.fastutil.ints.IntOpenHashSet import it.unimi.dsi.fastutil.objects.ObjectArrays import java.util.* import kotlin.math.max object BoxedIntArrayUtil { fun closeSorted(n: Int): Array<Int> { val random = Random() val data = Array(n) { (it + random.nextGaussian() * 100).toInt() } return data } fun ascending(n: Int): Array<Int> { return Array(n) { it } } fun descending(n: Int): Array<Int> { return Array(n) { n - it } } fun randomAscending(n: Int): Array<Int> { val random = Random() val data = Array(n) { it } ObjectArrays.shuffle(data, random) return data } fun random(n: Int): Array<Int> { val random = Random() return Array(n) { random.nextInt() } } fun duplicated(n: Int): Array<Int> { val random = Random() val repeatSize = max(n / 1_000, 100) val tempSet = IntOpenHashSet(repeatSize) while (tempSet.size < repeatSize) { tempSet.add(random.nextInt()) } val tempArray = tempSet.toIntArray() val data = Array(n) { tempArray[random.nextInt(repeatSize)] } ObjectArrays.shuffle(data, random) return data } }
1
Kotlin
1
1
eb6ce404fcb0488e2719eccd29d53132ba872141
1,297
fastmc-common
MIT License
demo-app/src/main/java/com/github/mrbean355/android/demo/CountryListActivity.kt
MrBean355
169,101,192
false
null
package com.github.mrbean355.android.demo import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.RecyclerView import com.github.mrbean355.android.enhancedadapter.demo.R class CountryListActivity : AppCompatActivity() { private lateinit var adapter: CountryAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_country_list) adapter = CountryAdapter() adapter.setItems(buildCountryList()) adapter.setSelectedItems(listOf(Country("Angola"), Country("South Africa"))) findViewById<RecyclerView>(R.id.recycler_view).adapter = adapter } /** * Filter the adapter's items based on the user's search query. */ private fun onSearchQueryEntered(query: String?) { adapter.filter(query) } /** * Display the currently selected items in a Toast. */ private fun onDoneClicked() { val message = StringBuilder() val selection = adapter.getSelectedItems() selection.forEach { if (message.isNotEmpty()) { message.append(", ") } message.append(it) } if (selection.isEmpty()) { message.append("(nothing)") } message.insert(0, "You selected: ") Toast.makeText(this, message, Toast.LENGTH_LONG).show() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.country_list, menu) val menuItem = menu?.findItem(R.id.action_search) val searchView = menuItem?.actionView as? SearchView searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { onSearchQueryEntered(query) return false } override fun onQueryTextChange(newText: String?): Boolean { onSearchQueryEntered(newText) return false } }) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_done) { onDoneClicked() return true } return super.onOptionsItemSelected(item) } private companion object { private val COUNTRIES = listOf( "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo", "The Democratic Republic of The", "Cook Islands", "Costa Rica", "Cote D'ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-bissau", "Guyana", "Haiti", "Heard Island and Mcdonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea", "Democratic People's Republic of", "Korea", "Republic of", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia", "The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Federated States of", "Moldova", "Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territory", "Occupied", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", "Saint Vincent and The Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and The South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Province of China", "Tajikistan", "Tanzania", "United Republic of", "Thailand", "Timor-leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam", "Virgin Islands", "British", "Virgin Islands", "U.S.", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" ) private fun buildCountryList(): List<Country> { return COUNTRIES.map { Country(it) } } } }
0
Kotlin
0
2
6d9eb4b63d1ed3d4596ff5357e9605d2f7e2b9c9
6,599
enhanced-adapter
Apache License 2.0
j2k/testData/fileOrElement/field/varWithInit.kt
staltz
38,581,975
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
// ERROR: Unresolved reference: Foo class C { var f = Foo(1, 2) }
0
Java
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
69
kotlin
Apache License 2.0
app/src/main/java/dev/koffein/shoppingreminder/fragments/ItemEditDialog.kt
xecua
378,459,404
false
null
package dev.koffein.shoppingreminder.fragments import android.app.Dialog import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.activityViewModels import androidx.fragment.app.setFragmentResult import com.google.android.gms.common.api.Status import com.google.android.libraries.places.api.Places import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.widget.AutocompleteSupportFragment import com.google.android.libraries.places.widget.listener.PlaceSelectionListener import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import dev.koffein.shoppingreminder.R import dev.koffein.shoppingreminder.databinding.DialogEdititemBinding import dev.koffein.shoppingreminder.models.Item import dev.koffein.shoppingreminder.viewmodels.MainActivityViewModel class ItemEditDialog : BottomSheetDialogFragment() { private lateinit var binding: DialogEdititemBinding private val viewModel by activityViewModels<MainActivityViewModel>() // null == 新規作成 private var item: Item? = null private var currentPlace: Place? = null override fun getTheme(): Int = R.style.CustomBottomSheetDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // むしろitemを取得する? val index = arguments?.getInt(ARGS_INDEX, -1) if (index != null && index != -1) { item = viewModel.items.value?.get(index) } if (!Places.isInitialized()) { Places.initialize(requireContext(), resources.getString(R.string.google_maps_key)) } } // onCreateDialogでbindしているのでonCreateViewが不要? // 中身のDialogを作って返す部分 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = BottomSheetDialog(requireContext(), R.style.CustomBottomSheetDialog) val inflater = LayoutInflater.from(requireContext()) binding = DialogEdititemBinding.inflate(inflater) item?.let { // edit binding.editItemName.setText(it.name) binding.editItemDesc.setText(it.description) } Log.d(TAG, "${parentFragmentManager.fragments}") (parentFragmentManager.findFragmentById(R.id.edit_item_place) as? AutocompleteSupportFragment) ?.apply { setText(item?.place) setPlaceFields(listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)) setCountry("JP") setOnPlaceSelectedListener(object : PlaceSelectionListener { override fun onPlaceSelected(p0: Place) { currentPlace = p0 Log.i(TAG, "$p0") } override fun onError(p0: Status) { Log.e(TAG, "error occurred: $p0") } }) } binding.editItemDelete.visibility = if (item == null) View.GONE else View.VISIBLE binding.editItemDelete.setOnClickListener { val bundle = bundleOf( "id" to item?.id ) setFragmentResult(DELETE_KEY, bundle) parentFragmentManager.beginTransaction().remove(this).commit() } binding.editItemSend.setOnClickListener { // placeが設定されてるitemをplaceを新たに設定せずに更新するとcurrentPlaceがnullになる問題(idも持っといてPlace Detailsを叩く?) val bundle = bundleOf( "isNew" to (item == null), "name" to binding.editItemName.text.toString(), "description" to binding.editItemDesc.text.toString(), "place" to currentPlace, "id" to item?.id ) setFragmentResult(RESULT_KEY, bundle) parentFragmentManager.beginTransaction().remove(this).commit() } dialog.setContentView(binding.root) return dialog } override fun onDestroyView() { super.onDestroyView() val placeFragment = parentFragmentManager.findFragmentById(R.id.edit_item_place) if (placeFragment != null) { parentFragmentManager.beginTransaction().remove(placeFragment).commit() } } companion object { const val TAG = "ItemEditDialog" const val DELETE_KEY = "ItemEditDialogDelete" const val RESULT_KEY = "ItemEditDialogResult" // 型安全にしたいなあ…… const val ARGS_INDEX = "index" fun newInstance() = ItemEditDialog() fun newInstance(index: Int): ItemEditDialog { val dialog = ItemEditDialog() val args = Bundle() args.putInt(ARGS_INDEX, index) dialog.arguments = args return dialog } } }
10
Kotlin
0
0
6726c2da3829a09f79233500f4608f5a9e18793f
4,912
ShoppingReminder
MIT License
src/main/kotlin/no/nav/amt/deltaker/bff/application/plugins/Monitoring.kt
navikt
701,285,451
false
{"Kotlin": 223100, "PLpgSQL": 635, "Dockerfile": 140}
package no.nav.amt.deltaker.bff.application.plugins import io.ktor.http.HttpHeaders import io.ktor.server.application.Application import io.ktor.server.application.call import io.ktor.server.application.install import io.ktor.server.metrics.micrometer.MicrometerMetrics import io.ktor.server.plugins.callid.CallId import io.ktor.server.plugins.callid.callIdMdc import io.ktor.server.plugins.callloging.CallLogging import io.ktor.server.request.path import io.ktor.server.response.respond import io.ktor.server.routing.get import io.ktor.server.routing.routing import io.micrometer.prometheus.PrometheusConfig import io.micrometer.prometheus.PrometheusMeterRegistry import org.slf4j.event.Level fun Application.configureMonitoring() { install(CallLogging) { level = Level.INFO filter { call -> call.request.path().startsWith("/") && !call.request.path().startsWith("/internal") } callIdMdc("call-id") } install(CallId) { header(HttpHeaders.XRequestId) verify { callId: String -> callId.isNotEmpty() } } val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) install(MicrometerMetrics) { registry = appMicrometerRegistry // ... } routing { get("/internal/prometheus") { call.respond(appMicrometerRegistry.scrape()) } } }
1
Kotlin
0
0
de95fb4b4137f4049830e2eab23fbf317d89ef09
1,385
study-ktor-2.2.4
MIT License
core/src/main/java/com/mksoftware101/core/datetime/AndroidThreeTenDateTime.kt
mksoftware101
357,660,329
false
null
package com.mksoftware101.core.datetime import android.app.Application import com.jakewharton.threetenabp.AndroidThreeTen object AndroidThreeTenDateTime { fun initialize(context: Application) { AndroidThreeTen.init(context) } }
0
Kotlin
0
0
7903f75ff06d5be43d78f9940b975b7933318b0d
245
yetanothernotes
Apache License 2.0
src/test/kotlin/no/nav/bidrag/beregn/forskudd/rest/BidragBeregnForskuddTestConfig.kt
navikt
240,206,383
false
null
package no.nav.bidrag.beregn.forskudd.rest import com.nimbusds.jose.JOSEObjectType import io.swagger.v3.oas.annotations.OpenAPIDefinition import io.swagger.v3.oas.annotations.info.Info import io.swagger.v3.oas.annotations.security.SecurityRequirement import no.nav.bidrag.beregn.forskudd.rest.BidragBeregnForskuddLocal.Companion.LOCAL_PROFILE import no.nav.bidrag.beregn.forskudd.rest.BidragBeregnForskuddTest.Companion.TEST_PROFILE import no.nav.bidrag.commons.web.test.HttpHeaderTestRestTemplate import no.nav.security.mock.oauth2.MockOAuth2Server import no.nav.security.mock.oauth2.token.DefaultOAuth2TokenCallback import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.http.HttpHeaders private val LOGGER = LoggerFactory.getLogger(BidragBeregnForskuddTestConfig::class.java) @Configuration @OpenAPIDefinition( info = Info(title = "bidrag-vedtak", version = "v1"), security = [SecurityRequirement(name = "bearer-key")], ) @Profile(TEST_PROFILE, LOCAL_PROFILE) class BidragBeregnForskuddTestConfig { @Autowired private lateinit var mockOAuth2Server: MockOAuth2Server @Bean open fun securedTestRestTemplate(testRestTemplate: TestRestTemplate): HttpHeaderTestRestTemplate { val httpHeaderTestRestTemplate = HttpHeaderTestRestTemplate(testRestTemplate) httpHeaderTestRestTemplate.add(HttpHeaders.AUTHORIZATION) { generateTestToken() } return httpHeaderTestRestTemplate } private fun generateTestToken(): String { val iss = mockOAuth2Server.issuerUrl(ISSUER) val newIssuer = iss.newBuilder().host("localhost").build() val token = mockOAuth2Server.issueToken( issuerId = ISSUER, clientId = "aud-localhost", tokenCallback = DefaultOAuth2TokenCallback( issuerId = ISSUER, subject = "aud-localhost", typeHeader = JOSEObjectType.JWT.type, audience = listOf("aud-localhost"), claims = mapOf("iss" to newIssuer.toString()), expiry = 3600, ), ) return "Bearer " + token.serialize() } }
7
null
0
1
6b07dbbba3b513f41e12457e51bd39809e84513d
2,492
bidrag-beregn-forskudd-rest
MIT License
src/main/kotlin/com/rainbow/server/rest/controller/AuthController.kt
DDD-Community
649,288,543
false
null
package com.rainbow.server.rest.controller import com.rainbow.server.rest.dto.member.MemberRequestDto import com.rainbow.server.service.KakaoLoginService import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import java.net.URI import org.springframework.http.HttpHeaders import org.springframework.web.bind.annotation.* import javax.servlet.http.Cookie import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @RestController @RequestMapping("/auth") class AuthController(private val kakaoLoginService: KakaoLoginService, @Value("\${oauth.kakao.client-id}") private val clientId: String) { @GetMapping("/kakao") fun loginKakao(@RequestParam("code") code:String,response:HttpServletResponse): ResponseEntity<Any> { val info=kakaoLoginService.kaKaoLogin(code) val body= info.sessionKey if(body!=null){ val cookie = Cookie("sessionKey", info.sessionKey ) cookie.path = "/" // 쿠키 경로 설정 (선택 사항) cookie.maxAge = 60*60*24*90 response.addCookie(cookie) return ResponseEntity.ok().body(info) } return ResponseEntity.ok().body(info) } @PostMapping("/signIn") fun signIn(@RequestBody memberInfo:MemberRequestDto,response:HttpServletResponse):ResponseEntity<Any>{ val newMember=kakaoLoginService.singIn(memberInfo) return ResponseEntity.ok().body(newMember) } @PostMapping("/logout") fun logout(request: HttpServletRequest, response: HttpServletResponse): ResponseEntity<Any> { val sessionKey = getSessionKeyFromCookie(request) // Redis에서 세션 정보 삭제 sessionKey?.let { kakaoLoginService.logout(it) } // 쿠키 삭제 val cookie = Cookie("sessionKey", "") cookie.maxAge = 0 cookie.path = "/" response.addCookie(cookie) return ResponseEntity.ok().build() } private fun getSessionKeyFromCookie(request: HttpServletRequest): String? { val cookies = request.cookies if (cookies != null) { for (cookie in cookies) { if (cookie.name == "sessionKey") { return cookie.value } } } return null } // @GetMapping("/kakao/logout") // fun logoutKakao(code: String): ResponseEntity<KakaoUserLogout> { // return ResponseEntity.ok(kakaoLoginService.logout(code)) // } @GetMapping("/kakao/signin") fun kakaoBackendSignPage( ): ResponseEntity<*> { val redirectUrl = "https://kauth.kakao.com/oauth/authorize?client_id=${clientId}&redirect_uri=http://localhost:8080/auth/kakao&response_type=code" val uri = URI(redirectUrl) val headers = HttpHeaders() headers.location = uri return ResponseEntity<Any>(headers, HttpStatus.SEE_OTHER) } @GetMapping("/get") fun findById(code: String): ResponseEntity<Any>{ return ResponseEntity.ok(kakaoLoginService.getById(code)) } }
1
Kotlin
0
3
22f9168caefe03575177bd38830afbcc797c3d4e
3,141
Rainbow-Server
MIT License
app/core/src/main/kotlin/net/averak/gsync/core/game_context/GameContext.kt
averak
697,429,765
false
{"Kotlin": 118988, "Groovy": 100615, "Java": 4456, "Makefile": 1201, "Dockerfile": 287}
package net.averak.gsync.core.game_context import net.averak.gsync.core.daterange.DateRange import net.averak.gsync.core.daterange.Dateline import java.time.LocalDateTime import java.util.* /** * 機能によらずアプリケーション横断的なコンテキスト */ data class GameContext( val masterVersion: UUID, val idempotencyKey: UUID, val dateline: Dateline, val currentTime: LocalDateTime, ) { fun getToday(): DateRange { return dateline.getDateRangeAtTime(currentTime) } }
18
Kotlin
0
1
289aec33c894dc44f5c74b5b209ca024046ca4b7
476
gsync
MIT License
app/src/main/java/com/santansarah/blescanner/presentation/scan/device/Device.kt
santansarah
588,753,371
false
null
package com.santansarah.blescanner.presentation.scan.device import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.Info import androidx.compose.material3.Divider import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.santansarah.blescanner.data.local.entities.displayName import com.santansarah.blescanner.domain.models.BleReadWriteCommands import com.santansarah.blescanner.domain.models.ScanUI import com.santansarah.blescanner.utils.windowinfo.AppLayoutInfo @Composable fun ShowDeviceBody( appLayoutInfo: AppLayoutInfo, scanUi: ScanUI, bleReadWriteCommands: BleReadWriteCommands, onShowUserMessage: (String) -> Unit, onEdit: (Boolean) -> Unit, isEditing: Boolean, onSave: (String) -> Unit, ) { val scannedDevice = scanUi.selectedDevice!!.scannedDevice if (isEditing) EditDevice(onSave = onSave, updateEdit = onEdit, scannedDevice.displayName()) else { ServicePager( appLayoutInfo = appLayoutInfo, selectedDevice = scanUi.selectedDevice, onRead = bleReadWriteCommands.onRead, onShowUserMessage = onShowUserMessage, onWrite = bleReadWriteCommands.onWrite, onReadDescriptor = bleReadWriteCommands.onReadDescriptor, onWriteDescriptor = bleReadWriteCommands.onWriteDescriptor ) } } @Composable fun ReadWriteMenu( expanded: Boolean, onExpanded: (Boolean) -> Unit, onState: (Int) -> Unit ) { Box( modifier = Modifier.fillMaxSize() ) { IconButton( modifier = Modifier.align(Alignment.TopEnd), onClick = { onExpanded(true) }) { Icon( //modifier = Modifier.then(Modifier.padding(0.dp)), imageVector = Icons.Default.MoreVert, contentDescription = "Actions" ) } DropdownMenu( modifier = Modifier.border( 1.dp, MaterialTheme.colorScheme.primaryContainer ), expanded = expanded, onDismissRequest = { onExpanded(false) } ) { DropdownMenuItem( //modifier = Modifier.background(MaterialTheme.colorScheme.primary), //enabled = char.canRead, text = { Text("Read") }, onClick = { onState(0) onExpanded(false) }, leadingIcon = { Icon( Icons.Outlined.Info, contentDescription = "Read" ) }) Divider(color = MaterialTheme.colorScheme.primaryContainer) DropdownMenuItem( //modifier = Modifier.background(MaterialTheme.colorScheme.primary), //enabled = char.canWrite, text = { Text("Write") }, onClick = { onState(1) onExpanded(false) }, leadingIcon = { Icon( Icons.Outlined.Edit, contentDescription = null ) }) } } } /* @Preview( uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF17191b ) @Preview( uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFc0e5dd ) @Composable fun PreviewDeviceDetail( @PreviewParameter(PreviewDeviceDetailProvider::class) deviceDetail: DeviceDetail ) { BLEScannerTheme { ShowDevice( PaddingValues(4.dp), ScanState( emptyList(), deviceDetail, ConnectionState.CONNECTING, null, null ), {}, {}, {}, {}, { _: String, _: String -> }, { _: String, _: String -> }, { _: String, _: String, _: String -> }, {}, false, {}, {} ) } }*/
0
Kotlin
1
7
25cf4144258357bcd16a2b4bb708db92f2f7cbcf
4,791
ble-scanner
MIT License
mobile/app/src/commonTest/kotlin/com/langsapp/GreetingTest.kt
szymonklimek
527,003,710
false
{"Kotlin": 60223, "Ruby": 2227, "Dockerfile": 400, "Swift": 342}
package com.langsapp import kotlin.test.Test import kotlin.test.assertEquals class GreetingTest { @Test fun testGreeting() { assertEquals("Hello!", Greeting().greeting()) } }
9
Kotlin
0
1
dfce6455d774865f5ec403870680c81ae279bc57
198
langsapp
Apache License 2.0
source-code/final-project/app/src/main/java/com/droidcon/tinyinvoice/data/local/mapper/TaxMapper.kt
droidcon-academy
733,026,693
false
{"Kotlin": 441934}
package com.droidcon.tinyinvoice.data.local.mapper import com.droidcon.db.TaxEntity import com.droidcon.tinyinvoice.domain.model.Tax fun TaxEntity.toTax(): Tax = Tax( id = id, desc = desc, value = value_, )
0
Kotlin
0
0
4b2b45ef5bead5c7a68a9ffc01cb962c59b3ee99
241
android-mc-sqldelight
Apache License 2.0
src/main/kotlin/me/circuitrcay/euler/challenges/oneToTwentyFive/Problem11.kt
adamint
134,989,290
false
null
package me.circuitrcay.euler.challenges.oneToTwentyFive import me.circuitrcay.euler.Problem class Problem11 : Problem<String>() { override fun calculate(): Any { val prompt = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""".replace("\n", " ").split(" ") var max = 0L for (x in 0..(prompt.size - 1)) getValidPossibilities(x, prompt).forEach { if (it > max) max = it } return max } private fun getValidPossibilities(index: Int, prompt: List<String>): List<Long> { val results = mutableListOf<Long>() // diagonal RIGHT if (index % 20 <= 16 && index / 20 >= 3 && index / 20 <= 16) { results.add(prompt[index].toLong() * prompt[index - 19].toLong() * prompt[index - 19 - 19].toLong() * prompt[index - 19 - 19 - 19].toLong()) results.add(prompt[index].toLong() * prompt[index + 21].toLong() * prompt[index + 21 + 21].toLong() * prompt[index + 21 + 21 + 21].toLong()) // diagonal LEFT results.add(prompt[index].toLong() * prompt[index - 21].toLong() * prompt[index - 21 - 21].toLong() * prompt[index - 21 - 21].toLong()) results.add(prompt[index].toLong() * prompt[index + 19].toLong() * prompt[index + 19 + 19].toLong() * prompt[index + 19 + 19 + 19].toLong()) } // horizontal if (index % 20 >= 3) results.add(prompt[index].toLong() * prompt[index - 1].toLong() * prompt[index - 2].toLong() * prompt[index - 3].toLong()) if (index % 20 <= 16) results.add(prompt[index].toLong() * prompt[index + 1].toLong() * prompt[index + 2].toLong() * prompt[index + 3].toLong()) // vertical if (index / 20 >= 3) results.add(prompt[index].toLong() * prompt[index - 20].toLong() * prompt[index - 40].toLong() * prompt[index - 60].toLong()) if (index / 20 <= 16) results.add(prompt[index].toLong() * prompt[index + 20].toLong() * prompt[index + 40].toLong() * prompt[index + 60].toLong()) return results } }
1
null
1
1
cebe96422207000718dbee46dce92fb332118665
3,366
project-euler-kotlin
Apache License 2.0
app/src/main/java/io/github/memydb/data/api/services/NinegagnsfwService.kt
Faierbel
176,805,921
false
{"Kotlin": 64104}
package io.github.memydb.data.api.services import io.github.memydb.data.api.ApiResponse import io.github.memydb.data.pojos.Page import io.github.memydb.utils.RefreshLiveData import retrofit2.http.GET import retrofit2.http.Path import javax.inject.Singleton @Singleton interface NinegagnsfwService { @GET("/9gagnsfw") fun getPage(): RefreshLiveData<ApiResponse<Page>> @GET("/9gagnsfw/page/{id}") fun getPage(@Path("id") id: String): RefreshLiveData<ApiResponse<Page>> }
10
Kotlin
0
0
b7e51171ac9a8cb4bb8eb1a8c096fd0b83d25631
489
MemyDB
MIT License
plant_app/android/app/src/main/kotlin/com/example/plant_app/MainActivity.kt
bongQ417
291,462,457
false
{"Text": 2, "Ignore List": 7, "Markdown": 7, "YAML": 3, "Dart": 37, "Gradle": 9, "INI": 4, "Java Properties": 3, "XML": 36, "Kotlin": 2, "OpenStep Property List": 12, "Objective-C": 18, "Swift": 3, "JSON": 9, "SVG": 17, "Shell": 1, "Batchfile": 1, "Java": 2, "C": 2}
package com.example.plant_app import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
null
1
1
cbe760c816fd23aaa9968cfd5150e92570c24434
126
flutter-demo
MIT License
app/src/main/java/com/example/myfirstproject/MainActivity.kt
arthurtsumoto
633,586,121
false
null
package com.example.myfirstproject import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { @SuppressLint("SuspiciousIndentation") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // setcontentview TEM A FUNÇÃO DE COLOCAR O LAYOUT JUNTO COM OS CÓDIGOS val btnCalcular: Button = findViewById (R.id.btnCalcular) val edtPeso: EditText = findViewById (R.id.edtMsg_Peso) val edtAltura: EditText = findViewById(R.id.edtMsg_Altura) btnCalcular.setOnClickListener { val alturaStr = edtAltura.text.toString() val pesoStr = edtPeso.text.toString() if(alturaStr.isNotEmpty() && pesoStr.isNotEmpty()){ val Altura = alturaStr.toDouble() val Peso = pesoStr.toDouble() val AlturaFinal: Double = Altura * Altura val Resultado: Double = Peso / AlturaFinal val intent = Intent(this, ResultActivity::class.java) .apply { putExtra("EXTRA_RESULTADO", Resultado) } startActivity(intent) } else { Toast.makeText( this, "Preencher todos os campos", Toast.LENGTH_LONG).show() } } }}
0
Kotlin
0
0
1582c29c358e6436345f1a07c113e07360ad9147
1,578
CalculadoraIMC
MIT License
build-logic/conventions/src/main/kotlin/modulecheck/builds/CleanPlugin.kt
RBusarow
316,627,145
false
null
/* * Copyright (C) 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 builds import com.rickbusarow.kgx.applyOnce import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.Delete import org.gradle.api.tasks.SourceTask import org.gradle.language.base.plugins.LifecycleBasePlugin import java.io.File abstract class CleanPlugin : Plugin<Project> { override fun apply(target: Project) { target.plugins.applyOnce("base") val deleteEmptyDirs = target.tasks .register("deleteEmptyDirs", Delete::class.java) { task -> task.description = "Delete all empty directories within a project." task.doLast { val subprojectDirs = target.subprojects .map { it.projectDir.path } target.projectDir.walkBottomUp() .filter { it.isDirectory } .filterNot { dir -> subprojectDirs.any { dir.path.startsWith(it) } } .filterNot { it.path.contains(".gradle") } .filterNot { it.path.contains(".git") } .filter { it.listFiles().isNullOrEmpty() } .forEach { it.deleteRecursively() } } } target.tasks.named(LifecycleBasePlugin.CLEAN_TASK_NAME) { task -> task.dependsOn(deleteEmptyDirs) } target.tasks.register("cleanGradle", SourceTask::class.java) { task -> task.source(".gradle") task.doLast { target.projectDir.walkBottomUp() .filter { it.isDirectory } .filter { it.path.contains(".gradle") } .all { it.deleteRecursively() } } } target.tasks.register("deleteSrcGen", Delete::class.java) { task -> task.setDelete("src-gen") } if (target == target.rootProject) { val deleteOrphanedProjectDirs = target.tasks .register("deleteOrphanedProjectDirs", Delete::class.java) { task -> task.description = buildString { append("Delete any 'build' or `.gradle` directory or `gradle.properties` file ") append("without an associated Gradle project.") } task.doLast { val websiteBuildDir = "${target.rootDir}/website/node_modules" target.projectDir.walkBottomUp() .filterNot { it.path.contains(".git") } .filterNot { it.path.startsWith(websiteBuildDir) } .filter { it.isOrphanedBuildOrGradleDir() || it.isOrphanedGradleProperties() } .forEach(File::deleteRecursively) } } deleteEmptyDirs.configure { it.dependsOn(deleteOrphanedProjectDirs) } } } }
76
null
7
95
24e7c7667490630d30cf8b59cd504cd863cd1fba
3,116
ModuleCheck
Apache License 2.0
src/main/kotlin/intro/IntLambda3.kt
readingbat
256,581,160
false
{"Gradle": 2, "Java Properties": 1, "YAML": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Makefile": 1, "Markdown": 1, "JSON": 1, "INI": 1, "XML": 2, "Kotlin": 32, "Java": 71}
package intro val tripleIt3: (Int) -> Int = { i: Int -> i * 3 } // Simplify things with it val quadItIt3: (Int) -> Int = { it * 4 } fun doubleIt3(i: Int): Int = i * 2 val doubleIt3: (Int) -> Int = ::doubleIt3 // Higher-order function as a parameter fun func3(i: Int, func: (Int) -> Int): Int = func.invoke(i) fun main() { println(func3(5, tripleIt3)) println(func3(10, quadItIt3)) println(func3(20, tripleIt3)) println(func3(30, ::doubleIt3)) println(func3(40, doubleIt3)) }
0
Java
0
0
cbabfb062d69633a451e6c09405fd5cb9653ca24
490
readingbat-java-content
Apache License 2.0
app/src/main/java/io/bibuti/opennews/data/db/NewsDao.kt
bibutikoley
325,942,445
false
null
package io.bibuti.opennews.data.db import androidx.paging.PagingSource import androidx.room.* /** * Defining the DAOs for performing DB operations */ @Dao interface NewsDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveNews(news: List<SingleNewsItem>) @Query("select * from news_table order by publishedAt asc") fun fetchNewsDataSource(): PagingSource<Int, SingleNewsItem> } /** * This is Database table */ @Entity(tableName = "news_table") data class SingleNewsItem( @PrimaryKey(autoGenerate = false) val newsUrl: String, val newsImageUrl: String, val newsTitle: String, val newsDescription: String, val newsContent: String, val authorName: String, val publishedAt: String, )
0
Kotlin
0
1
c59e27f8bc771d8339728657f7ee96d0e5d26520
755
OpenNews
MIT License
app/src/main/java/com/sticky/notes/feature_note/domain/use_case/NoteUseCases.kt
iAbanoubSamir
615,831,530
false
null
package com.sticky.notes.feature_note.domain.use_case data class NoteUseCases( val getNotes: GetNotesUseCase, val deleteNote: DeleteNoteUseCase, val addNote: AddNoteUseCase, val getNoteById: GetNoteByIdUseCase )
0
Kotlin
0
0
dd63fe522c2320df6962df1ac198749831e422a0
228
StickyNotes
Apache License 2.0
library/src/main/java/com/genaku/snappingseekbar/model/ISeekBarItem.kt
genaku
260,438,991
true
{"Kotlin": 51919, "HTML": 26243}
package com.genaku.snappingseekbar.model interface ISeekBarItem { val name: String }
0
Kotlin
0
0
3a120a74eceb65768c64c3e18c79a77e807b6a7d
90
SnappingSeekBar
Apache License 2.0
ActiveWindowSelectionHighlight/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* // ktlint-disable no-wildcard-imports import java.awt.event.ActionEvent import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.* // ktlint-disable no-wildcard-imports import javax.swing.text.Caret import javax.swing.text.DefaultCaret import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter import javax.swing.text.Highlighter.HighlightPainter fun makeUI() = JSplitPane().also { it.resizeWeight = .5 it.leftComponent = makeTabbedPane() it.rightComponent = makeTabbedPane() it.preferredSize = Dimension(320, 240) } private fun makeTabbedPane(): Component { val tabs = JTabbedPane() tabs.addChangeListener { requestFocusForVisibleComponent(tabs) } tabs.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent) { requestFocusForVisibleComponent(tabs) } }) tabs.add("Custom", makeTextArea(true)) tabs.addTab("Default", makeTextArea(false)) return tabs } fun requestFocusForVisibleComponent(tabs: JTabbedPane) { val cmd = "requestFocusForVisibleComponent" val a = ActionEvent(tabs, ActionEvent.ACTION_PERFORMED, cmd) EventQueue.invokeLater { tabs.actionMap[cmd].actionPerformed(a) } } private fun makeTextArea(flg: Boolean): Component { val textArea = object : JTextArea() { override fun updateUI() { caret = null super.updateUI() if (flg) { val oldCaret = caret val blinkRate = oldCaret.blinkRate val caret: Caret = FocusOwnerCaret() caret.blinkRate = blinkRate setCaret(caret) caret.isSelectionVisible = true } } } textArea.text = "FocusOwnerCaret: $flg\n111\n22222\n33333333\n" textArea.selectAll() return JScrollPane(textArea) } private class FocusOwnerCaret : DefaultCaret() { override fun focusLost(e: FocusEvent) { super.focusLost(e) updateSelectionHighlightPainter() } override fun focusGained(e: FocusEvent) { super.focusGained(e) updateSelectionHighlightPainter() } private fun updateSelectionHighlightPainter() { isSelectionVisible = false // removeHighlight isSelectionVisible = true // addHighlight } override fun getSelectionPainter(): HighlightPainter { val c = component val w = c.topLevelAncestor val isActive = w is Window && w.isActive return if (c.hasFocus() && isActive) super.getSelectionPainter() else NO_FOCUS_PAINTER } companion object { private val NO_FOCUS_PAINTER = DefaultHighlightPainter(Color.GRAY.brighter()) } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
Kotlin
3
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
2,974
kotlin-swing-tips
MIT License
mapper/src/main/kotlin/com/kncept/mapper/reflect/ReflectiveDataClassCreator.kt
kncept
761,612,876
false
{"Kotlin": 45446}
package com.kncept.mapper.reflect import kotlin.reflect.KClass import kotlin.reflect.KProperty1 import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.primaryConstructor class ReflectiveDataClassCreator<T : Any>( private val type: KClass<T>, val filterNullArgsInConstruction: Boolean ) : DataClassCreator<T> { override fun type(): KClass<T> { return type } override fun types(): Map<String, KProperty1<Any, Any>> { val memberProperties = type.declaredMemberProperties.map { it.name to it }.toMap() return type.primaryConstructor!! .parameters .map { it.name!! to memberProperties[it.name]!! } .toMap() as Map<String, KProperty1<Any, Any>> } override fun values(item: Any): Map<String, Any?> { return type.declaredMemberProperties.map { it.name to it.getter.call(item) }.toMap() } override fun create(args: Map<String, Any?>): T { if (filterNullArgsInConstruction) { val mappedArgs = type.primaryConstructor!! .parameters .map { if (args[it.name] == null && it.isOptional) null else it to args[it.name] } .filterNotNull() .toMap() return type.primaryConstructor!!.callBy(mappedArgs) } else { val mappedArgs = type.primaryConstructor!!.parameters.map { it to args[it.name] }.toMap() return type.primaryConstructor!!.callBy(mappedArgs) } } }
0
Kotlin
0
0
82253778969938aa016dc95a40ccb5b84a6b30c1
1,435
kotlin-dynamodb-mapper
MIT License
tmp/arrays/youTrackTests/7504.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-18608 fun getInt(v: String): Int = TODO("some error prone calculation") fun getLong(v: Int): Long = TODO("some error prone calculation") val res1: Long = try { getInt("oops").let { getLong(it) } } catch (e: Throwable) { getLong(0) }
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
258
bbfgradle
Apache License 2.0
app/src/main/java/com/example/jsonplaceholder/ui/login/LoginScreen.kt
Reshma2497
635,314,398
false
null
package com.example.jsonplaceholder.ui.login import android.annotation.SuppressLint import android.app.Activity import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.example.jsonplaceholder.R import com.example.jsonplaceholder.ui.navigation.Screen import com.example.jsonplaceholder.ui.theme.JSONPlaceHolderTheme import com.example.jsonplaceholder.ui.theme.SkyBlue import com.facebook.CallbackManager import com.facebook.FacebookCallback import com.facebook.FacebookException import com.facebook.login.LoginManager import com.facebook.login.LoginResult import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException @SuppressLint("RememberReturnType") @Composable fun LoginScreen( navController: NavController, viewModel: LoginViewModel = viewModel() ) { JSONPlaceHolderTheme { //get current context val context = LocalContext.current val navigateToSignUp: () -> Unit = { navController.navigate(Screen.SignUpScreen.route) } //Google signin val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestProfile() .build() val googleSignInLauncher = rememberLauncherForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { val intent = result.data val task = GoogleSignIn.getSignedInAccountFromIntent(intent) try { // Handle successful sign-in val account = task.getResult(ApiException::class.java) navController.navigate(Screen.Users.route) // ... } catch (e: ApiException) { // Handle failed sign-in // ... } } } val googleSignInClient = remember { GoogleSignIn.getClient(context, googleSignInOptions) } val signInIntent = googleSignInClient.signInIntent //facebook initialize val callbackManager = remember { CallbackManager.Factory.create() } //val context = LocalContext.current val facebookCallback = remember { object : FacebookCallback<LoginResult> { override fun onCancel() {} override fun onError(error: FacebookException) { TODO("Not yet implemented") } override fun onSuccess(result: LoginResult) { //onLoginSuccess() navController.navigate(Screen.Users.route) } } } LaunchedEffect(callbackManager) { LoginManager.getInstance().registerCallback(callbackManager, facebookCallback) } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Log in to your account", style = MaterialTheme.typography.h4 ) Spacer(modifier = Modifier.height(16.dp)) OutlinedTextField( value = viewModel.email.value, onValueChange = { newValue -> viewModel.email.value = newValue viewModel.validateEmail() }, isError = viewModel.isEmailValid.value, label = { Text(text = "Email address") }, modifier = Modifier.fillMaxWidth().testTag("email") ) Text( modifier = Modifier.padding(start = 8.dp).testTag("email_error"), text = viewModel.emailErrMsg.value, fontSize = 14.sp, color = Color.Red ) Spacer(modifier = Modifier.height(8.dp)) var passwordVisibility by remember { mutableStateOf(false) } OutlinedTextField( value = viewModel.password.value, onValueChange = { newValue -> viewModel.password.value = newValue viewModel.validatePassword() }, isError = viewModel.isPasswordValid.value, label = { Text(text = "Password") }, visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { val visibilityIcon = if (passwordVisibility) Icons.Filled.VisibilityOff else Icons.Filled.Visibility IconButton(onClick = { passwordVisibility = !passwordVisibility }) { Icon( imageVector = visibilityIcon, contentDescription = "Toggle password visibility" ) } }, modifier = Modifier.fillMaxWidth().testTag("password") ) Text( modifier = Modifier.padding(start = 8.dp).testTag("password_error"), text = viewModel.passwordErrMsg.value, fontSize = 14.sp, color = Color.Red ) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { viewModel.login() if (viewModel.isLoginSuccess.value) { Toast.makeText( context, "${viewModel.email.value} : Login Success", Toast.LENGTH_SHORT ).show() navController.navigate(Screen.Users.route) } }, modifier = Modifier.fillMaxWidth().testTag("Login"), enabled = viewModel.isEnabledLoginButton.value ) { Text(text = "Sign in") } Text( modifier = Modifier.padding(start = 8.dp), text = viewModel.loginErrorMessage.value, fontSize = 14.sp, color = Color.Red ) Spacer(modifier = Modifier.height(8.dp)) TextButton( onClick = { navigateToSignUp() }, modifier = Modifier.fillMaxWidth(), ) { Text( text = "Don't have an account? Sign up", color = SkyBlue ) } Spacer(modifier = Modifier.height(16.dp)) Text( text = "Or sign in with", style = MaterialTheme.typography.subtitle1 ) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { IconButton( onClick = { LoginManager.getInstance().logInWithReadPermissions( context as Activity, listOf("public_profile", "email") ) }, modifier = Modifier.size(48.dp) ) { Image( painter = painterResource(id = R.drawable.ic_facebook), contentDescription = "Sign in with Facebook" ) } Spacer(modifier = Modifier.width(16.dp)) IconButton( onClick = { googleSignInLauncher.launch(signInIntent) }, modifier = Modifier.size(48.dp) ) { Image( painter = painterResource(id = R.drawable.ic_google), contentDescription = "Sign in with Google" ) } } } } }
0
Kotlin
0
0
dfcae89e54196e236f15e4807e770f085b68342f
9,280
JSONPlaceHolder
MIT License
plugins/src/main/kotlin/org/jetbrains/gradle/plugins/liquibase/Activity.kt
JetBrains
386,075,247
false
null
package org.jetbrains.gradle.plugins.liquibase import org.gradle.api.Action import org.gradle.api.tasks.JavaExec open class Activity(val name: String) { internal val taskActionsMap = mutableMapOf<LiquibaseCommand, MutableList<Action<JavaExec>>>() .withDefault { mutableListOf() } internal val propertiesActions = mutableListOf<Action<LiquibaseProperties>>() fun properties(action: Action<LiquibaseProperties>) = propertiesActions.add(action) /** * Configures an [Action] that will be invoked against the task for * the given [command] for this Activity. */ fun onCommand(command: LiquibaseCommand, action: Action<JavaExec>) { taskActionsMap.getOrPut(command) { mutableListOf() }.add(action) } /** * Configures an [Action] that will be invoked against all tasks for * this Activity. */ fun onEachCommand(action: JavaExec.(LiquibaseCommand) -> Unit) { LiquibaseCommand.values().forEach { onCommand(it) { action(it) } } } /** * Define the name of the Main class in Liquibase that the plugin should * call to run Liquibase itself. */ var mainClassName = "liquibase.integration.commandline.Main" /** * Define the JVM arguments to use when running Liquibase. This defaults * to an empty array, which is almost always what you want. */ var jvmArgs = mutableListOf<String>() }
7
Kotlin
9
26
50be7c14b3bd707ed3a2fae4536fb5e4650aa8ce
1,426
package-search-gradle-plugins
Apache License 2.0
ble/src/main/java/com/bhm/ble/device/BleConnectedDeviceManager.kt
buhuiming
641,804,698
false
null
/* * Copyright (c) 2022-2032 buhuiming * 不能修改和删除上面的版权声明 * 此代码属于buhuiming编写,在未经允许的情况下不得传播复制 */ @file:Suppress("SENSELESS_COMPARISON") package com.bhm.ble.device import com.bhm.ble.BleManager import com.bhm.ble.control.BleLruHashMap import com.bhm.ble.data.Constants.DEFAULT_MAX_CONNECT_NUM /** * 连接设备BleConnectedDevice管理池 * * @author Buhuiming * @date 2023年05月26日 08时54分 */ internal class BleConnectedDeviceManager private constructor() { private val bleLruHashMap: BleLruHashMap = BleLruHashMap(BleManager.get().getOptions()?.maxConnectNum ?: DEFAULT_MAX_CONNECT_NUM) companion object { private var instance: BleConnectedDeviceManager = BleConnectedDeviceManager() @Synchronized fun get(): BleConnectedDeviceManager { if (instance == null) { instance = BleConnectedDeviceManager() } return instance } } /** * 添加设备控制器 */ fun buildBleConnectedDevice(bleDevice: BleDevice): BleConnectedDevice? { if (bleLruHashMap.containsKey(bleDevice.getKey())) { return bleLruHashMap[bleDevice.getKey()] } val bleConnectedDevice = BleConnectedDevice(bleDevice) bleLruHashMap[bleDevice.getKey()] = bleConnectedDevice return bleConnectedDevice } /** * 获取设备控制器 */ fun getBleConnectedDevice(bleDevice: BleDevice): BleConnectedDevice? { if (bleLruHashMap.containsKey(bleDevice.getKey())) { return bleLruHashMap[bleDevice.getKey()] } return null } /** * 移除设备控制器 */ @Synchronized fun removeBleConnectedDevice(key: String) { if (bleLruHashMap.containsKey(key)) { bleLruHashMap.remove(key) } } /** * 是否存在该设备 */ @Synchronized fun isContainDevice(bleDevice: BleDevice): Boolean { return bleLruHashMap.containsKey(bleDevice.getKey()) } /** * 获取所有已连接设备集合 */ @Synchronized fun getAllConnectedDevice(): MutableList<BleDevice> { val list = mutableListOf<BleDevice>() bleLruHashMap.forEach { it.value?.let { device -> if (BleManager.get().isConnected(device.bleDevice)) { list.add(device.bleDevice) } } } return list } /** * 断开某个设备的连接 释放资源 */ @Synchronized fun close(bleDevice: BleDevice) { getBleConnectedDevice(bleDevice)?.close() bleLruHashMap.remove(bleDevice.getKey()) } /** * 断开所有设备的连接 */ @Synchronized fun disConnectAll() { bleLruHashMap.values.forEach { it?.disConnect() } closeAll() } /** * 断开所有连接 释放资源 */ @Synchronized fun closeAll() { bleLruHashMap.values.forEach { it?.close() } bleLruHashMap.clear() } }
2
null
14
88
282f26c4d0de2546424db4a2bb0112a8549f5ae0
2,944
BleCore
The Unlicense