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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
component-acgpicture/src/main/java/com/rabtman/acgpicture/mvp/model/entity/AcgPicture.kt | magic-coder | 143,361,731 | false | null | package com.rabtman.acgpicture.mvp.model.entity
import com.fcannizzaro.jsoup.annotations.interfaces.Attr
import com.fcannizzaro.jsoup.annotations.interfaces.Items
import com.fcannizzaro.jsoup.annotations.interfaces.Selector
import com.fcannizzaro.jsoup.annotations.interfaces.Text
import com.google.gson.annotations.SerializedName
/**
* @author Rabtman
* acg图数据类
*/
/**
* animate-picture页面信息
*/
data class AnimatePicturePage(
@SerializedName("posts_per_page") val postsPerPage: Int = 0,
@SerializedName("response_posts_count") val responsePostsCount: Int = 0,
@SerializedName("page_number") val pageNumber: Int = 0,
@SerializedName("posts") val animatePictureItems: List<AnimatePictureItem>? = null,
@SerializedName("posts_count") val postsCount: Int = 0,
@SerializedName("max_pages") val maxPages: Int = 0
)
/**
* animate-picture图片信息
*/
data class AnimatePictureItem(
@SerializedName("id") val id: Int = 0,
@SerializedName("md5") val md5: String = "",
@SerializedName("md5_pixels") val md5Pixels: String = "",
@SerializedName("width") val width: Int = 0,
@SerializedName("height") val height: Int = 0,
@SerializedName("small_preview") val smallPreview: String = "",
@SerializedName("medium_preview") val mediumPreview: String = "",
@SerializedName("big_preview") val bigPreview: String = "",
@SerializedName("pubtime") val pubtime: String = "",
@SerializedName("score") val score: Int = 0,
@SerializedName("score_number") val scoreNumber: Int = 0,
@SerializedName("size") val size: Int = 0,
@SerializedName("download_count") val downloadCount: Int = 0,
@SerializedName("erotics") val erotics: Int = 0,
@SerializedName("color") val color: List<Int>? = null,
@SerializedName("ext") val ext: String = "",
@SerializedName("status") val status: Int = 0
)
@Selector("main")
class APicturePage {
@Items
var items: List<APictureItem>? = null
private val pageCount: String? = null
fun getPageCount(): Int {
val count = pageCount!!.substring(pageCount.lastIndexOf("/") + 1)
return try {
Integer.parseInt(count)
} catch (e: Exception) {
e.printStackTrace()
1
}
}
}
@Selector("div.grid-bor div div.pos-r.cart-list")
class APictureItem {
@Text("div h2 a")
var title: String = ""
@Attr(query = "div.thumb.pos-r div", attr = "style")
var thumbUrl: String = ""
get() = try {
field.substring(field.lastIndexOf("(") + 1, field.lastIndexOf(".") + 4)
} catch (e: Exception) {
e.printStackTrace()
""
}
@Attr(query = "div h2 a", attr = "href")
var contentLink: String = ""
var count: String = ""
}
| 1 | null | 1 | 1 | d37bcfd8e1ec0e3b3598f196c068de09df5b8673 | 2,857 | AcgClub | MIT License |
extension-compose/src/androidTest/java/com/mapbox/maps/extension/compose/internal/utils/CityLocations.kt | mapbox | 330,365,289 | false | {"Kotlin": 3551866, "Java": 89114, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2847, "CMake": 1201, "EJS": 1194} | package com.mapbox.maps.extension.compose.internal.utils
import com.mapbox.geojson.Point
internal object CityLocations {
val HELSINKI: Point = Point.fromLngLat(24.9384, 60.1699)
val MINSK: Point = Point.fromLngLat(27.561481, 53.902496)
val BERLIN = Point.fromLngLat(13.403, 52.562)
val KYIV = Point.fromLngLat(30.498, 50.541)
val WASHINGTON = Point.fromLngLat(-77.00897, 38.87031)
} | 216 | Kotlin | 126 | 435 | 7faf620b4694bd50f4b4399abcf6eca29e3173ba | 394 | mapbox-maps-android | Apache License 2.0 |
app/src/main/java/jp/juggler/subwaytooter/dialog/ActionsDialog.kt | tateisu | 89,120,200 | false | null | package jp.juggler.subwaytooter.dialog
import android.content.Context
import androidx.appcompat.app.AlertDialog
import jp.juggler.subwaytooter.R
import jp.juggler.util.notEmpty
import java.util.*
class ActionsDialog {
private val actionList = ArrayList<Action>()
private class Action(val caption: CharSequence, val action: () -> Unit)
fun addAction(caption: CharSequence, action: () -> Unit): ActionsDialog {
actionList.add(Action(caption, action))
return this
}
fun show(context: Context, title: CharSequence? = null): ActionsDialog {
AlertDialog.Builder(context).apply {
setNegativeButton(R.string.cancel, null)
setItems(actionList.map { it.caption }.toTypedArray()) { _, which ->
if (which >= 0 && which < actionList.size) {
actionList[which].action()
}
}
title?.notEmpty()?.let { setTitle(it) }
}.show()
return this
}
}
| 36 | Kotlin | 19 | 181 | 0955dff8db15e6285b780ffae68a1717f1df71e1 | 997 | SubwayTooter | Apache License 2.0 |
compiler/testData/debug/stepping/recursion.kt | prasenjitghose36 | 258,198,392 | true | {"Kotlin": 46593414, "Java": 7626725, "JavaScript": 200386, "HTML": 77284, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "CSS": 9270, "Swift": 8589, "Shell": 7220, "Batchfile": 5727, "Ruby": 1300, "Objective-C": 404, "Scala": 80} | //FILE: test.kt
fun box() {
val n = 3
val k = foo(n)
}
fun foo(n :Int ) : Int {
if (n == 1 || n == 0) {
return 1
}
return foo(n-1) * n
}
// LINENUMBERS
// test.kt:3
// test.kt:4
// test.kt:8
// test.kt:11
// test.kt:8
// test.kt:11
// test.kt:8
// test.kt:9
// test.kt:11
// test.kt:11
// test.kt:4
// test.kt:5
| 0 | null | 0 | 2 | acced52384c00df5616231fa5ff7e78834871e64 | 342 | kotlin | Apache License 2.0 |
tvlib/src/main/java/com/txl/tvlib/utils/ViewFocusHelper.kt | xiaolutang | 222,377,238 | false | null | package com.txl.tvlib.utils
import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import com.txl.commonlibrary.utils.DrawableUtils
/**
* 现阶段不要使用
* 统一对元素获取焦点进行处理,待开发
* */
class ViewFocusHelper : ViewTreeObserver.OnGlobalFocusChangeListener {
private var _activity: Activity? = null
private var _frameLayout: FrameLayout? = null
private var _focusBdColor: Int = 0
/**
* 上一个焦点元素的背景
*/
private var _oldFocusDrawable: Drawable? = null
private val _currentFocusDrawable: Drawable? = null
/**
* call after activity setContentView
*/
fun init(activity: Activity, focusBdColor: Int) {
this._activity = activity
this._focusBdColor = focusBdColor
_frameLayout = FrameLayout(_activity!!)
_frameLayout!!.isFocusable = false
_frameLayout!!.setBackgroundColor(Color.TRANSPARENT)
val params = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
_frameLayout!!.viewTreeObserver.addOnGlobalFocusChangeListener(this)
_activity!!.addContentView(_frameLayout, params)
}
fun destory() {
if (_frameLayout != null) {
_frameLayout!!.viewTreeObserver.removeOnGlobalFocusChangeListener(this)
}
_activity = null
}
override fun onGlobalFocusChanged(oldFocus: View?, newFocus: View?) {
lostFocus(oldFocus)
focusView(newFocus)
}
private fun focusView(newFocus: View?) {
_oldFocusDrawable = newFocus?.background
newFocus?.background = buildFocusBgDrawable()
}
private fun lostFocus(oldFocus: View?) {
if (_oldFocusDrawable != null) {
oldFocus?.background = _oldFocusDrawable
_oldFocusDrawable = null
}
}
/**
* 这个东西需要灵活的定制
*/
private fun buildFocusBgDrawable(): Drawable {
return DrawableUtils.makeFramelessRectangleDrawable(_focusBdColor, 0f)
}
} | 1 | null | 1 | 17 | 33d5fa6b4b6c11228fa761111668b2359570a9b9 | 2,168 | WanAndroidTv | Apache License 2.0 |
library/src/main/java/com/rtchagas/pingplacepicker/repository/googlemaps/CustomPlace.kt | rtchagas | 172,393,102 | false | null | package com.rtchagas.pingplacepicker.repository.googlemaps
import android.net.Uri
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.libraries.places.api.model.*
import kotlinx.parcelize.Parcelize
import com.google.android.libraries.places.api.model.Place.BooleanPlaceAttributeValue.UNKNOWN
@Parcelize
internal class CustomPlace(
var placeId: String,
var placeName: String,
var placePhotos: MutableList<PhotoMetadata>,
var placeAddress: String,
var placeTypes: MutableList<Type>,
var placeLatLng: LatLng
) : Place() {
override fun getUserRatingsTotal(): Int? {
return null
}
/**
* Default value only.
* Clients shouldn't rely on this.
*/
override fun getBusinessStatus(): BusinessStatus {
return BusinessStatus.OPERATIONAL
}
override fun getName(): String {
return placeName
}
override fun getOpeningHours(): OpeningHours? {
return null
}
override fun getCurbsidePickup(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getDelivery(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getDineIn(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getReservable(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesBeer(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesBreakfast(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesBrunch(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesDinner(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesLunch(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesVegetarianFood(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getServesWine(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getTakeout(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getWheelchairAccessibleEntrance(): BooleanPlaceAttributeValue {
return UNKNOWN
}
override fun getId(): String {
return placeId
}
override fun getPhotoMetadatas(): MutableList<PhotoMetadata> {
return placePhotos
}
override fun getSecondaryOpeningHours(): MutableList<OpeningHours>? {
return null
}
override fun getWebsiteUri(): Uri? {
return null
}
override fun getPhoneNumber(): String? {
return null
}
override fun getRating(): Double? {
return null
}
override fun getIconBackgroundColor(): Int? {
return null
}
override fun getPriceLevel(): Int? {
return null
}
override fun getAddressComponents(): AddressComponents? {
return null
}
override fun getCurrentOpeningHours(): OpeningHours? {
return null
}
override fun getAttributions(): MutableList<String> {
return mutableListOf()
}
override fun getAddress(): String {
return placeAddress
}
override fun getEditorialSummary(): String? {
return null
}
override fun getEditorialSummaryLanguageCode(): String? {
return null
}
override fun getIconUrl(): String? {
return null
}
override fun getPlusCode(): PlusCode? {
return null
}
override fun getUtcOffsetMinutes(): Int? {
return null
}
override fun getTypes(): MutableList<Type> {
return placeTypes
}
override fun getViewport(): LatLngBounds? {
return null
}
override fun describeContents(): Int {
return 0
}
override fun getLatLng(): LatLng {
return placeLatLng
}
}
| 15 | null | 56 | 142 | 3572f07005cba0754dcfc1976df2cde59d9114e9 | 3,914 | pingplacepicker | Apache License 2.0 |
app/src/main/java/soli/rxpermissions/FragmentTestActivity.kt | wanliLiu | 134,591,746 | false | {"Java": 27155, "Kotlin": 3332, "Shell": 373} | package soli.rxpermissions
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
*
* @author Soli
* @Time 2019/2/19 15:41
*/
class FragmentTestActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment)
val manager = supportFragmentManager
manager.beginTransaction().add(R.id.container, TestFragment()).commitAllowingStateLoss()
manager.executePendingTransactions()
}
} | 1 | null | 1 | 1 | ddae435d254b45f658852e1587d765682eb05918 | 553 | RxPermissions | Apache License 2.0 |
window/window/src/main/java/androidx/window/layout/util/ContextCompatHelper.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2022 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.window.layout.util
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.view.WindowManager
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.annotation.UiContext
import androidx.core.view.WindowInsetsCompat
@RequiresApi(Build.VERSION_CODES.R)
internal object ContextCompatHelper {
fun currentWindowBounds(@UiContext context: Context): Rect {
val wm = context.getSystemService(WindowManager::class.java)
return wm.currentWindowMetrics.bounds
}
fun maximumWindowBounds(@UiContext context: Context): Rect {
val wm = context.getSystemService(WindowManager::class.java)
return wm.maximumWindowMetrics.bounds
}
/**
* Computes the [WindowInsetsCompat] for platforms above [Build.VERSION_CODES.R], inclusive.
* @DoNotInline required for implementation-specific class method to prevent it from being
* inlined.
*
* @see androidx.window.layout.WindowMetrics.getWindowInsets
*/
@DoNotInline
fun currentWindowInsets(@UiContext context: Context): WindowInsetsCompat {
val wm = context.getSystemService(WindowManager::class.java)
val platformInsets = wm.currentWindowMetrics.windowInsets
return WindowInsetsCompat.toWindowInsetsCompat(platformInsets)
}
} | 22 | Kotlin | 778 | 4,514 | 469681f962a7700b394c8f1660326addaf05402e | 1,987 | androidx | Apache License 2.0 |
src/main/kotlin/io/github/fomin/oasgen/java/jackson/ConverterRegistry.kt | fomin | 221,897,565 | false | null | package io.github.fomin.oasgen.java.jackson
import io.github.fomin.oasgen.JsonSchema
class ConverterRegistry(private val converterMatchers: List<ConverterMatcher>) {
operator fun get(jsonSchema: JsonSchema): ConverterWriter {
converterMatchers.forEach { converterMatcher ->
val converterWriter = converterMatcher.match(this, jsonSchema)
if (converterWriter != null) return converterWriter
}
error("Can't find converter for schema $jsonSchema")
}
} | 2 | null | 1 | 1 | d1959fdb04f1b4d41a98a50abde3b4506889a6cf | 505 | schema-transformer | Apache License 2.0 |
kotlin_language/src/com/study/kotlin先决条件函数.kt | Tecode | 455,788,985 | false | {"Java": 409665, "Kotlin": 196048} | package com.study
fun main() {
var info: String? = null
var value002: Boolean = false
// checkNotNull(info)
// requireNotNull(info)
require(value002)
} | 1 | null | 1 | 1 | 78a8c1e661c3a8a3f9b3dee8c6cf806cfec49a98 | 170 | android_learning | MIT License |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/bugreporting/debuglog/upload/server/LogUploadApiV1.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.bugreporting.debuglog.upload.server
import com.google.gson.annotations.SerializedName
import okhttp3.MultipartBody
import retrofit2.http.Header
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
interface LogUploadApiV1 {
@Multipart
@POST("/api/logs")
suspend fun uploadLog(
@Header("cwa-otp") otp: String,
@Part logZip: MultipartBody.Part
): UploadResponse
data class UploadResponse(
@SerializedName("id") val id: String,
@SerializedName("hash") val hash: String?,
@SerializedName("errorCode") val errorCode: String?
)
}
| 120 | Kotlin | 514 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 654 | cwa-app-android | Apache License 2.0 |
client-lib/src/test/kotlin/com/icapps/niddler/lib/debugger/model/ServerDebuggerInterfaceTest.kt | Chimerapps | 189,958,781 | false | null | package com.icapps.niddler.lib.debugger.model
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import java.util.UUID
/**
* @author nicolaverbeeck
*/
internal class ServerDebuggerInterfaceTest {
private lateinit var mockedService: DebuggerService
private lateinit var debuggerInterface: DebuggerInterface
@Before
fun setUp() {
mockedService = mockk()
debuggerInterface = ServerDebuggerInterface(mockedService)
}
@Test
fun updateBlacklistAdd() {
every { mockedService.addBlacklistItem(any()) } just Runs
debuggerInterface.updateBlacklist(arrayListOf("test", "test2"))
verify { mockedService.addBlacklistItem("test") }
verify { mockedService.addBlacklistItem("test2") }
}
@Test
fun updateBlacklistRemoveAll() {
every { mockedService.addBlacklistItem(any()) } just Runs
every { mockedService.removeBlacklistItem(any()) } just Runs
debuggerInterface.updateBlacklist(arrayListOf("test", "test2"))
debuggerInterface.updateBlacklist(arrayListOf())
verify { mockedService.removeBlacklistItem("test") }
verify { mockedService.removeBlacklistItem("test2") }
}
@Test
fun updateBlacklistRemoveAndAdd() {
every { mockedService.addBlacklistItem(any()) } just Runs
every { mockedService.removeBlacklistItem(any()) } just Runs
debuggerInterface.updateBlacklist(arrayListOf("test", "test2"))
verify(exactly = 1) { mockedService.addBlacklistItem("test") }
verify(exactly = 1) { mockedService.addBlacklistItem("test2") }
debuggerInterface.updateBlacklist(arrayListOf("test3", "test"))
verify(exactly = 1) { mockedService.addBlacklistItem("test") }
verify { mockedService.removeBlacklistItem("test2") }
verify { mockedService.addBlacklistItem("test3") }
}
@Test
fun updateDefaultResponses() {
val uuids = mutableListOf<String>()
every { mockedService.addDefaultResponse(".*\\.png", any(), any(), any()) } answers {
val id = UUID.randomUUID().toString()
uuids += id
id
}
val actions = listOf(LocalRequestIntercept("1", true, ".*\\.png", "GET", null, DebugResponse(200, "OK", null, null, null)),
LocalRequestIntercept("2", true, ".*\\.png", "POST", null, DebugResponse(404, "Not found", null, null, null)))
debuggerInterface.updateDefaultResponses(actions)
verify { mockedService.addDefaultResponse(actions[0].regex, actions[0].matchMethod, actions[0].debugResponse!!, actions[0].active) }
verify { mockedService.addDefaultResponse(actions[1].regex, actions[1].matchMethod, actions[1].debugResponse!!, actions[1].active) }
assertEquals(uuids[0], actions[0].id)
assertEquals(uuids[1], actions[1].id)
}
@Test
fun updateDefaultResponsesRemoveAll() {
val uuids = mutableListOf<String>()
every { mockedService.addDefaultResponse(".*\\.png", any(), any(), any()) } answers {
val id = UUID.randomUUID().toString()
uuids += id
id
}
every { mockedService.removeRequestAction(any()) } just Runs
val actions = listOf(LocalRequestIntercept("1", true, ".*\\.png", null, null, DebugResponse(200, "OK", null, null, null)),
LocalRequestIntercept("2", true, ".*\\.png", "HEAD", null, DebugResponse(404, "Not found", null, null, null)))
debuggerInterface.updateDefaultResponses(actions)
assertEquals(uuids[0], actions[0].id)
assertEquals(uuids[1], actions[1].id)
debuggerInterface.updateDefaultResponses(emptyList())
verify(exactly = 1) { mockedService.addDefaultResponse(actions[0].regex, actions[0].matchMethod, actions[0].debugResponse!!, actions[0].active) }
verify(exactly = 1) { mockedService.addDefaultResponse(actions[1].regex, actions[1].matchMethod, actions[1].debugResponse!!, actions[1].active) }
verify { mockedService.removeRequestAction(or(uuids[0], uuids[1])) }
}
@Test
fun updateDefaultResponsesAddAndRemove() {
val uuids = mutableListOf<String>()
every { mockedService.addDefaultResponse(".*\\.png", any(), any(), any()) } answers {
val id = UUID.randomUUID().toString()
uuids += id
id
}
every { mockedService.removeRequestAction(any()) } just Runs
val actions = listOf(LocalRequestIntercept("1", true, ".*\\.png", "HEAD", null, DebugResponse(200, "OK", null, null, null)),
LocalRequestIntercept("2", true, ".*\\.png", "GET", null, DebugResponse(404, "Not found", null, null, null)))
debuggerInterface.updateDefaultResponses(actions)
assertEquals(uuids[0], actions[0].id)
assertEquals(uuids[1], actions[1].id)
val secondActions = listOf(actions[1], LocalRequestIntercept("3", true, ".*\\.png", "POST", null, DebugResponse(404, "Not found", null, null, null)))
debuggerInterface.updateDefaultResponses(secondActions)
verify(exactly = 1) { mockedService.addDefaultResponse(actions[0].regex, actions[0].matchMethod, actions[0].debugResponse!!, actions[0].active) }
verify(exactly = 1) { mockedService.addDefaultResponse(actions[1].regex, actions[1].matchMethod, actions[1].debugResponse!!, actions[1].active) }
verify(exactly = 1) { mockedService.addDefaultResponse(secondActions[1].regex, secondActions[1].matchMethod, secondActions[1].debugResponse!!, secondActions[1].active) }
verify(exactly = 1) { mockedService.removeRequestAction(uuids[0]) }
}
@Test
fun updateDefaultResponsesActivateLater() {
val uuids = mutableListOf<String>()
every { mockedService.addDefaultResponse(".*\\.png", any(), any(), any()) } answers {
val id = UUID.randomUUID().toString()
uuids += id
id
}
every { mockedService.muteAction(any()) } just Runs
every { mockedService.unmuteAction(any()) } just Runs
val actions = listOf(LocalRequestIntercept("1", true, ".*\\.png", "DELETE", null, DebugResponse(200, "OK", null, null, null)),
LocalRequestIntercept("2", false, ".*\\.png", "subscribe", null, DebugResponse(404, "Not found", null, null, null)))
debuggerInterface.updateDefaultResponses(actions)
assertEquals(uuids[0], actions[0].id)
assertEquals(uuids[1], actions[1].id)
actions[0].active = false
actions[1].active = true
debuggerInterface.updateDefaultResponses(actions)
verify(exactly = 1) { mockedService.addDefaultResponse(actions[0].regex, actions[0].matchMethod, actions[0].debugResponse!!, any()) }
verify(exactly = 1) { mockedService.addDefaultResponse(actions[1].regex, actions[1].matchMethod, actions[1].debugResponse!!, any()) }
verify(exactly = 1) { mockedService.muteAction(uuids[0]) }
verify(exactly = 1) { mockedService.unmuteAction(uuids[1]) }
}
@Test
fun mute() {
every { mockedService.setAllActionsMuted(any()) } just Runs
debuggerInterface.mute()
verify(exactly = 1) { mockedService.setAllActionsMuted(true) }
}
@Test
fun unmute() {
every { mockedService.setAllActionsMuted(any()) } just Runs
debuggerInterface.unmute()
verify(exactly = 1) { mockedService.setAllActionsMuted(false) }
}
@Test
fun updateDelaysDisable() {
every { mockedService.updateDelays(any()) } just Runs
debuggerInterface.updateDelays(DebuggerDelays(123, 456, 789))
debuggerInterface.updateDelays(null)
verify(exactly = 1) { mockedService.updateDelays(DebuggerDelays(null, null, null)) }
assertNull(debuggerInterface.debugDelays())
}
@Test
fun updateDelaysEnable() {
every { mockedService.updateDelays(DebuggerDelays(123, 456, 789)) } just Runs
debuggerInterface.updateDelays(DebuggerDelays(123, 456, 789))
verify(exactly = 1) { mockedService.updateDelays(DebuggerDelays(123, 456, 789)) }
assertEquals(DebuggerDelays(123, 456, 789), debuggerInterface.debugDelays())
}
@Test
fun activate() {
every { mockedService.setActive(any()) } just Runs
debuggerInterface.activate()
verify(exactly = 1) { mockedService.setActive(true) }
}
@Test
fun deactivate() {
every { mockedService.setActive(any()) } just Runs
debuggerInterface.deactivate()
verify(exactly = 1) { mockedService.setActive(false) }
}
@Test
fun connect() {
every { mockedService.connect() } just Runs
debuggerInterface.connect()
verify(exactly = 1) { mockedService.connect() }
}
@Test
fun disconnect() {
every { mockedService.disconnect() } just Runs
debuggerInterface.disconnect()
verify(exactly = 1) { mockedService.disconnect() }
}
} | 6 | null | 1 | 25 | f1be6466cfa1c64877c3302425871ba83de93fcf | 9,168 | niddler-ui | Apache License 2.0 |
clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/models/OrgApacheSlingCommonsThreadsImplDefaultThreadPoolFactoryProperties.kt | shinesolutions | 190,217,155 | false | null | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
import org.openapitools.server.models.ConfigNodePropertyBoolean
import org.openapitools.server.models.ConfigNodePropertyDropDown
import org.openapitools.server.models.ConfigNodePropertyInteger
import org.openapitools.server.models.ConfigNodePropertyString
/**
*
* @param name
* @param minPoolSize
* @param maxPoolSize
* @param queueSize
* @param maxThreadAge
* @param keepAliveTime
* @param blockPolicy
* @param shutdownGraceful
* @param daemon
* @param shutdownWaitTime
* @param priority
*/
data class OrgApacheSlingCommonsThreadsImplDefaultThreadPoolFactoryProperties (
val name: ConfigNodePropertyString? = null,
val minPoolSize: ConfigNodePropertyInteger? = null,
val maxPoolSize: ConfigNodePropertyInteger? = null,
val queueSize: ConfigNodePropertyInteger? = null,
val maxThreadAge: ConfigNodePropertyInteger? = null,
val keepAliveTime: ConfigNodePropertyInteger? = null,
val blockPolicy: ConfigNodePropertyDropDown? = null,
val shutdownGraceful: ConfigNodePropertyBoolean? = null,
val daemon: ConfigNodePropertyBoolean? = null,
val shutdownWaitTime: ConfigNodePropertyInteger? = null,
val priority: ConfigNodePropertyDropDown? = null
) {
}
| 12 | null | 1 | 4 | c2f6e076971d2592c1cbd3f70695c679e807396b | 1,638 | swagger-aem-osgi | Apache License 2.0 |
zhihu/src/main/java/com/zhihu/viewmodel/ZhiHuDetailViewModel.kt | android-develop-team | 104,902,767 | false | null | package com.zhihu.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MediatorLiveData
import com.common.base.BaseEntity
import com.common.base.ENTITY_ERROR
import com.common.base.ENTITY_LOADING
import com.common.base.ENTITY_SUCCESS
import com.zhihu.model.ZhiHuDetailModel
import com.zhihu.model.net.server.ZLServer
import io.reactivex.network.RxNetWork
import io.reactivex.network.RxNetWorkListener
/**
* by y on 31/10/2017.
*/
class ZhiHuDetailViewModel(application: Application) : AndroidViewModel(application), RxNetWorkListener<ZhiHuDetailModel> {
val zhiHuDetail: MediatorLiveData<BaseEntity<ZhiHuDetailModel>> = MediatorLiveData()
fun request(slug: Int): ZhiHuDetailViewModel {
RxNetWork.instance.cancel(ZhiHuDetailViewModel::class.java.simpleName)
RxNetWork.instance.getApi(ZhiHuDetailViewModel::class.java.simpleName,
RxNetWork.observable(ZLServer::class.java).getDetail(slug), this)
return this
}
override fun onNetWorkComplete() {
}
override fun onNetWorkError(e: Throwable) {
zhiHuDetail.value = BaseEntity(type = ENTITY_ERROR)
}
override fun onNetWorkStart() {
zhiHuDetail.value = BaseEntity(type = ENTITY_LOADING)
}
override fun onNetWorkSuccess(data: ZhiHuDetailModel) {
zhiHuDetail.value = BaseEntity(ENTITY_SUCCESS, 0, data)
}
}
| 0 | Kotlin | 0 | 0 | 5bcaa3a94ade134f750b2ebd9e10d472d7ef9772 | 1,422 | AppK | Apache License 2.0 |
app/src/main/java/ht/pq/khanh/multitask/forecast/ForecastFragment.kt | khanhpq29 | 105,360,322 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 28, "XML": 86, "Kotlin": 63} | package ht.pq.khanh.multitask.forecast
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import butterknife.BindView
import butterknife.ButterKnife
import com.pawegio.kandroid.IntentFor
import com.pawegio.kandroid.d
import ht.pq.khanh.api.forecast.Forecast
import ht.pq.khanh.api.forecast.List
import ht.pq.khanh.bus.event.NetworkEvent
import ht.pq.khanh.bus.RxBus
import ht.pq.khanh.extension.inflateLayout
import ht.pq.khanh.extension.showToast
import ht.pq.khanh.multitask.R
import ht.pq.khanh.multitask.weather.WeatherDetailActivity
import ht.pq.khanh.util.Common
import io.reactivex.disposables.CompositeDisposable
/**
* Created by khanhpq on 9/25/17.
*/
class ForecastFragment : Fragment(), ForecastContract.View, ForecastAdapter.OnWeatherItemClickListener, SwipeRefreshLayout.OnRefreshListener {
@BindView(R.id.listForecast)
lateinit var recyclerForecast: RecyclerView
@BindView(R.id.no_layout)
lateinit var noLayout: RelativeLayout
@BindView(R.id.swipe_view)
lateinit var swipeLayout: SwipeRefreshLayout
private var forecastAdapter: ForecastAdapter? = null
private lateinit var presenter: ForecastPresenter
private var listForecast: MutableList<List> = arrayListOf()
private lateinit var location: String
private val disposal: CompositeDisposable by lazy { CompositeDisposable() }
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = container!!.inflateLayout(R.layout.fragment_forecast)
ButterKnife.bind(this, view)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
swipeLayout.isRefreshing = true
forecastAdapter = ForecastAdapter(context, listForecast)
presenter = ForecastPresenter(this, disposal)
presenter.networkChange()
val itemRclDecorator = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
val linearManager = LinearLayoutManager(activity)
val locationPref = activity.getSharedPreferences(Common.LOCATION_PREFERENCE, Context.MODE_PRIVATE)
location = locationPref.getString("Location_name", "London")
d(location)
presenter.fetchData(location)
recyclerForecast.apply {
layoutManager = linearManager
adapter = forecastAdapter
addItemDecoration(itemRclDecorator)
setHasFixedSize(true)
}
forecastAdapter?.setOnWeatherItemClickListener(this)
swipeLayout.setOnRefreshListener(this)
}
override fun addForecast(forecast: Forecast) {
listForecast.addAll(forecast.list)
forecastAdapter?.notifyDataSetChanged()
}
override fun showError(t: Throwable) {
swipeLayout.isRefreshing = false
t.printStackTrace()
}
override fun showProgressDialog() {
swipeLayout.isRefreshing = true
}
override fun hideProgressDialog() {
swipeLayout.isRefreshing = false
}
override fun onDestroyView() {
super.onDestroyView()
swipeLayout.isRefreshing = false
disposal.clear()
}
override fun onStop() {
super.onStop()
disposal.clear()
}
override fun onRefresh() {
presenter.fetchData(location)
}
override fun changeNetworkState() {
disposal.add(RxBus.getInstance().toObservable(NetworkEvent::class.java)
.subscribe({ event: NetworkEvent ->
if (event.isConnected) {
onRefresh()
} else {
context.showToast("check network")
}
}, { throwable: Throwable? ->
throwable?.printStackTrace()
}))
}
override fun onWeatherItemClick(position: Int) {
val item = listForecast[position]
val intent = IntentFor<WeatherDetailActivity>(activity)
intent.putExtra("weather_detail", item)
startActivity(intent)
}
}
| 0 | Kotlin | 0 | 0 | cfa0157381f8f5bcc4b46e80e5bca57c13292a0b | 4,470 | My-Task | Apache License 2.0 |
app/src/androidTest/java/org/maishameds/ui/views/DashboardActivityTest.kt | mijiga | 368,744,678 | true | {"Kotlin": 81028, "Ruby": 5224, "Shell": 1036} | /*
* Copyright 2020 MaishaMeds
*
* 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.maishameds.ui.views
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.ScrollToAction
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.agoda.kakao.recycler.KRecyclerItem
import com.agoda.kakao.recycler.KRecyclerView
import com.agoda.kakao.screen.Screen
import com.agoda.kakao.screen.Screen.Companion.idle
import com.agoda.kakao.text.KSnackbar
import com.agoda.kakao.text.KTextView
import io.mockk.clearMocks
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.Matcher
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.test.KoinTest
import org.koin.test.mock.declare
import org.maishameds.R
import org.maishameds.data.repository.PostRepository
import org.maishameds.fake.fakePost
import org.maishameds.ui.viewmodel.PostViewModel
class RecyclerviewScrollActions(private val original: ScrollToAction = ScrollToAction()) :
ViewAction by original {
override fun getConstraints(): Matcher<View> = CoreMatchers.anyOf(
allOf(
withEffectiveVisibility(Visibility.VISIBLE),
isDescendantOfA(isAssignableFrom(RecyclerView::class.java))
),
original.constraints
)
}
@LargeTest
@RunWith(AndroidJUnit4::class)
class DashboardActivityTest : KoinTest {
private val postRepository = mockk<PostRepository>(relaxUnitFun = true)
@After
fun tearDown() {
clearMocks(postRepository)
}
@Test
fun testData_isDisplayed_whenPositiveResults_areReturned() = runBlocking {
coEvery {
postRepository.getPosts()
} returns flowOf(fakePost)
declare {
PostViewModel(
postRepository
)
}
ActivityScenario.launch(DashboardActivity::class.java)
Screen.onScreen<MaishaMedsScreen> {
this.posts {
act {
RecyclerviewScrollActions()
}
idle(3000)
isDisplayed()
firstChild<Item> {
isVisible()
title {
hasText(fakePost.first().postTitle)
}
body {
hasText(fakePost.first().postBody)
}
}
}
}
idle(3000)
}
class MaishaMedsScreen : Screen<MaishaMedsScreen>() {
val posts: KRecyclerView = KRecyclerView(
{
withId(R.id.recyclerView)
},
itemTypeBuilder = {
itemType(::Item)
}
)
val snackbar = KSnackbar()
}
class Item(parent: Matcher<View>) : KRecyclerItem<Item>(parent) {
val title = KTextView { withId(R.id.textViewPostTitle) }
val body = KTextView { withId(R.id.textViewPostBody) }
}
} | 0 | null | 0 | 0 | e14e73b2caf2a2b0dbc415c03c84c8b19dee4a33 | 3,852 | maishameds | The Unlicense |
src/test/kotlin/com/exactpro/th2/lwdataprovider/TestSseMessageSearchRequest.kt | th2-net | 433,117,188 | false | {"Kotlin": 763554, "Python": 4531, "Dockerfile": 112} | /*******************************************************************************
* Copyright 2022 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.lwdataprovider
import com.exactpro.cradle.utils.TimeUtils
import com.exactpro.th2.common.grpc.Direction
import com.exactpro.th2.dataprovider.lw.grpc.BookId
import com.exactpro.th2.dataprovider.lw.grpc.MessageSearchRequest
import com.exactpro.th2.dataprovider.lw.grpc.MessageStream
import com.exactpro.th2.dataprovider.lw.grpc.MessageStreamPointer
import com.exactpro.th2.lwdataprovider.entities.exceptions.InvalidRequestException
import com.exactpro.th2.lwdataprovider.entities.requests.SearchDirection
import com.exactpro.th2.lwdataprovider.entities.requests.SseMessageSearchRequest
import com.google.protobuf.Int32Value
import com.google.protobuf.Timestamp
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.time.Instant
import com.exactpro.th2.dataprovider.lw.grpc.TimeRelation as GrpcTimeRelation
class TestSseMessageSearchRequest {
@Nested
inner class TestConstructorParam {
private val DEFAULT: Map<String, List<String>> = mapOf(
"bookId" to listOf("test"), "stream" to listOf("test")
)
private fun params(vararg pairs: Pair<String, List<String>>): Map<String, List<String>> {
return DEFAULT + mapOf(*pairs)
}
// when startTimestamp and resumeFromIdsList - nulls, should throw exception
@Test
fun testEmptyParamsMap(){
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(mapOf())
}
}
// resumeFromId != null, startTimestamp == null and endTimestamp != null
@Test
fun testStartTimestampNullResumeIdListNotNull(){
val messageSearchReq = SseMessageSearchRequest(params("messageId" to listOf("test:name:1:${TimeUtils.toIdTimestamp(Instant.now())}:1"),
"endTimestamp" to listOf("2")))
Assertions.assertNull(messageSearchReq.startTimestamp, "start timestamp must be null")
}
// startTimestamp - 1, endTimestamp - 2, searchDirection - AFTER (default)
@Test
fun testEndAfterStartDirectionDefault(){
val messageSearchReq = SseMessageSearchRequest(params("startTimestamp" to listOf("1"),
"endTimestamp" to listOf("2", "3")))
Assertions.assertEquals(SearchDirection.next, messageSearchReq.searchDirection, "search direction must be AFTER")
Assertions.assertNotNull(messageSearchReq.startTimestamp, "start timestamp must be not null")
Assertions.assertNotNull(messageSearchReq.endTimestamp, "end time stamp must be not null")
Assertions.assertTrue(messageSearchReq.endTimestamp!! > messageSearchReq.startTimestamp!!){
"end timestamp: " + messageSearchReq.endTimestamp + " must be after start timestamp: " + messageSearchReq.startTimestamp
}
}
// startTimestamp - 1, endTimestamp - 2, searchDirection - BEFORE
@Test
fun testEndAfterStartDirectionBefore(){
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(params("startTimestamp" to listOf("1"),
"endTimestamp" to listOf("2"), "searchDirection" to listOf("previous")))
}
}
// startTimestamp - 3, endTimestamp - 2, searchDirection - BEFORE
@Test
fun testEndBeforeStartDirectionBefore(){
val messageSearchReq = SseMessageSearchRequest(params("startTimestamp" to listOf("3"),
"endTimestamp" to listOf("2"), "searchDirection" to listOf("previous")))
Assertions.assertEquals(SearchDirection.previous, messageSearchReq.searchDirection, "search direction must be BEFORE")
Assertions.assertNotNull(messageSearchReq.startTimestamp, "start timestamp must be not null")
Assertions.assertNotNull(messageSearchReq.endTimestamp, "end timestamp must be not null")
Assertions.assertTrue(messageSearchReq.endTimestamp!! < messageSearchReq.startTimestamp!!){
"end timestamp: " + messageSearchReq.endTimestamp + " must be after before timestamp: " + messageSearchReq.startTimestamp
}
}
// startTimestamp - 3, endTimestamp - 2, searchDirection - AFTER
@Test
fun testEndBeforeStartDirectionAfter(){
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(params("startTimestamp" to listOf("3"),
"endTimestamp" to listOf("2"), "searchDirection" to listOf("next")))
}
}
@Test
fun testLimitNotSetEndTimestampNotSet(){
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(params("startTimestamp" to listOf("1")))
}
}
@Test
fun testLimitSetEndTimestampSet(){
val messageSearchReq = SseMessageSearchRequest(params("startTimestamp" to listOf("1"),
"endTimestamp" to listOf("2"), "resultCountLimit" to listOf("5")))
Assertions.assertEquals(Instant.ofEpochMilli(2), messageSearchReq.endTimestamp)
}
}
@Nested
inner class TestConstructorGrpc {
// when startTimestamp and resumeFromId - nulls, should throw exception
@Test
fun testEmptyRequest(){
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(createBuilder().build())
}
}
// resumeFromId != null, startTimestamp == null and endTimestamp != null
@Test
fun testStartTimestampNullResumeIdNotNull(){
val messageStreamP = MessageStreamPointer.newBuilder()
val endTimestamp = Timestamp.newBuilder().setNanos(2)
val grpcRequest = createBuilder().addStreamPointer(messageStreamP)
.setEndTimestamp(endTimestamp).build()
val messageSearchReq = SseMessageSearchRequest(grpcRequest)
Assertions.assertNull(messageSearchReq.startTimestamp, "start timestamp must be null")
}
// startTimestamp - 1, endTimestamp - 2, searchDirection - AFTER (default)
@Test
fun testEndAfterStartDirectionDefault(){
val startTimestamp = Timestamp.newBuilder().setNanos(1).build()
val endTimestamp = Timestamp.newBuilder().setNanos(2).build()
val grpcRequest = createBuilder().setStartTimestamp(startTimestamp).setEndTimestamp(endTimestamp).build()
val messageSearchReq = SseMessageSearchRequest(grpcRequest)
Assertions.assertEquals(SearchDirection.next, messageSearchReq.searchDirection, "search direction must be AFTER")
Assertions.assertNotNull(messageSearchReq.startTimestamp, "start timestamp must be not null")
Assertions.assertNotNull(messageSearchReq.endTimestamp, "end timestamp must be not null")
Assertions.assertTrue(messageSearchReq.endTimestamp!! > messageSearchReq.startTimestamp!!){
"end timestamp: " + messageSearchReq.endTimestamp + " must be after start timestamp: " + messageSearchReq.startTimestamp
}
}
// startTimestamp - 1, endTimestamp - 2, searchDirection - BEFORE
@Test
fun testEndAfterStartDirectionBefore(){
val startTimestamp = Timestamp.newBuilder().setNanos(1).build()
val endTimestamp = Timestamp.newBuilder().setNanos(2).build()
val grpcRequest = createBuilder().setStartTimestamp(startTimestamp).setEndTimestamp(endTimestamp).
setSearchDirection(GrpcTimeRelation.PREVIOUS).build()
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(grpcRequest)
}
}
// startTimestamp - 3, endTimestamp - 2, searchDirection - BEFORE
@Test
fun testEndBeforeStartDirectionBefore(){
val startTimestamp = Timestamp.newBuilder().setNanos(3).build()
val endTimestamp = Timestamp.newBuilder().setNanos(2).build()
val grpcRequest = createBuilder().setStartTimestamp(startTimestamp).setEndTimestamp(endTimestamp).
setSearchDirection(GrpcTimeRelation.PREVIOUS).build()
val messageSearchReq = SseMessageSearchRequest(grpcRequest)
Assertions.assertEquals(SearchDirection.previous, messageSearchReq.searchDirection, "search direction must be BEFORE")
Assertions.assertNotNull(messageSearchReq.startTimestamp, "start timestamp must be not null")
Assertions.assertNotNull(messageSearchReq.endTimestamp, "end timestamp must be not null")
Assertions.assertTrue(messageSearchReq.endTimestamp!! < messageSearchReq.startTimestamp!!){
"end timestamp: " + messageSearchReq.endTimestamp + " must be before start timestamp: " + messageSearchReq.startTimestamp
}
}
// startTimestamp - 3, endTimestamp - 2, searchDirection - AFTER
@Test
fun testEndBeforeStartDirectionAfter(){
val startTimestamp = Timestamp.newBuilder().setNanos(3).build()
val endTimestamp = Timestamp.newBuilder().setNanos(2).build()
val grpcRequest = createBuilder().setStartTimestamp(startTimestamp).setEndTimestamp(endTimestamp).
setSearchDirection(GrpcTimeRelation.NEXT).build()
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
SseMessageSearchRequest(grpcRequest)
}
}
@Test
fun testLimitNotSetEndTimestampNotSet(){
assertThrows<InvalidRequestException>("must throw invalidRequestException"){
val startTimestamp = Timestamp.newBuilder().setNanos(1).build()
SseMessageSearchRequest(createBuilder().setStartTimestamp(startTimestamp).build())
}
}
@Test
fun testLimitSetEndTimestampSet(){
val startTimestamp = Timestamp.newBuilder().setNanos(1).build()
val endTimestamp = Timestamp.newBuilder().setNanos(2).build()
val resultCountLimit = Int32Value.newBuilder().setValue(5).build()
val grpcRequest = createBuilder().setStartTimestamp(startTimestamp).setEndTimestamp(endTimestamp).
setResultCountLimit(resultCountLimit).build()
val messageSearchReq = SseMessageSearchRequest(grpcRequest)
Assertions.assertEquals(Instant.ofEpochSecond(0, 2), messageSearchReq.endTimestamp)
}
private fun createBuilder(): MessageSearchRequest.Builder = MessageSearchRequest.newBuilder()
.setBookId(BookId.newBuilder().setName("test"))
.addStream(MessageStream.newBuilder().setName("test").setDirection(Direction.FIRST))
}
}
| 2 | Kotlin | 0 | 0 | 9277b3bdf3badffff3eadde4dc53a274af673a1e | 11,831 | th2-lw-data-provider | Apache License 2.0 |
app/src/main/java/com/emretnkl/myshopapp/data/interceptor/AuthInterceptor.kt | emretnkl | 559,308,167 | false | null | package com.emretnkl.myshopapp.data.interceptor
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
class AuthInterceptor @Inject constructor() : Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
val requestBuilder = chain.request()
val newUrl = requestBuilder.url.newBuilder()
.build()
val newRequest = requestBuilder.newBuilder().url(newUrl).build()
return chain.proceed(newRequest)
}
} | 0 | Kotlin | 0 | 1 | 77ee7168cf5484f38f0665082c7dd26b38973622 | 494 | MyShopApp | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/domain/GetWeatherData.kt | cmota | 350,468,275 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.domain
import android.util.Log
import com.example.androiddevchallenge.data.OpenWeatherAPI
import com.example.androiddevchallenge.data.UNITS
import com.example.androiddevchallenge.domain.model.City
import com.example.androiddevchallenge.presentation.cb.WeatherDataEvent
import kotlinx.coroutines.coroutineScope
private const val TAG = "GetWeatherData"
class GetWeatherData {
suspend fun invoke(city: City, units: UNITS, event: WeatherDataEvent) {
try {
val result = OpenWeatherAPI.getWeather(city.lat, city.lon, units)
Log.d(TAG, "Result=$result")
coroutineScope {
event.onWeatherDataFetched(result)
}
} catch (e: Exception) {
Log.d(TAG, "Unable to get data for city=$city. Reason=$e")
coroutineScope {
event.onWeatherDataFailed()
}
}
}
}
| 0 | Kotlin | 0 | 8 | d8dc19fc15cecd944e3d85a983f4c459b5e8003b | 1,550 | wwweather | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/audio/AnalyserNode.kt | karakum-team | 393,199,102 | false | null | // Automatically generated - do not modify!
package web.audio
import js.typedarrays.Float32Array
import js.typedarrays.Uint8Array
external class AnalyserNode(
context: BaseAudioContext,
options: AnalyserOptions = definedExternally,
) : AudioNode {
var fftSize: Int
val frequencyBinCount: Int
var maxDecibels: Double
var minDecibels: Double
var smoothingTimeConstant: Double
fun getByteFrequencyData(array: Uint8Array)
fun getByteTimeDomainData(array: Uint8Array)
fun getFloatFrequencyData(array: Float32Array)
fun getFloatTimeDomainData(array: Float32Array)
}
| 0 | Kotlin | 6 | 22 | 340fa5d93f874ebf14810ab797a9808af574e058 | 607 | types-kotlin | Apache License 2.0 |
service-group/service-odds/src/main/kotlin/org/waambokt/service/odds/Main.kt | mille5a9 | 552,448,940 | false | null | package org.waambokt.service.odds
import org.waambokt.common.WaamboktGrpcServer
import org.waambokt.common.constants.Env
import org.waambokt.common.constants.Environment
fun main() {
val env = Environment(Env.PORT, Env.ODDS, Env.MONGO_CONNECTION_STRING, Env.ISPROD)
val port = env["PORT"].toInt()
val server = WaamboktGrpcServer(
port,
OddsService(env)
)
server.start()
server.blockUntilShutdown()
}
| 3 | Kotlin | 0 | 0 | 5c64109e3308aed47182b80b2306b90eaa498ff2 | 442 | waambookt | MIT License |
service-group/service-odds/src/main/kotlin/org/waambokt/service/odds/Main.kt | mille5a9 | 552,448,940 | false | null | package org.waambokt.service.odds
import org.waambokt.common.WaamboktGrpcServer
import org.waambokt.common.constants.Env
import org.waambokt.common.constants.Environment
fun main() {
val env = Environment(Env.PORT, Env.ODDS, Env.MONGO_CONNECTION_STRING, Env.ISPROD)
val port = env["PORT"].toInt()
val server = WaamboktGrpcServer(
port,
OddsService(env)
)
server.start()
server.blockUntilShutdown()
}
| 3 | Kotlin | 0 | 0 | 5c64109e3308aed47182b80b2306b90eaa498ff2 | 442 | waambookt | MIT License |
backend.native/tests/interop/j2objc/main.kt | jparachoniak | 273,011,783 | false | {"Markdown": 45, "Git Config": 1, "Gradle": 40, "Java Properties": 8, "Shell": 31, "YAML": 5, "Text": 27, "Ignore List": 6, "Batchfile": 16, "Gradle Kotlin DSL": 43, "XML": 37, "Kotlin": 1396, "INI": 40, "OpenStep Property List": 14, "JSON": 6, "Objective-C": 55, "C": 65, "Java": 5, "C++": 80, "Swift": 49, "Pascal": 1, "Python": 3, "CMake": 2, "HTML": 2, "JavaScript": 3, "Objective-C++": 10, "Groovy": 12, "EJS": 1, "CSS": 1, "Dockerfile": 1, "Ruby": 1} | import kotlinx.cinterop.*
import kotlin.test.*
fun main(args: Array<String>) {
autoreleasepool {
testMethods()
testInterfaces()
testInheritance()
testNestedClasses()
testFields()
}
}
private fun testInterfaces() {
val myObject = j2objctest.Foo()
val myInterfaceObject = implementsFooInterface()
assertEquals(13, testInterface(myObject, 7))
assertEquals(13, myInterfaceObject.fib(7))
assertEquals(13, myObject.testKotlinInterface(myInterfaceObject,7))
}
private fun testInheritance() {
val myObject = j2objctest.Foo()
val myExtensionObject = j2objctest.ExtendsFoo()
assertEquals(100, myExtensionObject.return100())
assertEquals(-10, myExtensionObject.returnNum(-10))
assertEquals(1, myExtensionObject.add2(-9,-10))
assertTrue(myExtensionObject.returnFoo() is j2objctest.Foo)
// add2/add3 overridden to x-y/x-(y-z)
assertEquals(-15, myExtensionObject.add2(16,31))
assertEquals(2, myExtensionObject.add3(1,2,3))
assertEquals(-16, myExtensionObject.add3(-12,3,-1))
assertEquals(47, doAddTo(myObject, 16,31))
assertEquals(-15, doAddTo(myExtensionObject, 16,31))
}
private fun testNestedClasses() {
val myObject = j2objctest.Foo()
val innerClass = j2objctest.Foo_InnerClass(myObject)
val nestedClass = j2objctest.Foo_NestedClass()
assertEquals(6.0, innerClass.myInnerFunc(2.0, 3.0))
assertEquals(6.0, nestedClass.myNestedFunc(3.0,2.0))
}
private fun testFields() {
val myObject = j2objctest.Foo()
val myObject2 = j2objctest.Foo()
assertEquals(10, myObject.myInt)
assertEquals(10, myObject2.myInt)
myObject.myInt = 4
assertEquals(4, myObject.myInt)
assertEquals(10, myObject2.myInt)
assertEquals(20, j2objctest.Foo.myStaticInt)
assertEquals(20, j2objctest.Foo.myStaticInt)
j2objctest.Foo.myStaticInt = 30
assertEquals(30, j2objctest.Foo.myStaticInt)
assertEquals(30, j2objctest.Foo.myStaticInt)
}
private fun testMethods() {
val myObject = j2objctest.Foo()
assertEquals(100, myObject.return100())
assertEquals(43, myObject.returnNum(43))
assertEquals(47, myObject.add2(16,31))
assertEquals(13, myObject.fib(7))
assertEquals("Hello world!", myObject.returnString("Hello world!"))
assertEquals(100, j2objctest.Foo.return100Static())
}
class implementsFooInterface: j2objctest.ComTestFooInterface, platform.darwin.NSObject() {
override fun fib(n: Int): Int {
if (n == 0 || n == 1)
return n
return fib(n-1) + fib(n-2)
}
}
fun testInterface(i: j2objctest.ComTestFooInterface, n: Int): Int {
return i.fib(n)
}
fun doAddTo(obj: j2objctest.Foo, a: Int, b: Int): Int {
return obj.add2(a,b)
}
| 1 | null | 1 | 1 | 910ce379553eaf418bff33961c98a3072c272498 | 2,622 | kotlin-native | Apache License 2.0 |
codes/src/test/kotlin/lang/zip.kt | cheroliv | 522,283,474 | false | {"Kotlin": 82422, "CSS": 35079, "FreeMarker": 16831, "JavaScript": 8865, "Groovy": 7785, "Java": 5477, "TypeScript": 3488, "HTML": 794, "Shell": 48, "SCSS": 35} | @file:Suppress("NonAsciiCharacters")
//(4)
package lang
import data.DataTest.basics
import kotlin.test.Test
class ZipTest {
@Test fun main() {
// zip:
// Renvoie une liste de paires construites à partir des éléments
// de ce tableau et de l'autre tableau avec le même index.
// La liste renvoyée a la longueur de la collection la plus courte.
// list des Pair<String,Boolean> associant les elements par occurence
println(basics.zip(someBooleans))
//list des résultats du texte et de la condition contains() rapproché par pair
println(basics.zip(basics.map { it.contains("t") }))
}
}
val someBooleans = arrayOf(
false,
true,
true,
false
)
| 0 | Kotlin | 0 | 3 | ceec34716c5f077b72409f1fe1ecb35ea1ba9ceb | 752 | cheroliv-site | MIT License |
codes/src/test/kotlin/lang/zip.kt | cheroliv | 522,283,474 | false | {"Kotlin": 82422, "CSS": 35079, "FreeMarker": 16831, "JavaScript": 8865, "Groovy": 7785, "Java": 5477, "TypeScript": 3488, "HTML": 794, "Shell": 48, "SCSS": 35} | @file:Suppress("NonAsciiCharacters")
//(4)
package lang
import data.DataTest.basics
import kotlin.test.Test
class ZipTest {
@Test fun main() {
// zip:
// Renvoie une liste de paires construites à partir des éléments
// de ce tableau et de l'autre tableau avec le même index.
// La liste renvoyée a la longueur de la collection la plus courte.
// list des Pair<String,Boolean> associant les elements par occurence
println(basics.zip(someBooleans))
//list des résultats du texte et de la condition contains() rapproché par pair
println(basics.zip(basics.map { it.contains("t") }))
}
}
val someBooleans = arrayOf(
false,
true,
true,
false
)
| 0 | Kotlin | 0 | 3 | ceec34716c5f077b72409f1fe1ecb35ea1ba9ceb | 752 | cheroliv-site | MIT License |
CryptoAC/src/commonMain/kotlin/eu/fbk/st/cryptoac/model/tuple/AttributeTuple.kt | stfbk | 292,768,224 | false | {"JavaScript": 22741621, "Kotlin": 2367601, "Shell": 14642, "Batchfile": 9481, "SCSS": 6830, "CSS": 5868, "Open Policy Agent": 2902, "HTML": 984, "Assembly": 419} | package eu.fbk.st.cryptoac.model.tuple
import io.ktor.utils.io.core.*
import kotlinx.serialization.Serializable
/**
* An AttributeTuple links a User with an Attribute.
* An AttributeTuple is defined by a [username] and
* an [attributeName] with an optional [attributeValue]
*/
//@Serializable TODO decomment (this caused a weird error at compile-time, check whether the error is still there or was resolved (e.g., with an update)
class AttributeTuple(
val username: String,
val attributeName: String,
val attributeValue: String? = null,
) : Tuple() {
/**
* Return the concatenation of all identifying
* fields of the tuple for computing the digital signature
*/
override fun getBytesForSignature(): ByteArray = (
"$username$attributeName${attributeValue ?: ""}"
).toByteArray()
/** Return a String array of the significant fields of this tuple */
override fun toArray(): Array<String> = arrayOf(
username,
attributeName,
attributeValue ?: ""
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AttributeTuple) return false
if (!super.equals(other)) return false
if (username != other.username) return false
if (attributeName != other.attributeName) return false
if (attributeValue != other.attributeValue) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + username.hashCode()
result = 31 * result + attributeName.hashCode()
result = 31 * result + (attributeValue?.hashCode() ?: 0)
return result
}
}
| 0 | JavaScript | 0 | 2 | 13958f84e7e8c5e40a78afc5c737e6443bc1ac37 | 1,719 | CryptoAC | Apache License 2.0 |
idea/testData/quickfix/implement/privateConstructor.kt | zeesh49 | 67,883,175 | true | {"Java": 17992465, "Kotlin": 15424948, "JavaScript": 177557, "Protocol Buffer": 44176, "HTML": 38996, "Lex": 17538, "ANTLR": 9689, "CSS": 9358, "Groovy": 7541, "IDL": 5313, "Shell": 4704, "Batchfile": 3703} | // "Implement abstract class" "false"
abstract class Base private constructor | 0 | Java | 0 | 1 | 261a30029907fedcecbe760aec97021d85a9ba9a | 78 | kotlin | Apache License 2.0 |
modules/wasm-binary/src/commonMain/kotlin/visitor/FunctionSectionVisitor.kt | wasmium | 761,480,110 | false | {"Kotlin": 597834, "JavaScript": 203} | package org.wasmium.wasm.binary.visitor
import org.wasmium.wasm.binary.tree.FunctionType
public interface FunctionSectionVisitor {
public fun visitFunction(functionType: FunctionType)
public fun visitEnd()
}
| 0 | Kotlin | 0 | 3 | dc846f459f0bda1527cad253614df24bbdea012f | 220 | wasmium-wasm-binary | Apache License 2.0 |
app/src/main/java/br/com/nicolas/checkbitcoin/data/remote/BitcoinDataSource.kt | Aleixo-Dev | 536,771,782 | false | null | package br.com.nicolas.checkbitcoin.data.remote
import androidx.room.Delete
import br.com.nicolas.checkbitcoin.data.local.model.CoinEntity
import br.com.nicolas.checkbitcoin.model.Coin
import br.com.nicolas.checkbitcoin.model.CoinList
import kotlinx.coroutines.flow.Flow
interface BitcoinDataSource {
fun getBitcoins() : Flow<CoinList>
fun getAllCoinInDatabase() : Flow<CoinList>
suspend fun saveCoin(coin: Coin)
fun deleteCoin(delete: Coin) : Flow<Unit>
} | 4 | Kotlin | 1 | 2 | 5e783d6141e104ae5e685a3787d6582e9bae8224 | 476 | CheckBitcoin | MIT License |
app/src/main/java/com/mmdub/qofee/data/room/RoomSource.kt | fahmigutawan | 648,655,600 | false | null | package com.mmdub.qofee.data.room
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import com.mmdub.qofee.model.entity.FavoriteEntity
import javax.inject.Inject
class RoomSource @Inject constructor(
private val db:QofeeDatabase
) {
private val favoriteDao = db.favoriteDao()
suspend fun getAllFavorite() = favoriteDao.getAll()
suspend fun getFavoriteById(id:String) = favoriteDao.getById(id)
suspend fun insertFavorite(favoriteEntity: FavoriteEntity) = favoriteDao.insert(favoriteEntity)
suspend fun deleteFavorite(favoriteEntity: FavoriteEntity) = favoriteDao.delete(favoriteEntity)
} | 0 | Kotlin | 0 | 0 | d36bc41b799b0a21640bd7489808e9bf89250392 | 649 | Jetpack-Qofee | MIT License |
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/groups/methods/GroupsSearchMethod.kt | alatushkin | 156,866,851 | false | null | package name.alatushkin.api.vk.generated.groups.methods
import com.fasterxml.jackson.core.type.TypeReference
import name.alatushkin.api.vk.VkMethod
import name.alatushkin.api.vk.api.VkList
import name.alatushkin.api.vk.api.VkSuccess
import name.alatushkin.api.vk.generated.groups.Group
import name.alatushkin.api.vk.generated.groups.SearchSort
import name.alatushkin.api.vk.generated.groups.SearchType
/**
* Returns a list of communities matching the search criteria.
*
* [https://vk.com/dev/groups.search]
* @property [q] Search query string.
* @property [type] Community type. Possible values: 'group, page, event.'
* @property [country_id] Country ID.
* @property [city_id] City ID. If this parameter is transmitted, country_id is ignored.
* @property [future] '1' — to return only upcoming events. Works with the 'type' = 'event' only.
* @property [market] '1' — to return communities with enabled market only.
* @property [sort] Sort order. Possible values: *'0' — default sorting (similar the full version of the site),, *'1' — by growth speed,, *'2'— by the "day attendance/members number" ratio,, *'3' — by the "Likes number/members number" ratio,, *'4' — by the "comments number/members number" ratio,, *'5' — by the "boards entries number/members number" ratio.
* @property [offset] Offset needed to return a specific subset of results.
* @property [count] Number of communities to return. "Note that you can not receive more than first thousand of results, regardless of 'count' and 'offset' values."
*/
class GroupsSearchMethod() : VkMethod<VkList<Group>>(
"groups.search",
HashMap()
) {
var q: String? by props
var type: SearchType? by props
var countryId: Long? by props
var cityId: Long? by props
var future: Boolean? by props
var market: Boolean? by props
var sort: SearchSort? by props
var offset: Long? by props
var count: Long? by props
constructor(
q: String? = null,
type: SearchType? = null,
countryId: Long? = null,
cityId: Long? = null,
future: Boolean? = null,
market: Boolean? = null,
sort: SearchSort? = null,
offset: Long? = null,
count: Long? = null
) : this() {
this.q = q
this.type = type
this.countryId = countryId
this.cityId = cityId
this.future = future
this.market = market
this.sort = sort
this.offset = offset
this.count = count
}
fun setQ(q: String): GroupsSearchMethod {
this.q = q
return this
}
fun setType(type: SearchType): GroupsSearchMethod {
this.type = type
return this
}
fun setCountryId(countryId: Long): GroupsSearchMethod {
this.countryId = countryId
return this
}
fun setCityId(cityId: Long): GroupsSearchMethod {
this.cityId = cityId
return this
}
fun setFuture(future: Boolean): GroupsSearchMethod {
this.future = future
return this
}
fun setMarket(market: Boolean): GroupsSearchMethod {
this.market = market
return this
}
fun setSort(sort: SearchSort): GroupsSearchMethod {
this.sort = sort
return this
}
fun setOffset(offset: Long): GroupsSearchMethod {
this.offset = offset
return this
}
fun setCount(count: Long): GroupsSearchMethod {
this.count = count
return this
}
override val classRef = GroupsSearchMethod.classRef
companion object {
val classRef = object : TypeReference<VkSuccess<VkList<Group>>>() {}
}
}
| 2 | Kotlin | 3 | 10 | 123bd61b24be70f9bbf044328b98a3901523cb1b | 3,645 | kotlin-vk-api | MIT License |
prototype/src/main/kotlin/com/yonatankarp/prototype/ElfWarlord.kt | yonatankarp | 688,273,506 | false | {"Kotlin": 83091} | package com.yonatankarp.prototype
/**
* ElfWarlord.
*/
data class ElfWarlord(private val helpType: String) : Warlord() {
override fun clone() = copy()
override fun toString() = "Elven warlord helps in $helpType"
}
| 11 | Kotlin | 0 | 4 | 3e46a7062197798329ed2a8862c93854d5046edc | 226 | kotlin-design-patterns | MIT License |
common/src/main/java/cn/lvsong/lib/library/utils/Constants.kt | Jooyer | 243,921,264 | false | null | package cn.lvsong.lib.library.utils
/**
* Desc:
* Author: Jooyer
* Date: 2019-02-21
* Time: 23:50
*/
object Constants {
const val CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"
const val WIFI_STATE_CHANGED = "android.net.wifi.WIFI_STATE_CHANGED"
const val STATE_CHANGE = "android.net.wifi.STATE_CHANGE"
} | 0 | null | 3 | 9 | da74777556a9cd278ba7a36f30db18393874caee | 338 | Basics | Apache License 2.0 |
solutions/src/GameOfLife.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | null | class GameOfLife {
fun gameOfLife(board: Array<IntArray>) : Unit {
if (board.isEmpty()) {
return;
}
if (board[0].isEmpty()) {
return
}
val height = board.size
val spaceSet = mutableSetOf<Pair<Int,Int>>()
val spaceMap = mutableMapOf<Pair<Int,Int>, Int>()
for (i in board.indices) {
for (j in board[0].indices) {
spaceSet.add(Pair(i,j))
spaceMap[Pair(i,j)] = board[i][j]
}
}
val visited = mutableSetOf(Pair(0,0))
val queue = mutableListOf(Pair(0,0))
while(queue.isNotEmpty()) {
var currentSpace = queue.removeAt(0)
//Calc Space
val spaces = getAdjacentSpaces(currentSpace,spaceSet)
val numNeighbors = spaces.map { spaceMap[it]!! }.sum()
val newVal = when {
numNeighbors < 2 -> 0
numNeighbors > 3 -> 0
numNeighbors == 3 && board[currentSpace.first][currentSpace.second] == 0 -> 1
(numNeighbors == 2 || numNeighbors == 3) && board[currentSpace.first][currentSpace.second] == 1 -> 1
else -> 0
}
println("${currentSpace} -> $newVal")
board[currentSpace.first][currentSpace.second] = newVal
spaces.filter { !visited.contains(it) }.forEach {
visited.add(it)
queue.add(it)
}
}
}
fun getAdjacentSpaces(space: Pair<Int,Int>, spaceSet: Set<Pair<Int,Int>>) : List<Pair<Int,Int>> {
val h = space.first
val w = space.second
return listOf(
Pair(h+1,w),
Pair(h-1,w),
Pair(h,w+1),
Pair(h,w-1),
Pair(h+1,w+1),
Pair(h-1,w+1),
Pair(h-1,w-1),
Pair(h+1,w-1)
).filter { spaceSet.contains(it) }
}
} | 1 | null | 1 | 1 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,970 | leetcode-solutions | MIT License |
android/src/newarch/BlockStoreSpec.kt | matinzd | 608,877,661 | false | null | package com.blockstore
import com.facebook.react.bridge.ReactApplicationContext
abstract class BlockStoreSpec internal constructor(context: ReactApplicationContext) :
NativeBlockStoreSpec(context) {
}
| 1 | null | 1 | 1 | f0a88f6d626144e03e9a5b45d76bc8f69fb8cf66 | 205 | react-native-block-store | MIT License |
shared/src/commonMain/kotlin/viewModel/CalculatorViewModel.kt | theodore-norvell | 726,244,640 | false | {"Kotlin": 108001, "Swift": 592, "Shell": 228} | package viewModel
import dev.icerock.moko.mvvm.viewmodel.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import model.data.NumberDisplayMode
import model.state.ButtonDescription
import model.state.CalculatorModel
import model.state.EvalMode
data class UIState(
val top : String,
val stackStrings : List<String>,
val envPairs : List<Pair<String,String>>,
val buttons : List<List<ButtonDescription>>,
val base : String,
val displayMode: String,
val evalMode: String,
val error : String? = null,
)
class CalculatorViewModel(private val calculatorModel : CalculatorModel) : ViewModel() {
private val _uiState : MutableStateFlow<UIState>
= MutableStateFlow(UIState( "", emptyList(), emptyList(), calculatorModel.buttons(), "",
displayMode = "", evalMode = "", error = null))
val uiState : StateFlow<UIState> = _uiState.asStateFlow()
init {
calculatorModel.connect { this.updateUIState() }
updateUIState()
}
override fun onCleared() {
super.onCleared()
}
fun click(desc : ButtonDescription ) { desc.primaryOperation.clickAction(calculatorModel) }
private fun updateUIState() {
println( "Updating UI state")
viewModelScope.launch{
_uiState.update {
// Strings to display
// Does not change buttons
it.copy( top = calculatorModel.renderTop(),
stackStrings = calculatorModel.renderStack(),
envPairs = calculatorModel.renderEnv(),
base = calculatorModel.mode().base.toString(),
displayMode = calculatorModel.mode().displayMode.toString(),
evalMode = calculatorModel.mode().evalMode.toString(),
error = calculatorModel.nextError() )
}
}
}
fun cancelError() {
calculatorModel.cancelError()
}
fun setBase( newBase: Int ) = calculatorModel.setBase( newBase )
fun setDisplayMode( newMode : NumberDisplayMode ) = calculatorModel.setDisplayMode( newMode )
fun setEvalMode( newMode : EvalMode) = calculatorModel.setEvalMode( newMode )
fun makeVarRef(name: String) = calculatorModel.makeVarRef( name )
} | 0 | Kotlin | 0 | 0 | 1b6e5fd5c1ac3320888d76a16c4a16aeca2e7390 | 2,445 | compose-app | Apache License 2.0 |
idea-plugin/src/main/kotlin/arrow/meta/ide/plugins/proofs/utils/Utils.kt | mattmoore | 217,621,376 | false | null | package arrow.meta.ide.plugins.proofs.utils
import arrow.meta.ide.IdeMetaPlugin
import arrow.meta.ide.dsl.utils.replaceK
import arrow.meta.internal.Noop
import arrow.meta.phases.CompilerContext
import arrow.meta.phases.ExtensionPhase
import arrow.meta.plugins.proofs.phases.CoercionProof
import arrow.meta.plugins.proofs.phases.areTypesCoerced
import arrow.meta.plugins.proofs.phases.coerceProof
import arrow.meta.quotes.ktFile
import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.nj2k.postProcessing.type
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtImportList
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import java.awt.Color
import java.awt.Font
import java.awt.event.MouseEvent
import javax.swing.Icon
/**
* Similar to [arrow.meta.ide.dsl.editor.lineMarker.LineMarkerSyntax.addLineMarkerProviderM], is an extension for
* PsiElements that are not leafs so it will look for the first Leaf corresponding the targeted psiElement
*/
internal fun <A : PsiElement> IdeMetaPlugin.addLineMarkerProviderM(
icon: Icon,
transform: (PsiElement) -> A?,
composite: Class<A>,
message: DescriptorRenderer.Companion.(A) -> String = Noop.string2(),
commonIcon: MergeableLineMarkerInfo<PsiElement>.(others: List<MergeableLineMarkerInfo<*>>) -> Icon = { icon },
mergeWith: MergeableLineMarkerInfo<PsiElement>.(other: MergeableLineMarkerInfo<*>) -> Boolean = { this.icon == it.icon },
navigate: (event: MouseEvent, element: PsiElement) -> Unit = Noop.effect2,
placed: GutterIconRenderer.Alignment = GutterIconRenderer.Alignment.RIGHT,
clickAction: AnAction? = null
): ExtensionPhase =
addLineMarkerProvider(
{ PsiTreeUtil.findChildOfType(transform(it), LeafPsiElement::class.java) },
{
it.onComposite(composite) { psi: A ->
mergeableLineMarkerInfo(icon, it, { message(DescriptorRenderer.Companion, psi) }, commonIcon, mergeWith, placed, navigate, clickAction)
}
}
)
internal val implicitProofAnnotatorTextAttributes =
TextAttributes(null, null, Color(192, 192, 192), EffectType.WAVE_UNDERSCORE, Font.PLAIN)
internal fun KtDotQualifiedExpression.implicitParticipatingTypes(): Pair<KotlinType, KotlinType>? =
receiverExpression.resolveKotlinType().pairOrNull(selectorExpression?.resolveKotlinType())
internal fun KotlinType?.pairOrNull(b: KotlinType?): Pair<KotlinType, KotlinType>? =
if (this != null && b != null) Pair(this, b)
else null
internal fun KtExpression.resolveKotlinType(): KotlinType? =
analyze(BodyResolveMode.PARTIAL).getType(this)
internal fun CompilerContext.explicit(ktValueArgument: KtValueArgument): KtExpression? =
// Get the coerced types (parameter type and actual definition type)
ktValueArgument.participatingTypes()?.let { pairType ->
ktValueArgument.getArgumentExpression()
?.takeIf { it.resolveKotlinType() == pairType.first }
?.let { replaceWithProof(it, pairType) }
}
internal fun CompilerContext.explicit(ktProperty: KtProperty): KtExpression? =
ktProperty.participatingTypes()?.let { pairType ->
ktProperty.initializer?.let { replaceWithProof(it, pairType) }
}
private fun CompilerContext.replaceWithProof(ktExpression: KtExpression, pairType: Pair<KotlinType, KotlinType>): KtExpression? =
coerceProof(pairType.first, pairType.second)?.let { proof: CoercionProof ->
// Add import (if needed)
val importList: KtImportList? = ktExpression.containingKtFile.importList
val importableFqName: FqName? = proof.through.importableFqName
val throughPackage: FqName? = proof.through.ktFile()?.packageFqName
val notImported: Boolean = importList?.let { ktImportList ->
!ktImportList.imports.any { it.importedFqName == importableFqName }
} ?: true
val differentPackage: Boolean = ktExpression.containingKtFile.packageFqName != throughPackage
if (notImported && differentPackage) {
importableFqName?.let { fqName: FqName ->
importDirective(ImportPath(fqName, false)).value?.let { importDirective: KtImportDirective ->
importList?.add(importDirective as PsiElement)
}
}
}
// Replace with Proof
"${ktExpression.text}.${proof.through.name}()".expression.value?.let { new: KtExpression ->
ktExpression.replaceK(new)
}
}
internal fun KtElement.participatingTypes(): Pair<KotlinType, KotlinType>? =
when (this) {
is KtProperty -> participatingTypes()
is KtValueArgument -> participatingTypes()
else -> null
}
internal fun CompilerContext?.isCoerced(ktElement: KtElement): Boolean =
ktElement.participatingTypes()?.let { (subtype, supertype) ->
this.areTypesCoerced(subtype, supertype)
} ?: false
private fun KtProperty.participatingTypes(): Pair<KotlinType, KotlinType>? {
val subType: KotlinType? = initializer?.resolveKotlinType()
val superType: KotlinType? = type()
return subType.pairOrNull(superType)
}
// TODO: can't resolve Pair<Type, Type> or other HKT * -> *
private fun KtValueArgument.participatingTypes(): Pair<KotlinType, KotlinType>? {
val subType: KotlinType? = getArgumentExpression()?.resolveKotlinType()
val ktCallExpression: KtCallExpression? = PsiTreeUtil.getParentOfType(this, KtCallExpression::class.java)
val myselfIndex: Int = ktCallExpression?.valueArguments?.indexOf(this) ?: 0
val superType: KotlinType? = ktCallExpression.getResolvedCall(analyze())?.let { resolvedCall: ResolvedCall<out CallableDescriptor> ->
resolvedCall.resultingDescriptor.valueParameters.getOrNull(myselfIndex)?.type
}
return subType.pairOrNull(superType)
} | 1 | null | 1 | 1 | d97c914cdcd3075122f4398cee3dbb5cafa0142b | 6,728 | arrow-meta | Apache License 2.0 |
src/main/kotlin/org/wfanet/measurement/common/grpc/TransportSecurity.kt | VideoAmp | 368,272,602 | true | {"Kotlin": 1266935, "Starlark": 227446, "C++": 158561, "Shell": 7082} | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.grpc
import io.grpc.netty.GrpcSslContexts
import io.netty.handler.ssl.ClientAuth
import io.netty.handler.ssl.SslContext
import io.netty.handler.ssl.SslContextBuilder
import org.wfanet.measurement.common.crypto.SigningCerts
private const val TLS_V13_PROTOCOL = "TLSv1.3"
/**
* Converts this [SigningCerts] into an [SslContext] for a gRPC client with
* client authentication (mTLS).
*/
fun SigningCerts.toClientTlsContext(): SslContext {
return GrpcSslContexts.forClient()
.protocols(TLS_V13_PROTOCOL)
.keyManager(privateKey, certificate)
.trustManager(trustedCertificates)
.build()
}
/**
* Converts this [SigningCerts] into an [SslContext] for a gRPC server with TLS.
*/
fun SigningCerts.toServerTlsContext(clientAuth: ClientAuth = ClientAuth.NONE): SslContext {
return GrpcSslContexts.configure(SslContextBuilder.forServer(privateKey, certificate))
.protocols(TLS_V13_PROTOCOL)
.trustManager(trustedCertificates)
.clientAuth(clientAuth)
.build()
}
| 1 | null | 1 | 4 | 66fd8f1a81b7d93f23d769f7be76d529b6a8d222 | 1,645 | cross-media-measurement | Apache License 2.0 |
app/common/src/main/kotlin/me/zhanghai/android/files/provider/smb/SmbWatchKey.kt | overphoenix | 621,371,055 | false | null | package me.zhanghai.android.files.provider.smb
import me.zhanghai.android.files.provider.common.AbstractWatchKey
internal class SmbWatchKey(
watchService: SmbWatchService,
path: SmbPath
) : AbstractWatchKey<SmbWatchKey, SmbPath>(watchService, path)
| 0 | Kotlin | 0 | 0 | 64264f261c2138d5f1932789702661917bbfae28 | 259 | phoenix-android | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt | patxibocos | 344,205,064 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.androiddevchallenge.ui.theme.MyTheme
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
sealed class State(val total: Int) {
class Stopped(seconds: Int = 0) : State(seconds)
class Countdown(total: Int, val seconds: Int) : State(total)
}
class MainViewModel : ViewModel() {
private val _state = MutableLiveData<State>(State.Stopped())
val state: LiveData<State> = _state
private var currentTimer: Job? = null
fun startTimer() {
val currentState = _state.value
if (currentState !is State.Stopped) {
return
}
val seconds = currentState.total
if (seconds <= 0) {
return
}
// _state.value = State.Started(seconds)
_state.value = State.Countdown(seconds, seconds)
this.currentTimer = viewModelScope.launch {
timer(seconds).collect {
_state.value = if (it == 0) {
State.Stopped(0)
} else {
State.Countdown(seconds, it)
}
}
}
}
fun stopTimer() {
currentTimer?.cancel()
_state.value = State.Stopped(0)
}
fun incrementSecond() {
val currentState = _state.value
if (currentState !is State.Stopped) {
return
}
_state.value = State.Stopped(currentState.total + 1)
}
fun decrementSecond() {
val currentState = _state.value
if (currentState !is State.Stopped) {
return
}
if (currentState.total <= 0) {
return
}
_state.value = State.Stopped(currentState.total - 1)
}
}
class MainActivity : AppCompatActivity() {
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyTheme {
val state by viewModel.state.observeAsState(State.Stopped())
MyApp(
state,
viewModel::startTimer,
viewModel::stopTimer,
viewModel::incrementSecond,
viewModel::decrementSecond,
)
}
}
}
}
// Start building your app here!
@Composable
fun MyApp(
state: State,
timerStarted: () -> Unit = {},
timerStopped: () -> Unit = {},
secondsIncremented: () -> Unit = {},
secondsDecremented: () -> Unit = {},
) {
Surface(
color = MaterialTheme.colors.background,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Timer(state, timerStarted, timerStopped, secondsIncremented, secondsDecremented)
}
}
@Composable
fun Timer(
state: State,
timerStarted: () -> Unit = {},
timerStopped: () -> Unit = {},
secondsIncremented: () -> Unit = {},
secondsDecremented: () -> Unit = {},
) {
val sizes = listOf(
MaterialTheme.typography.h3,
MaterialTheme.typography.h2,
MaterialTheme.typography.h1
)
val styleIndex by animateIntAsState(targetValue = state.total % sizes.size)
Box(contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
when (state) {
is State.Countdown -> {
val ratio = state.seconds / state.total.toFloat()
val alpha by animateFloatAsState(targetValue = ratio)
Box(contentAlignment = Alignment.Center) {
CircularProgressIndicator(
modifier = Modifier
.size(300.dp)
.alpha(1 - alpha),
progress = state.seconds / state.total.toFloat(),
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "${state.seconds}",
style = sizes[styleIndex],
)
Button(
onClick = { timerStopped() },
shape = CircleShape,
colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.error),
modifier = Modifier.padding(top = 30.dp)
) {
Text(text = "Stop")
}
}
}
}
is State.Stopped -> {
Row(verticalAlignment = Alignment.CenterVertically) {
Button(
onClick = { secondsDecremented() },
shape = CircleShape,
modifier = Modifier.size(50.dp),
contentPadding = PaddingValues(15.dp)
) {
Box(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colors.secondary)
.height(5.dp)
)
}
Text(
text = "${state.total}",
style = sizes[styleIndex],
modifier = Modifier.padding(start = 30.dp, end = 30.dp)
)
Button(
onClick = { secondsIncremented() },
shape = CircleShape,
modifier = Modifier.size(50.dp),
contentPadding = PaddingValues(15.dp)
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colors.secondary)
.height(5.dp)
)
Box(
modifier = Modifier
.fillMaxHeight()
.background(MaterialTheme.colors.secondary)
.width(5.dp)
)
}
}
}
Button(
onClick = { timerStarted() },
shape = CircleShape,
enabled = state.total > 0,
modifier = Modifier.padding(top = 30.dp)
) {
Text(text = "GO!")
}
}
}
}
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreview() {
MyTheme {
MyApp(State.Stopped())
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun DarkPreview() {
MyTheme(darkTheme = true) {
MyApp(State.Countdown(5, 5))
}
}
fun timer(seconds: Int): Flow<Int> = flow {
for (s in (seconds - 1) downTo 0) {
delay(1000L)
emit(s)
}
}
| 0 | Kotlin | 0 | 0 | 187c1021ff5d213964bad4bd14deb8dfae6f9b52 | 10,179 | android-dev-challenge-compose-week-2 | Apache License 2.0 |
app/src/main/java/spoiler/blocker/util/ComposeUtil.kt | muthuraj57 | 473,692,304 | false | {"Kotlin": 36877} | /* $Id$ */
package spoiler.blocker.util
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import com.google.accompanist.systemuicontroller.rememberSystemUiController
/**
* Created by Muthuraj on 25/04/22.
*/
@Composable
fun SystemBarColors(){
val systemUiController = rememberSystemUiController()
val useDarkIcons = MaterialTheme.colors.isLight
SideEffect {
// Update all of the system bar colors to be transparent, and use
// dark icons if we're in light theme
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
}
} | 1 | Kotlin | 3 | 7 | 77b7145a4f57c315b473cdc5087120339693653c | 760 | SpoilerBlocker | Apache License 2.0 |
buildSrc/src/main/kotlin/karakum/mui/Files.kt | karakum-team | 387,062,541 | false | {"Kotlin": 1399430, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86} | package karakum.mui
import java.io.File
internal fun File.existed(
vararg names: String,
): Sequence<File> =
listFiles { file -> file.name in names }!!
.asSequence()
| 0 | Kotlin | 5 | 36 | 8465a0cb0cc3635d7b7c88637e850cca689029fb | 184 | mui-kotlin | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/auditing/AuditEventType.kt | uk-gov-mirror | 356,783,334 | true | {"Kotlin": 428549, "HTML": 83335, "CSS": 12598, "Shell": 6092, "Mustache": 4485, "Dockerfile": 945} | package uk.gov.justice.digital.hmpps.pecs.jpc.auditing
enum class AuditEventType(val label: String) {
DOWNLOAD_SPREADSHEET("Download spreadsheet"),
JOURNEY_PRICE("Journey price"),
JOURNEY_PRICE_BULK_UPDATE("Journey price bulk update"),
LOCATION("Location"),
LOG_IN("Log in"),
LOG_OUT("Log out"),
REPORTING_DATA_IMPORT("Reporting data import");
companion object {
/**
* Attempts to map the supplied value to the supported audit event types. Returns null if no match found.
*/
fun map(value: String): AuditEventType? =
values().firstOrNull { it.label.toUpperCase() == value.toUpperCase().trim() }
}
}
| 0 | Kotlin | 0 | 0 | 448660ac4b18cc4c8cf3c137a902ed7a99a9fff4 | 644 | ministryofjustice.calculate-journey-variable-payments | MIT License |
src/main/kotlin/design_patterns/Builder.kt | DmitryTsyvtsyn | 418,166,620 | false | {"Kotlin": 228861} | package design_patterns
/**
*
* Builder is is a generative design pattern that is used to create complex objects,
*
* separates the construction of an object from its representation
*
*/
/**
* The first variant
*/
class HttpConnectionClient1 private constructor(
private val dnsServerAddress: String,
private val callTimeout: Int,
private val connectTimeout: Int,
private val readTimeout: Int,
private val writeTimeout: Int,
// class can have many more fields
) {
override fun toString() = """
dns -> $dnsServerAddress
call timeout -> $callTimeout
connect timeout -> $connectTimeout
read timeout -> $readTimeout
write timeout -> $writeTimeout
""".trimIndent()
class Builder {
private var dnsServerAddress: String = "8.8.8.8"
private var callTimeout: Int = 0
private var connectTimeout: Int = 10_000
private var readTimeout: Int = 10_000
private var writeTimeout: Int = 0
fun dnsServerAddress(address: String) = apply {
dnsServerAddress = address
}
fun callTimeout(timeout: Int) = apply {
// we can add some checks such as:
// if (timeout < 0) throw IllegalArgumentException("Uncorrected timeout: $timeout")
callTimeout = timeout
}
fun connectTimeout(timeout: Int) = apply {
connectTimeout = timeout
}
fun readTimeout(timeout: Int) = apply {
readTimeout = timeout
}
fun writeTimeout(timeout: Int) = apply {
writeTimeout = timeout
}
fun build() = HttpConnectionClient1(dnsServerAddress, callTimeout, connectTimeout, readTimeout, writeTimeout)
}
}
/**
* The second variant
*/
class HttpConnectionClient2 private constructor() {
private var dnsServerAddress: String = "8.8.8.8"
private var callTimeout: Int = 0
private var connectTimeout: Int = 10_000
private var readTimeout: Int = 10_000
private var writeTimeout: Int = 0
override fun toString() = """
dns -> $dnsServerAddress
call timeout -> $callTimeout
connect timeout -> $connectTimeout
read timeout -> $readTimeout
write timeout -> $writeTimeout
""".trimIndent()
companion object {
fun newBuilder() = HttpConnectionClient2().Builder()
}
inner class Builder {
fun dnsServerAddress(address: String) = apply {
dnsServerAddress = address
}
fun callTimeout(timeout: Int) = apply {
// we can add some checks such as:
// if (timeout < 0) throw IllegalArgumentException("Uncorrected timeout: $timeout")
callTimeout = timeout
}
fun connectTimeout(timeout: Int) = apply {
connectTimeout = timeout
}
fun readTimeout(timeout: Int) = apply {
readTimeout = timeout
}
fun writeTimeout(timeout: Int) = apply {
writeTimeout = timeout
}
fun build() = this@HttpConnectionClient2
}
}
/**
* Kotlin variant with default arguments
*/
class HttpConnectionClient3(
private val dnsServerAddress: String = "8.8.8.8",
private val callTimeout: Int = 0,
private val connectTimeout: Int = 10_000,
private val readTimeout: Int = 10_000,
private val writeTimeout: Int = 0
) {
override fun toString() = """
dns -> $dnsServerAddress
call timeout -> $callTimeout
connect timeout -> $connectTimeout
read timeout -> $readTimeout
write timeout -> $writeTimeout
""".trimIndent()
} | 0 | Kotlin | 135 | 788 | 1f89f062a056e24cc289ffdd0c6e23cadf8df887 | 3,653 | Kotlin-Algorithms-and-Design-Patterns | MIT License |
app/src/main/java/ru/dimon6018/metrolauncher/content/oobe/WelcomeActivity.kt | queuejw | 659,118,377 | false | null | package ru.dimon6018.metrolauncher.content.oobe
import android.app.Activity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.WindowCompat
import androidx.fragment.app.commit
import ru.dimon6018.metrolauncher.Application.Companion.PREFS
import ru.dimon6018.metrolauncher.Application.Companion.applyWindowInsets
import ru.dimon6018.metrolauncher.R
import ru.dimon6018.metrolauncher.content.oobe.fragments.ConfigureFragment
import ru.dimon6018.metrolauncher.content.oobe.fragments.WelcomeFragment
class WelcomeActivity: AppCompatActivity() {
private var textLabel: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.oobe)
textLabel = findViewById(R.id.appbarTextView)
WindowCompat.setDecorFitsSystemWindows(window, false)
val coordinatorLayout: CoordinatorLayout = findViewById(R.id.coordinator)
applyWindowInsets(coordinatorLayout)
if (PREFS!!.launcherState != 2) {
supportFragmentManager.commit {
replace(R.id.fragment_container_view, WelcomeFragment(), "oobe")
}
} else {
supportFragmentManager.commit {
replace(R.id.fragment_container_view, ConfigureFragment(), "oobe")
}
}
}
companion object {
fun setText(activity: Activity, text: String) {
activity.findViewById<TextView>(R.id.appbarTextView)!!.text = text
}
}
} | 1 | null | 1 | 28 | 9f3e2e04378f3ac16e526f18c02a19631ed9e181 | 1,639 | MetroPhoneLauncher | MIT License |
src/main/kotlin/Main.kt | istepaniuk | 459,632,371 | false | {"Dockerfile": 1052, "Kotlin": 1020} | package com.istepaniuk.kotnijn
import com.rabbitmq.client.CancelCallback
import com.rabbitmq.client.ConnectionFactory
import com.rabbitmq.client.DeliverCallback
import com.rabbitmq.client.Delivery
import java.nio.charset.StandardCharsets
fun main() {
val rabbitHost = System.getenv("RABBITMQ_HOST")
println("Connecting to $rabbitHost...")
val factory = ConnectionFactory()
factory.host = rabbitHost
val connection = factory.newConnection()
val channel = connection.createChannel()
channel.queueDeclare("some-queue", false, false, false, null)
println("Waiting for messages...")
val deliverCallback = DeliverCallback { _: String?, delivery: Delivery ->
val message = String(delivery.body, StandardCharsets.UTF_8)
println("Received: '$message'")
}
val cancelCallback = CancelCallback { consumerTag: String? ->
println("Canceled!")
}
channel.basicConsume(
"some-queue", true, "test-consumer", deliverCallback, cancelCallback
)
}
| 0 | Dockerfile | 0 | 0 | c6c77d4a238e760be03194cc9750ab4623e5e2d0 | 1,020 | kotnijn | MIT License |
app/src/main/java/com/victor/loclarm/ui/home/SearchResultsAdapter.kt | ManuvelVictor | 828,185,613 | false | {"Kotlin": 50923} | package com.victor.loclarm.ui.home
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.libraries.places.api.model.AutocompletePrediction
import com.victor.loclarm.R
class SearchResultsAdapter(
private val onPlaceSelected: (String) -> Unit
) : ListAdapter<AutocompletePrediction, SearchResultsAdapter.SearchResultViewHolder>(PlaceDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchResultViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_search_result, parent, false)
return SearchResultViewHolder(view)
}
override fun onBindViewHolder(holder: SearchResultViewHolder, position: Int) {
val prediction = getItem(position)
holder.bind(prediction)
holder.itemView.setOnClickListener {
onPlaceSelected(prediction.placeId)
}
}
class SearchResultViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val placeNameTextView: TextView = itemView.findViewById(R.id.place_name_text_view)
fun bind(prediction: AutocompletePrediction) {
placeNameTextView.text = prediction.getPrimaryText(null).toString()
}
}
class PlaceDiffCallback : DiffUtil.ItemCallback<AutocompletePrediction>() {
override fun areItemsTheSame(oldItem: AutocompletePrediction, newItem: AutocompletePrediction): Boolean {
return oldItem.placeId == newItem.placeId
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: AutocompletePrediction, newItem: AutocompletePrediction): Boolean {
return oldItem == newItem
}
}
} | 0 | Kotlin | 0 | 0 | cd7a647bf6177045c38d248a3c8861548f40d8ac | 1,962 | Loclarm | Apache License 2.0 |
android/sloth/src/main/java/com/lambdapioneer/sloth/impl/LongSlothParams.kt | lambdapioneer | 686,670,023 | false | {"Kotlin": 193815, "Swift": 59894, "Jupyter Notebook": 51867, "Python": 8774, "Shell": 906} | package com.lambdapioneer.sloth.impl
import com.lambdapioneer.sloth.utils.ceilToNextKiB
/**
* The LongSloth parameters as defined in the paper.
*
* The [l] parameter is rounded up to the next KiB. See [SlothLib.determineParameter] as a practical
* way to determine a suitable L parameter.
*
* The [lambda] parameter is the overall security parameter and usually set to 128.
*/
class LongSlothParams(
l: Int = SECURITY_PARAMETER_L_DEFAULT,
internal val lambda: Int = SECURITY_PARAMETER_LAMBDA_DEFAULT
) {
internal val l = ceilToNextKiB(l)
companion object {
const val SECURITY_PARAMETER_L_DEFAULT = 100 * 1024
const val SECURITY_PARAMETER_LAMBDA_DEFAULT = 128
}
}
| 2 | Kotlin | 1 | 6 | a6250b210b138bf803d94c022c09e95be8dab5f6 | 709 | sloth | MIT License |
console-framework-client/src/main/java/io/axoniq/console/framework/eventprocessor/ProcessorReportCreator.kt | AxonIQ | 682,516,729 | false | {"Kotlin": 152634, "Java": 24388} | /*
* Copyright (c) 2022-2023. AxonIQ B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.console.framework.eventprocessor
import io.axoniq.console.framework.api.*
import io.axoniq.console.framework.eventprocessor.metrics.ProcessorMetricsRegistry
import org.axonframework.common.ReflectionUtils
import org.axonframework.config.EventProcessingConfiguration
import org.axonframework.eventhandling.*
import org.axonframework.eventhandling.deadletter.DeadLetteringEventHandlerInvoker
import org.axonframework.eventhandling.pooled.PooledStreamingEventProcessor
import org.axonframework.messaging.deadletter.SequencedDeadLetterQueue
class ProcessorReportCreator(
private val processingConfig: EventProcessingConfiguration,
private val metricsRegistry: ProcessorMetricsRegistry,
) {
fun createReport() = ProcessorStatusReport(
processingConfig.eventProcessors()
.filter { it.value is StreamingEventProcessor }
.map { entry ->
val sep = entry.value as StreamingEventProcessor
ProcessorStatus(
entry.key,
entry.value.toProcessingGroupStatuses(),
sep.tokenStoreIdentifier,
sep.toType(),
sep.isRunning,
sep.isError,
sep.maxCapacity(),
sep.processingStatus().filterValues { !it.isErrorState }.size,
sep.processingStatus().map { (_, segment) -> segment.toStatus(entry.key) },
)
}
)
fun createSegmentOverview(processorName: String): SegmentOverview {
val tokenStore = processingConfig.tokenStore(processorName)
val segments = tokenStore.fetchSegments(processorName)
return SegmentOverview(
segments.map { Segment.computeSegment(it, *segments) }
.map { SegmentDetails(it.segmentId, it.mergeableSegmentId(), it.mask) }
)
}
private fun StreamingEventProcessor.toType(): ProcessorMode {
return when (this) {
is TrackingEventProcessor -> ProcessorMode.TRACKING
is PooledStreamingEventProcessor -> ProcessorMode.POOLED
else -> ProcessorMode.UNKNOWN
}
}
private fun EventTrackerStatus.toStatus(name: String) = SegmentStatus(
segment = this.segment.segmentId,
mergeableSegment = this.segment.mergeableSegmentId(),
mask = this.segment.mask,
oneOf = this.segment.mask + 1,
caughtUp = this.isCaughtUp,
error = this.isErrorState,
errorType = this.error?.javaClass?.typeName,
errorMessage = this.error?.message,
ingestLatency = metricsRegistry.ingestLatencyForProcessor(name, this.segment.segmentId).getValue(),
commitLatency = metricsRegistry.commitLatencyForProcessor(name, this.segment.segmentId).getValue(),
)
private fun EventProcessor.toProcessingGroupStatuses(): List<ProcessingGroupStatus> =
if (this is AbstractEventProcessor) {
val invoker = this.eventHandlerInvoker()
if (invoker is MultiEventHandlerInvoker) {
invoker.delegates().map { i -> i.toProcessingGroupStatus(this.name) }
} else {
listOf(invoker.toProcessingGroupStatus(this.name))
}
} else {
listOf(ProcessingGroupStatus(this.name, null))
}
private fun EventHandlerInvoker.toProcessingGroupStatus(processorName: String): ProcessingGroupStatus =
if (this is DeadLetteringEventHandlerInvoker) {
this.getStatusByReflectionOrDefault(processorName)
} else {
ProcessingGroupStatus(processorName, null)
}
private fun DeadLetteringEventHandlerInvoker.getStatusByReflectionOrDefault(processorName: String): ProcessingGroupStatus {
val queueField = this.getField("queue") ?: return ProcessingGroupStatus(processorName, null)
val queue = ReflectionUtils.getFieldValue<SequencedDeadLetterQueue<EventMessage<Any>>>(queueField, this)
val processingGroupField = queue.getField("processingGroup")
?: return ProcessingGroupStatus(processorName, null)
val processingGroup = ReflectionUtils.getFieldValue<String>(processingGroupField, queue)
return ProcessingGroupStatus(processingGroup, queue.amountOfSequences())
}
private fun Any.getField(name: String) =
this::class.java.declaredFields.firstOrNull { it.name == name }
}
| 2 | Kotlin | 0 | 0 | d7576c8e23685cb1f3a5444be722db7f3c356b49 | 5,328 | console-framework-client | Apache License 2.0 |
src/main/kotlin/com/illuzionzstudios/mist/item/loader/CustomItemLoader.kt | IlluzionzDev | 265,799,633 | false | {"Kotlin": 392279} | package com.illuzionzstudios.mist.item.loader
import com.illuzionzstudios.mist.config.ConfigSection
import com.illuzionzstudios.mist.item.CustomItem
/**
* Custom item loader for normal implementation
*/
class CustomItemLoader(section: ConfigSection) : BaseCustomItemLoader<CustomItem>(section) {
override fun returnImplementedObject(configSection: ConfigSection?): CustomItem {
return CustomItem()
}
} | 0 | Kotlin | 4 | 0 | 9d4b8f85492f61f5ff109004210460a952a6fc38 | 421 | Mist | MIT License |
OneSignalSDK/onesignal/core/src/main/java/com/onesignal/core/internal/language/impl/LanguageProviderDevice.kt | OneSignal | 33,515,679 | false | {"Kotlin": 1777584, "Java": 49349, "Shell": 748} | package com.onesignal.core.internal.language.impl
import java.util.Locale
internal class LanguageProviderDevice {
val language: String
get() {
return when (val language = Locale.getDefault().language) {
HEBREW_INCORRECT -> HEBREW_CORRECTED
INDONESIAN_INCORRECT -> INDONESIAN_CORRECTED
YIDDISH_INCORRECT -> YIDDISH_CORRECTED
CHINESE -> language + "-" + Locale.getDefault().country
else -> language
}
}
companion object {
private const val HEBREW_INCORRECT = "iw"
private const val HEBREW_CORRECTED = "he"
private const val INDONESIAN_INCORRECT = "in"
private const val INDONESIAN_CORRECTED = "id"
private const val YIDDISH_INCORRECT = "ji"
private const val YIDDISH_CORRECTED = "yi"
private const val CHINESE = "zh"
}
}
| 65 | Kotlin | 367 | 604 | b03d5f5395f141ef3fed817d5d4d118b768e7294 | 910 | OneSignal-Android-SDK | Apache License 2.0 |
api/src/main/kotlin/pl/bas/microtwitter/configs/GsonConfiguration.kt | Humberd | 105,806,448 | false | {"YAML": 2, "Text": 1, "Ignore List": 3, "Groovy": 1, "Markdown": 3, "XML": 13, "JSON with Comments": 2, "JSON": 6, "Dockerfile": 4, "JavaScript": 2, "EditorConfig": 1, "HTML": 43, "SCSS": 55, "SVG": 1, "Batchfile": 1, "Shell": 1, "Maven POM": 1, "INI": 1, "Java Properties": 6, "Kotlin": 49, "Java": 1} | package pl.bas.microtwitter.configs
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import mu.KLogging
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import pl.bas.microtwitter.serializers.DateDeserializer
import pl.bas.microtwitter.serializers.DateSerializer
import java.util.*
@Configuration
class GsonConfiguration {
companion object : KLogging()
@Bean
fun gson(): Gson = GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Date::class.java, DateSerializer())
.registerTypeAdapter(Date::class.java, DateDeserializer())
.create()
}
| 0 | Kotlin | 0 | 3 | f0b33295f1b18d553480bb46ed50b813000dbbd4 | 681 | MicroTwitter | MIT License |
src/main/kotlin/io/github/settingdust/konge/configurate/WatchingPropertyResourceBundle.kt | SettingDust | 364,781,361 | false | null | package io.github.settingdust.konge.configurate
import org.spongepowered.configurate.reactive.Subscriber
import java.nio.file.Path
import java.util.*
import kotlin.io.path.inputStream
class WatchingPropertyResourceBundle constructor(
path: Path
) : ResourceBundle(), Subscriber<PropertyResourceBundle> {
private var propertyResourceBundle: PropertyResourceBundle
override fun submit(item: PropertyResourceBundle) {
propertyResourceBundle = item
}
public override fun setParent(parent: ResourceBundle?) = super.setParent(parent)
public override fun handleGetObject(key: String): Any? = propertyResourceBundle.handleGetObject(key)
override fun getKeys(): Enumeration<String> = propertyResourceBundle.keys
override fun handleKeySet(): Set<String> = propertyResourceBundle.keySet()
init {
propertyResourceBundle = PropertyResourceBundle(path.inputStream())
}
} | 0 | Kotlin | 0 | 0 | 70d398e33ce383799559fa7121c5eff5ced1eca4 | 921 | konge | Apache License 2.0 |
dino-core/src/main/kotlin/org/ufoss/dino/internal/ForwardingSource.kt | ufoss-org | 264,428,446 | false | {"Kotlin": 511559, "Java": 78614} | /*
* Copyright 2023 UFOSS, Org. Use of this source code is governed by the Apache 2.0 license.
*
* Forked from Okio (https://github.com/square/okio), original copyright is below
*
* Copyright (C) 2013 Square, Inc.
*
* 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.ufoss.dino.internal
import org.ufoss.dino.Source
internal abstract class ForwardingSource internal constructor(
@get:JvmName("delegate")
val delegate: Source,
) : Source by delegate {
override fun toString() = "${javaClass.simpleName}($delegate)"
}
| 14 | Kotlin | 0 | 9 | 3bf047f5b049ee75d49224363b8f45806d1228a2 | 1,060 | dino | Apache License 2.0 |
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/helpers/utils/AuthUtil.kt | MihailsKuzmins | 240,947,625 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 323, "XML": 156, "Java": 1, "JSON": 1} | package jp.mihailskuzmins.sugoinihongoapp.helpers.utils
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthException
import com.google.firebase.auth.FirebaseUser
import jp.mihailskuzmins.sugoinihongoapp.extensions.firebase.isAuthenticated
import jp.mihailskuzmins.sugoinihongoapp.extensions.invoke
import jp.mihailskuzmins.sugoinihongoapp.resources.Action
import jp.mihailskuzmins.sugoinihongoapp.resources.AuthResult
class AuthUtil {
private val mAuth = FirebaseAuth.getInstance()
val isAuthenticated: Boolean
get() = mAuth.isAuthenticated
val userId: String?
get() {
val currentUser = mAuth.currentUser
return if (currentUser?.isEmailVerified == true) currentUser.uid
else null
}
val userEmail: String
get() = mAuth.currentUser?.email ?: ""
private val mCurrentUser: FirebaseUser
get() = mAuth.currentUser!!
fun signIn(email: String, password: String, onErrorAction: (AuthResult) -> Unit) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
task.exception?.let {
getAuthResult(it)
.invoke(onErrorAction)
return@addOnCompleteListener
}
task.result?.let {
val result = if (it.user?.isEmailVerified == true) AuthResult.Success
else AuthResult.EmailNotVerified
onErrorAction(result)
return@addOnCompleteListener
}
onErrorAction(AuthResult.Unknown)
}
}
fun signUp(email: String, password: String, onAuthResult: (AuthResult) -> Unit) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
task.exception?.let {
getAuthResult(it)
.invoke(onAuthResult)
return@addOnCompleteListener
}
sendEmailVerification(onAuthResult)
}
}
fun sendPasswordReset(email: String, onAuthResult: (AuthResult) -> Unit) {
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener { task ->
task.exception?.let {
getAuthResult(it)
.invoke(onAuthResult)
return@addOnCompleteListener
}
onAuthResult.invoke(AuthResult.Success)
}
}
fun sendEmailVerification(onAuthResult: ((AuthResult) -> Unit)? = null) {
val check = when {
mAuth.currentUser == null -> AuthResult.NotAuthenticated
mAuth.currentUser?.isEmailVerified == true -> AuthResult.EmailAlreadyVerified
else -> AuthResult.Success
}
if (check != AuthResult.Success) {
onAuthResult?.invoke(check)
return
}
mAuth.currentUser
?.sendEmailVerification()
?.addOnCompleteListener { task ->
task.exception?.let {
getAuthResult(it)
.invoke { x -> onAuthResult?.invoke(x) }
return@addOnCompleteListener
}
onAuthResult?.invoke(AuthResult.Success)
}
}
fun changePassword(currentPassword: String, newPassword: String, onAuthResult: (AuthResult) -> Unit) {
reauthenticate(currentPassword, onAuthResult) {
mCurrentUser.updatePassword(newPassword)
.addOnCompleteListener { task ->
task.exception?.let {
getAuthResult(it).invoke(onAuthResult)
return@addOnCompleteListener
}
onAuthResult(AuthResult.Success)
}
}
}
fun signOut() =
mAuth.signOut()
fun deleteAccount(email: String, password: String, onAuthResult: (AuthResult) -> Unit) {
val check = when {
mAuth.currentUser == null -> AuthResult.NotAuthenticated
email != userEmail -> AuthResult.InvalidEmail
else -> AuthResult.Success
}
if (check != AuthResult.Success) {
onAuthResult(check)
.invoke { return@deleteAccount }
}
reauthenticate(password, onAuthResult) {
mAuth.currentUser
?.delete()
?.addOnCompleteListener { task ->
task.exception?.let {
onAuthResult(AuthResult.ServerNotReachable)
return@addOnCompleteListener
}
onAuthResult(AuthResult.Success)
}
}
}
private fun reauthenticate(password: String, onAuthResult: (AuthResult) -> Unit, action: Action) {
val authCredential = EmailAuthProvider.getCredential(userEmail, password)
mCurrentUser
.reauthenticate(authCredential)
.addOnCompleteListener { reauthTask ->
reauthTask.exception?.let {
getAuthResult(it).invoke(onAuthResult)
return@addOnCompleteListener
}
action()
}
}
private fun getAuthResult(exception: Exception): AuthResult {
if (exception !is FirebaseAuthException)
return AuthResult.ServerNotReachable
return when(exception.errorCode) {
"ERROR_INVALID_EMAIL" -> AuthResult.InvalidEmail
"ERROR_EMAIL_ALREADY_IN_USE" -> AuthResult.EmailAlreadyInUse
"ERROR_USER_NOT_FOUND" -> AuthResult.UserNotFound
"ERROR_WRONG_PASSWORD" -> AuthResult.WrongPassword
else -> AuthResult.Unknown
}
}
} | 1 | null | 1 | 1 | 57e19b90b4291dc887a92f6d57f9be349373a444 | 5,228 | sugoi-nihongo-android | Apache License 2.0 |
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/FitnessRequest.kt | pennlabs | 16,791,473 | false | {"Kotlin": 627855, "Java": 96324, "HTML": 1719} | package com.pennapps.labs.pennmobile.classes
class FitnessRequest(
favoriteFitnessRooms: ArrayList<Int>,
) {
var rooms: ArrayList<Int> = favoriteFitnessRooms
}
| 0 | Kotlin | 5 | 34 | 01bfecf5452621bbb2d7ebc005615e3e1d46bcfe | 169 | penn-mobile-android | MIT License |
app/src/main/java/com/dluvian/voyage/ui/theme/Style.kt | dluvian | 766,355,809 | false | {"Kotlin": 991595} | package com.dluvian.voyage.ui.theme
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.style.TextDecoration
val MentionStyle = SpanStyle(color = HyperlinkBlue)
val HashtagStyle = SpanStyle(color = TallPoppyRed)
val UrlStyle = SpanStyle(textDecoration = TextDecoration.Underline)
| 36 | Kotlin | 4 | 39 | 9fe406eada1a905c8f1a2510196babd647444eff | 304 | voyage | MIT License |
app/src/main/java/com/anbui/recipely/domain/models/OrderStatus.kt | AnBuiii | 667,858,307 | false | {"Kotlin": 492766} | package com.anbui.recipely.domain.models
data class OrderStatus(
val id: String?,
val time: String,
val title: String,
)
val exampleOrderStatus = listOf(
OrderStatus(id = "213", "12:47 Yesterday", "Order is processing"),
OrderStatus(id = "2123", "20:47 Yesterday", "Order is ready to pickup"),
OrderStatus(id = "676", "22:47 Yesterday", "Order is being delivered"),
OrderStatus(id = "09230", "8:47 Today", "Successful delivery")
)
| 0 | Kotlin | 1 | 4 | 3608a1a3307309b8552649c7a5334eea7ded8f3a | 461 | Recipely | Apache License 2.0 |
TimeTracker/app/src/main/java/nz/ac/uclive/rog19/seng440/assignment1/model/GodModelSerialized.kt | rogino | 544,712,439 | false | null | package nz.ac.uclive.rog19.seng440.assignment1.model
import android.content.Context
import android.util.Log
import com.beust.klaxon.Klaxon
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import nz.ac.uclive.rog19.seng440.assignment1.TAG
import nz.ac.uclive.rog19.seng440.assignment1.minusDays
import java.io.FileInputStream
import java.io.FileOutputStream
import java.time.Instant
fun GodModel.serialize(maxEntryAge: Long = 3): GodModelSerialized {
val now = Instant.now()
val entries = timeEntries.filter { now.minusDays(maxEntryAge).isBefore(it.startTime) }
return GodModelSerialized(tags, projects.values, entries)
}
class GodModelSerialized(
val tags: Collection<String>,
val projects: Collection<Project>,
var entries: Collection<TimeEntry>
) {
fun populateModelIfEmpty(model: GodModel = GodModel()): GodModel {
if (model.timeEntries.isEmpty()) {
Log.d(TAG, "Add ${entries?.count()} entries from disk to the model")
model.setEntries(entries)
}
if (model.projects.isEmpty()) {
Log.d(TAG, "Add ${projects?.count()} projects from disk to the model")
model.setProjects(projects)
}
if (model.tags.isEmpty()) {
Log.d(TAG, "Add ${tags?.count()} tags from disk to the model")
model.setTags(tags)
}
return model
}
companion object {
val FILE_NAME = "model.json"
val MAX_ENTRY_AGE: Long = 3
val jsonConverter = Klaxon().converter(DateTimeConverter)
suspend fun saveModelToFile(context: Context, model: GodModel) {
var newModel: GodModelSerialized
withContext(Dispatchers.Main) {
newModel = model.serialize()
val now = Instant.now()
newModel.entries = newModel.entries.filter {
now.minusDays(MAX_ENTRY_AGE).isBefore(it.startTime)
}
}
saveModelToFile(context, newModel)
}
suspend fun saveModelToFile(context: Context, model: GodModelSerialized) {
withContext(Dispatchers.IO) {
Log.d(TAG, "Serializing model to JSON")
val serialized = jsonConverter.toJsonString(model)
Log.d(TAG, "Finished serializing model to JSON (len ${serialized.length})")
var file: FileOutputStream? = null
try {
Log.d(TAG, "Writing $FILE_NAME to disk")
file = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE)
file.write(serialized.toByteArray())
Log.d(TAG, "Finished writing $FILE_NAME to disk")
} catch (err: Throwable) {
Log.d(TAG, "Failed to write $FILE_NAME to disk or serialize it")
Log.d(TAG, err.stackTraceToString())
} finally {
file?.close()
}
}
}
suspend fun readAndPopulateModel(
context: Context,
model: GodModel
) {
withContext(Dispatchers.IO) {
var file: FileInputStream? = null
try {
Log.d(TAG, "Reading $FILE_NAME from disk")
file = context.openFileInput(FILE_NAME)
val newModel = jsonConverter.parse<GodModelSerialized>(file)
Log.d(TAG, "Finished reading $FILE_NAME from disk")
if (newModel == null) return@withContext;
val now = Instant.now()
newModel.entries = newModel.entries.filter {
now.minusDays(MAX_ENTRY_AGE).isBefore(it.startTime)
}
withContext(Dispatchers.Main) {
newModel.populateModelIfEmpty(model)
}
} catch (err: Throwable) {
Log.d(TAG, "Failed to read $FILE_NAME from disk or parse it as JSON")
Log.d(TAG, err.stackTraceToString())
null
} finally {
file?.close()
}
}
}
suspend fun clear(context: Context) {
Log.d(TAG, "Deleting $FILE_NAME")
withContext(Dispatchers.IO) {
context.deleteFile(FILE_NAME)
Log.d(TAG, "Deleted $FILE_NAME")
}
}
}
} | 0 | Kotlin | 0 | 0 | 35e2bb302acf950ec7cb8df2bf4c29ff865c8f72 | 4,498 | TimeTracker | MIT License |
src/rider/main/kotlin/com/github/rafaelldi/diagnosticsclientplugin/toolWindow/DiagnosticsToolWindowListener.kt | rafaelldi | 487,741,199 | false | null | package com.github.rafaelldi.diagnosticsclientplugin.toolWindow
import com.github.rafaelldi.diagnosticsclientplugin.generated.diagnosticsHostModel
import com.github.rafaelldi.diagnosticsclientplugin.toolWindow.DiagnosticsToolWindowFactory.Companion.DIAGNOSTICS_CLIENT_TOOL_WINDOW
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.jetbrains.rider.projectView.solution
class DiagnosticsToolWindowListener(private val project: Project) : ToolWindowManagerListener {
override fun toolWindowShown(toolWindow: ToolWindow) {
if (toolWindow.id != DIAGNOSTICS_CLIENT_TOOL_WINDOW) return
val model = project.solution.diagnosticsHostModel
if (model.processList.active.valueOrNull == true) return
model.processList.active.set(true)
}
} | 3 | Kotlin | 0 | 4 | 8d4cfd9f4992ad10010d80c2359158399f4846aa | 874 | diagnostics-client-plugin | MIT License |
ktlint-ruleset-k2dart/src/test/kotlin/com/beyondeye/k2dart/FutureInsteadOfSuspendRuleTest.kt | beyondeye | 562,395,931 | false | {"Kotlin": 1923856, "Dart": 8001, "Shell": 3301, "Batchfile": 2733} | package com.beyondeye.k2dart
import com.pinterest.ktlint.ruleset.k2dart.rules.FutureInsteadOfSuspendRule
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
// *DARIO* this for collecting result of a lint of operation
class FutureInsteadOfSuspendRuleTest {
@Test
fun `comment out suspend keyword and change return type to future`() {
val code =
"""
class A
suspend fun fun1():A
{
return A()
}
suspend fun fun2()=12
suspend fun anotherAsyncFun():Int {
return 1
}
""".trimIndent()
val formattedCode =
"""
class A
/* suspend */ fun fun1():Future<A>
{
return A()
}
/* suspend */ fun fun2():Future<Object> =12
/* suspend */ fun anotherAsyncFun():Future<Int> {
return 1
}
""".trimIndent()
val actualFormattedCode = runRulesOnCodeFragment(code, listOf(FutureInsteadOfSuspendRule()))
Assertions.assertThat(actualFormattedCode).isEqualTo(formattedCode)
}
}
| 0 | Kotlin | 1 | 13 | 073e0639da809c867a53973d6a1b40e7216c8c29 | 1,203 | kotlin2dart | MIT License |
sms-persistence/src/main/kotlin/team/msg/sms/persistence/teacher/repository/TeacherJpaRepository.kt | GSM-MSG | 625,717,097 | false | {"Kotlin": 336463, "Shell": 1480, "Dockerfile": 288} | package team.msg.sms.persistence.teacher.repository
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import team.msg.sms.persistence.teacher.entity.TeacherJpaEntity
import team.msg.sms.persistence.user.entity.UserJpaEntity
import java.util.*
@Repository
interface TeacherJpaRepository : JpaRepository<TeacherJpaEntity, UUID>{
fun existsByUser(user: UserJpaEntity): Boolean
} | 6 | Kotlin | 0 | 8 | 96965345d930054ec7bf4642ee809d09cf4c2103 | 441 | SMS-BackEnd | MIT License |
app/src/main/java/com/heirko/prim/util/logging/CrashReportingTree.kt | heralight | 72,844,582 | false | {"Gradle": 3, "Java Properties": 3, "Shell": 1, "JSON": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "XML": 8, "Proguard": 1, "Kotlin": 39, "Java": 3} | package com.heirko.prim.util.logging;
import android.util.Log;
import timber.log.Timber;
class CrashReportingTree : Timber.Tree() {
override fun log(priority: Int, tag: String, message: String, t: Throwable) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return
}
}
}
| 0 | Kotlin | 0 | 1 | 30419e37f670e3c35c4c8b0db1a7f9ad7eae63d4 | 318 | primhipster | Apache License 2.0 |
src/main/kotlin/lv/yu/kot/xxxxx/xxxxx_12/KOT_xxxxx_12_10.kt | yu-2023 | 578,621,989 | false | {"Kotlin": 279730, "Java": 6372, "Batchfile": 1235, "HTML": 274} |
/**
*
* Kotlin package lv.yu.kot.xxxxx.xxxxx_12
*
* Kotlin program KOT_xxxxx_12_10.kt Apache License 2.0
*
* Copyright (c) Yuri Utkin 2023 mob.+371 12345678 https://www.jago.lv
*
*/
package lv.yu.kot.xxxxx.xxxxx_12
import java.awt.Color
import java.awt.BorderLayout
import javax.swing.JTabbedPane
import javax.swing.SwingConstants
import javax.swing.JInternalFrame
public var JTabbedPane_xxxxx_10_12 = JTabbedPane()
public var JInternalFrame_xxxxx_10_12 = JInternalFrame()
fun KOT_xxxxx_12_10() {
JTabbedPane_xxxxx_10_12 = JTabbedPane()
JTabbedPane_xxxxx_10_12.removeAll()
KOT_xxxxx_12_about_10()
KOT_xxxxx_12_help_10()
JTabbedPane_xxxxx_10_12.setTabPlacement(SwingConstants.BOTTOM)
JTabbedPane_xxxxx_10_12.setTabLayoutPolicy(1)
JInternalFrame_xxxxx_10_12 = JInternalFrame("12 XXXXX XXXXX XXXXX", true, false, true, true)
JInternalFrame_xxxxx_10_12.setLayout(BorderLayout())
JInternalFrame_xxxxx_10_12.setBackground(Color.GRAY)
JInternalFrame_xxxxx_10_12.isVisible = true
JInternalFrame_xxxxx_10_12.add(JTabbedPane_xxxxx_10_12, BorderLayout.CENTER)
} // end KOT_xxxxx_12_10()
| 0 | Kotlin | 0 | 0 | 8930cfb6134e4576983962692bb923ee552f7227 | 1,224 | yu-kotlin | Apache License 2.0 |
composeApp/src/commonMain/kotlin/com/borealnetwork/allen/modules/home_client/presentation/ui/home/HomeClientViewCompose.kt | baudelioandalon | 742,906,893 | false | {"Kotlin": 481999, "Swift": 618} | package com.borealnetwork.allen.modules.home_client.presentation.ui.home
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Card
import androidx.compose.material.Scaffold
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.borealnetwork.allen.domain.model.PromotionItem
import com.borealnetwork.allen.modules.cart.domain.navigation.CartClientScreen
import com.borealnetwork.allen.modules.home_client.domain.view_model.HomeClientViewModel
import com.borealnetwork.allen.modules.notifications.domain.navigation.NotificationsClientScreen
import com.borealnetwork.allen.modules.orders.domain.navigation.OrdersClientScreen
import com.borealnetwork.allen.modules.product.domain.navigation.ProductClientScreen
import com.borealnetwork.allen.modules.product.domain.view_models.ShowProductViewModel
import com.borealnetwork.allen.modules.stores.domain.navigation.StoresScreen
import com.borealnetwork.allen.platform
import com.borealnetwork.allensharedui.components.BoldText
import com.borealnetwork.allensharedui.components.BrandingHorizontal
import com.borealnetwork.allensharedui.components.CategoryItem
import com.borealnetwork.allensharedui.components.CategorySelectorItem
import com.borealnetwork.allensharedui.components.HorizontalContainerListItem
import com.borealnetwork.allensharedui.components.ProductItem
import com.borealnetwork.allensharedui.components.ToolbarSearchHome
import com.borealnetwork.allensharedui.components.drawer.DrawerBodyClient
import com.borealnetwork.allensharedui.components.drawer.DrawerHeaderClient
import com.borealnetwork.allensharedui.components.drawer.model.DrawerOptions
import com.borealnetwork.allensharedui.components.drawer.model.MenuItem
import com.borealnetwork.allensharedui.theme.GrayBackgroundMain
import com.borealnetwork.allensharedui.theme.categorySelectorColors
import com.borealnetwork.shared.domain.models.START_INDEX
import com.borealnetwork.shared.domain.models.StateApi
import com.borealnetwork.shared.domain.models.cart.MinimalProductModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import moe.tlaster.precompose.lifecycle.Lifecycle
import moe.tlaster.precompose.lifecycle.LifecycleObserver
import moe.tlaster.precompose.lifecycle.LocalLifecycleOwner
import moe.tlaster.precompose.navigation.Navigator
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.painterResource
import org.koin.compose.koinInject
@Composable
fun HomeClientViewCompose(
navigator: Navigator,
homeClientViewModel: HomeClientViewModel,
showProductViewModel: ShowProductViewModel
) {
val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()
val productsResult = homeClientViewModel.productsResult.collectAsState().value
val lastProductsList = listOf(
MinimalProductModel(
skuProduct = "dd323234",
nameProduct = "Sensor Dummy",
imgProduct = "imagen",
categoryItem = "Electronica",
price = 34.54,
discountPercentage = 0.0
),
MinimalProductModel(
skuProduct = "dd323234",
nameProduct = "Sensor Dummy",
imgProduct = "imagen",
categoryItem = "Electronica",
price = 34.0,
discountPercentage = 0.0
)
)
Scaffold(modifier = Modifier
.fillMaxWidth(), drawerShape = RectangleShape, topBar = {
ToolbarSearchHome(startClicked = {
scope.launch {
scaffoldState.drawerState.open()
}
}, cartClicked = {
navigator.navigate(
route = CartClientScreen.ShoppingCartClientScreen.route
)
}, searchClicked = {
navigator.navigate(ProductClientScreen.SearchClientScreen.route)
})
},
drawerGesturesEnabled = scaffoldState.drawerState.isOpen,
scaffoldState = scaffoldState,
drawerContent = {
DrawerHeaderClient {
scope.launch {
scaffoldState.drawerState.close()
}
}
DrawerBodyClient(
items = listOf(
MenuItem(
"Compras",
icon = "ic_cart_icon.xml",
contentDescription = "Cart",
option = DrawerOptions.Buys
),
MenuItem(
"Favoritos",
icon = "ic_heart_icon.xml",
contentDescription = "Favorites",
option = DrawerOptions.Favorites
),
MenuItem(
"Tiendas",
icon = "ic_stores_icon.xml",
contentDescription = "Stores",
option = DrawerOptions.Stores
),
MenuItem(
"Notificaciónes",
icon = "ic_bell_icon.xml",
contentDescription = "Notifications",
option = DrawerOptions.Notifications
),
MenuItem(
"Salir",
icon = "ic_arrow_right.xml",
contentDescription = "Exit",
option = DrawerOptions.Exit,
close = 0
),
MenuItem(
"Cerrar sesión",
icon = "ic_close_session_icon.xml",
contentDescription = "Close session",
option = DrawerOptions.CloseSession
)
),
versionName = platform().versionName
) {
println("Clicked on ${it.option.name}")
when (it.option) {
DrawerOptions.Exit -> {
}
DrawerOptions.Buys -> {
scope.launch {
scaffoldState.drawerState.close()
}
navigator.navigate(
route = OrdersClientScreen.OrdersListClientScreen.route
)
}
DrawerOptions.Favorites -> {
scope.launch {
scaffoldState.drawerState.close()
}
navigator.navigate(route = ProductClientScreen.FavoritesProductsClient.route)
}
DrawerOptions.Stores -> {
scope.launch {
scaffoldState.drawerState.close()
}
navigator.navigate(
route = StoresScreen.StoresInMapScreen.route
)
}
DrawerOptions.Notifications -> {
scope.launch {
scaffoldState.drawerState.close()
}
navigator.navigate(route = NotificationsClientScreen.NotificationsDefaultClientScreen.route)
}
else -> {
}
}
}
},
content = {
val lifecycle = LocalLifecycleOwner.current
lifecycle.lifecycle.addObserver(object : LifecycleObserver {
override fun onStateChanged(state: Lifecycle.State) {
when (state) {
Lifecycle.State.Initialized -> {
}
Lifecycle.State.Active -> {
homeClientViewModel.getProducts()
}
Lifecycle.State.InActive -> {
}
Lifecycle.State.Destroyed -> {
}
}
}
})
Box(
modifier = Modifier
.fillMaxSize()
.background(White)
) {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.background(GrayBackgroundMain)
) {
item {
Card(
modifier = Modifier
.fillMaxWidth(),
shape = RectangleShape,
elevation = 5.dp
) {
TopContainer()
}
}
item {
Card(
modifier = Modifier
.padding(top = 30.dp)
.fillMaxWidth(),
shape = RectangleShape,
elevation = 5.dp
) {
BrandingContainer()
}
}
item {
Card(
modifier = Modifier
.padding(top = 30.dp)
.fillMaxWidth(),
shape = RectangleShape,
elevation = 5.dp
) {
HorizontalContainerListItem(
startText = "Ultimos articulos",
endText = "Ver todos",
listItem = if (productsResult?.status == StateApi.Success) {
productsResult.response?.map {
MinimalProductModel(
skuProduct = it.skuProduct,
nameProduct = it.nameProduct,
imgProduct = it.variants.first().images.first(),
categoryItem = it.categoryItem,
price = it.price,
discountPercentage = it.discount
)
} ?: lastProductsList
} else {
lastProductsList
}
) { minimalProductModel, index ->
ProductItem(minimalProductModel) {
productsResult?.response?.get(index)?.let { modelSelected ->
showProductViewModel.setTopProductModel(modelSelected)
navigator.navigate(ProductClientScreen.ShowProductClient.route)
}
}
}
}
}
item {
Card(
modifier = Modifier
.padding(top = 30.dp)
.fillMaxWidth(),
shape = RectangleShape,
elevation = 5.dp
) {
CategoryListContainer()
}
}
item {
Card(
modifier = Modifier
.padding(top = 30.dp, bottom = 40.dp)
.fillMaxWidth(),
shape = RectangleShape,
elevation = 5.dp
) {
HorizontalContainerListItem(
startText = "Ofertas",
endText = "Ver todos",
listItem = lastProductsList
) { minimalProductModel, index ->
ProductItem(minimalProductModel) {
navigator.navigate(ProductClientScreen.ShowProductClient.route)
}
}
}
}
}
}
it.calculateBottomPadding()
})
}
@Composable
fun TopContainer() {
Column {
AutoSliding()
CategoryHorizontalContainer()
}
}
@Composable
fun CategoryHorizontalContainer() {
LazyRow(
modifier = Modifier
.background(White)
) {
items(4) {
CategoryItem()
}
}
}
@Composable
fun BrandingContainer(
modifier: Modifier = Modifier,
hideTitle: Boolean = false
) {
Column(
modifier = modifier
.background(White)
) {
if (!hideTitle) {
BoldText(
modifier = Modifier.padding(start = 30.dp, top = 20.dp),
text = "Marcas",
color = Black,
fontSize = 20.sp
)
}
BrandingHorizontal(
modifier = Modifier.padding(
top = 30.dp,
bottom = 35.dp
)
)
}
}
@Composable
fun CategoryListContainer() {
Column(
modifier = Modifier
.background(White)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
BoldText(
modifier = Modifier.padding(start = 30.dp, top = 20.dp),
text = "Tecnologia", color = Black,
fontSize = 20.sp
)
}
LazyRow(
modifier = Modifier
.padding(
top = 30.dp,
bottom = 35.dp
)
) {
items(10) { index ->
CategorySelectorItem(
index % 2 != 0,
categorySelectorColors[index % categorySelectorColors.size]
)
}
}
}
}
@Composable
fun AutoSliding() {
val promotion = listOf(
PromotionItem("Title one", "pager_one.png"),
PromotionItem("Title two", "pager_two.png")
)
val page = rememberSaveable {
mutableStateOf(START_INDEX)
}
LaunchedEffect(Unit) {
while (true) {
yield()
delay(3000)
if (page.value == 0) {
page.value += 1
} else {
page.value = 0
}
}
}
Column(
modifier = Modifier
.wrapContentSize()
.background(White),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(resource = DrawableResource(promotion[0].imgUrl)),
contentDescription = promotion[page.value].title,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxSize()
)
}
} | 0 | Kotlin | 0 | 0 | 91db61b2632874e897148b99c13ffbb01011ce7a | 16,754 | AllenMultiplatform | Apache License 2.0 |
AstroYoga/core-network/src/main/java/com/shushant/astroyoga/network/utils/Extensions.kt | ShushantTiwari-ashu | 667,410,698 | false | null | package com.shushant.astroyoga.network.utils
import kotlinx.serialization.json.Json
import timber.log.Timber
import javax.inject.Singleton
@Singleton
val json = Json { encodeDefaults = true }
const val HOROSCOPE = "horoscope"
const val LOCATIONS = "https://nominatim.openstreetmap.org/"
const val ASTROYOGA_URL = "http://URL/v1/"
const val CREATE_USER = "create"
suspend fun <T : Any> handleRequest(requestFunc: suspend () -> T): Either<T> {
return try {
val resposne = requestFunc.invoke()
Either.success(resposne)
} catch (he: Exception) {
Timber.e(he.localizedMessage)
Either.error(he.message ?: "")
}
} | 0 | Kotlin | 0 | 0 | 9882d51d4a1d975249109c097da0c7b141e6ff69 | 655 | AstroYoga-Full-kotlin-stack-App | Apache License 2.0 |
src/commonMain/kotlin/org/scriptonbasestar/validation/constraint/prop-constraint.kt | ScriptonBasestar-io | 465,352,777 | false | null | package org.scriptonbasestar.validation.constraint
import org.scriptonbasestar.validation.Constraint
import org.scriptonbasestar.validation.builder.ValidationBuilderBase
import org.scriptonbasestar.validation.util.format
fun <T> ValidationBuilderBase<T>.const(expected: T, hint: String? = null) =
addConstraint(
hint ?: "must be {0}".format(expected?.let { "'$it'" } ?: "null"),
) { expected == it }
inline fun <reified T> ValidationBuilderBase<T>.uniqueItems(unique: Boolean, hint: String? = null): Constraint<T> =
addConstraint(
hint ?: "all items must be unique"
) {
!unique || when (it) {
is Iterable<*> -> it.distinct().count() == it.count()
is Array<*> -> it.distinct().count() == it.count()
else -> throw IllegalStateException("uniqueItems can not be applied to type ${T::class}")
}
}
| 0 | Kotlin | 0 | 0 | 568458da4a20dd9082d71bdc63a269267c0f555e | 883 | sb-validation-dsl | MIT License |
app/src/test/java/com/duckduckgo/app/onboarding/ui/OnboardingPageManagerTest.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.app.onboarding.ui
import com.duckduckgo.app.browser.defaultbrowsing.DefaultBrowserDetector
import com.duckduckgo.app.global.DefaultRoleBrowserDialog
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class OnboardingPageManagerTest {
private lateinit var testee: OnboardingPageManager
private val onboardingPageBuilder: OnboardingPageBuilder = mock()
private val mockDefaultBrowserDetector: DefaultBrowserDetector = mock()
private val defaultRoleBrowserDialog: DefaultRoleBrowserDialog = mock()
@Before
fun setup() {
testee = OnboardingPageManagerWithTrackerBlocking(
defaultRoleBrowserDialog,
onboardingPageBuilder,
mockDefaultBrowserDetector,
)
}
@Test
fun whenDDGIsNotDefaultBrowserThenExpectedOnboardingPagesAreTwo() {
configureDeviceSupportsDefaultBrowser()
whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false)
whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false)
testee.buildPageBlueprints()
assertEquals(2, testee.pageCount())
}
@Test
fun whenDDGIsNotDefaultBrowserAndShouldShowBrowserDialogThenExpectedOnboardingPagesAre1() {
configureDeviceSupportsDefaultBrowser()
whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(false)
whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true)
testee.buildPageBlueprints()
assertEquals(1, testee.pageCount())
}
@Test
fun whenDDGAsDefaultBrowserThenSinglePageOnBoarding() {
configureDeviceSupportsDefaultBrowser()
whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true)
whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false)
testee.buildPageBlueprints()
assertEquals(1, testee.pageCount())
}
@Test
fun whenDDGAsDefaultBrowserAndShouldShowBrowserDialogThenSinglePageOnBoarding() {
configureDeviceSupportsDefaultBrowser()
whenever(mockDefaultBrowserDetector.isDefaultBrowser()).thenReturn(true)
whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true)
testee.buildPageBlueprints()
assertEquals(1, testee.pageCount())
}
@Test
fun whenDeviceDoesNotSupportDefaultBrowserThenSinglePageOnBoarding() {
configureDeviceDoesNotSupportDefaultBrowser()
whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(false)
testee.buildPageBlueprints()
assertEquals(1, testee.pageCount())
}
@Test
fun whenDeviceDoesNotSupportDefaultBrowserAndShouldShowBrowserDialogThenSinglePageOnBoarding() {
configureDeviceDoesNotSupportDefaultBrowser()
whenever(defaultRoleBrowserDialog.shouldShowDialog()).thenReturn(true)
testee.buildPageBlueprints()
assertEquals(1, testee.pageCount())
}
private fun configureDeviceSupportsDefaultBrowser() {
whenever(mockDefaultBrowserDetector.deviceSupportsDefaultBrowserConfiguration()).thenReturn(true)
}
private fun configureDeviceDoesNotSupportDefaultBrowser() {
whenever(mockDefaultBrowserDetector.deviceSupportsDefaultBrowserConfiguration()).thenReturn(false)
}
}
| 0 | Kotlin | 0 | 0 | 54351d039b85138a85cbfc7fc3bd5bc53637559f | 3,400 | DuckDuckGo | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/repository/DogRepository.kt | yoshida0261 | 342,434,882 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class DogRepository {
val list = listOf<Dog>(
Dog("taro", 0, R.drawable.dog1, "生まれたばかりのかわいい柴犬"),
Dog("jiro", 2, R.drawable.dog2, "細めた目がかわいい柴犬"),
Dog("sabro", 5, R.drawable.dog3, "きりっとした顔がかわいい柴犬"),
Dog("siro", 4, R.drawable.dog4, "出した舌がかわいい柴犬"),
Dog("goro", 2, R.drawable.dog5, "コロンとした姿がかわいい柴犬")
)
fun getDogData(): List<Dog> {
return list
}
}
data class Dog(val name: String, val age: Int, val image: Int, val descript: String)
| 11 | Kotlin | 0 | 0 | 8b2d83392229223c20e6912aceabcf72895eecdf | 1,768 | jetpackdog | Apache License 2.0 |
korge-core/src/korlibs/render/TouchEventHandler.kt | korlibs | 80,095,683 | false | {"Kotlin": 4210038, "C": 105670, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 1068, "Shell": 439, "CMake": 202, "Batchfile": 41, "CSS": 33} | package korlibs.render
import korlibs.datastructure.*
import korlibs.datastructure.lock.*
import korlibs.event.*
class TouchEventHandler {
@PublishedApi
internal val lock = NonRecursiveLock()
@PublishedApi
internal val touchesEventPool = Pool { TouchEvent() }
@PublishedApi
internal var lastTouchEvent: TouchEvent = TouchEvent()
inline fun handleEvent(gameWindow: GameWindow, kind: TouchEvent.Type, emitter: (TouchEvent) -> Unit) {
val currentTouchEvent = lock {
val currentTouchEvent = touchesEventPool.alloc()
currentTouchEvent.copyFrom(lastTouchEvent)
currentTouchEvent.startFrame(kind)
emitter(currentTouchEvent)
currentTouchEvent.endFrame()
lastTouchEvent.copyFrom(currentTouchEvent)
currentTouchEvent
}
gameWindow.queue {
try {
gameWindow.dispatch(currentTouchEvent)
} finally {
lock { touchesEventPool.free(currentTouchEvent) }
}
}
}
}
| 464 | Kotlin | 123 | 2,497 | 1a565007ab748e00a4d602fcd78f7d4032afaf0b | 1,064 | korge | Apache License 2.0 |
taxiql-query-engine/src/test/java/com/orbitalhq/VyneProjectionTest.kt | orbitalapi | 541,496,668 | false | {"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337} | package com.orbitalhq
import app.cash.turbine.test
import app.cash.turbine.testIn
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.common.base.Stopwatch
import com.orbitalhq.models.*
import com.orbitalhq.models.facts.FactBag
import com.orbitalhq.models.json.parseJson
import com.orbitalhq.models.json.parseJsonCollection
import com.orbitalhq.models.json.parseJsonModel
import com.orbitalhq.models.json.parseKeyValuePair
import com.orbitalhq.query.*
import com.orbitalhq.query.projection.ProjectionProvider
import com.orbitalhq.schemas.OperationInvocationException
import com.orbitalhq.schemas.OperationNames
import com.orbitalhq.schemas.Type
import com.orbitalhq.schemas.fqn
import com.orbitalhq.schemas.taxi.TaxiSchema
import com.orbitalhq.utils.Benchmark
import com.orbitalhq.utils.StrategyPerformanceProfiler
import com.winterbe.expekt.expect
import com.winterbe.expekt.should
import io.kotest.matchers.collections.shouldContainInOrder
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import lang.taxi.utils.log
import lang.taxi.utils.quoted
import org.junit.Ignore
import org.junit.Test
import java.math.BigDecimal
import java.time.Instant
import java.util.concurrent.TimeUnit
import kotlin.test.assertFailsWith
import kotlin.test.fail
import kotlin.time.ExperimentalTime
@ExperimentalCoroutinesApi
@ExperimentalTime
class VyneProjectionTest {
val testSchema = """
// Primitives
type OrderId inherits String
type TradeId inherits String
type OrderDate inherits Date
type Price inherits Decimal
type TradeNo inherits String
model CommonOrder {
id: OrderId
date: OrderDate
tradeNo : TradeNo
}
model CommonTrade {
id: TradeId
orderId: OrderId
price: Price
}
model Order {}
model Trade {}
// Broker specific types
type Broker1Order inherits Order {
broker1ID: OrderId
broker1Date: OrderDate
broker1TradeId: TradeId
}
type Broker1Trade inherits Trade {
broker1TradeID: TradeId
@Id
broker1OrderID: OrderId
broker1Price: Price
broker1TradeNo: TradeNo
}
// services
service Broker1Service {
operation getBroker1Orders( start : OrderDate, end : OrderDate) : Broker1Order[] (OrderDate >= start, OrderDate < end)
operation getBroker1Trades( orderId: OrderId) : Broker1Trade[]
operation findOneByOrderId( orderId: OrderId ) : Broker1Trade
operation getBroker1TradesForOrderIds( orderIds: OrderId[]) : Broker1Trade[]
operation findSingleByOrderID( id : OrderId ) : Broker1Order( OrderId = id )
}
""".trimIndent()
@Test
fun `Should throw error when there is no discovery path and model is closed`() = runBlocking {
val schemaStr = """
closed model Film {
id : FilmId inherits Int
}
""".trimIndent()
val schema = TaxiSchema.from(schemaStr)
val (vyne, _) = testVyne(schema)
val exception = assertFailsWith<UnresolvedTypeInQueryException> {
vyne.query(
"""
find { Film } as {
filmId: FilmId
}
""".trimIndent()
).firstRawObject()
}
exception.message!!.shouldBe("No data sources were found that can return Film")
}
@Test
fun `tail spin`() = runBlocking {
val schemaStr = """
type Puid inherits Int
type CfiCode inherits String
type ProductCode inherits String
type ProductType inherits String
model CfiToPuid {
@Id
@PrimaryKey
cfiCode : CfiCode? by column("CFICode")
puid : Puid? by column("PUID")
}
model Product {
code: ProductCode
productType: ProductType
puid: Puid
}
model Target {
@FirstNotEmpty code: ProductCode?
productType: ProductType
cfiCode : CfiCode
@FirstNotEmpty puid : Puid?
}
model Order {
cfiCode : CfiCode
}
@Datasource
service CfiToPuidCaskService {
operation findSingleByCfiCode( id : CfiCode ) : CfiToPuid( CfiCode == id )
}
@Datasource
service MockCaskService {
operation findSingleByPuid( id : Puid ) : Product( Puid == id )
}
@Datasource
service OrderService {
operation `findAll`( ) : Order[]
}
""".trimIndent()
val schema = TaxiSchema.from(schemaStr)
val (vyne, stubService) = testVyne(schema)
stubService.addResponse(
"findSingleByCfiCode",
vyne.parseJsonModel(
"CfiToPuid", """{
"cfiCode": "XXX",
"puid": null
}"""
)
)
stubService.addResponse("findSingleByPuid") { _, parameters ->
throw java.lang.IllegalArgumentException("")
}
stubService.addResponse(
"`findAll`",
vyne.parseJsonModel(
"Order[]", """
[
{
"cfiCode": "XXX"
}
]
"""
)
)
val queryResult = vyne.query(
"""
find {
Order[]
} as Target[]""".trimIndent()
)
queryResult.results.test {
expectTypedObject()
awaitComplete()
}
}
@Test
fun `can perform simple projection`() = runBlocking {
val (vyne, _) = testVyne(
"""
type FirstName inherits String
type LastName inherits String
type PersonId inherits String
model Person {
id : PersonId
firstName : FirstName
lastName : LastName
}
""".trimIndent()
)
vyne.addModel(vyne.parseJsonModel("Person", """{ "id" : "1" , "firstName" : "Jimmy", "lastName" : "Schmit" } """))
val result = vyne.query("""find { Person } as { first : FirstName }""")
val list = result.rawResults
.test {
expectRawMap().should.equal(mapOf("first" to "Jimmy"))
awaitComplete()
}
}
@Test
fun `project by enriching from other services`() = runBlocking {
val schemaStr = """
type Symbol inherits String
type Field1 inherits String
type ParentType inherits String
type ChildType inherits ParentType
type GrandChildType inherits ChildType
type ProvidedByService inherits String
model ServiceData {
@Id
input : ChildType
field: ProvidedByService
}
model Target {
id: Symbol
field1: Field1
field2: ProvidedByService
}
model Order {
id: Symbol
field1: Field1
child: ChildType
}
@DataSource
service HelperService {
operation getData( input : ChildType) : ServiceData
}
service OrderService {
operation `findAll`( ) : Order[]
}
""".trimIndent()
val schema = TaxiSchema.from(schemaStr)
val (vyne, stubService) = testVyne(schema)
stubService.addResponse(
"getData",
vyne.parseJsonModel(
"ServiceData", """{
"field": "This is Provided By External Service"
}"""
)
)
stubService.addResponse(
"`findAll`",
vyne.parseJsonModel(
"Order[]", """
[
{
"id": "id1",
"field1": "Field - 1",
"child": "Child 1"
},
{
"id": "id2",
"field1": "Field - 2",
"child": "Child 2"
}
]
"""
)
)
val queryResult = vyne.query(
"""
find {
Order[]
} as Target[]""".trimIndent()
)
queryResult.results.test {
expectTypedObject()["field2"].value.should.equal("This is Provided By External Service")
expectTypedObject()["field2"].value.should.equal("This is Provided By External Service")
awaitComplete()
}
}
@Test
@Ignore("Querying on base types has been disabled: See ADR 20240215-find-does-not-query-on-base-types/")
fun `project an array of Orders to the array of CommonOrder`() = runBlocking {
// prepare
val schema = """
type OrderDate inherits Date
type OrderId inherits String
type UserId inherits String
type UserName inherits String
model CommonOrder {
id: OrderId
date: OrderDate
traderId: UserId
traderName: UserName
}
model Order {
}
type Broker1Order inherits Order {
broker1ID: OrderId
broker1Date: OrderDate
traderId: UserId
}
type Broker2Order inherits Order {
broker2ID: OrderId
broker2Date: OrderDate
}
// operations
service Broker1Service {
operation getBroker1Orders( start : OrderDate, end : OrderDate) : Broker1Order[] (OrderDate >= start && OrderDate < end)
}
service Broker2Service {
operation getBroker2Orders( start : OrderDate, end : OrderDate) : Broker2Order[] (OrderDate >= start && OrderDate < end)
}
service UserService {
operation getUserNameFromId(userId: UserId):UserName
}
""".trimIndent()
val noOfRecords = 100
val (vyne, stubService) = testVyne(schema)
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker1Order[]", generateBroker1OrdersWithTraderId(noOfRecords))
}
stubService.addResponse("getBroker2Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker2Order[]", "[]")
}
stubService.addResponse("getUserNameFromId") { _, parameters ->
parameters.should.have.size(1)
val userName = when (val userId = parameters[0].second.value as String) {
"trader0" -> "<NAME>"
"trader1" -> "<NAME>"
else -> TODO("Unknown userId=$userId")
}
listOf(vyne.parseKeyValuePair("UserName", userName))
}
runTest {
val query = """
find {
Order[](OrderDate >= "2000-01-01" && OrderDate < "2020-12-30")
} as CommonOrder[]""".trimIndent()
val turbine = vyne.query(query).rawResults.testIn(this)
val resultList = turbine.expectMany<Map<String, Any?>>(100)
// Note - don't assert using indexes, as result order is indeterminate given
// parallel execution.
resultList.should.contain.elements(
mapOf(
"id" to "broker1Order1",
"date" to "2020-01-01",
"traderId" to "trader1",
"traderName" to "<NAME>"
),
mapOf(
"id" to "broker1Order1",
"date" to "2020-01-01",
"traderId" to "trader0",
"traderName" to "<NAME>"
)
)
turbine.awaitComplete()
}
}
private fun generateBroker1OrdersWithTraderId(noOfRecords: Int): String {
val buf = StringBuilder()
buf.append("[")
for (i in 1..noOfRecords) {
buf.append("""{ "broker1ID" : "broker1Order1", "broker1Date" : "2020-01-01", "traderId" : "trader${i % 2}"}""")
if (i < noOfRecords) {
buf.append(",")
}
}
buf.append("]")
return buf.toString()
}
@Ignore(
"""
This test is ignored, As we stopped adding facts into QueryContext for:
1. Remote service call results.
2. Arguments that we populate for remote calls.
We expect
orderInstrumentType: OrderInstrumentType
of CommonOrder in the result equals to OrderInstrumentType1
but since we stopped adding facts for 1. and 2. it is populated as null and hence this fails.
Revisit this when 0.18.x becomes stable.
"""
)
@Test
fun `project to CommonOrder and resolve Enum synonyms and Instruments`() = runBlocking {
// prepare
val schema = """
// Primitives
type OrderId inherits String
type OrderDate inherits Date
type InstrumentId inherits String
type InstrumentDescription inherits String
// common types
type Instrument {
@Id
id: InstrumentId
instrument_type: InstrumentType
description: InstrumentDescription
}
enum InstrumentType {
Type1,
Type2
}
enum OrderInstrumentType {
OrderInstrumentType1 synonym of InstrumentType.Type1,
OrderInstrumentType2 synonym of InstrumentType.Type2
}
enum BankDirection {
BUY("sell"),
SELL("buy")
}
model CommonOrder {
id: OrderId
date: OrderDate
direction: BankDirection
instrument: Instrument
orderInstrumentType: OrderInstrumentType
}
model Order {}
// Broker specific types
enum Broker1Direction {
BankBuys("bankbuys") synonym of BankDirection.BUY,
BankSells("banksells") synonym of BankDirection.SELL
}
type Broker1Order inherits Order {
broker1ID: OrderId
broker1Date: OrderDate
broker1Direction: Broker1Direction
instrumentId: InstrumentId
}
// services
service Broker1Service {
operation getBroker1Orders( start : OrderDate, end : OrderDate) : Broker1Order[] (OrderDate >= start, OrderDate < end)
}
service InstrumentService {
operation getInstrument( instrument: InstrumentId ) : Instrument
}
""".trimIndent()
val noOfRecords = 2
val (vyne, stubService) = testVyne(schema)
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
val orders = generateBroker1Orders(noOfRecords)
TypedInstance.from(vyne.type("Broker1Order[]"), orders, vyne.schema) as List<TypedInstance>
}
stubService.addResponse("getInstrument") { _, parameters ->
parameters.should.have.size(1)
val instrumentId = parameters[0].second.value as String
val (instrumentDescription, instrumentType) = when (instrumentId) {
"instrument0" -> "UST 2Y5Y10Y" to "Type1"
"instrument1" -> "GBP/USD 1Year Swap" to "Type2"
else -> TODO("Unknown userId=$instrumentId")
}
val instrumentResponse =
"""{"id":"$instrumentId", "description": "$instrumentDescription", "instrument_type": "$instrumentType"}"""
listOf(vyne.parseJson("Instrument", instrumentResponse))
}
runTest {
val turbine = vyne
.query("""find { Order[] (OrderDate >= "2000-01-01", OrderDate < "2020-12-30") } as CommonOrder[]""".trimIndent())
.rawResults
.testIn(this)
val resultList = turbine.expectManyRawMaps(noOfRecords)
resultList[0].should.equal(
mapOf(
"id" to "broker1Order0",
"date" to "2020-01-01",
"direction" to "sell",
"instrument" to mapOf(
"id" to "instrument0",
"description" to "UST 2Y5Y10Y",
"instrument_type" to "Type1"
),
"orderInstrumentType" to "OrderInstrumentType1"
)
)
resultList[1].should.equal(
mapOf(
"id" to "broker1Order1",
"date" to "2020-01-01",
"direction" to "sell",
"instrument" to mapOf(
"id" to "instrument1",
"description" to "GBP/USD 1Year Swap",
"instrument_type" to "Type2"
),
"orderInstrumentType" to "OrderInstrumentType2"
)
)
turbine.awaitComplete()
}
}
@Test
@Ignore
fun `project to CommonOrder with Trades`() = runBlocking {
// TODO confirm how the mappings should look like
val noOfRecords = 100
val schema = """
// Primitives
type OrderId inherits String
type TradeId inherits String
type OrderDate inherits Date
type Price inherits Decimal
type TradeNo inherits String
type IdentifierCl inheritss inherits String
enum Direction {
BUY,
SELL
}
model CommonOrder {
id: OrderId
date: OrderDate
tradeNo : TradeNo
identifierType: IdentifierClass
direction: Direction
}
model CommonTrade {
id: TradeId
orderId: OrderId
price: Price
}
model Order {}
model Trade {}
type extension CommonOrder {
identifierType: IdentifierClass = 'ISIN'
direction: Direction = Direction.SELL
}
// Broker specific types
type Broker1Order inherits Order {
broker1ID: OrderId
broker1Date: OrderDate
broker1TradeId: TradeId
}
type Broker1Trade inherits Trade {
broker1TradeID: TradeId
broker1OrderID: OrderId
broker1Price: Price
broker1TradeNo: TradeNo
}
// services
service Broker1Service {
operation getBroker1Orders( start : OrderDate, end : OrderDate) : Broker1Order[] (OrderDate >= start, OrderDate < end)
operation getBroker1Trades( orderId: OrderId) : Broker1Trade[]
operation findOneByOrderId( orderId: OrderId ) : Broker1Trade
operation getBroker1TradesForOrderIds( orderIds: OrderId[]) : Broker1Trade[]
}
""".trimIndent()
val (vyne, stubService) = testVyne(schema)
val orders = generateBroker1Orders(noOfRecords)
val trades = generateOneBroker1TradeForEachOrder(noOfRecords)
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker1Order[]", orders)
}
stubService.addResponse("getBroker1Trades") { _, parameters ->
parameters.should.have.size(1)
vyne.parseJsonCollection("Broker1Trade[]", trades)
}
var getBroker1TradesForOrderIdsInvocationCount = 0
stubService.addResponse("getBroker1TradesForOrderIds") { _, parameters ->
parameters.should.have.size(1)
val orderIds = parameters[0].second.value as List<TypedValue>
val buf = StringBuilder("[")
val json = orderIds.mapIndexed { index, typedValue ->
generateBroker1Trades(typedValue.value as String, index)
}.joinToString(",", prefix = "[", postfix = "]")
getBroker1TradesForOrderIdsInvocationCount++
vyne.parseJsonCollection("Broker1Trade[]", json)
}
var findOneByOrderIdInvocationCount = 0
stubService.addResponse("findOneByOrderId") { _, parameters ->
parameters.should.have.size(1)
val orderId = parameters[0].second.value as String
findOneByOrderIdInvocationCount++
listOf(
vyne.parseJsonModel(
"Broker1Trade", """
{
"broker1OrderID" : "broker1Order$orderId",
"broker1TradeID" : "trade_id_$orderId",
"broker1Price" : 10.1,
"broker1TradeNo": "trade_no_$orderId"
}
""".trimIndent()
)
)
}
runTest {
val turbine = vyne
.query("""find { Order[] (OrderDate >= "2000-01-01", OrderDate < "2020-12-30") } as CommonOrder[]""".trimIndent())
.rawResults
.testIn(this)
val resultList = turbine.expectManyRawMaps(noOfRecords)
resultList.forEachIndexed { index, result ->
result.should.equal(
mapOf(
"id" to "broker1Order$index",
"date" to "2020-01-01",
"tradeNo" to "trade_no_broker1Order$index",
"identifierType" to "ISIN",
"direction" to "Direction.SELL"
)
)
}
turbine.awaitComplete()
}
// TODO
// ProjectionHeuristics not currently working as part of reactive refactor. Need to revisit this (LENS-527).
// findOneByOrderIdInvocationCount.should.equal(0)
// getBroker1TradesForOrderIdsInvocationCount.should.equal(1)
}
@Test
@Ignore("One-to-many not currenty supported")
fun `One to Many Mapping Projection with a date between query`() = runBlocking {
val (vyne, stubService) = testVyne(testSchema)
// 1 order and 3 matching trades.
val numberOfOrders = 1
val numberOfCorrespondingTrades = 3
// Generate 2 orders/
// 1 order will have 3 corresponding trades whereas the other order has none..
val orders = generateBroker1Orders(numberOfOrders + 1)
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker1Order[]", orders)
}
var getBroker1TradesForOrderIdsInvocationCount = 0
stubService.addResponse("getBroker1TradesForOrderIds") { _, parameters ->
parameters.should.have.size(1)
val orderIds = parameters[0].second.value as List<TypedValue>
val json = (0 until numberOfCorrespondingTrades).map { index ->
generateBroker1Trades(orderIds.first().value as String, 0, index, "10.$index")
}.joinToString(",", prefix = "[", postfix = "]")
getBroker1TradesForOrderIdsInvocationCount++
vyne.parseJsonCollection("Broker1Trade[]", json)
}
var findOneByOrderIdInvocationCount = 0
stubService.addResponse("findOneByOrderId") { _, parameters ->
parameters.should.have.size(1)
val orderId = parameters[0].second.value as String
findOneByOrderIdInvocationCount++
listOf(TypedNull.create(vyne.type("Broker1Trade")))
}
// act
val result =
vyne.query("""find { Order[] (OrderDate >= "2000-01-01", OrderDate < "2020-12-30") } as CommonOrder[]""".trimIndent())
// assert
expect(result.isFullyResolved).to.be.`true`
val resultList = result.rawObjects()
resultList.size.should.be.equal(numberOfCorrespondingTrades + 1)
resultList.forEachIndexed { index, typedObject ->
if (index < 3) {
// First three results corresponding to 1 order 3 trades setup
typedObject.should.equal(
mapOf(
"id" to "broker1Order0",
"date" to "2020-01-01",
"tradeNo" to "trade_no_$index"
)
)
} else {
//last result, corresponding to an order without a trade and hence it doesn't contain a tradeNo.
typedObject.should.equal(
mapOf(
"id" to "broker1Order1",
"date" to "2020-01-01",
"tradeNo" to null // See TypedObjectFactory.build() for discussion on returning nulls
)
)
}
}
findOneByOrderIdInvocationCount.should.equal(1) // 1 call for the order without a trade.
getBroker1TradesForOrderIdsInvocationCount.should.equal(1)
Unit
}
@Test
@Ignore("One-to-many not supported currently")
fun `One to Many Mapping Projection with an Id equals query`() = runBlocking {
val (vyne, stubService) = testVyne(testSchema)
// 1 order and 3 matching trades.
val numberOfOrders = 1
val numberOfCorrespondingTrades = 3
// Generate 2 orders/
// 1 order will have 3 corresponding trades whereas the other order has none..
val orders = generateBroker1Orders(numberOfOrders + 1)
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker1Order[]", orders)
}
var getBroker1TradesForOrderIdsInvocationCount = 0
stubService.addResponse("getBroker1TradesForOrderIds") { _, parameters ->
parameters.should.have.size(1)
val orderIds = parameters[0].second.value as List<TypedValue>
val json = (0 until numberOfCorrespondingTrades).map { index ->
generateBroker1Trades(orderIds.first().value as String, 0, index, "10.$index")
}.joinToString(",", prefix = "[", postfix = "]")
getBroker1TradesForOrderIdsInvocationCount++
vyne.parseJsonCollection("Broker1Trade[]", json)
}
var findOneByOrderIdInvocationCount = 0
stubService.addResponse("findOneByOrderId") { _, parameters ->
parameters.should.have.size(1)
val orderId = parameters[0].second.value as String
findOneByOrderIdInvocationCount++
listOf(TypedNull.create(vyne.type("Broker1Trade")))
}
//find by order Id and project
stubService.addResponse("findSingleByOrderID") { _, parameters ->
parameters.should.have.size(1)
if (parameters.first().second.value == "broker1Order0") {
listOf(vyne.parseJsonModel("Broker1Order", generateBroker1Order(0)))
} else {
listOf(vyne.parseJsonModel("Broker1Order", "{}"))
}
}
val findByOrderIdResult =
vyne.query("""find { Order (OrderId = "broker1Order0") } as CommonOrder[]""".trimIndent())
val result = findByOrderIdResult.results.toList()
result.should.not.be.empty
findByOrderIdResult.typedInstances().should.have.size(numberOfCorrespondingTrades)
Unit
}
@Test
@Ignore("One-to-many not currently supported")
fun `One to Many Mapping Projection with an Id equals query returning zero match`() = runBlocking {
val (vyne, stubService) = testVyne(testSchema)
// 1 order and 3 matching trades.
val numberOfOrders = 1
val numberOfCorrespondingTrades = 3
// Generate 2 orders/
// 1 order will have 3 corresponding trades whereas the other order has none..
val orders = generateBroker1Orders(numberOfOrders + 1)
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker1Order[]", orders)
}
var getBroker1TradesForOrderIdsInvocationCount = 0
stubService.addResponse("getBroker1TradesForOrderIds") { _, parameters ->
parameters.should.have.size(1)
val orderIds = parameters[0].second.value as List<TypedValue>
val json = (0 until numberOfCorrespondingTrades).map { index ->
generateBroker1Trades(orderIds.first().value as String, 0, index, "10.$index")
}.joinToString(",", prefix = "[", postfix = "]")
getBroker1TradesForOrderIdsInvocationCount++
vyne.parseJsonCollection("Broker1Trade[]", json)
}
var findOneByOrderIdInvocationCount = 0
stubService.addResponse("findOneByOrderId") { _, parameters ->
parameters.should.have.size(1)
val orderId = parameters[0].second.value as String
findOneByOrderIdInvocationCount++
listOf(TypedNull.create(vyne.type("Broker1Trade")))
}
//find by order Id and project
stubService.addResponse("findSingleByOrderID") { _, parameters ->
parameters.should.have.size(1)
if (parameters.first().second.value == "broker1Order0") {
listOf(vyne.parseJsonModel("Broker1Order", generateBroker1Order(0)))
} else {
listOf(TypedNull.create(vyne.type("Broker1Order")))
// vyne.parseJsonModel("Broker1Order", "{}")
}
}
// find by a non-existing order Id and project
val noResult = vyne.query("""find { Order (OrderId = "MY SPECIAL ORDER ID") } as CommonOrder[]""".trimIndent())
noResult.typedInstances().should.be.empty
Unit
}
@Test
@Ignore("One-to-many not supported currently")
fun `Multiple orders with same id and multiple trades with same order Id`() = runBlocking {
val (vyne, stubService) = testVyne(testSchema)
val numberOfCorrespondingTrades = 3
// 2 orders (with same id) will have 3 corresponding trades
val orders = listOf(
generateBroker1Order(0, "2020-01-01"),
generateBroker1Order(0, "2021-01-01")
).joinToString(prefix = "[", postfix = "]")
stubService.addResponse("getBroker1Orders") { _, parameters ->
parameters.should.have.size(2)
vyne.parseJsonCollection("Broker1Order[]", orders)
}
var getBroker1TradesForOrderIdsInvocationCount = 0
stubService.addResponse("getBroker1TradesForOrderIds") { _, parameters ->
parameters.should.have.size(1)
val orderIds = parameters[0].second.value as List<TypedValue>
val json = (0 until numberOfCorrespondingTrades).map { index ->
generateBroker1Trades(orderIds.first().value as String, 0, index, "10.$index")
}.joinToString(prefix = "[", postfix = "]")
getBroker1TradesForOrderIdsInvocationCount++
vyne.parseJsonCollection("Broker1Trade[]", json)
}
var findOneByOrderIdInvocationCount = 0
stubService.addResponse("findOneByOrderId") { _, parameters ->
parameters.should.have.size(1)
val orderId = parameters[0].second.value as String
findOneByOrderIdInvocationCount++
listOf(TypedNull.create(vyne.type("Broker1Trade")))
}
// act
val result =
vyne.query("""find { Order[] (OrderDate >= "2000-01-01", OrderDate < "2020-12-30") } as CommonOrder[]""".trimIndent())
// assert
expect(result.isFullyResolved).to.be.`true`
val resultList = result.rawObjects()
resultList.should.have.size(2 * numberOfCorrespondingTrades)
resultList.forEachIndexed { index, resultMember ->
if (index < numberOfCorrespondingTrades) {
// First three results corresponding to 1 order 3 trades setup
resultMember.should.equal(
mapOf(
"id" to "broker1Order0",
"date" to "2020-01-01",
"tradeNo" to "trade_no_$index"
)
)
} else {
resultMember.should.equal(
mapOf(
"id" to "broker1Order0",
"date" to "2021-01-01",
"tradeNo" to "trade_no_${index - numberOfCorrespondingTrades}"
)
)
}
}
findOneByOrderIdInvocationCount.should.equal(0)
getBroker1TradesForOrderIdsInvocationCount.should.equal(1)
Unit
}
private fun generateBroker1Trades(
orderId: String,
index: Int,
tradeId: Int? = null,
price: String? = null
): String {
val brokerTraderId = tradeId?.let { "trade_id_$it" } ?: "trade_id_$index"
val brokerTradeNo = tradeId?.let { "trade_no_$it" } ?: "trade_no_$index"
val brokerPrice = price ?: "10.1"
return """
{
"broker1OrderID" : "$orderId",
"broker1TradeID" : "$brokerTraderId",
"broker1Price" : "$brokerPrice",
"broker1TradeNo": "$brokerTradeNo"
}
""".trimMargin()
}
private fun generateOneBroker1TradeForEachOrder(noOfRecords: Int): String {
val buf = StringBuilder("[")
for (i in 0 until noOfRecords) {
buf.append(
"""
{
"broker1OrderID" : "broker1Order$i",
"broker1TradeID" : "trade_id_$i",
"broker1Price" : "10.1",
"broker1TradeNo": "trade_no_$i"
}
""".trimMargin()
)
if (i < noOfRecords - 1) {
buf.append(",")
}
}
buf.append("]")
return buf.toString()
}
private fun generateBroker1Order(intSuffix: Int, date: String = "2020-01-01"): String {
return """
{
"broker1ID" : "broker1Order${intSuffix}",
"broker1Date" : "$date",
"broker1Direction" :
"bankbuys",
"instrumentId" : "instrument${intSuffix % 2}",
"broker1TradeId": "trade_id_$intSuffix"
}
""".trimMargin()
}
private fun generateBroker1Orders(noOfRecords: Int): String {
val buf = StringBuilder("[")
for (i in 0 until noOfRecords) {
buf.append(generateBroker1Order(i))
if (i < noOfRecords - 1) {
buf.append(",")
}
}
buf.append("]")
return buf.toString()
}
//
// @Test
// fun `missing Country does not break Client projection`() = runBlocking {
// // prepare
// val testSchema = """
// model Client {
// name : PersonName as String
// country : CountryCode as String
// }
// model Country {
// @Id
// countryCode : CountryCode
// countryName : CountryName as String
// }
// model ClientAndCountry {
// personName : PersonName
// countryName : CountryName
// }
//
// service MultipleInvocationService {
// operation getCustomers():Client[]
// operation getCountry(CountryCode): Country
// }
// """.trimIndent()
//
// val (vyne, stubService) = testVyne(testSchema)
// stubService.addResponse(
// "getCustomers", vyne.parseJsonCollection(
// "Client[]", """
// [
// { name : "Jimmy", country : "UK" },
// { name : "Devrim", country : "TR" }
// ]
// """.trimIndent()
// )
// )
//
// stubService.addResponse("getCountry") { _, parameters ->
// val countryCode = parameters.first().second.value!!.toString()
// if (countryCode == "UK") {
// listOf(vyne.parseJsonModel("Country", """{"countryCode": "UK", "countryName": "United Kingdom"}"""))
// } else {
// listOf(TypedObject(vyne.schema.type("Country"), emptyMap(), Provided))
// }
// }
//
// // act
// val result = vyne.query("""find { Client[] } as ClientAndCountry[]""".trimIndent())
//
// // assert
// result.rawResults.test {
// expectRawMap().should.equal(mapOf("personName" to "Jimmy", "countryName" to "United Kingdom"))
// expectRawMap().should.equal(mapOf("personName" to "Devrim", "countryName" to null))
// awaitComplete()
// }
// }
//
// @Test
// fun `duplicate matches with same values in projection is resolved without any errors`() = runBlocking {
// // prepare
// val testSchema = """
// type OrderId inherits String
// type TraderName inherits String
// type InstrumentId inherits String
// type MaturityDate inherits Date
// type TradeId inherits String
// type InstrumentName inherits String
// model Order {
// orderId: OrderId
// traderName : TraderName
// instrumentId: InstrumentId
// }
// model Instrument {
// @Id
// instrumentId: InstrumentId
// maturityDate: MaturityDate
// name: InstrumentName
// }
// model Trade {
// @Id
// orderId: OrderId
// maturityDate: MaturityDate
// tradeId: TradeId
// }
//
// model Report {
// orderId: OrderId
// tradeId: TradeId
// instrumentName: InstrumentName
// maturityDate: MaturityDate
// traderName : TraderName
// }
//
// service MultipleInvocationService {
// operation getOrders(): Order[]
// operation getTrades(orderIds: OrderId): Trade
// operation getTrades(orderIds: OrderId[]): Trade[]
// operation getInstrument(instrumentId: InstrumentId): Instrument
// }
// """.trimIndent()
//
// val maturityDate = "2025-12-01"
// val (vyne, stubService) = testVyne(testSchema)
// stubService.addResponse(
// "getOrders", vyne.parseJsonCollection(
// "Order[]", """
// [
// {
// "orderId": "orderId_0",
// "traderName": "john",
// "instrumentId": "Instrument_0"
// }
// ]
// """.trimIndent()
// )
// )
//
// stubService.addResponse(
// "getInstrument", vyne.parseJsonModel(
// "Instrument", """
// {
// "maturityDate": "$maturityDate",
// "instrumentId": "Instrument_0",
// "name": "2040-11-20 0.1 Bond"
// }
// """.trimIndent()
// )
// )
//
// stubService.addResponse(
// "getTrades", vyne.parseJsonCollection(
// "Trade[]", """
// [{
// "maturityDate": "$maturityDate",
// "orderId": "orderId_0",
// "tradeId": "Trade_0"
// }]
// """.trimIndent()
// )
// )
// val result = vyne.query("""find { Order[] } as Report[]""".trimIndent())
// result.isFullyResolved.should.be.`true`
// result.rawObjects().should.equal(
// listOf(
// mapOf(
// "orderId" to "orderId_0",
// "traderName" to "john",
// "tradeId" to "Trade_0",
// "instrumentName" to "2040-11-20 0.1 Bond",
// "maturityDate" to maturityDate
// )
// )
// )
// }
//
//
@Test
fun `can use calculated fields on output models`(): Unit = runBlocking {
val (vyne, _) = testVyne(
"""
type Quantity inherits Int
type Value inherits Int
type Cost inherits Int
model Input {
qty : Quantity
value : Value
}
model Output {
qty : Quantity
value : Value
cost : Cost by (this.qty * this.value)
}
""".trimIndent()
)
val input = vyne.parseJsonModel("Input", """{ "qty" : 100, "value" : 2 }""", source = Provided)
val output = vyne.from(input).build("Output").firstTypedObject()
output["cost"].value.should.equal(200)
}
@Test
fun `can use when by`(): Unit = runBlocking {
val (vyne, _) = testVyne(
"""
model Input {
str: StringPriceType inherits String
value : Price? inherits Decimal
}
enum PriceType {
Percentage("%"),
Basis("Bps")
}
model SampleType {
price: Price?
tempPriceType: StringPriceType?
priceType: PriceType? by when {
this.price == null -> null
this.price != null -> (PriceType) this.tempPriceType
}
}
""".trimIndent()
)
val input = vyne.parseJsonModel("Input", """{ "value": 100, "str": "Percentage" }""", source = Provided)
val result = vyne.from(input).build("SampleType")
.firstTypedObject()
result["priceType"].value.should.equal("Percentage")
Unit
}
@Test
fun `A service annotated with @DataSource will not be invoked twice`() = runBlocking {
val testSchema = """
model Client {
name : PersonName inherits String
country : CountryCode inherits String
}
model Country {
countryCode : CountryCode
countryName : CountryName inherits String
}
model ClientAndCountry {
personName : PersonName
countryName : CountryName
}
@Datasource
service MultipleInvocationService {
operation getCustomers():Client[]
operation getCountry(CountryCode): Country
}
""".trimIndent()
var getCountryInvoked = false
val (vyne, stubService) = testVyne(testSchema)
stubService.addResponse(
"getCustomers", vyne.parseJsonModel(
"Client[]", """
[
{ name : "Jimmy", country : "UK" },
{ name : "Devrim", country : "TR" }
]
""".trimIndent()
)
)
stubService.addResponse("getCountry") { _, parameters ->
getCountryInvoked = true
val countryCode = parameters.first().second.value!!.toString()
if (countryCode == "UK") {
listOf(vyne.parseJsonModel("Country", """{"countryCode": "UK", "countryName": "United Kingdom"}"""))
} else {
listOf(TypedObject(vyne.schema.type("Country"), emptyMap(), Provided))
}
}
// act
val result = vyne.query("""find { Client[] } as ClientAndCountry[]""".trimIndent())
result.rawResults.test {
expectRawMap().should.equal(mapOf("personName" to "Jimmy", "countryName" to null))
expectRawMap().should.equal(
mapOf(
"personName" to "Devrim",
"countryName" to null
) // See TypedObjectFactory.build() for discussion on returning nulls
)
getCountryInvoked.should.be.`false`
awaitComplete()
}
}
@Test
fun `All services referenced in @DataSource will not be invoked twice`() = runBlocking {
val testSchema = """
model Client {
name : PersonName inherits String
country : CountryCode inherits String
}
model Country {
countryCode : CountryCode
countryName : CountryName inherits String
}
model ClientAndCountry {
personName : PersonName
countryName : CountryName
}
service CountryService {
operation findByCountryCode(CountryCode): Country
}
@Datasource(exclude = "[[CountryService]]")
service MultipleInvocationService {
operation getCustomers():Client[]
operation getCountry(CountryCode): Country
}
""".trimIndent()
var getCountryInvoked = false
val (vyne, stubService) = testVyne(testSchema)
stubService.addResponse(
"findByCountryCode",
vyne.parseJsonModel(
"Country", """
{countryCode: "UK", countryName: "United Kingdom"}
""".trimIndent()
)
)
stubService.addResponse(
"getCustomers", vyne.parseJsonModel(
"Client[]", """
[
{ name : "Jimmy", country : "UK" },
{ name : "Devrim", country : "TR" }
]
""".trimIndent()
)
)
stubService.addResponse("getCountry") { _, parameters ->
getCountryInvoked = true
val countryCode = parameters.first().second.value!!.toString()
if (countryCode == "UK") {
listOf(vyne.parseJsonModel("Country", """{"countryCode": "UK", "countryName": "United Kingdom"}"""))
} else {
listOf(TypedObject(vyne.schema.type("Country"), emptyMap(), Provided))
}
}
// act
val result = vyne.query("""find { Client[] } as ClientAndCountry[]""".trimIndent())
result.rawResults
.test {
expectRawMap().should.equal(mapOf("personName" to "Jimmy", "countryName" to null))
expectRawMap().should.equal(
mapOf(
"personName" to "Devrim",
"countryName" to null
)
)
getCountryInvoked.should.be.`false`
awaitComplete()
}
}
@Test
fun `should output offset correctly`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
model InputModel {
@Format( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
inputField: Instant
}
model OutputModel {
@Format(value ="yyyy-MM-dd'T'HH:mm:ss.SSSZ", offset = 60 )
myField : Instant
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
""".trimIndent()
)
val inputInstant1 = "2020-08-19T13:07:09.591Z"
val inputInstant2 = "2020-08-18T13:07:09.591Z"
val outputInstant1 = "2020-08-19T14:07:09.591+0100"
val outputInstant2 = "2020-08-18T14:07:09.591+0100"
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "inputField": "$inputInstant1" },
{ "inputField": "$inputInstant2" }
]
""".trimIndent()
)
)
val result = vyne.query("""find { InputModel[] } as OutputModel[]""".trimIndent())
result.rawObjects().should.equal(
listOf(
mapOf("myField" to outputInstant1),
mapOf("myField" to outputInstant2)
)
)
}
@Test
fun `should output offset correctly without any format`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
model InputModel {
@Format( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
inputField: Instant
}
model OutputModel {
@Format(offset = 60)
myField : Instant
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
""".trimIndent()
)
val inputInstant1 = "2020-08-19T13:07:09.591Z"
val inputInstant2 = "2020-08-18T13:07:09.591Z"
val outputInstant1 = "2020-08-19T14:07:09.591+01"
val outputInstant2 = "2020-08-18T14:07:09.591+01"
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "inputField": "$inputInstant1" },
{ "inputField": "$inputInstant2" }
]
""".trimIndent()
)
)
val result = vyne.query("""find { InputModel[] } as OutputModel[]""".trimIndent()).rawObjects()
result.shouldNotBeNull()
result.should.be.equal(
listOf(
mapOf("myField" to outputInstant1),
mapOf("myField" to outputInstant2)
)
)
}
@Test
fun `Calculated fields should be correctly set in projected type`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
type QtyFill inherits Decimal
type UnitMultiplier inherits Decimal
type FilledNotional inherits Decimal
model InputModel {
multiplier: UnitMultiplier = 2.0
qtyFill: QtyFill
}
model OutputModel {
qtyHit : QtyFill?
unitMultiplier: UnitMultiplier?
filledNotional : FilledNotional? by (this.qtyHit * this.unitMultiplier)
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "qtyFill": 200, "multiplier": 2 }
]
""".trimIndent()
)
)
val result = vyne.query("""find { InputModel[] } as OutputModel[]""".trimIndent())
result.rawObjects().should.be.equal(
listOf(
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("2"),
"filledNotional" to BigDecimal("400")
)
)
)
}
@Test
fun `when calculating fields then lineage is set on output`() = runBlocking {
val (vyne, stubs) = testVyne(
"""
type Quantity inherits Int
type Price inherits Int
model Order {
quantity : Quantity
price : Price
}
model Output {
quantity : Quantity
price : Price
averagePrice : Decimal by (this.price / this.quantity)
}
service OrderService {
operation listOrders():Order[]
}
""".trimIndent()
)
// The below responseJson will trigger a divide-by-zero
val responseJson = """[
|{ "quantity" : 0 , "price" : 2 }
|]""".trimMargin()
stubs.addResponse(
"listOrders", vyne.parseJsonModel(
"Order[]", """[
|{ "quantity" : 100 , "price" : 2 },
|{ "quantity" : 0 , "price" : 2 }
|]""".trimMargin()
)
)
val queryResult = vyne.query("find { Order[] } as Output[]")
// val resultList = queryResult.results.toList()
// resultList.should.not.be.`null`
val outputCollection = queryResult.results.test {
val outputModel = expectTypedObject()
val averagePrice = outputModel["averagePrice"]
averagePrice.value.should.equal(0.02.toBigDecimal())
val averagePriceDataSource = averagePrice.source as EvaluatedExpression
averagePriceDataSource.expressionTaxi.should.equal("this.price / this.quantity")
averagePriceDataSource.inputs[0].value.should.equal(2)
averagePriceDataSource.inputs[0].source.should.equal(Provided)
val modelWithError = expectTypedObject()
val priceWithError = modelWithError["averagePrice"]
priceWithError.value.should.be.`null`
priceWithError.source.should.be.instanceof(FailedEvaluatedExpression::class.java)
val failedExpression = priceWithError.source as FailedEvaluatedExpression
failedExpression.errorMessage.should.equal("BigInteger divide by zero")
failedExpression.inputs[0].value.should.equal(2)
failedExpression.inputs[1].value.should.equal(0)
awaitComplete()
}
}
@Test
fun `should project to pure anonymous type with single field`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
type QtyFill inherits Decimal
type UnitMultiplier inherits Decimal
type FilledNotional inherits Decimal
type InputId inherits String
model InputModel {
multiplier: UnitMultiplier = 2.0
qtyFill: QtyFill
id: InputId
}
model OutputModel {
qtyHit : QtyFill?
unitMultiplier: UnitMultiplier?
filledNotional : FilledNotional? by (this.qtyHit * this.unitMultiplier)
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "qtyFill": 200, "multiplier": 2, "id": "input1" },
{ "qtyFill": 200, "multiplier": 2, "id": "input2" },
{ "qtyFill": 200, "multiplier": 2, "id": "input3" }
]
""".trimIndent()
)
)
val result = vyne.query(
"""
find {
InputModel[]
} as {
id
}[]
""".trimIndent()
)
result.rawObjects().should.be.equal(
listOf(
mapOf("id" to "input1"), mapOf("id" to "input2"), mapOf("id" to "input3")
)
)
}
@Test
fun `should project to pure anonymous type with multiple fields`() = runBlocking {
val (vyne, stubService) = testVyne(
"""
type QtyFill inherits Decimal
type UnitMultiplier inherits Decimal
type FilledNotional inherits Decimal
type InputId inherits String
type TraderId inherits String
type TraderName inherits String
type TraderSurname inherits String
model InputModel {
multiplier: UnitMultiplier = 2.0
qtyFill: QtyFill
id: InputId
traderId: TraderId
}
model OutputModel {
qtyHit : QtyFill?
unitMultiplier: UnitMultiplier?
filledNotional : FilledNotional? by (this.qtyHit * this.unitMultiplier)
}
model TraderInfo {
@Id
traderId: TraderId
traderName: TraderName
traderSurname: TraderSurname
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
service TraderService {
operation getTrader(TraderId): TraderInfo
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "qtyFill": 200, "multiplier": 1, "id": "input1", "traderId": "tId1" },
{ "qtyFill": 200, "multiplier": 2, "id": "input2", "traderId": "tId2" },
{ "qtyFill": 200, "multiplier": 3, "id": "input3", "traderId": "tId3" }
]
""".trimIndent()
)
)
stubService.addResponse("getTrader") { _, parameters ->
when (parameters.first().second.value) {
"tId1" -> listOf(
vyne.parseJsonModel(
"TraderInfo",
"""{"traderId": "tId1", "traderName": "Butch", "traderSurname": "Cassidy"}"""
)
)
"tId2" -> listOf(
vyne.parseJsonModel(
"TraderInfo",
"""{"traderId": "tId2", "traderName": "Sundance", "traderSurname": "Kidd"}"""
)
)
"tId3" -> listOf(
vyne.parseJsonModel(
"TraderInfo",
"""{"traderId": "tId3", "traderName": "Travis", "traderSurname": "Bickle"}"""
)
)
else -> listOf(TypedNull.create(vyne.type("TraderInfo")))
}
}
val result = vyne.query(
"""
find {
InputModel[]
} as {
id
multiplier: UnitMultiplier
traderName: TraderName by InputModel['traderId']
}[]
""".trimIndent()
)
result.rawResults.test {
expectRawMapsToEqual(
listOf(
mapOf("id" to "input1", "multiplier" to BigDecimal("1"), "traderName" to "Butch"),
mapOf("id" to "input2", "multiplier" to BigDecimal("2"), "traderName" to "Sundance"),
mapOf("id" to "input3", "multiplier" to BigDecimal("3"), "traderName" to "Travis")
)
)
awaitComplete()
}
}
@Test
@Ignore("this feature is currently disabled - add this test back if reintroducing")
fun `should project to anonymous type extending discovery type`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
type QtyFill inherits Decimal
type UnitMultiplier inherits Decimal
type FilledNotional inherits Decimal
type InputId inherits String
type TraderId inherits String
type TraderName inherits String
type TraderSurname inherits String
model InputModel {
multiplier: UnitMultiplier = 2
qtyFill: QtyFill
id: InputId
}
model OutputModel {
qtyHit : QtyFill?
unitMultiplier: UnitMultiplier?
filledNotional : FilledNotional? by (this.qtyHit * this.unitMultiplier)
traderId: TraderId = "id1"
}
model TraderInfo {
@Id
traderId: TraderId
traderName: TraderName
traderSurname: TraderSurname
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
service TraderService {
operation getTrader(TraderId): TraderInfo
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "qtyFill": 200, "multiplier": 1, "id": "input1" },
{ "qtyFill": 200, "multiplier": 2, "id": "input2" },
{ "qtyFill": 200, "multiplier": 3, "id": "input3" }
]
""".trimIndent()
)
)
stubService.addResponse(
"getTrader", vyne.parseJsonModel(
"TraderInfo",
"""
{
"traderId": "id1",
"traderName": "John",
"traderSurname" : "Doe"
}
""".trimIndent()
)
)
val result =
vyne.query(
"""
find {
InputModel[]
} as OutputModel {
inputId: InputId
traderName: TraderName by OutputModel['traderId']
}[]
""".trimIndent()
)
result.rawObjects().should.be.equal(
listOf(
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("1"),
"filledNotional" to BigDecimal("200"),
"traderId" to "id1",
"inputId" to "input1",
"traderName" to "John"
),
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("2"),
"filledNotional" to BigDecimal("400"),
"traderId" to "id1",
"inputId" to "input2",
"traderName" to "John"
),
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("3"),
"filledNotional" to BigDecimal("600"),
"traderId" to "id1",
"inputId" to "input3",
"traderName" to "John"
)
)
)
}
@Test
@Ignore("this feature is currently disabled - add this test back if reintroducing")
fun `should project to anonymous extending the projectiont target type and containing an anonymously typed field`(): Unit =
runBlocking {
val (vyne, stubService) = testVyne(
"""
type QtyFill inherits Decimal
type UnitMultiplier inherits Decimal
type FilledNotional inherits Decimal
type InputId inherits String
type TraderId inherits String
type TraderName inherits String
type TraderSurname inherits String
model InputModel {
multiplier: UnitMultiplier = 2
qtyFill: QtyFill
id: InputId
}
model OutputModel {
qtyHit : QtyFill?
unitMultiplier: UnitMultiplier?
filledNotional : FilledNotional? by (this.qtyHit * this.unitMultiplier)
traderId: TraderId = "id1"
}
model TraderInfo {
@Id
traderId: TraderId
traderName: TraderName
traderSurname: TraderSurname
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
service TraderService {
operation getTrader(TraderId): TraderInfo
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "qtyFill": 200, "multiplier": 1, "id": "input1" },
{ "qtyFill": 200, "multiplier": 2, "id": "input2" },
{ "qtyFill": 200, "multiplier": 3, "id": "input3" }
]
""".trimIndent()
)
)
stubService.addResponse(
"getTrader", vyne.parseJsonModel(
"TraderInfo",
"""
{
"traderId": "id1",
"traderName": "John",
"traderSurname" : "Doe"
}
""".trimIndent()
)
)
val result =
vyne.query(
"""
find {
InputModel[]
} as OutputModel {
inputId: InputId
trader: {
name: TraderName
surname: TraderSurname
} by OutputModel['traderId']
}[]
""".trimIndent()
)
result.rawObjects().should.be.equal(
listOf(
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("1"),
"filledNotional" to BigDecimal("200"),
"traderId" to "id1",
"inputId" to "input1",
"trader" to mapOf("name" to "John", "surname" to "Doe")
),
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("2"),
"filledNotional" to BigDecimal("400"),
"traderId" to "id1",
"inputId" to "input2",
"trader" to mapOf("name" to "John", "surname" to "Doe")
),
mapOf(
"qtyHit" to BigDecimal("200"),
"unitMultiplier" to BigDecimal("3"),
"filledNotional" to BigDecimal("600"),
"traderId" to "id1",
"inputId" to "input3",
"trader" to mapOf("name" to "John", "surname" to "Doe")
)
)
)
}
@Test
@Ignore("This syntax is deprecated, will revisit if/when needed")
fun `should project to anonymous type containing an anonymously typed field`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
type QtyFill inherits Decimal
type UnitMultiplier inherits Decimal
type FilledNotional inherits Decimal
type InputId inherits String
type TraderId inherits String
type TraderName inherits String
type TraderSurname inherits String
model InputModel {
multiplier: UnitMultiplier = 2
qtyFill: QtyFill
id: InputId
traderId: TraderId
}
model OutputModel {
qtyHit : QtyFill?
unitMultiplier: UnitMultiplier?
filledNotional : FilledNotional? by (this.qtyHit * this.unitMultiplier)
}
model TraderInfo {
@Id
traderId: TraderId
traderName: TraderName
traderSurname: TraderSurname
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
service TraderService {
operation getTrader(TraderId): TraderInfo
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonModel(
"InputModel[]", """
[
{ "qtyFill": 200, "multiplier": 1, "id": "input1", "traderId": "tId1" },
{ "qtyFill": 200, "multiplier": 2, "id": "input2", "traderId": "tId2" },
{ "qtyFill": 200, "multiplier": 3, "id": "input3", "traderId": "tId3" }
]
""".trimIndent()
)
)
stubService.addResponse("getTrader") { _, parameters ->
when (parameters.first().second.value) {
"tId1" -> listOf(
vyne.parseJsonModel(
"TraderInfo",
"""{"traderId": "tId1", "traderName": "Butch", "traderSurname": "Cassidy"}"""
)
)
"tId2" -> listOf(
vyne.parseJsonModel(
"TraderInfo",
"""{"traderId": "tId2", "traderName": "Sundance", "traderSurname": "Kidd"}"""
)
)
"tId3" -> listOf(
vyne.parseJsonModel(
"TraderInfo",
"""{"traderId": "tId3", "traderName": "Travis", "traderSurname": "Bickle"}"""
)
)
else -> listOf(TypedNull.create(vyne.type("TraderInfo")))
}
}
val result = vyne.query(
"""
find {
InputModel[]
} as {
id
multiplier: UnitMultiplier
trader: {
name: TraderName
surname: TraderSurname
} by InputModel['traderId']
}[]
""".trimIndent()
)
result.rawObjects().should.be.equal(
listOf(
mapOf(
"id" to "input1",
"multiplier" to BigDecimal("1"),
"trader" to mapOf("name" to "Butch", "surname" to "Cassidy")
),
mapOf(
"id" to "input2",
"multiplier" to BigDecimal("2"),
"trader" to mapOf("name" to "Sundance", "surname" to "Kidd")
),
mapOf(
"id" to "input3",
"multiplier" to BigDecimal("3"),
"trader" to mapOf("name" to "Travis", "surname" to "Bickle")
)
)
)
}
@Test
fun `avoid recursive parameter discovery`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
type Isin inherits String
type Ric inherits String
type InstrumentIdentifierType inherits String
type InputId inherits String
model InputModel {
id: InputId
ric : Ric?
}
model OutputModel {
isin: Isin
}
// The request contains a parameter that is present on the response.
// Therefore, in order to construct the request, the response can be invoked.
// This leads to circular logic, which causes a stack overflow.
// This test asserts that behaviour is prevented.
parameter model InstrumentReferenceRequest {
Identifier : Ric?
IdentifierType: InstrumentIdentifierType?
}
parameter model InstrumentReferenceResponse {
ricCode : Ric?
instrumentType: InstrumentIdentifierType?
isin: Isin
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
service InstrumentService {
operation getInstrumentFromRic( @RequestBody request:InstrumentReferenceRequest) : InstrumentReferenceResponse
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "id": "input1", "ric": "ric1" },
{ "id": "input2" },
{ "id": "input3" }
]
""".trimIndent()
)
)
val result =
vyne.query(
"""
find {
InputModel[]
} as OutputModel []
""".trimIndent()
)
result.rawObjects().should.be.equal(
listOf(
mapOf("isin" to null),
mapOf("isin" to null),
mapOf("isin" to null)
)
)
}
@Test
@Ignore("Not sure what this is testing, but has started failing.")
fun `invalid post operation caching`(): Unit = runBlocking {
val (vyne, stubService) = testVyne(
"""
type Isin inherits String
type Ric inherits String
type InstrumentIdentifierType inherits String
type InputId inherits String
model InputModel {
id: InputId
ric : Ric?
instrumentType: InstrumentIdentifierType? = "Ric"
}
model OutputModel {
isin: Isin
}
parameter model InstrumentReferenceRequest {
Identifier : Ric?
IdentifierType: InstrumentIdentifierType?
}
parameter model InstrumentReferenceResponse {
isin: Isin
}
@Datasource
service MultipleInvocationService {
operation getInputData(): InputModel[]
}
service InstrumentService {
operation getInstrumentFromRic( @RequestBody request:InstrumentReferenceRequest) : InstrumentReferenceResponse
}
""".trimIndent()
)
stubService.addResponse(
"getInputData", vyne.parseJsonCollection(
"InputModel[]", """
[
{ "id": "input1", "ric": "ric1", "instrumentType": "ric" },
{ "id": "input2", "ric": "ric2", "instrumentType": "ric" },
{ "id": "input3", "ric": "ric3", "instrumentType": "ric" }
]
""".trimIndent()
)
)
stubService.addResponse("getInstrumentFromRic") { _, parameters ->
val isinValue = (parameters.first().second as TypedObject).value.values.map { it.value }.joinToString("_")
listOf(
vyne.parseJsonModel(
"InstrumentReferenceResponse", """
{"isin": "$isinValue"}
""".trimIndent()
)
)
}
val result =
vyne.query(
"""
find {
InputModel[]
} as OutputModel []
""".trimIndent()
)
result.rawObjects().should.be.equal(
listOf(
mapOf("isin" to "ric1_ric"),
mapOf("isin" to "ric2_ric"),
mapOf("isin" to "ric3_ric")
)
)
}
@Test
fun `If Vyne is enriching an entity, and a model returned from a service defines an Id field, then Vyne will only invoke that service the input parameter identifies the output model`(): Unit =
runBlocking {
val testSchema = """
type UserId inherits String
type TradeId inherits String
type Isin inherits String
type TradePrice inherits Decimal
type TradeDate inherits Date
model Trade {
salesPersonId: UserId
@Id
tradeId: TradeId
isin: Isin
tradePrice: TradePrice
}
model Input {
userId: UserId
tradeId: TradeId
}
model Report {
tradePrice: TradePrice
tradeDate: TradeDate
}
@Datasource
service InputService {
operation `findAll`(): Input[]
}
service DataService {
operation findLatestTradeForSalesPerson(UserId) : Trade
operation findTrade(TradeId) : Trade
}
""".trimIndent()
val (vyne, stubService) = testVyne(testSchema)
stubService.addResponse(
"`findAll`", vyne.parseJsonCollection(
"Input[]", """
[
{ userId : "userX", tradeId: "InstrumentX" }
]
""".trimIndent()
)
)
stubService.addResponse("findLatestTradeForSalesPerson") { _, parameters ->
fail("Should not be invoked")
}
var findTradeInvoked = false
stubService.addResponse("findTrade") { _, _ ->
findTradeInvoked = true
throw IllegalArgumentException()
}
// act
val result = vyne.query("""find { Input[] } as Report[]""".trimIndent())
// assert
result.rawObjects().should.be.equal(
listOf(
mapOf("tradePrice" to null, "tradeDate" to null)
)
)
findTradeInvoked.should.be.`true`
}
@Test
fun `If Vyne is enriching an entity, and a model returned from a service does not define an Id field, then Vyne will use any possible path to discover the inputs to call the service`(): Unit =
runBlocking {
val testSchema = """
type ProductId inherits String
type AssetClass inherits String
type Isin inherits String
type OrderId inherits String
parameter model IsinDiscoveryRequest {
productId : ProductId?
assetClass : AssetClass?
}
model IsinDiscoveryResult {
isin : Isin
}
model Input {
orderId: OrderId
productId : ProductId?
assetClass : AssetClass?
}
model Output {
orderId: OrderId
isin : Isin
}
@Datasource
service InputService {
operation `findAll`(): Input[]
}
service DataService {
operation lookupIsin(IsinDiscoveryRequest):IsinDiscoveryResult
}
""".trimIndent()
val (vyne, stubService) = testVyne(testSchema)
stubService.addResponse(
"`findAll`", vyne.parseJsonCollection(
"Input[]", """
[
{ orderId : "OrderX", productId: "ProductX", assetClass: "AssetClassX" }
]
""".trimIndent()
)
)
stubService.addResponse(
"lookupIsin", vyne.parseJsonModel(
"IsinDiscoveryResult", """
{ isin : "Isin1" }
""".trimIndent()
)
)
val result = vyne.query("""find { Input[] } as Output[]""".trimIndent())
result.rawObjects().should.be.equal(
listOf(
mapOf("orderId" to "OrderX", "isin" to "Isin1")
)
)
}
@Test
fun `When an object has multiple independent fields that identify it, all these fields can be used for enrichment`() =
runBlocking {
val testSchema = """
type UserId inherits String
type Type1TradeId inherits String
type Type2TradeId inherits String
type Isin inherits String
type TradePrice inherits Decimal
type TradeDate inherits Date
model Trade {
salesPersonId: UserId
@Id
tradeId1: Type1TradeId
@Id
tradeId2: Type2TradeId
isin: Isin
tradePrice: TradePrice
}
model Input {
userId: UserId
tradeId1: Type1TradeId?
tradeId2: Type2TradeId?
}
model Report {
tradePrice: TradePrice
tradeDate: TradeDate
}
@Datasource
service InputService {
operation `findAll`(): Input[]
}
service DataService {
operation findLatestTradeForSalesPerson(UserId) : Trade
operation findTradeByType1Id(Type1TradeId) : Trade
operation findTradeByType2Id(Type2TradeId) : Trade
}
""".trimIndent()
val (vyne, stubService) = testVyne(testSchema)
stubService.addResponse(
"`findAll`", vyne.parseJsonCollection(
"Input[]", """
[
{ userId : "userX", tradeId1: "InstrumentX" },
{ userId : "userX", tradeId2: "InstrumentY" }
]
""".trimIndent()
)
)
stubService.addResponse("findLatestTradeForSalesPerson") { _, _ ->
fail("Should not be invoked")
}
var findTradeByType1IdInvoked = false
stubService.addResponse("findTradeByType1Id") { _, _ ->
findTradeByType1IdInvoked = true
throw IllegalArgumentException()
}
var findTradeByType2IdInvoked = false
stubService.addResponse("findTradeByType2Id") { _, _ ->
findTradeByType2IdInvoked = true
throw IllegalArgumentException()
}
// act
val result = vyne.query("""find { Input[] } as Report[]""".trimIndent())
// assert
result.rawObjects().should.be.equal(
listOf(
mapOf("tradePrice" to null, "tradeDate" to null),
mapOf("tradePrice" to null, "tradeDate" to null)
)
)
findTradeByType1IdInvoked.should.be.`true`
findTradeByType2IdInvoked.should.be.`true`
}
@Test
fun `when an enum synonym is used the lineage is still captured correctly`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
enum CountryCode {
NZ,
AUS
}
enum Country {
NewZealand synonym of CountryCode.NZ,
Australia synonym of CountryCode.AUS
}
model Person {
name : FirstName inherits String
country : CountryCode
}
service PeopleService {
operation listPeople():Person[]
}
"""
)
val people = TypedInstance.from(
vyne.type("Person[]"), """[
|{ "name" : "Mike" , "country" : "AUS" },
|{ "name" : "Marty", "country" : "NZ" }]
""".trimMargin(), vyne.schema, source = Provided
)
stub.addResponse("listPeople", people, modifyDataSource = true)
val results = vyne.query(
"""find { Person[] } as {
| name : FirstName
| country : Country
| }[]
""".trimMargin()
)
.typedObjects()
val first = results[0]
val countrySource = first["country"].source as MappedSynonym
val remoteSource = countrySource.source.source as OperationResultDataSourceWrapper
remoteSource.operationResultReferenceSource.operationName.fullyQualifiedName.should.equal("PeopleService@@listPeople")
}
@Test
fun `when multiple equvialent paths are possible, they are filtered and services are only invoked once`(): Unit =
runBlocking {
// This test is tricky.
// The below schema generates multiple equvialent paths, and we want to ensure that they are detected, filtered out, and
// only a single invocation on the service is performed.
//
// Start : Type_instance(Movie@252528169)
// {TYPE_INSTANCE}:Movie@252528169 -[Instance has attribute]-> {PROVIDED_INSTANCE_MEMBER}:Movie/director (cost: 2.0)
// {PROVIDED_INSTANCE_MEMBER}:Movie/director -[Is an attribute of]-> {TYPE_INSTANCE}:DirectorName (cost: 4.0)
// {TYPE_INSTANCE}:DirectorName -[can populate]-> {PARAMETER}:param/DirectorName (cost: 6.0)
// {PARAMETER}:param/DirectorName -[Is parameter on]-> {OPERATION}:MovieService@@resolveDirectorName (cost: 8.0)
// {OPERATION}:MovieService@@resolveDirectorName -[provides]-> {TYPE_INSTANCE}:DirectorIdNameMap (cost: 10.0)
// {TYPE_INSTANCE}:DirectorIdNameMap -[Instance has attribute]-> {PROVIDED_INSTANCE_MEMBER}:DirectorIdNameMap/id (cost: 12.0)
// {PROVIDED_INSTANCE_MEMBER}:DirectorIdNameMap/id -[Is an attribute of]-> {TYPE_INSTANCE}:DirectorId (cost: 112.0)
// {TYPE_INSTANCE}:DirectorId -[can populate]-> {PARAMETER}:param/DirectorId (cost: 114.0)
// {PARAMETER}:param/DirectorId -[Is parameter on]-> {OPERATION}:MovieService@@findDirector (cost: 116.0)
// {OPERATION}:MovieService@@findDirector -[provides]-> {TYPE_INSTANCE}:Director (cost: 216.0)
// {TYPE_INSTANCE}:Director -[Instance has attribute]-> {PROVIDED_INSTANCE_MEMBER}:Director/birthday (cost: 217.0)
// {PROVIDED_INSTANCE_MEMBER}:Director/birthday -[Is an attribute of]-> {TYPE_INSTANCE}:DateOfBirth (cost: 218.0)
// {TYPE_INSTANCE}:DateOfBirth -[Is instanceOfType of]-> {TYPE}:DateOfBirth (cost: 219.0)
//
//
// is equivalent to -890830206:
// Start : Type_instance(Movie@252528169)
// {TYPE_INSTANCE}:Movie@252528169 -[Instance has attribute]-> {PROVIDED_INSTANCE_MEMBER}:Movie/director (cost: 1.0)
// {PROVIDED_INSTANCE_MEMBER}:Movie/director -[Is an attribute of]-> {TYPE_INSTANCE}:DirectorName (cost: 2.0)
// {TYPE_INSTANCE}:DirectorName -[can populate]-> {PARAMETER}:param/DirectorName (cost: 3.0)
// {PARAMETER}:param/DirectorName -[Is parameter on]-> {OPERATION}:MovieService@@resolveDirectorName (cost: 4.0)
// {OPERATION}:MovieService@@resolveDirectorName -[provides]-> {TYPE_INSTANCE}:DirectorIdNameMap (cost: 5.0)
// {TYPE_INSTANCE}:DirectorIdNameMap -[Instance has attribute]-> {PROVIDED_INSTANCE_MEMBER}:DirectorIdNameMap/id (cost: 6.0)
// {PROVIDED_INSTANCE_MEMBER}:DirectorIdNameMap/id -[Is an attribute of]-> {TYPE_INSTANCE}:DirectorId (cost: 7.0)
// {TYPE_INSTANCE}:DirectorId -[can populate]-> {PARAMETER}:param/DirectorId (cost: 8.0)
// {PARAMETER}:param/DirectorId -[Is parameter on]-> {OPERATION}:MovieService@@findDirector (cost: 9.0)
// {OPERATION}:MovieService@@findDirector -[provides]-> {TYPE_INSTANCE}:Director (cost: 10.0)
// {TYPE_INSTANCE}:Director -[Is instanceOfType of]-> {TYPE}:Director (cost: 11.0)
// {TYPE}:Director -[Has attribute]-> {MEMBER}:Director/birthday (cost: 12.0)
// {MEMBER}:Director/birthday -[Is type of]-> {TYPE}:DateOfBirth (cost: 13.0).
//
//
// Both evaluate to: Simplified path -780930048:
// START_POINT -> Movie@252528169
// OBJECT_NAVIGATION -> Movie/director
// PARAM_POPULATION -> param/DirectorName
// OPERATION_INVOCATION -> MovieService@@resolveDirectorName returns DirectorIdNameMap
// OBJECT_NAVIGATION -> DirectorIdNameMap/id
// PARAM_POPULATION -> param/DirectorId
// OPERATION_INVOCATION -> MovieService@@findDirector returns Director
// OBJECT_NAVIGATION -> Director/birthday
val (vyne, stub) = testVyne(
"""
model Director {
name : DirectorName inherits String
id : DirectorId inherits Int
birthday : DateOfBirth inherits Date
}
model DirectorIdNameMap {
name : DirectorName
id : DirectorId
}
model Movie {
title : MovieTitle inherits String
director: DirectorName
}
model Output {
title : MovieTitle
directorDob : DateOfBirth
}
service MovieService {
operation findMovies():Movie[]
operation resolveDirectorName(DirectorName):DirectorIdNameMap
operation findDirector(DirectorId):Director
}
"""
)
stub.addResponse(
"findMovies", vyne.parseJson(
"Movie[]",
"""[
| { "title" : "A new hope" , "director" : "<NAME>" }
| ]
""".trimMargin()
)
)
stub.addResponse(
"resolveDirectorName", vyne.parseJson(
"DirectorIdNameMap",
"""{ "name": "<NAME>", "id": null }"""
)
)
stub.addResponse("findDirector") { _, _ -> error("This shouldn't be called ") }
val result = vyne.query("""find { Movie[] } as Output[] """)
.typedObjects()
result.should.have.size(1)
stub.invocations["resolveDirectorName"]!!.should.have.size(1)
}
@Test
fun concurrency_test(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
type DirectorName inherits String
type ReleaseYear inherits Int
model Actor {
@Id actorId : ActorId inherits String
name : ActorName inherits String
}
model Movie {
@Id movieId : MovieId inherits String
title : MovieTitle inherits String
starring : ActorId
}
model OutputModel {
@Id movieId : MovieId inherits String
title : MovieTitle inherits String
starring : ActorName
director : DirectorName
releaseYear : ReleaseYear
}
service Services {
operation findAllMovies():Movie[]
operation findActor(ActorId):Actor
}
""".trimIndent()
)
stub.addResponseFlow("findActor") { remoteOperation, params ->
val actorId = params[0].second.value as String
flow {
// kotlinx.coroutines.delay(500)
val actor = TypedInstance.from(
vyne.type("Actor"),
"""{ "actorId" : ${actorId.quoted()} , "name" : "<NAME> Clone #$actorId" } """,
vyne.schema,
source = Provided
)
emit(actor)
}
}
val movieCount = 500
stub.addResponse("findAllMovies") { _, params ->
val movies = (0 until movieCount).map { index ->
val movie = mapOf(
"movieId" to index.toString(),
"title" to "Mission Impossible $index",
"starring" to index.toString()
)
vyne.parseJsonModel("Movie", jacksonObjectMapper().writeValueAsString(movie))
}
movies
}
val start = Stopwatch.createStarted()
var summary: StrategyPerformanceProfiler.SearchStrategySummary? = null
val f = Benchmark.benchmark("run concurrency test with $movieCount", warmup = 5, iterations = 5) {
runBlocking {
val result = vyne.query("find { Movie[] } as OutputModel[]")
.results.toList()
result.should.have.size(movieCount)
val duration = start.elapsed(TimeUnit.MILLISECONDS)
summary = StrategyPerformanceProfiler.summarizeAndReset()
}
}
log().warn("Test completed: $summary")
}
@Test
fun `can use a date format on an anonymous type`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
model Transaction {
id : TransactionId inherits Int
date : TransactionDate inherits Instant
}
service TransactionService {
operation listTransactions():Transaction[]
}
"""
)
stub.addResponse(
"listTransactions", vyne.parseJson(
"Transaction[]", """[
|{ "id" : 1 , "date" : "2020-12-08T15:00:00Z" },
|{ "id" : 3 , "date" : "2020-12-10T14:20:00Z" }
|]
""".trimMargin()
)
)
val results = vyne.query(
"""find { Transaction[] } as { id : TransactionId
@Format( 'dd-MMM-yy')
date : TransactionDate
}[]"""
)
.rawObjects()
results.should.have.size(2)
results.should.equal(
listOf(
mapOf("id" to 1, "date" to "08-Dec-20"),
mapOf("id" to 3, "date" to "10-Dec-20")
)
)
}
@Test
@Ignore("Querying on base types has been disabled: See ADR 20240215-find-does-not-query-on-base-types/")
fun `when the initial query fails vyne doesnt attempt to perform a projection`(): Unit = runBlocking {
val explodingProjectionProvider: ProjectionProvider = object : ProjectionProvider {
override fun project(
results: Flow<TypedInstance>,
declaredSourceType: Type,
projection: Projection,
context: QueryContext,
globalFacts: FactBag,
metricTags: MetricTags
): Flow<TypedInstanceWithMetadata> {
return results.map { typedInstance ->
error("THis shouldn't have been called!! $typedInstance")
}
}
override fun process(
source: Flow<TypedInstanceWithMetadata>,
context: QueryContext,
block: suspend CoroutineScope.(item: TypedInstanceWithMetadata) -> Flow<TypedInstanceWithMetadata>
): Flow<TypedInstanceWithMetadata> {
return source.flatMapConcat {
block(it)
}
}
}
val (vyne, stub) = testVyne(
"""
model Person {
name : FullName inherits String
}
parameter model LookupRequest {
apiKey : ApiKey inherits String
}
service DataService {
operation findPeople(apiKey:ApiKey):Person[]
}
""".trimIndent(),
projectionProvider = explodingProjectionProvider
)
stub.addResponse("findPeople") { op, _ ->
throw OperationInvocationException("This service call failed", 503, RemoteCall(
service = OperationNames.serviceName(op.qualifiedName).fqn(),
address = "",
isFailed = true,
durationMs = 0,
exchange = EmptyExchangeData,
operation = OperationNames.operationName(op.qualifiedName),
response = null,
responseMessageType = ResponseMessageType.FULL,
responseTypeName = op.returnType.name,
timestamp = Instant.now()
), emptyList())
}
assertFailsWith<OperationInvocationException> {
vyne.query(
"""
|given { apiKey : ApiKey = 'jimmy' }
|find { Person[] } as {
| nope : FullName
|}[]
""".trimMargin()
)
.rawObjects()
}
}
@Test
fun `can project the result of an expression as a property from the result`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
model Actor {
actorId : ActorId inherits Int
name : ActorName inherits String
}
model Film {
title : FilmTitle inherits String
headliner : ActorId
cast: Actor[]
}
service DataService {
operation getFilms():Film[]
}
""".trimIndent()
)
stub.addResponse(
"getFilms", vyne.parseJson(
"Film[]", """[
|{
| "title" : "Star Wars",
| "headliner" : 1 ,
| "cast": [
| { "actorId" : 1 , "name" : "<NAME>" },
| { "actorId" : 2 , "name" : "<NAME>" }
| ]
| }
|]
""".trimMargin()
)
)
val result = vyne.query(
"""
find { Film[] } as (film:Film) -> {
title : FilmTitle
// This is the test...
// using "as" to project Actor to ActorName
star : singleBy(film.cast, (Actor) -> Actor::ActorId, film.headliner) as ActorName
}[]
""".trimMargin()
)
.firstTypedObject()
result.should.not.be.`null`
// result.should.equal(mapOf("title" to "Star Wars", "star" to "Mark Hamill"))
}
@Test
fun `should resolve items on inline projection`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
type CreditScore inherits String
type BloodType inherits String
model Person {
id : PersonId inherits Int
name : PersonName inherits String
}
model ActorDetails {
bloodType : BloodType
creditScore : CreditScore
}
model Movie {
cast : Person[]
}
service MyService {
operation findMovies():Movie[]
operation getActorDetails(PersonId):ActorDetails
}
"""
)
stub.addResponse(
"findMovies", vyne.parseJson(
"Movie[]", """[
|{ "cast" : [
| { "id" : 1, "name" : "<NAME>" },
| { "id" : 2, "name" : "<NAME>" }
| ] }
|]""".trimMargin()
)
)
val actorDetails = vyne.parseJson(
"ActorDetails",
"""{ "bloodType" : "O+", "creditScore" : "AAA" } """
)
stub.addResponse("getActorDetails", actorDetails)
val result = vyne.query(
"""
find { Movie[] } as {
cast : Person[]
aListers : filter(this.cast, (Person) -> containsString(PersonName, 'a')) as { // Inferred return type is Person
bloodType : BloodType
creditScore : CreditScore
...except { id }
}[]
}[]"""
).firstTypedObject()
val alisters = result["aListers"].toRawObject() as List<Map<String, Any>>
alisters.shouldBe(
listOf(
mapOf(
"name" to "<NAME>",
"bloodType" to "O+",
"creditScore" to "AAA"
),
mapOf(
"name" to "<NAME>",
"bloodType" to "O+",
"creditScore" to "AAA"
)
)
)
}
@Test
fun `should use values in given clause to invoke services for data in nested projection`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
type CreditScore inherits String
type BloodType inherits String
type AgentId inherits String
model Person {
id : PersonId inherits Int
name : PersonName inherits String
}
model ActorDetails {
bloodType : BloodType
creditScore : CreditScore
}
model Movie {
movieId: MovieId inherits Int
star : Person
}
service MyService {
operation findMovies():Movie
// This is the test
// Operation requires 3 params, that come from different
// scopes
// AgentId -> From the given {} clause
// MovieId -> From the parent projection scope
// PersonId -> From the current projection scope
operation getActorDetails(MovieId,AgentId,PersonId):ActorDetails
}
"""
)
stub.addResponse(
"findMovies", vyne.parseJson(
"Movie[]", """[
|{
| "movieId" : 1,
| "star" : { "id" : 1, "name" : "<NAME>" }
| }
|]""".trimMargin()
)
)
val actorDetails = vyne.parseJson(
"ActorDetails",
"""{ "bloodType" : "O+", "creditScore" : "AAA" } """
)
stub.addResponse("getActorDetails", actorDetails)
val result = vyne.query(
"""
given { AgentId = "123" }
find { Movie } as {
cast : Person as {
details: {
name : PersonName
bloodType : BloodType
}
}
}"""
).firstTypedObject()["cast"].toRawObject() as Map<String, Any>
result.shouldBe(
mapOf(
"details" to mapOf(
"name" to "<NAME>",
"bloodType" to "O+"
)
)
)
val calls = stub.invocations["getActorDetails"]!!
calls.shouldContainInOrder(
vyne.typedValue("MovieId", 1),
vyne.typedValue("AgentId", "123"),
vyne.typedValue("PersonId", "1"),
)
}
@Test
fun `will populate collection on inline projection`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
type CreditScore inherits String
type BloodType inherits String
type AgentId inherits String
model Person {
id : PersonId inherits Int
name : PersonName inherits String
}
model Award {
year : AwardYear inherits Int
name : AwardTitle inherits String
}
model ActorDetails {
creditScore : CreditScore
awards : Award[]
}
model Movie {
movieId: MovieId inherits Int
star : Person
}
service MyService {
operation findMovies():Movie
operation getActorDetails(PersonId):ActorDetails
}
"""
)
stub.addResponse(
"findMovies", vyne.parseJson(
"Movie[]", """[
|{
| "movieId" : 1,
| "star" : { "id" : 1, "name" : "<NAME>" }
| }
|]""".trimMargin()
)
)
val actorDetails = vyne.parseJson(
"ActorDetails",
"""{ "creditScore" : "AAA" , "awards" : [
|{ "name" : "Top bloke", "year" : 2023 },
|{ "name" : "Snappy dresser" , "year" : 2023 }
|] } """.trimMargin()
)
stub.addResponse("getActorDetails", actorDetails)
val result = vyne.query(
"""
find { Movie } as {
cast : Person as {
details: {
name : PersonName
awards : Award[]
}
}
}"""
).firstTypedObject()["cast"].toRawObject() as Map<String, Any>
result.shouldBe(
mapOf(
"details" to mapOf(
"name" to "<NAME>",
"awards" to listOf(
mapOf("year" to 2023, "name" to "Top bloke"),
mapOf("year" to 2023, "name" to "Snappy dresser"),
)
)
)
)
}
@Test
fun `a nested inline projection can request data from a parent scope`(): Unit = runBlocking {
val (vyne, stub) = testVyne(
"""
model Person {
id : PersonId inherits Int
name : PersonName inherits String
}
model Movie {
movieId: MovieId inherits Int
data : MovieData
}
model MovieData {
contributors: Contributors
}
model Contributors {
cast : Person[]
}
service MyService {
operation findMovies():Movie
}
"""
)
val movie = vyne.parseJson(
"Movie", """{
| "movieId" : 1,
| "data" : {
| "contributors" : {
| "cast" : [
| { "id" : 1, "name" : "<NAME>" },
| { "id" : 2, "name" : "<NAME>" }
| ]
| }
| }
| }""".trimMargin()
) as TypedObject
val movieData = movie["data"]
// val factBag = FieldAndFactBag(mapOf("data" to movieData), listOf(), listOf(ScopedFact(ProjectionFunctionScope.implicitThis(vyne.type("Movie").taxiType), movie)), vyne.schema)
// val personName =
// factBag.getFactOrNull(vyne.schema.type("PersonName[]"), FactDiscoveryStrategy.ANY_DEPTH_ALLOW_MANY)
// personName.shouldNotBeNull()
stub.addResponse(
"findMovies", movie
)
val result = vyne.query(
"""
find { Movie } as {
data : MovieData as {
actors : {
cast : PersonName[]
}
}
}"""
).firstRawObject()
result.shouldBe(
mapOf(
"data" to mapOf(
"actors" to mapOf(
"cast" to listOf(
"<NAME>",
"<NAME>"
)
)
)
)
)
}
// ORB-119
@Test
fun `projected objects where parent and child have the same field names are populated correctly`():Unit = runBlocking() {
val (vyne,stub) = testVyne("""
type DirectorId inherits Int
type MovieId inherits Int
model Movie {
movieId : MovieId
directorId : DirectorId
}
service MovieService {
operation getMovie():Movie
}
""".trimIndent())
val movie = vyne.parseJson("Movie", """ { "movieId" : 1, "directorId" : 2 }""")
stub.addResponse("getMovie", movie)
val result = vyne.query(
"""find { Movie } as {
|id : MovieId
|crew : {
| id : DirectorId
|}
|}
""".trimMargin()
)
.firstRawObject()
result
.shouldBe(mapOf("id" to 1, "crew" to mapOf("id" to 2)))
}
}
| 9 | TypeScript | 10 | 292 | 2be59abde0bd93578f12fc1e2ecf1f458a0212ec | 99,592 | orbital | Apache License 2.0 |
app/src/main/java/com/example/trackingmypantry/LoginPage.kt | S1mplyD | 390,643,897 | false | null | package com.example.trackingmypantry
import android.app.*
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class LoginPage : AppCompatActivity() {
//Companion object creato per salvare l'access token e renderlo disponibile in qualsiasi punto del codice
companion object {
var accessToken = ""
}
//Shared preferences per salvare il token su file e lo stato del "Ricordami"
lateinit var sharedPreferences: SharedPreferences
var isRemembered = false
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_page)
//Controllo se durante il login l'utente ha scelto di essere ricordato
sharedPreferences = getSharedPreferences("SHARED_PREF", Context.MODE_PRIVATE)
isRemembered = sharedPreferences.getBoolean("CHECKBOX", false)
//Se l'utente ha scelto di essere ricordato recupero il suo access token dalle shared preference
if (isRemembered) {
accessToken = sharedPreferences.getString("ACCESS_TOKEN", "").toString()
val i = Intent(this, HomePage::class.java)
startActivity(i)
finish()
}
val loginMail: EditText = findViewById(R.id.loginMail)
val loginPassword: EditText = findViewById(R.id.loginPassword)
val loginButton = findViewById<Button>(R.id.loginButton)
val rememberMe: CheckBox = findViewById(R.id.rememberUser)
//Controllo che i campi di log in non siano vuoti e faccio una chiamata http a login
loginButton.setOnClickListener {
if (loginMail.text.isNullOrBlank() || loginPassword.text.isNullOrBlank()) {
Toast.makeText(this, "Empty field", Toast.LENGTH_SHORT).show()
} else {
HTTPcalls().login(
loginMail.text,
loginPassword.text,
this,
this@LoginPage,
rememberMe.isChecked
)
}
}
//Link che permette a chi non è registrato di essere reindirizzato alla pagina apposita
val registerLink: TextView = findViewById(R.id.linkToRegister)
registerLink.setOnClickListener {
val i = Intent(this, RegisterPage::class.java)
startActivity(i)
}
}
}
class AccessToken(val accessToken: String) | 0 | Kotlin | 0 | 0 | 9aa353e2edb72aed4a70d56d16b55a298bdbe109 | 2,686 | TrackingMyPantry | MIT License |
sample/todo/list/src/commonMain/kotlin/com/arkivanov/todo/list/integration/TodoListImpl.kt | tchigher | 323,974,338 | true | {"Kotlin": 44199} | package com.arkivanov.todo.list.integration
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.decompose.lifecycle.doOnDestroy
import com.arkivanov.decompose.value.Value
import com.arkivanov.decompose.value.operator.map
import com.arkivanov.mvikotlin.core.binder.BinderLifecycleMode
import com.arkivanov.mvikotlin.core.store.StoreFactory
import com.arkivanov.todo.database.TodoDatabaseQueries
import com.arkivanov.todo.list.TodoList
import com.arkivanov.todo.list.TodoList.Data
import com.arkivanov.todo.list.TodoList.Events
import com.arkivanov.todo.list.TodoList.Input
import com.arkivanov.todo.list.TodoList.Model
import com.arkivanov.todo.list.TodoList.Output
import com.arkivanov.todo.list.store.ListStore.Intent
import com.arkivanov.todo.list.store.ListStore.State
import com.arkivanov.todo.list.store.ListStoreFactory
import com.arkivanov.todo.utils.asValue
import com.arkivanov.todo.utils.bind
import com.arkivanov.todo.utils.getStore
import com.badoo.reaktive.base.Consumer
import com.badoo.reaktive.observable.Observable
import com.badoo.reaktive.observable.mapNotNull
internal class TodoListImpl(
componentContext: ComponentContext,
storeFactory: StoreFactory,
queries: TodoDatabaseQueries,
input: Observable<Input>,
private val output: Consumer<Output>
) : TodoList, Events, ComponentContext by componentContext {
private val store = instanceKeeper.getStore { ListStoreFactory(storeFactory, ListStoreDatabase(queries)).create() }
override val model: Model =
object : Model, Events by this {
override val data: Value<Data> = store.asValue().map { it.asData() }
}
init {
bind(lifecycle, BinderLifecycleMode.CREATE_DESTROY) {
input.mapNotNull(inputToIntent) bindTo store
}
}
private fun State.asData(): Data =
Data(items = items)
override fun onItemClicked(id: Long) {
output.onNext(Output.Selected(id = id))
}
override fun onDoneChanged(id: Long, isDone: Boolean) {
store.accept(Intent.SetDone(id = id, isDone = isDone))
}
}
| 0 | null | 0 | 0 | fbec0ac19f813bb6e619ceb6d482c098e8e1dfc9 | 2,097 | Decompose | Apache License 2.0 |
src/main/kotlin/com/pandus/llm/rag/RagKotlinApplication.kt | bodyangug | 858,960,448 | false | {"Kotlin": 20353} | package com.pandus.llm.rag
import com.pandus.llm.rag.configuration.appModule
import com.pandus.llm.rag.configuration.configureRouting
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.json.Json
import org.koin.ktor.plugin.Koin
// TODO:
// 1. Add logging, add docker file for chroma;
// 2. Add auth.
fun main(args: Array<String>) {
EngineMain.main(args)
}
fun Application.module() {
configureRouting()
install(ContentNegotiation) {
json(Json {
prettyPrint = true
})
}
install(Koin) {
modules(appModule(environment))
}
}
| 0 | Kotlin | 0 | 1 | fa6368a4297c1cd5d1fa142630ab267db6a9d145 | 725 | kotlin-rag | MIT License |
pumpkin-protocol-modern/src/main/kotlin/pumpkin/protocol/modern/type/NBT.kt | ItsDoot | 224,063,495 | false | null | package pumpkin.protocol.modern.type
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.ByteBufOutputStream
import pumpkin.nbt.NBTCompound
import pumpkin.nbt.NBTTag
import pumpkin.nbt.readNBT
import pumpkin.nbt.readNBTCompound
import pumpkin.nbt.readNamedNBT
import pumpkin.nbt.readNamedNBTCompound
import pumpkin.nbt.writeNBT
import pumpkin.nbt.writeNamedNBT
import java.io.DataInputStream
import java.io.DataOutputStream
fun ByteBuf.readNBT(): NBTTag =
DataInputStream(ByteBufInputStream(this)).readNBT()
fun ByteBuf.readNamedNBT(): Pair<String?, NBTTag> =
DataInputStream(ByteBufInputStream(this)).readNamedNBT()
fun ByteBuf.readNBTCompound(): NBTCompound =
DataInputStream(ByteBufInputStream(this)).readNBTCompound()
fun ByteBuf.readNamedNBTCompound(): Pair<String?, NBTCompound> =
DataInputStream(ByteBufInputStream(this)).readNamedNBTCompound()
fun ByteBuf.writeNBT(tag: NBTTag): ByteBuf {
DataOutputStream(ByteBufOutputStream(this)).writeNBT(tag)
return this
}
fun ByteBuf.writeNBT(name: String, tag: NBTTag): ByteBuf {
DataOutputStream(ByteBufOutputStream(this)).writeNamedNBT(name, tag)
return this
} | 0 | Kotlin | 1 | 1 | afa6c39fc722f616ee8410b325a402b92994082f | 1,193 | pumpkin | MIT License |
app/src/main/java/com/codelab/basics/MainActivity.kt | leeeyubin | 772,455,663 | false | {"Kotlin": 5127} | package com.codelab.basics
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.codelab.basics.ui.theme.BasicsCodelabTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BasicsCodelabTheme {
MyApp(modifier = Modifier.fillMaxSize())
}
}
}
}
@Composable
fun MyApp(
modifier: Modifier = Modifier,
names: List<String> = listOf("world", "Compose")
) {
Column(modifier = modifier.padding(vertical = 4.dp)) {
for (name in names) {
Greeting(name = name)
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Surface(
color = MaterialTheme.colorScheme.primary,
modifier = modifier.padding(vertical = 4.dp, horizontal = 8.dp)
) {
Row(modifier = Modifier.padding(24.dp)) {
Column(modifier = Modifier.weight(1f)) {
Text(text = "Hello ")
Text(text = name)
}
ElevatedButton(
onClick = { }
) {
Text("Show more")
}
}
}
}
@Preview(showBackground = true, widthDp = 320)
@Composable
fun GreetingPreview() {
BasicsCodelabTheme {
MyApp()
}
} | 0 | Kotlin | 0 | 0 | 0e27da1f1e8b3877f37620484be31614419512dc | 1,958 | Compose-Android | Apache License 2.0 |
app/src/main/java/org/simple/clinic/patient/PatientModule.kt | ParanoidBeing | 177,529,359 | true | {"Markdown": 10, "Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Kotlin": 634, "XML": 160, "Java": 13, "Proguard": 1, "JSON": 27, "INI": 1, "C": 3, "Makefile": 2} | package org.simple.clinic.patient
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import io.reactivex.Observable
import io.reactivex.Single
import org.simple.clinic.BuildConfig
import org.simple.clinic.patient.businessid.BusinessId
import org.simple.clinic.patient.businessid.BusinessIdMeta
import org.simple.clinic.patient.businessid.BusinessIdMetaAdapter
import org.simple.clinic.patient.businessid.MoshiBusinessIdMetaAdapter
import org.simple.clinic.patient.filter.SearchPatientByName
import org.simple.clinic.patient.filter.SortByWeightedNameParts
import org.simple.clinic.patient.filter.WeightedLevenshteinSearch
import org.simple.clinic.patient.fuzzy.AgeFuzzer
import org.simple.clinic.patient.fuzzy.PercentageFuzzer
import org.simple.clinic.phone.PhoneNumberMaskerConfig
import org.simple.clinic.util.UtcClock
@Module
open class PatientModule {
@Provides
open fun provideAgeFuzzer(utcClock: UtcClock): AgeFuzzer = PercentageFuzzer(utcClock = utcClock, fuzziness = 0.2F)
@Provides
open fun provideFilterPatientByName(): SearchPatientByName = WeightedLevenshteinSearch(
minimumSearchTermLength = 3,
maximumAllowedEditDistance = 350F,
// Values are taken from what sqlite spellfix uses internally.
characterSubstitutionCost = 150F,
characterDeletionCost = 100F,
characterInsertionCost = 100F,
resultsComparator = SortByWeightedNameParts())
@Provides
open fun providePatientConfig(): Observable<PatientConfig> = Observable.just(PatientConfig(
limitOfSearchResults = 100,
scanSimpleCardFeatureEnabled = false,
recentPatientLimit = 10
))
@Provides
open fun phoneNumberMaskerConfig(): Single<PhoneNumberMaskerConfig> =
Single.just(PhoneNumberMaskerConfig(
maskingEnabled = false,
phoneNumber = BuildConfig.MASKED_PHONE_NUMBER
))
@Provides
fun provideBusinessIdMetaAdapter(moshi: Moshi): BusinessIdMetaAdapter {
@Suppress("UNCHECKED_CAST")
val adapters: Map<BusinessId.MetaVersion, JsonAdapter<BusinessIdMeta>> = mapOf(
BusinessId.MetaVersion.BpPassportV1 to
moshi.adapter(BusinessIdMeta.BpPassportV1::class.java) as JsonAdapter<BusinessIdMeta>
)
return MoshiBusinessIdMetaAdapter(adapters)
}
}
| 0 | Kotlin | 0 | 0 | f8216d5a942a37c65fc2cfca8e647a0e51d6568a | 2,322 | simple-android | MIT License |
soil-query-compose-runtime/src/commonMain/kotlin/soil/query/compose/runtime/Catch.kt | soil-kt | 789,648,330 | false | {"Kotlin": 789346, "Makefile": 1014} | // Copyright 2024 Soil Contributors
// SPDX-License-Identifier: Apache-2.0
package soil.query.compose.runtime
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import soil.query.core.DataModel
import soil.query.core.uuid
/**
* Catch for a [DataModel] to be rejected.
*
* @param state The [DataModel] to catch.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun Catch(
state: DataModel<*>,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: Throwable) -> Unit = { Throw(error = it) }
) {
Catch(
state = state,
filterIsInstance = { it },
isEnabled = isEnabled,
content = content
)
}
/**
* Catch for any [DataModel]s to be rejected.
*
* @param state1 The first [DataModel] to catch.
* @param state2 The second [DataModel] to catch.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun Catch(
state1: DataModel<*>,
state2: DataModel<*>,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: Throwable) -> Unit = { Throw(error = it) }
) {
Catch(
state1 = state1,
state2 = state2,
filterIsInstance = { it },
isEnabled = isEnabled,
content = content
)
}
/**
* Catch for any [DataModel]s to be rejected.
*
* @param state1 The first [DataModel] to catch.
* @param state2 The second [DataModel] to catch.
* @param state3 The third [DataModel] to catch.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun Catch(
state1: DataModel<*>,
state2: DataModel<*>,
state3: DataModel<*>,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: Throwable) -> Unit = { Throw(error = it) }
) {
Catch(
state1 = state1,
state2 = state2,
state3 = state3,
filterIsInstance = { it },
isEnabled = isEnabled,
content = content
)
}
/**
* Catch for any [DataModel]s to be rejected.
*
* @param states The [DataModel]s to catch.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun Catch(
vararg states: DataModel<*>,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: Throwable) -> Unit = { Throw(error = it) }
) {
Catch(
states = states,
filterIsInstance = { it },
isEnabled = isEnabled,
content = content
)
}
/**
* Catch for a [DataModel] to be rejected.
*
* @param state The [DataModel] to catch.
* @param filterIsInstance A function to filter the error.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun <T : Throwable> Catch(
state: DataModel<*>,
filterIsInstance: (err: Throwable) -> T?,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: T) -> Unit = { Throw(error = it) }
) {
val err = state.error.takeIf { isEnabled }?.let(filterIsInstance)
if (err != null) {
with(CatchScope) { content(err) }
}
}
/**
* Catch for any [DataModel]s to be rejected.
*
* @param state1 The first [DataModel] to catch.
* @param state2 The second [DataModel] to catch.
* @param filterIsInstance A function to filter the error.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun <T : Throwable> Catch(
state1: DataModel<*>,
state2: DataModel<*>,
filterIsInstance: (err: Throwable) -> T?,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: T) -> Unit = { Throw(error = it) }
) {
val err = listOf(state1, state2).takeIf { isEnabled }
?.firstNotNullOfOrNull { it.error }
?.let(filterIsInstance)
if (err != null) {
with(CatchScope) { content(err) }
}
}
/**
* Catch for any [DataModel]s to be rejected.
*
* @param state1 The first [DataModel] to catch.
* @param state2 The second [DataModel] to catch.
* @param state3 The third [DataModel] to catch.
* @param filterIsInstance A function to filter the error.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun <T : Throwable> Catch(
state1: DataModel<*>,
state2: DataModel<*>,
state3: DataModel<*>,
filterIsInstance: (err: Throwable) -> T?,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: T) -> Unit = { Throw(error = it) }
) {
val err = listOf(state1, state2, state3).takeIf { isEnabled }
?.firstNotNullOfOrNull { it.error }
?.let(filterIsInstance)
if (err != null) {
with(CatchScope) { content(err) }
}
}
/**
* Catch for any [DataModel]s to be rejected.
*
* @param states The [DataModel]s to catch.
* @param filterIsInstance A function to filter the error.
* @param isEnabled Whether to catch the error.
* @param content The content to display when the query is rejected. By default, it [throws][CatchScope.Throw] the error.
*/
@Composable
fun <T : Throwable> Catch(
vararg states: DataModel<*>,
filterIsInstance: (err: Throwable) -> T?,
isEnabled: Boolean = true,
content: @Composable CatchScope.(err: T) -> Unit = { Throw(error = it) }
) {
val err = states.takeIf { isEnabled }
?.firstNotNullOfOrNull { it.error }
?.let(filterIsInstance)
if (err != null) {
with(CatchScope) { content(err) }
}
}
/**
* A scope for handling error content within the [Catch] function.
*/
object CatchScope {
/**
* Throw propagates the caught exception to a [CatchThrowHost].
*
* @param error The caught exception.
* @param key The key to identify the caught exception.
* @param host The [CatchThrowHost] to manage the caught exception. By default, it uses the [LocalCatchThrowHost].
*/
@Composable
fun Throw(
error: Throwable,
key: Any? = null,
host: CatchThrowHost = LocalCatchThrowHost.current,
) {
val id = remember(Unit) { key ?: uuid() }
LaunchedEffect(id, error) {
host[id] = error
}
DisposableEffect(id) {
onDispose {
host.remove(id)
}
}
}
}
| 0 | Kotlin | 1 | 109 | 25c3fdd81db98ea44afbaf2776421373ed2d3d05 | 6,989 | soil | Apache License 2.0 |
presentation/src/main/java/com/gugugu/dialog/root/feature/meal/viewmodel/MealViewModel.kt | Team-GuGuGu | 680,772,038 | false | {"Kotlin": 89201} | package com.gugugu.dialog.root.feature.meal.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import com.gugugu.dialog.root.feature.meal.mvi.MealSideEffect
import com.gugugu.dialog.root.feature.meal.mvi.MealState
import com.gugugu.dialog.util.getDate
import com.gugugu.domain.usecase.meal.CreateSchoolUseCase
import com.gugugu.domain.usecase.meal.GetMealUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import org.orbitmvi.orbit.Container
import org.orbitmvi.orbit.ContainerHost
import org.orbitmvi.orbit.syntax.simple.intent
import org.orbitmvi.orbit.syntax.simple.postSideEffect
import org.orbitmvi.orbit.syntax.simple.reduce
import org.orbitmvi.orbit.viewmodel.container
import javax.inject.Inject
@HiltViewModel
class MealViewModel @Inject constructor(
private val getMealUseCase: GetMealUseCase,
private val createSchoolUseCase: CreateSchoolUseCase
): ContainerHost<MealState, MealSideEffect>, ViewModel() {
override val container: Container<MealState, MealSideEffect> = container(MealState())
fun load(date: String) = intent {
getMealUseCase(
GetMealUseCase.Param(
date = date
)
).onSuccess {
Log.d("TAG", "load: $it")
reduce {
state.copy(
loading = false,
mealData = it
)
}
}.onFailure {
Log.d("TAG", "load: $it")
postSideEffect(MealSideEffect.ToastError(it))
}
}
fun schoolSave() = intent {
createSchoolUseCase(
CreateSchoolUseCase.Param(
local = "D10",
schoolCode = "7240454"
)
).onSuccess {
}.onFailure {
postSideEffect(MealSideEffect.ToastError(it))
}
}
} | 2 | Kotlin | 0 | 0 | 281a5d1645c5526cbbf4b89fc69e05d94d72a766 | 1,834 | gugugu-android | MIT License |
exam-mq/src/main/java/io/github/adven27/concordion/extensions/exam/mq/commands/Mq.kt | Adven27 | 97,571,739 | false | null | package io.github.adven27.concordion.extensions.exam.mq.commands
import io.github.adven27.concordion.extensions.exam.core.readFile
import io.github.adven27.concordion.extensions.exam.core.resolveToObj
import org.concordion.api.Element
import org.concordion.api.Evaluator
fun parsePayload(link: Element, eval: Evaluator): String {
link.childElements.filter { it.localName == "code" }.forEach {
parseOption(it).also { (name, value) -> eval.setVariable("#$name", eval.resolveToObj(value)) }
}
return link.getAttributeValue("href").readFile(eval)
}
fun parseOption(el: Element) = el.text.split("=", limit = 2).let { it[0] to it[1] }
| 1 | JavaScript | 4 | 17 | afe287665d835f9f212c00143822e0a0069c7d69 | 652 | Exam | MIT License |
src/jvmMain/kotlin/blue/starry/jsonkt/cli/JsonToKotlinClass.kt | StarryBlueSky | 122,053,336 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 StarryBlueSky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED")
package blue.starry.jsonkt.cli
import blue.starry.jsonkt.*
import blue.starry.jsonkt.cli.property.*
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.util.*
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
fun generateModelClass(): String {
print("Model name? (Optional): ")
val modelName = readLine().orEmpty()
print("Use type strict mode? (Y/n): ")
val printComments = readLine().orEmpty().lowercase(Locale.getDefault()) == "y"
println("Input json string. If blank line is input, quit.")
while (true) {
var text = ""
while (true) {
val line = readLine()
if (line.isNullOrBlank()) {
break
}
text += line
}
try {
return text.toModelString(modelName, printComments)
} catch (e: Throwable) {
System.err.write("Invalid json format: ${e.localizedMessage}\n".toByteArray())
continue
}
}
}
/*
* toModelString
*/
fun JsonObject.toModelString(modelName: String? = null, printComments: Boolean? = null): String {
return JsonToKotlinClass(this).convert(modelName, printComments)
}
fun String.toModelString(modelName: String? = null, printComments: Boolean? = null): String {
return JsonToKotlinClass(toJsonObject()).convert(modelName, printComments)
}
@Suppress("LiftReturnOrAssignment")
class JsonToKotlinClass internal constructor(private val json: JsonObject) {
fun convert(targetModelName: String?, printComments: Boolean?): String {
return buildString {
appendLine("import blue.starry.jsonkt.*")
appendLine("import blue.starry.jsonkt.delegation.*\n")
with(JsonObjectParser(json)) {
val modelName = targetModelName.orEmpty().ifBlank { "Model" }
append(toModelString(modelName, printComments ?: true))
}
nullablePrimitiveCache.clear()
nullableObjectCache.clear()
nullableArrayCache.clear()
}.trimEnd()
}
private class JsonObjectParser(private val json: JsonObject) {
fun toModelString(name: String, printComments: Boolean): String {
return buildString {
val subModels = mutableListOf<String>()
append("data class $name(override val json: JsonObject): JsonModel {\n")
json.map { pair ->
val (key, value) = pair
when (value) {
is JsonObject -> when {
value.toString() == "{}" -> JsonObjectProperty(pair, printComments)
value.isNullable -> JsonNullableModelProperty(pair, printComments)
else -> JsonModelProperty(pair, printComments)
}
is JsonArray -> when {
value.isEmpty() || value.all { element -> element is JsonArray } -> JsonArrayProperty(pair, printComments)
value.all { element -> element is JsonObject } -> when {
value.isNullable -> JsonNullableModelListProperty(pair, printComments)
else -> JsonModelListProperty(pair, printComments)
}
value.all { element -> element is JsonPrimitive } -> JsonPrimitiveListProperty(pair, printComments)
else -> throw IllegalStateException("Not all elements in array are same type. These must be JsonObject, JsonArray or JsonPrimitive. ($key: $value)")
}
is JsonNull -> JsonNullProperty(pair, printComments)
is JsonPrimitive -> when {
value.isNullable -> JsonNullablePrimitiveProperty(pair, printComments)
else -> JsonPrimitiveProperty(pair, printComments)
}
else -> throw IllegalArgumentException("Unknown type: $value")
}
}.sortedBy { it.key }.forEach {
if (it is JsonModelProperty) {
val parser = JsonObjectParser(it.element.jsonObject)
subModels.add(parser.toModelString(it.modelName, printComments))
} else if (it is JsonModelListProperty) {
val values = mutableMapOf<String, MutableSet<JsonElement>>()
it.element.jsonArray.forEach { element ->
element.jsonObject.forEach { k, v ->
if (k in values) {
values[k]?.add(v)
} else {
values[k] = mutableSetOf(v)
}
}
}
val altJson = jsonObjectOf(*values.map { (k, v) ->
when {
v.all { element -> element !is JsonNull } -> k to v.run {
if (all { element -> element is JsonObject }) {
val innerValues = mutableMapOf<String, Pair<MutableSet<JsonElement>, Boolean>>()
forEach { element ->
element.jsonObject.forEach { k, v ->
if (k in innerValues) {
innerValues[k]?.first?.add(v)
} else {
innerValues[k] =
mutableSetOf(v) to (size != count { element -> k in element.jsonObject })
}
}
}
jsonObjectOf(*innerValues.map { (k, v) ->
k to v.run {
first.first().apply {
if (second) {
@Suppress("LiftReturnOrAssignment") when (this) {
is JsonPrimitive -> isNullable = true
is JsonObject -> isNullable = true
is JsonArray -> isNullable = true
}
}
}
}
}.toTypedArray())
} else {
first()
}
}
v.all { element -> element is JsonNull } -> k to JsonNull
else -> k to v.find { element -> element !is JsonNull }!!.apply {
jsonPrimitive.isNullable = true
}
}
}.toTypedArray())
val parser = JsonObjectParser(altJson)
subModels.add(parser.toModelString(it.modelName, printComments))
}
append(" ${it.toPropertyString()}\n")
}
append("}\n\n")
subModels.forEach {
append("$it\n")
}
}.replace("\n\n\n", "\n\n")
}
}
}
private val nullablePrimitiveCache = mutableMapOf<JsonPrimitive, Boolean>()
private var JsonPrimitive.isNullable: Boolean
get() = nullablePrimitiveCache[this] ?: false
set(value) = nullablePrimitiveCache.set(this, value)
private val nullableObjectCache = mutableMapOf<JsonObject, Boolean>()
private var JsonObject.isNullable: Boolean
get() = nullableObjectCache[this] ?: false
set(value) = nullableObjectCache.set(this, value)
private val nullableArrayCache = mutableMapOf<JsonArray, Boolean>()
private var JsonArray.isNullable: Boolean
get() = nullableArrayCache[this] ?: false
set(value) = nullableArrayCache.set(this, value)
| 4 | Kotlin | 0 | 7 | feedf7bd90e11bd9ce29c909b448f04fe3c19207 | 9,889 | Json.kt | MIT License |
app/src/main/java/org/p2p/wallet/solend/model/SolendConfiguration.kt | p2p-org | 306,035,988 | false | null | package org.p2p.wallet.solend.model
class SolendConfiguration
| 8 | Kotlin | 16 | 28 | 71b282491cdafd26be1ffc412a971daaa9c06c61 | 63 | key-app-android | MIT License |
presentation/src/main/java/dev/olog/basil/presentation/main/MainFragmentViewModel.kt | ologe | 167,401,725 | false | null | package dev.olog.basil.presentation.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.olog.basil.core.Ingredient
import dev.olog.basil.core.Recipe
import dev.olog.basil.core.RecipeCategory
import dev.olog.basil.core.RecipeGateway
import dev.olog.basil.presentation.utils.map
import dev.olog.basil.presentation.utils.switchMap
import kotlinx.coroutines.launch
import javax.inject.Inject
class MainFragmentViewModel @Inject constructor(
private val gateway: RecipeGateway
) : ViewModel() {
private val recipesLiveData = MutableLiveData<List<Recipe>>()
private val currentRecipeLiveData = MutableLiveData(0)
private val currentRecipeCategoryPublisher = MutableLiveData(RecipeCategory.Entree)
init {
viewModelScope.launch {
val data = gateway.getAll()
recipesLiveData.value = data
}
}
fun updateVisibleCategory(category: RecipeCategory) {
currentRecipeCategoryPublisher.value = category
}
fun observeCurrentRecipeCategory(): LiveData<RecipeCategory> = currentRecipeCategoryPublisher
fun updatePosition(position: Int) {
currentRecipeLiveData.value = position
}
fun observeRecipes(): LiveData<List<Recipe>> {
return currentRecipeCategoryPublisher.switchMap { category ->
recipesLiveData.map { it.filter { it.category == category } }
}
}
fun observeCurrentRecipe(): LiveData<Recipe?> {
return currentRecipeLiveData.switchMap { index ->
recipesLiveData.map { it.getOrNull(index) }
}
}
fun observeCurrentIngredients(): LiveData<List<Ingredient>> {
return observeCurrentRecipe().map { it?.ingredients ?: emptyList() }
}
}
| 2 | Kotlin | 3 | 11 | c8c3f7991e4fec934d7e1a3018ee6a1be7862dd8 | 1,833 | basil | MIT License |
packages/expo-analytics-segment/android/src/main/java/expo/modules/analytics/segment/SegmentPackage.kt | m-salamon | 386,730,267 | true | {"Objective-C": 19978938, "Java": 19589248, "C++": 9727122, "Objective-C++": 3945281, "TypeScript": 3631776, "Kotlin": 1825787, "JavaScript": 981296, "Starlark": 614816, "Ruby": 596630, "Swift": 470473, "C": 282752, "HTML": 84145, "Shell": 47571, "Assembly": 46734, "Makefile": 40773, "CMake": 13969, "Groovy": 11053, "CSS": 3918, "Batchfile": 89} | package expo.modules.analytics.segment
import android.content.Context
import org.unimodules.core.BasePackage
import org.unimodules.core.ExportedModule
class SegmentPackage : BasePackage() {
override fun createExportedModules(context: Context): List<ExportedModule> {
return listOf(SegmentModule(context))
}
}
| 0 | Objective-C | 0 | 0 | 5079aa440d6196abccdacf88af53d85cd1a007e9 | 319 | expo | MIT License |
sdk/src/main/java/com/mapbox/maps/extension/observable/model/RenderFrameFinishedEventData.kt | mohammadrezabk | 366,568,157 | true | {"Gradle Kotlin DSL": 19, "Markdown": 21, "JSON": 7, "Java Properties": 2, "Shell": 4, "Ignore List": 12, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Makefile": 1, "YAML": 3, "INI": 17, "Kotlin": 572, "XML": 191, "JavaScript": 2, "Java": 39, "Proguard": 3, "Gradle": 5, "CMake": 1, "C++": 1, "Python": 5, "EJS": 1} | package com.mapbox.maps.extension.observable.model
import com.google.gson.annotations.SerializedName
import com.mapbox.maps.plugin.delegates.listeners.eventdata.RenderMode
/**
*The data class for Map Loading Error event data in Observer
*/
data class RenderFrameFinishedEventData(
/**
* The render-mode value tells whether the Map has all data ("full") required to render the visible viewport.
*/
@SerializedName("render-mode") val renderMode: RenderMode,
/**
* The needs-repaint value provides information about ongoing transitions that trigger Map repaint.
*/
@SerializedName("needs-repaint") val needsRepaint: Boolean,
/**
* The placement-changed value tells if the symbol placement has been changed in the visible viewport.
*/
@SerializedName("placement-changed") val placementChanged: Boolean
) | 0 | null | 0 | 0 | 232cd3011936142d35fc76d7353debb74b219659 | 834 | mapbox-maps-android | Apache License 2.0 |
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/common/ExampleUtils.kt | axbaretto | 68,967,334 | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.beam.examples.kotlin.common
import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest
import com.google.api.client.http.HttpRequestInitializer
import com.google.api.services.bigquery.Bigquery
import com.google.api.services.bigquery.model.*
import com.google.api.services.pubsub.Pubsub
import com.google.api.services.pubsub.model.Subscription
import com.google.api.services.pubsub.model.Topic
import com.google.auth.Credentials
import com.google.auth.http.HttpCredentialsAdapter
import com.google.cloud.hadoop.util.ChainingHttpRequestInitializer
import org.apache.beam.sdk.PipelineResult
import org.apache.beam.sdk.extensions.gcp.auth.NullCredentialInitializer
import org.apache.beam.sdk.extensions.gcp.util.RetryHttpRequestInitializer
import org.apache.beam.sdk.extensions.gcp.util.Transport
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryOptions
import org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions
import org.apache.beam.sdk.options.PipelineOptions
import org.apache.beam.sdk.util.BackOffUtils
import org.apache.beam.sdk.util.FluentBackoff
import org.apache.beam.sdk.util.Sleeper
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.Uninterruptibles
import org.joda.time.Duration
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* The utility class that sets up and tears down external resources, and cancels the streaming
* pipelines once the program terminates.
*
*
* It is used to run Beam examples.
*/
class ExampleUtils
/** Do resources and runner options setup. */
(private val options: PipelineOptions) {
private val bigQueryClient: Bigquery by lazy {
newBigQueryClient(options as BigQueryOptions).build()
}
private val pubsubClient: Pubsub by lazy {
newPubsubClient(options as PubsubOptions).build()
}
private val pipelinesToCancel = Sets.newHashSet<PipelineResult>()
private val pendingMessages = Lists.newArrayList<String>()
/**
* Sets up external resources that are required by the example, such as Pub/Sub topics and
* BigQuery tables.
*
* @throws IOException if there is a problem setting up the resources
*/
@Throws(IOException::class)
fun setup() {
val sleeper = Sleeper.DEFAULT
val backOff = FluentBackoff.DEFAULT.withMaxRetries(3).withInitialBackoff(Duration.millis(200)).backoff()
var lastException: Throwable? = null
try {
do {
try {
setupPubsub()
setupBigQueryTable()
return
} catch (e: GoogleJsonResponseException) {
lastException = e
}
} while (BackOffUtils.next(sleeper, backOff))
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
// Ignore InterruptedException
}
throw RuntimeException(lastException)
}
/**
* Sets up the Google Cloud Pub/Sub topic.
*
*
* If the topic doesn't exist, a new topic with the given name will be created.
*
* @throws IOException if there is a problem setting up the Pub/Sub topic
*/
@Throws(IOException::class)
fun setupPubsub() {
val pubsubOptions = options as ExamplePubsubTopicAndSubscriptionOptions
if (pubsubOptions.pubsubTopic.isNotEmpty()) {
pendingMessages.add("**********************Set Up Pubsub************************")
setupPubsubTopic(pubsubOptions.pubsubTopic)
pendingMessages.add(
"The Pub/Sub topic has been set up for this example: ${pubsubOptions.pubsubTopic}")
if (pubsubOptions.pubsubSubscription.isNotEmpty()) {
setupPubsubSubscription(
pubsubOptions.pubsubTopic, pubsubOptions.pubsubSubscription)
pendingMessages.add(
"The Pub/Sub subscription has been set up for this example: ${pubsubOptions.pubsubSubscription}")
}
}
}
/**
* Sets up the BigQuery table with the given schema.
*
*
* If the table already exists, the schema has to match the given one. Otherwise, the example
* will throw a RuntimeException. If the table doesn't exist, a new table with the given schema
* will be created.
*
* @throws IOException if there is a problem setting up the BigQuery table
*/
@Throws(IOException::class)
fun setupBigQueryTable() {
val bigQueryTableOptions = options as ExampleBigQueryTableOptions
pendingMessages.add("******************Set Up Big Query Table*******************")
setupBigQueryTable(
bigQueryTableOptions.project,
bigQueryTableOptions.bigQueryDataset,
bigQueryTableOptions.bigQueryTable,
bigQueryTableOptions.bigQuerySchema)
pendingMessages.add(
"""
The BigQuery table has been set up for this example:
${bigQueryTableOptions.project}:
${bigQueryTableOptions.bigQueryDataset}.
${bigQueryTableOptions.bigQueryTable}
""".trimIndent()
)
}
/** Tears down external resources that can be deleted upon the example's completion. */
private fun tearDown() {
pendingMessages.add("*************************Tear Down*************************")
val pubsubOptions = options as ExamplePubsubTopicAndSubscriptionOptions
if (pubsubOptions.pubsubTopic.isNotEmpty()) {
try {
deletePubsubTopic(pubsubOptions.pubsubTopic)
pendingMessages.add(
"The Pub/Sub topic has been deleted: ${pubsubOptions.pubsubTopic}")
} catch (e: IOException) {
pendingMessages.add(
"Failed to delete the Pub/Sub topic : ${pubsubOptions.pubsubTopic}")
}
if (pubsubOptions.pubsubSubscription.isNotEmpty()) {
try {
deletePubsubSubscription(pubsubOptions.pubsubSubscription)
pendingMessages.add(
"The Pub/Sub subscription has been deleted: ${pubsubOptions.pubsubSubscription}")
} catch (e: IOException) {
pendingMessages.add(
"Failed to delete the Pub/Sub subscription : ${pubsubOptions.pubsubSubscription}")
}
}
}
val bigQueryTableOptions = options as ExampleBigQueryTableOptions
pendingMessages.add(
"""
The BigQuery table might contain the example's output, and it is not deleted automatically:
${bigQueryTableOptions.project}:
${bigQueryTableOptions.bigQueryDataset}.
${bigQueryTableOptions.bigQueryTable}
""".trimIndent())
pendingMessages.add(
"Please go to the Developers Console to delete it manually. Otherwise, you may be charged for its usage.")
}
@Throws(IOException::class)
private fun setupBigQueryTable(
projectId: String, datasetId: String, tableId: String, schema: TableSchema) {
val datasetService = bigQueryClient.datasets()
if (executeNullIfNotFound(datasetService.get(projectId, datasetId)) == null) {
val newDataset = Dataset()
.setDatasetReference(
DatasetReference().setProjectId(projectId).setDatasetId(datasetId))
datasetService.insert(projectId, newDataset).execute()
}
val tableService = bigQueryClient.tables()
val table = executeNullIfNotFound(tableService.get(projectId, datasetId, tableId))
table?.let {
if (it.schema != schema) {
throw RuntimeException(
"""
Table exists and schemas do not match, expecting:
${schema.toPrettyString()}, actual:
${table.schema.toPrettyString()}
""".trimIndent()
)
}
} ?: run {
val newTable = Table()
.setSchema(schema)
.setTableReference(
TableReference()
.setProjectId(projectId)
.setDatasetId(datasetId)
.setTableId(tableId))
tableService.insert(projectId, datasetId, newTable).execute()
}
}
@Throws(IOException::class)
private fun setupPubsubTopic(topic: String) =
pubsubClient.projects().topics().create(topic, Topic().setName(topic)).execute()
@Throws(IOException::class)
private fun setupPubsubSubscription(topic: String, subscription: String) {
val subInfo = Subscription().setAckDeadlineSeconds(60).setTopic(topic)
pubsubClient.projects().subscriptions().create(subscription, subInfo).execute()
}
/**
* Deletes the Google Cloud Pub/Sub topic.
*
* @throws IOException if there is a problem deleting the Pub/Sub topic
*/
@Throws(IOException::class)
private fun deletePubsubTopic(topic: String) {
with(pubsubClient.projects().topics()) {
executeNullIfNotFound(get(topic))?.let {
delete(topic).execute()
}
}
}
/**
* Deletes the Google Cloud Pub/Sub subscription.
*
* @throws IOException if there is a problem deleting the Pub/Sub subscription
*/
@Throws(IOException::class)
private fun deletePubsubSubscription(subscription: String) {
with(pubsubClient.Projects().subscriptions()) {
get(subscription)?.let {
delete(subscription).execute()
}
}
}
/** Waits for the pipeline to finish and cancels it before the program exists. */
fun waitToFinish(result: PipelineResult) {
pipelinesToCancel.add(result)
if (!(options as ExampleOptions).keepJobsRunning) {
addShutdownHook(pipelinesToCancel)
}
try {
result.waitUntilFinish()
} catch (e: UnsupportedOperationException) {
// Do nothing if the given PipelineResult doesn't support waitUntilFinish(),
// such as EvaluationResults returned by DirectRunner.
tearDown()
printPendingMessages()
} catch (e: Exception) {
throw RuntimeException("Failed to wait the pipeline until finish: $result")
}
}
private fun addShutdownHook(pipelineResults: Collection<PipelineResult>) {
Runtime.getRuntime()
.addShutdownHook(
Thread {
tearDown()
printPendingMessages()
for (pipelineResult in pipelineResults) {
try {
pipelineResult.cancel()
} catch (e: IOException) {
println("Failed to cancel the job.")
println(e.message)
}
}
for (pipelineResult in pipelineResults) {
var cancellationVerified = false
for (retryAttempts in 6 downTo 1) {
if (pipelineResult.state.isTerminal) {
cancellationVerified = true
break
} else {
println(
"The example pipeline is still running. Verifying the cancellation.")
}
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS)
}
if (!cancellationVerified) {
println(
"Failed to verify the cancellation for job: $pipelineResult")
}
}
})
}
private fun printPendingMessages() {
println()
println("***********************************************************")
println("***********************************************************")
for (message in pendingMessages) {
println(message)
}
println("***********************************************************")
println("***********************************************************")
}
companion object {
private const val SC_NOT_FOUND = 404
/**
* \p{L} denotes the category of Unicode letters, so this pattern will match on everything that is
* not a letter.
*
*
* It is used for tokenizing strings in the wordcount examples.
*/
const val TOKENIZER_PATTERN = "[^\\p{L}]+"
/** Returns a BigQuery client builder using the specified [BigQueryOptions]. */
private fun newBigQueryClient(options: BigQueryOptions): Bigquery.Builder {
return Bigquery.Builder(
Transport.getTransport(),
Transport.getJsonFactory(),
chainHttpRequestInitializer(
options.gcpCredential,
// Do not log 404. It clutters the output and is possibly even required by the
// caller.
RetryHttpRequestInitializer(ImmutableList.of(404))))
.setApplicationName(options.appName)
.setGoogleClientRequestInitializer(options.googleApiTrace)
}
/** Returns a Pubsub client builder using the specified [PubsubOptions]. */
private fun newPubsubClient(options: PubsubOptions): Pubsub.Builder {
return Pubsub.Builder(
Transport.getTransport(),
Transport.getJsonFactory(),
chainHttpRequestInitializer(
options.gcpCredential,
// Do not log 404. It clutters the output and is possibly even required by the
// caller.
RetryHttpRequestInitializer(ImmutableList.of(404))))
.setRootUrl(options.pubsubRootUrl)
.setApplicationName(options.appName)
.setGoogleClientRequestInitializer(options.googleApiTrace)
}
private fun chainHttpRequestInitializer(
credential: Credentials?, httpRequestInitializer: HttpRequestInitializer): HttpRequestInitializer {
return credential?.let {
ChainingHttpRequestInitializer(
HttpCredentialsAdapter(credential), httpRequestInitializer)
} ?: run {
ChainingHttpRequestInitializer(
NullCredentialInitializer(), httpRequestInitializer)
}
}
@Throws(IOException::class)
private fun <T> executeNullIfNotFound(request: AbstractGoogleClientRequest<T>): T? {
return try {
request.execute()
} catch (e: GoogleJsonResponseException) {
if (e.statusCode == SC_NOT_FOUND) {
null
} else {
throw e
}
}
}
}
}
| 74 | null | 4252 | 9 | c20455fe0a97c885a8ef11d60d3381020c9f1bdc | 16,995 | beam | Apache License 2.0 |
mill-router/src/androidMain/kotlin/coder/stanley/mill/router/Utils.kt | ZegJoker | 704,425,127 | false | {"Kotlin": 49503} | package coder.stanley.mill.router
import java.util.UUID
internal actual fun uuid(): String {
return UUID.randomUUID().toString()
}
| 0 | Kotlin | 0 | 2 | ec45dd62712b9654c7794d50b53a2461b099c3af | 137 | mill | Apache License 2.0 |
src/main/kotlin/com/team2898/robot/commands/Balance/DriveOntoChargestation.kt | bpsrobotics | 587,113,427 | false | {"Kotlin": 160018} | package com.team2898.robot.commands.Balance
import com.bpsrobotics.engine.utils.`M/s`
import com.bpsrobotics.engine.utils.MovingAverage
import com.team2898.robot.subsystems.Drivetrain
import com.team2898.robot.subsystems.Odometry
import edu.wpi.first.wpilibj.Timer
import edu.wpi.first.wpilibj2.command.CommandBase
import kotlin.math.absoluteValue
/**
* Drives until the robot thinks it's on charge station (The pitch changes)
* @property direction The direction in which to drive
*/
class DriveOntoChargestation(private val direction: DriveDirection) : CommandBase() {
/** The pitch of the robot */
private val pitchAvg = MovingAverage(16)
/** Stops the robot if it doesn't tip within a timeframe */
private val stopTimer = Timer()
override fun initialize() {
stopTimer.reset()
stopTimer.start()
}
override fun execute() {
pitchAvg.add(Odometry.NavxHolder.navx.pitch.toDouble())
// If timer hasn't elapsed one second, continue trying to drive onto charge station
if(!stopTimer.hasElapsed(1.0)){
Drivetrain.stupidDrive(`M/s`(1.0 * direction.multiplier), `M/s`(1.0 * direction.multiplier))
} else {
// If robot pitch hasn't changed yet, it is not infront of charge station, so stop running.
Drivetrain.stupidDrive(`M/s`(0.0), `M/s`(0.0))
}
}
override fun end(interrupted: Boolean) {
//Stop robot
Drivetrain.fullStop()
}
override fun isFinished(): Boolean {
//If the pitch for each respective direction has been reached, stop.
return pitchAvg.average.absoluteValue > 5.0
}
} | 0 | Kotlin | 0 | 2 | 5505250ed263fe1ec273b325c3228cc6e340cbba | 1,650 | 2898-2023-charged-up | Apache License 2.0 |
app/src/main/java/com/arvinq/urbandictionaryandroid/MainActivity.kt | arvinq | 283,706,589 | false | null | package com.arvinq.urbandictionaryandroid
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
// viewDidLoad equivalent
// only called once but when app is rotated,
// activity is reloaded again which in turn calls this onCreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) //like loadView()
searchButton.setOnClickListener {
println("${textField.text}") //prints the text in textfield
println("$textField") //prints the textfield object
navigateToSearchResultsForWord(textField.text.toString())
}
}
private fun navigateToSearchResultsForWord(word: String) {
// let intent = Intent(self, SearchResultsActivity.self) //swift equivalent
val intent = Intent(this, SearchResultsActivity::class.java)
intent.putExtra(termKey, word) //one way of passing in values across multiple activity
startActivity(intent)
}
companion object {
//static let termKey = "termKey"
const val termKey = "termKey"
}
} | 0 | Kotlin | 0 | 0 | 670251e4631b004e65b46642f236e2a203468b59 | 1,281 | urbanDictionary | MIT License |
app/src/main/java/com/crinoid/socialloginhelper/instagram/basicdisplay/BDInstagramHelper.kt | CrinoidTechnologies | 228,843,233 | false | null | package com.crinoid.socialloginhelper.instagram.basicdisplay
import android.content.Context
import android.text.TextUtils
import androidx.fragment.app.FragmentManager
import com.crinoid.retrofit.MyRetrofitApiInterface
import com.crinoid.socialloginhelper.instagram.AuthenticationDialog
import com.crinoid.socialloginhelper.instagram.Globals.*
import com.crinoid.utils.SharedPrefs
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class BDInstagramHelper : AuthenticationDialog.AuthenticationListener {
private var mAuhListener: DataListener<InstagramBDUserData>? = null
private var isLoggingIn = false
val isLoggedIn: Boolean
get() = !TextUtils.isEmpty(sharedPrefs.localData.AccessToken?.accessToken) && sharedPrefs.localData.instaUserBd != null
val userData: InstagramBDUserData?
get() = sharedPrefs.localData.instaUserBd
fun logout() {
sharedPrefs.localData.AccessToken = null
sharedPrefs.localData.instaUserBd = null
sharedPrefs.saveDataLocally()
}
fun performLogin(
fragmentManager: FragmentManager,
authListener: DataListener<InstagramBDUserData>?,
languageCode: String?
) {
if (isLoggedIn) {
authListener?.onSuccess(sharedPrefs.localData.instaUserBd)
return
}
if (isLoggingIn) {
return
}
isLoggingIn = true
this.mAuhListener = authListener
val authenticationDialog = AuthenticationDialog(
this,
INSTAGRAM_BASE_URL +
"oauth/authorize/?app_id=" +
INSTAGRAM_APP_ID +
"&redirect_uri=" + INSTAGRAM_REDIRECT_URL +
"&response_type=code&display=touch&scope=" + INSTAGRAM_LOGIN_SCOPES,
languageCode
)
val ft = fragmentManager.beginTransaction()
val prev = fragmentManager.findFragmentByTag("dialog")
if (prev != null) {
ft.remove(prev)
}
ft.addToBackStack(null)
authenticationDialog.isCancelable = true
authenticationDialog.show(ft, "dialog")
}
override fun onCodeReceived(code: String?) {
sharedPrefs.localData.instaAcessCode = code
sharedPrefs.saveDataLocally()
fetchShortLivedAccessToken(object : DataListener<AccessTokenWithCodeResponseData> {
override fun onSuccess(data: AccessTokenWithCodeResponseData?) {
data?.let {
fetchLongLivedAccessToken(object :
DataListener<AccessTokenRefreshResponseData> {
override fun onSuccess(data: AccessTokenRefreshResponseData?) {
fetchProfileData(object : DataListener<InstagramBDUserData> {
override fun onSuccess(data: InstagramBDUserData?) {
isLoggingIn = false
if (mAuhListener != null) {
mAuhListener!!.onSuccess(data)
}
}
override fun onFailure(error: String?) {
isLoggingIn = false
sharedPrefs.localData.AccessToken = null
sharedPrefs.saveDataLocally()
mAuhListener?.onFailure(error)
}
}, true)
}
override fun onFailure(error: String?) {
mAuhListener?.onFailure(error)
}
}, it.accessToken)
}
}
override fun onFailure(error: String?) {
mAuhListener?.onFailure(error)
}
})
}
override fun onTokenReceived(auth_token: String) {
}
override fun onError(error: String) {
isLoggingIn = false
if (mAuhListener != null) {
mAuhListener!!.onFailure(error)
}
}
override fun onComplete() {
isLoggingIn = false
}
interface DataListener<T> {
fun onSuccess(data: T?)
fun onFailure(error: String?)
}
companion object {
private const val API_END_POINT = "https://graph.instagram.com/"
private const val USER_API_END_POINT = API_END_POINT
const val SELF_USER_API_END_POINT = USER_API_END_POINT + "me/"
const val EXCHANGE_ACCESS_TOKEN_API_END_POINT = API_END_POINT + "access_token"
const val REFRESH_ACCESS_TOKEN_API_END_POINT = API_END_POINT + "refresh_access_token"
const val GET_ACCESS_TOKEN_FROM_CODE_API_END_POINT =
INSTAGRAM_BASE_URL + "oauth/access_token"
var API_BASE_URL = "https://your.api-base.url"
var READ_OUT_TIME = 50000
var WRITE_OUT_TIME = 50000
private val apiInterface: MyRetrofitApiInterface
private lateinit var sharedPrefs: SharedPrefs
fun initialiseWithContext(context: Context) {
sharedPrefs = SharedPrefs(context = context)
}
init {
var httpClient = OkHttpClient.Builder()
httpClient.readTimeout(READ_OUT_TIME.toLong(), TimeUnit.MILLISECONDS)
httpClient.connectTimeout(WRITE_OUT_TIME.toLong(), TimeUnit.MILLISECONDS)
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
httpClient.addInterceptor(logging)
var builder =
Retrofit.Builder().baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
builder.client(httpClient.build())
var retrofit = builder.build()
apiInterface = retrofit.create(MyRetrofitApiInterface::class.java)
}
fun fetchProfileData(listener: DataListener<InstagramBDUserData>?, forceRefresh: Boolean) {
if (!forceRefresh && sharedPrefs.localData.instaUserBd != null) {
listener?.onSuccess(sharedPrefs.localData.instaUserBd)
return
}
apiInterface.getSelfBDInstagramProfile(
sharedPrefs.localData.AccessToken?.accessToken!!,
INSTAGRAM_USER_FIELDS
)
.enqueue(object : Callback<InstagramBDUserData> {
override fun onResponse(
call: Call<InstagramBDUserData>,
response: Response<InstagramBDUserData>
) {
if (response.body() != null) {
sharedPrefs.localData.instaUserBd = response.body()
sharedPrefs.saveDataLocally()
listener?.onSuccess(sharedPrefs.localData.instaUserBd)
} else {
listener?.onFailure("")
}
}
override fun onFailure(
call: Call<InstagramBDUserData>,
t: Throwable
) {
listener?.onFailure(t.message)
}
})
}
fun fetchShortLivedAccessToken(
listener: DataListener<AccessTokenWithCodeResponseData>?
) {
if (sharedPrefs.localData.instaAcessCode == null) {
listener?.onFailure("Access code is not set. Please authorize app by login first")
return
}
apiInterface.getIGAccessTokenFromCode(
INSTAGRAM_APP_ID,
INSTAGRAM_APP_SECRET,
"authorization_code",
INSTAGRAM_REDIRECT_URL,
sharedPrefs.localData.instaAcessCode!!
)
.enqueue(object : Callback<AccessTokenWithCodeResponseData> {
override fun onResponse(
call: Call<AccessTokenWithCodeResponseData>,
response: Response<AccessTokenWithCodeResponseData>
) {
if (response.body() != null) {
if (response.body()?.errorMessage == null) {
listener?.onSuccess(response.body())
} else {
listener?.onFailure(response.body()?.errorMessage)
}
} else {
var tmp = response.errorBody()?.string()
listener?.onFailure(response.errorBody()?.string())
}
}
override fun onFailure(
call: Call<AccessTokenWithCodeResponseData>,
t: Throwable
) {
listener?.onFailure(t.message)
}
})
}
fun fetchLongLivedAccessToken(
listener: DataListener<AccessTokenRefreshResponseData>?, shortLivedAccessToken: String
) {
apiInterface.exchangeIGBDAccessToken(
shortLivedAccessToken,
INSTAGRAM_APP_SECRET,
IGBD_GRANT_TYPE_EXCHANGE
)
.enqueue(object : Callback<AccessTokenRefreshResponseData> {
override fun onResponse(
call: Call<AccessTokenRefreshResponseData>,
response: Response<AccessTokenRefreshResponseData>
) {
if (response.body() != null) {
if (response.body()?.error == null) {
sharedPrefs.localData.AccessToken = response.body()
listener?.onSuccess(response.body())
} else {
listener?.onFailure(response.body()?.error?.message)
}
} else {
listener?.onFailure("")
}
}
override fun onFailure(
call: Call<AccessTokenRefreshResponseData>,
t: Throwable
) {
listener?.onFailure(t.message)
}
})
}
fun refreshTokenIfNeeded(listener: DataListener<AccessTokenRefreshResponseData>?): Boolean {
if (sharedPrefs.isLoggedIn()) {
sharedPrefs.localData.AccessToken?.let {
var diff =
System.currentTimeMillis() - sharedPrefs.localData.iGBDTokenRefreshTime
if (diff > it.expiresInMillis * 0.8f) {
refreshLongLivedAccessToken(listener, it.accessToken)
return true
}
}
}
return false
}
fun refreshLongLivedAccessToken(
listener: DataListener<AccessTokenRefreshResponseData>?, expiredAccessToken: String
) {
apiInterface.refreshIGBDAccessToken(
expiredAccessToken,
INSTAGRAM_APP_SECRET,
IGBD_GRANT_TYPE_REFRESH
)
.enqueue(object : Callback<AccessTokenRefreshResponseData> {
override fun onResponse(
call: Call<AccessTokenRefreshResponseData>,
response: Response<AccessTokenRefreshResponseData>
) {
if (response.body() != null) {
if (response.body()?.error == null) {
sharedPrefs.localData.AccessToken = response.body()
listener?.onSuccess(response.body())
} else {
listener?.onFailure(response.body()?.error?.message)
}
} else {
listener?.onFailure("")
}
}
override fun onFailure(
call: Call<AccessTokenRefreshResponseData>,
t: Throwable
) {
listener?.onFailure(t.message)
}
})
}
}
}
| 1 | Kotlin | 1 | 2 | 1fbeed7498b8cdbe29683fcf8db76b7f7aa3f60f | 12,803 | android-social-login-helper | MIT License |
app/src/main/java/com/tomorrowit/datacollect/presentation/place_and_time/PlaceAndTimeActivity.kt | 2Morrow-IT-Solutions | 800,950,127 | false | {"Kotlin": 95553} | package com.tomorrowit.datacollect.presentation.place_and_time
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.tomorrowit.datacollect.databinding.ActivityPlaceAndTimeBinding
import com.tomorrowit.datacollect.domain.models.BasicDataModel
import com.tomorrowit.datacollect.presentation.adapters.RecyclerViewAdapterBasicDataModel
import com.tomorrowit.datacollect.utils.extensions.finishAnimation
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
@AndroidEntryPoint
class PlaceAndTimeActivity : AppCompatActivity() {
private lateinit var binding: ActivityPlaceAndTimeBinding
private val viewModel: PlaceAndTimeViewModel by viewModels()
private lateinit var recyclerViewAdapter: RecyclerViewAdapterBasicDataModel
private val arrayData: MutableList<BasicDataModel> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPlaceAndTimeBinding.inflate(layoutInflater)
setContentView(binding.root)
observeState()
binding.activitySpaceAndTimeToolbar.setNavigationOnClickListener {
this.finish()
}
recyclerViewAdapter = RecyclerViewAdapterBasicDataModel(
this,
arrayData
)
binding.activitySpaceAndTimeRv.adapter = recyclerViewAdapter
}
private fun observeState() {
viewModel.state.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).distinctUntilChanged()
.onEach { state ->
when (state) {
is PlaceAndTimeState.Init -> {}
is PlaceAndTimeState.ShowList -> {
setRv(state.list)
}
}
}.launchIn(lifecycleScope)
}
private suspend fun setRv(list: List<BasicDataModel>) {
withContext(Dispatchers.Main) {
arrayData.clear()
arrayData.addAll(list)
}
}
override fun finish() {
super.finish()
finishAnimation()
}
} | 0 | Kotlin | 0 | 0 | 38d6333a12e87acd62c82464867fce420fba7de1 | 2,419 | data-collect | MIT License |
sdkpushexpress/src/main/java/com/pushexpress/sdk/local_settings/SdkSettingsRepositoryImpl.kt | pushexpress | 600,907,986 | false | null | package com.pushexpress.sdk.local_settings
import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import java.util.*
class SdkSettingsRepositoryImpl(private val context: Context) : SdkSettingsRepository {
private val Context.dataStore: DataStore<Preferences> by
preferencesDataStore(name = "sdkpushexpress")
private val instanceToken = stringPreferencesKey(INSTANCE_TOKEN)
private val installTs = longPreferencesKey(INSTALL_TS)
private val appId = stringPreferencesKey(APP_ID)
private val extId = stringPreferencesKey(EXT_ID)
@Volatile
private var firebaseToken: String? = null
private val onscreenCnt = intPreferencesKey(ONSCREEN_CNT)
private val onscreenSec = longPreferencesKey(ONSCREEN_SEC)
private val resumedTs = longPreferencesKey(RESUMED_TS)
private val stoppedTs = longPreferencesKey(STOPPED_TS)
init {
runBlocking {
if (isSdkWasNotInitialized()) {
context.dataStore.edit { settings ->
settings[instanceToken] = UUID.randomUUID().toString()
settings[installTs] = System.currentTimeMillis() / 1000
settings[appId] = ""
settings[extId] = ""
settings[onscreenCnt] = 0
settings[onscreenSec] = 0
settings[resumedTs] = 0
settings[stoppedTs] = 0
}
}
}
}
override fun saveFirebaseToken(firebaseToken: String) {
this.firebaseToken = firebaseToken
}
override suspend fun savePushExpressExternalId(externalId: String) {
context.dataStore.edit { settings ->
settings[this.extId] = externalId
}
}
override suspend fun savePushExpressAppId(pushExpressAppId: String) {
context.dataStore.edit { settings ->
settings[this.appId] = pushExpressAppId
}
}
override suspend fun updateAppResumed() {
context.dataStore.edit { settings ->
settings[onscreenCnt] = (settings[onscreenCnt] ?: 0) + 1
settings[resumedTs] = System.currentTimeMillis() / 1000
Log.d(TAG, "appResumed: ${settings[resumedTs]} " +
"${settings[onscreenCnt]} ${settings[onscreenSec] ?: 0}")
}
}
override suspend fun updateAppStopped() {
context.dataStore.edit { settings ->
val nowTs = System.currentTimeMillis() / 1000
val lastResumedTs = settings[resumedTs] ?: nowTs
val fgSec = (nowTs - lastResumedTs).coerceAtLeast(0)
settings[onscreenSec] = (settings[onscreenSec] ?:0) + fgSec
settings[stoppedTs] = nowTs
Log.d(TAG, "appStopped: ${settings[stoppedTs]} ${settings[onscreenCnt]} ${settings[onscreenSec]}")
}
}
override suspend fun getSdkSettings(): SdkSettings {
return context.dataStore.data.map {
SdkSettings(
it[instanceToken].orEmpty(),
it[installTs] ?: 0,
it[appId].orEmpty(),
it[extId].orEmpty(),
firebaseToken,
it[onscreenCnt] ?: 0,
it[onscreenSec] ?: 0,
it[resumedTs] ?: 0,
it[stoppedTs] ?: 0,
)
}.first()
}
private suspend fun isSdkWasNotInitialized() = context.dataStore.data.first()[instanceToken] == null
companion object {
private const val INSTANCE_TOKEN = "ic_token"
private const val INSTALL_TS = "install_ts"
private const val APP_ID = "app_id"
private const val EXT_ID = "ext_id"
private const val ONSCREEN_CNT = "onscreen_cnt"
private const val ONSCREEN_SEC = "onscreen_sec"
private const val RESUMED_TS = "resumed_ts"
private const val STOPPED_TS = "stopped_ts"
private const val TAG = "SdkPushExpress"
}
} | 0 | Kotlin | 0 | 2 | 859b31c5d13a8f5283789993e0e1e43f6c652657 | 4,209 | pushexpress-android-sdk | Apache License 2.0 |
src/test/kotlin/io/dmitrijs/aoc2022/Day09Test.kt | lakiboy | 578,268,213 | false | null | package io.dmitrijs.aoc2022
import io.dmitrijs.aoc2022.Resources.resourceAsLines
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import kotlin.test.Test
import kotlin.test.assertEquals
@DisplayName("Day 9")
internal class Day09Test {
private val problemInput = resourceAsLines("day09")
private val exampleInput = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent().lines()
@Nested
@DisplayName("Puzzle 1")
inner class Puzzle1 {
@Test
fun `solves example`() {
assertEquals(13, Day09(exampleInput).puzzle1())
}
@Test
fun `solves problem`() {
assertEquals(6_503, Day09(problemInput).puzzle1())
}
}
@Nested
@DisplayName("Puzzle 2")
inner class Puzzle2 {
@Test
fun `solves example`() {
assertEquals(1, Day09(exampleInput).puzzle2())
}
@Test
fun `solves example2`() {
val exampleInput = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lines()
assertEquals(36, Day09(exampleInput).puzzle2())
}
@Test
fun `solves problem`() {
assertEquals(2_724, Day09(problemInput).puzzle2())
}
}
}
| 0 | Kotlin | 0 | 1 | 8c09e743c90ba5d8fa787b10f3383dd18a52a2ff | 1,462 | advent-of-code-2022-kotlin | Apache License 2.0 |
app/src/main/java/com/wasisto/camrnghttp/server/domain/interfaces/Rng.kt | awasisto | 359,086,572 | false | null | /*
* Copyright 2021 Andika Wasisto
*
* 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.wasisto.camrnghttp.server.domain.interfaces
interface Rng {
fun randBytes(bytes: ByteArray)
} | 0 | Kotlin | 2 | 1 | aa16e9b8435211b45896dad34364f06cc635b689 | 705 | camrng-http | Apache License 2.0 |
app/src/main/java/dev/gusriil/mindfullconnect/android/MindfullConnectApplication.kt | gusriil | 462,092,296 | false | null | package dev.gusriil.mindfullconnect.android
import android.app.Application
import dev.gusriil.mindfullconnect.android.koin.accountModule
import dev.gusriil.mindfullconnect.android.koin.networkModule
import dev.gusriil.mindfullconnect.android.koin.viewModelsModule
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
class MindfullConnectApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MindfullConnectApplication)
modules(accountModule, viewModelsModule, networkModule)
}
}
} | 0 | Kotlin | 0 | 2 | e67415e2dda0121911cbd2a41852ac44411570d8 | 625 | MindfullConnect | Apache License 2.0 |
monarch-language-pack/src/main/kotlin/io/github/dingyi222666/monarch/languages/LanguageWgsl.kt | dingyi222666 | 757,956,116 | false | {"Kotlin": 3309534} | package io.github.dingyi222666.monarch.languages
import io.github.dingyi222666.monarch.common.*
import io.github.dingyi222666.monarch.loader.dsl.*
import io.github.dingyi222666.monarch.types.IMonarchLanguage
public val WgslLanguage: IMonarchLanguage by lazy {
buildMonarchLanguage {
tokenPostfix = ".wgsl"
unicode = true
defaultToken = "invalid"
"atoms" and listOf("true", "false")
keywords("alias", "break", "case", "const", "const_assert", "continue", "continuing", "default",
"diagnostic", "discard", "else", "enable", "fn", "for", "if", "let", "loop", "override",
"requires", "return", "struct", "switch", "var", "while")
"reserved" and listOf("NULL", "Self", "abstract", "active", "alignas", "alignof", "as", "asm",
"asm_fragment", "async", "attribute", "auto", "await", "become", "binding_array", "cast",
"catch", "class", "co_await", "co_return", "co_yield", "coherent", "column_major", "common",
"compile", "compile_fragment", "concept", "const_cast", "consteval", "constexpr",
"constinit", "crate", "debugger", "decltype", "delete", "demote", "demote_to_helper", "do",
"dynamic_cast", "enum", "explicit", "export", "extends", "extern", "external",
"fallthrough", "filter", "final", "finally", "friend", "from", "fxgroup", "get", "goto",
"groupshared", "highp", "impl", "implements", "import", "inline", "instanceof", "interface",
"layout", "lowp", "macro", "macro_rules", "match", "mediump", "meta", "mod", "module",
"move", "mut", "mutable", "namespace", "new", "nil", "noexcept", "noinline",
"nointerpolation", "noperspective", "null", "nullptr", "of", "operator", "package",
"packoffset", "partition", "pass", "patch", "pixelfragment", "precise", "precision",
"premerge", "priv", "protected", "pub", "public", "readonly", "ref", "regardless",
"register", "reinterpret_cast", "require", "resource", "restrict", "self", "set", "shared",
"sizeof", "smooth", "snorm", "static", "static_assert", "static_cast", "std", "subroutine",
"super", "target", "template", "this", "thread_local", "throw", "trait", "try", "type",
"typedef", "typeid", "typename", "typeof", "union", "unless", "unorm", "unsafe", "unsized",
"use", "using", "varying", "virtual", "volatile", "wgsl", "where", "with", "writeonly",
"yield")
"predeclared_enums" and listOf("read", "write", "read_write", "function", "private",
"workgroup", "uniform", "storage", "perspective", "linear", "flat", "center", "centroid",
"sample", "vertex_index", "instance_index", "position", "front_facing", "frag_depth",
"local_invocation_id", "local_invocation_index", "global_invocation_id", "workgroup_id",
"num_workgroups", "sample_index", "sample_mask", "rgba8unorm", "rgba8snorm", "rgba8uint",
"rgba8sint", "rgba16uint", "rgba16sint", "rgba16float", "r32uint", "r32sint", "r32float",
"rg32uint", "rg32sint", "rg32float", "rgba32uint", "rgba32sint", "rgba32float",
"bgra8unorm")
"predeclared_types" and listOf("bool", "f16", "f32", "i32", "sampler", "sampler_comparison",
"texture_depth_2d", "texture_depth_2d_array", "texture_depth_cube",
"texture_depth_cube_array", "texture_depth_multisampled_2d", "texture_external",
"texture_external", "u32")
"predeclared_type_generators" and listOf("array", "atomic", "mat2x2", "mat2x3", "mat2x4",
"mat3x2", "mat3x3", "mat3x4", "mat4x2", "mat4x3", "mat4x4", "ptr", "texture_1d",
"texture_2d", "texture_2d_array", "texture_3d", "texture_cube", "texture_cube_array",
"texture_multisampled_2d", "texture_storage_1d", "texture_storage_2d",
"texture_storage_2d_array", "texture_storage_3d", "vec2", "vec3", "vec4")
"predeclared_type_aliases" and listOf("vec2i", "vec3i", "vec4i", "vec2u", "vec3u", "vec4u",
"vec2f", "vec3f", "vec4f", "vec2h", "vec3h", "vec4h", "mat2x2f", "mat2x3f", "mat2x4f",
"mat3x2f", "mat3x3f", "mat3x4f", "mat4x2f", "mat4x3f", "mat4x4f", "mat2x2h", "mat2x3h",
"mat2x4h", "mat3x2h", "mat3x3h", "mat3x4h", "mat4x2h", "mat4x3h", "mat4x4h")
"predeclared_intrinsics" and listOf("bitcast", "all", "any", "select", "arrayLength", "abs",
"acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "ceil", "clamp", "cos", "cosh",
"countLeadingZeros", "countOneBits", "countTrailingZeros", "cross", "degrees",
"determinant", "distance", "dot", "exp", "exp2", "extractBits", "faceForward",
"firstLeadingBit", "firstTrailingBit", "floor", "fma", "fract", "frexp", "inverseBits",
"inverseSqrt", "ldexp", "length", "log", "log2", "max", "min", "mix", "modf", "normalize",
"pow", "quantizeToF16", "radians", "reflect", "refract", "reverseBits", "round", "saturate",
"sign", "sin", "sinh", "smoothstep", "sqrt", "step", "tan", "tanh", "transpose", "trunc",
"dpdx", "dpdxCoarse", "dpdxFine", "dpdy", "dpdyCoarse", "dpdyFine", "fwidth",
"fwidthCoarse", "fwidthFine", "textureDimensions", "textureGather", "textureGatherCompare",
"textureLoad", "textureNumLayers", "textureNumLevels", "textureNumSamples", "textureSample",
"textureSampleBias", "textureSampleCompare", "textureSampleCompareLevel",
"textureSampleGrad", "textureSampleLevel", "textureSampleBaseClampToEdge", "textureStore",
"atomicLoad", "atomicStore", "atomicAdd", "atomicSub", "atomicMax", "atomicMin",
"atomicAnd", "atomicOr", "atomicXor", "atomicExchange", "atomicCompareExchangeWeak",
"pack4x8snorm", "pack4x8unorm", "pack2x16snorm", "pack2x16unorm", "pack2x16float",
"unpack4x8snorm", "unpack4x8unorm", "unpack2x16snorm", "unpack2x16unorm", "unpack2x16float",
"storageBarrier", "workgroupBarrier", "workgroupUniformLoad")
operators("&", "&&", "->", "/", "=", "==", "!=", ">", ">=", "<", "<=", "%", "-", "--", "+",
"++", "|", "||", "*", "<<", ">>", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", ">>=",
"<<=")
symbols("[!%&*+\\-\\.\\/:;<=>^|_~,]+")
tokenizer {
root {
"enable|requires|diagnostic".action("keyword").state("@directive")
"[_\\p{XID_Start}]\\p{XID_Continue}*".action {
cases {
"@atoms" and "variable.predefined"
"@keywords" and "keyword"
"@reserved" and "invalid"
"@predeclared_enums" and "variable.predefined"
"@predeclared_types" and "variable.predefined"
"@predeclared_type_generators" and "variable.predefined"
"@predeclared_type_aliases" and "variable.predefined"
"@predeclared_intrinsics" and "variable.predefined"
"@default" and "identifier"
}
}
include("@commentOrSpace")
include("@numbers")
"[{}()\\[\\]]".token("@brackets")
"@".action("annotation").state("@attribute")
"@symbols".action {
cases {
"@operators" and "operator"
"@default" and "delimiter"
}
}
".".token("invalid")
}
"commentOrSpace" rules {
"\\s+".token("white")
"\\/\\*".action("comment").state("@blockComment")
"\\/\\/.*${'$'}".token("comment")
}
"blockComment" rules {
"[^\\/*]+".token("comment")
"\\/\\*".action("comment").state("@push")
"\\*\\/".action("comment").state("@pop")
"[\\/*]".token("comment")
}
"attribute" rules {
include("@commentOrSpace")
"\\w+".action("annotation").state("@pop")
}
"directive" rules {
include("@commentOrSpace")
"[()]".token("@brackets")
",".token("delimiter")
"[_\\p{XID_Start}]\\p{XID_Continue}*".token("meta.content")
";".action("delimiter").state("@pop")
}
"numbers" rules {
"0[fh]".token("number.float")
"[1-9][0-9]*[fh]".token("number.float")
"[0-9]*\\.[0-9]+([eE][+-]?[0-9]+)?[fh]?".token("number.float")
"[0-9]+\\.[0-9]*([eE][+-]?[0-9]+)?[fh]?".token("number.float")
"[0-9]+[eE][+-]?[0-9]+[fh]?".token("number.float")
"0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+(?:[pP][+-]?[0-9]+[fh]?)?".token("number.hex")
"0[xX][0-9a-fA-F]+\\.[0-9a-fA-F]*(?:[pP][+-]?[0-9]+[fh]?)?".token("number.hex")
"0[xX][0-9a-fA-F]+[pP][+-]?[0-9]+[fh]?".token("number.hex")
"0[xX][0-9a-fA-F]+[iu]?".token("number.hex")
"[1-9][0-9]*[iu]?".token("number")
"0[iu]?".token("number")
}
}
}
}
| 0 | Kotlin | 0 | 2 | 134f0979102fdba388b98db13893ff333968d603 | 8,592 | monarch-kt | Apache License 2.0 |
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/bugreporting/censors/dcc/CwaUserCensorTest.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.bugreporting.censors.dcc
import de.rki.coronawarnapp.covidcertificate.common.certificate.CertificatePersonIdentifier
import de.rki.coronawarnapp.covidcertificate.person.core.PersonCertificatesSettings
import io.kotest.matchers.shouldBe
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runBlockingTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import testhelpers.BaseTest
@Suppress("MaxLineLength")
class CwaUserCensorTest : BaseTest() {
@MockK lateinit var personCertificatesSettings: PersonCertificatesSettings
@BeforeEach
fun setup() {
MockKAnnotations.init(this)
}
private fun createInstance() = CwaUserCensor(personCertificatesSettings)
@Test
fun `censoring of certificate person identifier works`() = runBlockingTest {
every { personCertificatesSettings.currentCwaUser } returns flowOf(
CertificatePersonIdentifier(
"1982-02-11",
"LIME",
"MOTHER<MANDY"
)
)
val censor = createInstance()
val certDataToCensor =
"PersonCertificatesProvider: vaccPersons=[], tests=[], recos=[], cwaUser=CertificatePersonIdentifier(dateOfBirthFormatted=1982-02-11, lastNameStandardized=LIME, firstNameStandardized=MOTHER<MANDY)"
censor.checkLog(certDataToCensor)!!
.compile()!!.censored shouldBe "PersonCertificatesProvider: vaccPersons=[], tests=[], recos=[], cwaUser=CertificatePersonIdentifier(dateOfBirthFormatted=cwaUser/dateOfBirth, lastNameStandardized=cwaUser/lastNameStandardized, firstNameStandardized=cwaUser/firstNameStandardized)"
}
@Test
fun `checkLog() should return null if nothing should be censored`() = runBlockingTest {
every { personCertificatesSettings.currentCwaUser } returns flowOf(null)
val censor = createInstance()
val certDataToCensor = "Nothing interesting here"
censor.checkLog(certDataToCensor) shouldBe null
}
}
| 6 | null | 516 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 2,134 | cwa-app-android | Apache License 2.0 |
app/src/main/java/com/android/compose/swiggyclone/ui/theme/Theme.kt | lspradeep | 390,047,512 | false | null | package com.android.compose.swiggyclone.ui.theme
import android.app.StatusBarManager
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.MaterialTheme.colors
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import com.google.accompanist.systemuicontroller.rememberSystemUiController
private val DarkColorPalette = darkColors(
primary = primaryColor,
primaryVariant = primaryVariant,
secondary = secondaryColor,
secondaryVariant = secondaryVariant,
onSecondary = black,
background = bgColor,
surface = white,
onSurface = black,
onPrimary = black,
)
private val LightColorPalette = lightColors(
primary = primaryColor,
primaryVariant = primaryVariant,
secondary = secondaryColor,
secondaryVariant = secondaryVariant,
onSecondary = black,
background = bgColor,
surface = white,
onSurface = black,
onPrimary = black,
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun SwiggyCloneTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable() () -> Unit
) {
val sysUiController = rememberSystemUiController()
SideEffect {
sysUiController.setSystemBarsColor(
color = white
)
}
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content,
)
} | 0 | Kotlin | 0 | 0 | 7074a38e40626aa4399b6279149daea33f3bec23 | 1,852 | swiggy-clone | MIT License |
app/src/main/java/com/airy/juju/viewModel/factroy/UserDetailViewModelFactory.kt | AiryMiku | 174,809,394 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 1, "Kotlin": 112, "XML": 76, "Java": 1} | package com.airy.juju.viewModel.factroy
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.airy.juju.viewModel.activity.UserDetailViewModel
/**
* Created by Airy on 2019/4/15
* Mail: <EMAIL>
* Github: AiryMiku
*/
class UserDetailViewModelFactory (private val id: Int): ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return UserDetailViewModel(id) as T
}
} | 0 | Kotlin | 1 | 1 | 3b0a2035373f9e6dfdf985c5b71c30dcce414273 | 510 | JuJu_Android | MIT License |
src/main/kotlin/nox/manifest/OsgiManifest.kt | teris-io | 95,603,773 | false | null | /*
* Copyright (c) <NAME> 2017. License: MIT
*/
package nox.manifest
import aQute.bnd.osgi.Analyzer
import com.google.common.collect.Multimap
import com.google.common.collect.MultimapBuilder
import groovy.lang.Closure
import nox.core.Version
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.java.archives.internal.DefaultManifest
import org.gradle.internal.file.PathToFileResolver
import org.gradle.util.ConfigureUtil
import org.gradle.util.WrapUtil
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.file.Path
import java.util.*
import java.util.function.Supplier
import java.util.jar.Manifest
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashSet
/**
* OSGiJarManifest provides a drop in replacement for jar.manifest
*/
class OsgiManifest(private val classpathSupplier: Supplier<Set<File>>, private val jarSupplier: Supplier<File>, fileResolver: PathToFileResolver) : DefaultManifest(fileResolver) {
var spec: ManifestSpec? = null
var from: File? = null
var fromVersion: Version? = null
fun spec(symbolicName: String, version: Any, vararg configs: Closure<*>) {
this.spec = ManifestSpec(symbolicName, Version(version.toString()))
for (config in configs) {
ConfigureUtil.configure<ManifestSpec>(config, this.spec)
}
}
fun spec(from: Path, version: Any) {
this.from = from.toFile()
this.fromVersion = Version(version.toString())
}
fun spec(from: File, version: Any) {
this.from = from
this.fromVersion = Version(version.toString())
}
fun spec(project: Project, vararg configs: Closure<*>) {
spec(toSymbolicName(project.group.toString(), project.name),
Version(project.version.toString()), *configs)
}
fun toSymbolicName(groupId: String, artifactId: String): String {
if (artifactId.startsWith(groupId)) {
return artifactId
}
val parts = (groupId + "." + artifactId).split("[\\.-]".toRegex())
val elements = LinkedHashSet(parts)
return elements.joinToString(".")
}
override fun getEffectiveManifest(): DefaultManifest {
try {
val baseManifest = DefaultManifest(null)
baseManifest.attributes(attributes)
for ((key, value) in generateManifest().mainAttributes) {
baseManifest.attributes(
WrapUtil.toMap(key.toString(), value.toString()))
}
// this changing value prevented incremental builds...
baseManifest.attributes.remove("Bnd-LastModified")
return getEffectiveManifestInternal(baseManifest)
} catch (ex: IOException) {
throw GradleException(ex.message, ex)
}
}
@Throws(IOException::class)
private fun generateManifest(): Manifest {
if (from != null) {
FileInputStream(from).use { s ->
val manifest = Manifest(s)
if (fromVersion != null) {
manifest.mainAttributes.putValue(Analyzer.BUNDLE_VERSION, fromVersion.toString())
}
return manifest
}
}
if (spec == null) {
throw GradleException("Please provide manifest 'spec' or 'from' file")
}
val mspec = spec!!
val analyzer = Analyzer()
analyzer.setBundleSymbolicName(mspec.symbolicName + if (mspec.singleton) ";singleton:=true" else "")
analyzer.bundleVersion = mspec.version.toString()
val instructions: Multimap<String, String> = MultimapBuilder.hashKeys().linkedHashSetValues().build()
instructions.putAll(mspec.instructions())
instructions.put(Analyzer.IMPORT_PACKAGE, "*")
instructions.put(Analyzer.EXPORT_PACKAGE, "*;-noimport:=true;version=" + mspec.version.toString(Version.Component.Build))
for (instruction in instructions.keySet()) {
val values = ArrayList(instructions.get(instruction))
val value = values.joinToString(",")
analyzer.properties.setProperty(instruction, value)
}
if (!mspec.activator.isNullOrBlank()) {
analyzer.properties.setProperty(Analyzer.BUNDLE_ACTIVATOR, mspec.activator!!)
}
if (!mspec.uses) {
analyzer.setProperty(Analyzer.NOUSES, "true")
}
var jar: File? = jarSupplier.get()
if (jar == null || !jar.exists()) {
jar = File.createTempFile("osgi", UUID.randomUUID().toString())
jar.delete()
jar.mkdir()
jar.deleteOnExit()
}
analyzer.setJar(jar)
val classpath = classpathSupplier.get()
if (classpath.isNotEmpty()) {
analyzer.setClasspath(classpath)
}
try {
val res = analyzer.calcManifest()
var imports = res.mainAttributes.getValue(Analyzer.IMPORT_PACKAGE)
if (!imports.isNullOrBlank()) {
imports = imports.replace(";common=split", "")
res.mainAttributes.putValue(Analyzer.IMPORT_PACKAGE, imports)
}
return res
} catch (ex: Exception) {
throw IllegalStateException(ex)
}
}
}
| 0 | Kotlin | 1 | 0 | af54ed589739c3d44a4131d6e17edbcc041c4e2b | 4,624 | nox | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.