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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
reposilite-backend/src/main/kotlin/com/reposilite/statistics/StatsCommand.kt
|
dzikoysk
| 96,474,388
| false
| null |
/*
* Copyright (c) 2021 dzikoysk
*
* 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.reposilite.statistics
import com.reposilite.console.CommandContext
import com.reposilite.console.CommandStatus.FAILED
import com.reposilite.console.api.ReposiliteCommand
import com.reposilite.shared.extensions.take
import panda.std.Option
import panda.utilities.console.Effect.BLACK_BOLD
import panda.utilities.console.Effect.RESET
import picocli.CommandLine.Command
import picocli.CommandLine.Parameters
private const val DEFAULT_TOP_LIMIT = 20
@Command(name = "stats", description = ["Display collected metrics"])
internal class StatsCommand(private val statisticsFacade: StatisticsFacade) : ReposiliteCommand {
@Parameters(index = "0", paramLabel = "[<repository>]", description = ["Repository to search in.", "By default it aggregates results from all repositories."], defaultValue = "")
private lateinit var repository: String
@Parameters(index = "1", paramLabel = "[<filter>]", description = ["Accepts string as pattern and int as limiter"], defaultValue = "")
private lateinit var filter: String
override fun execute(context: CommandContext) {
context.append("Statistics: ")
context.append(" Unique resolved requests: ${statisticsFacade.countUniqueRecords()}")
context.append(" All resolved requests: ${statisticsFacade.countRecords()}")
val limiter = Option.attempt(NumberFormatException::class.java) { filter.toInt() }.orElseGet(DEFAULT_TOP_LIMIT)
val phrase = take(limiter != DEFAULT_TOP_LIMIT, "", filter)
statisticsFacade.findResolvedRequestsByPhrase(repository, phrase, limiter)
.peek { response ->
context.append("Search results:")
context.append(" Filter: '${highlight(phrase)}' / Limit: $limiter")
if (repository.isNotEmpty()) context.append(" In repository: $repository")
context.append(" Sum of matched requests: ${response.sum}")
context.append(" Records:")
response.requests.forEachIndexed { order, request -> context.append(" ${order + 1}. /${request.gav} (${request.count})") }
if (response.requests.isEmpty()) context.append(" ~ Matching records not found ~")
}
.onError {
context.append("Cannot fetch statistics: $it")
context.status = FAILED
}
}
private fun highlight(value: Any): String =
BLACK_BOLD.toString() + value.toString() + RESET
}
| 27
|
Kotlin
|
85
| 998
|
1d84b2c54465f0c95d79051e3ae29820b14c2f60
| 3,071
|
reposilite
|
Apache License 2.0
|
src/main/kotlin/wotw/server/game/MultiverseEvents.kt
|
ori-community
| 387,772,660
| false
| null |
package wotw.server.game
import wotw.server.database.model.User
import wotw.server.database.model.World
import wotw.server.database.model.WorldMembership
data class WorldCreatedEvent(
val world: World,
)
data class WorldDeletedEvent(
val worldId: Long,
)
data class PlayerJoinedEvent(
val player: User,
)
data class PlayerMovedEvent( // Moved inside a universe
val player: User,
)
data class PlayerLeftEvent(
val player: User,
)
data class MultiverseEvent(
val event: String,
val sender: WorldMembership,
val payload: Any? = null,
)
data class DebugEvent(
val event: String,
val payload: Any? = null,
)
| 15
| null |
2
| 4
|
f4ddafb928c513e95379c86c561c939bebe9bf94
| 651
|
wotw-rando-server
|
MIT License
|
app/src/main/java/com/gwongsi/ododlight/MainActivity.kt
|
gwong1si4
| 218,705,380
| false
| null |
package com.gwongsi.ododlight
import android.content.Context
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import com.camerakit.CameraKitView
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
class MainActivity : AppCompatActivity() {
lateinit var cameraKitView: CameraKitView
lateinit var imageButton: Button
lateinit var videoButton: Button
lateinit var popoButton: Button
private var torchIsOn = false
private var hasTorch = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
cameraKitView = findViewById<View>(R.id.camera) as CameraKitView
hasTorch = applicationContext.packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
imageButton = findViewById(R.id.imageBtn)
imageButton.setOnClickListener(View.OnClickListener {
cameraKitView.captureImage(CameraKitView.ImageCallback { cameraKitView, bytes ->
Log.e("Return Image: ", "Size: ${bytes.size}")
})
})
videoButton = findViewById(R.id.videoBtn)
videoButton.setOnClickListener(View.OnClickListener {
cameraKitView.captureVideo(CameraKitView.VideoCallback { cameraKitView, any ->
Log.e("Return Video: ","")
})
})
popoButton = findViewById(R.id.popoBtn)
popoButton.setOnClickListener(View.OnClickListener {
popoLightToggle()
Log.e("popoLightToggle ","")
})
}
private fun popoLightToggle() {
if (torchIsOn){
setTorchOff()
} else {
setTorchOn()
}
}
private fun setTorchOn() {
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
val cameraId = cameraManager.getCameraIdList()[0]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true)
}
torchIsOn = true
// imageFlashlight.setImageResource(R.drawable.btn_switch_on)
} catch (e: CameraAccessException) {
Log.e("popoLightToggle ", e.localizedMessage)
}
}
private fun setTorchOff() {
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
val cameraId = cameraManager.getCameraIdList()[0]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false)
}
torchIsOn = true
// imageFlashlight.setImageResource(R.drawable.btn_switch_on)
} catch (e: CameraAccessException) {
}
}
override fun onStart() {
super.onStart()
cameraKitView.onStart()
}
override fun onResume() {
super.onResume()
cameraKitView.onResume()
}
override fun onPause() {
cameraKitView.onPause()
super.onPause()
}
override fun onStop() {
cameraKitView.onStop()
super.onStop()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
cameraKitView.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
| 0
|
Kotlin
|
0
| 0
|
723b63f7adce6c341113ca7779220b5a080baec1
| 3,687
|
ododLightAndroid
|
MIT License
|
platform/backend/core/src/main/kotlin/io/hamal/core/adapter/Exec.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 2265145, "C": 1398401, "TypeScript": 281481, "Lua": 117790, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
|
package io.hamal.core.adapter
import io.hamal.lib.domain.GenerateDomainId
import io.hamal.lib.domain._enum.ReqStatus.Submitted
import io.hamal.lib.domain.vo.ExecId
import io.hamal.lib.domain.vo.ReqId
import io.hamal.repository.api.Exec
import io.hamal.repository.api.ExecQueryRepository
import io.hamal.repository.api.ExecQueryRepository.ExecQuery
import io.hamal.repository.api.ReqCmdRepository
import io.hamal.repository.api.submitted_req.ExecCompleteSubmitted
import io.hamal.repository.api.submitted_req.ExecFailSubmitted
import io.hamal.request.ExecCompleteReq
import io.hamal.request.ExecFailReq
import org.springframework.stereotype.Component
interface ExecGetPort {
operator fun <T : Any> invoke(execId: ExecId, responseHandler: (Exec) -> T): T
}
interface ExecListPort {
operator fun <T : Any> invoke(query: ExecQuery, responseHandler: (List<Exec>) -> T): T
}
interface ExecCompletePort {
operator fun <T : Any> invoke(
execId: ExecId,
req: ExecCompleteReq,
responseHandler: (ExecCompleteSubmitted) -> T
): T
}
interface ExecFailPort {
operator fun <T : Any> invoke(
execId: ExecId,
req: ExecFailReq,
responseHandler: (ExecFailSubmitted) -> T
): T
}
interface ExecPort : ExecGetPort, ExecListPort, ExecCompletePort, ExecFailPort
@Component
class ExecAdapter(
private val execQueryRepository: ExecQueryRepository,
private val generateDomainId: GenerateDomainId,
private val reqCmdRepository: ReqCmdRepository
) : ExecPort {
override fun <T : Any> invoke(execId: ExecId, responseHandler: (Exec) -> T) =
responseHandler(execQueryRepository.get(execId))
override fun <T : Any> invoke(query: ExecQuery, responseHandler: (List<Exec>) -> T) =
responseHandler(execQueryRepository.list(query))
override fun <T : Any> invoke(
execId: ExecId,
req: ExecCompleteReq,
responseHandler: (ExecCompleteSubmitted) -> T
): T {
val exec = execQueryRepository.get(execId)
return ExecCompleteSubmitted(
id = generateDomainId(::ReqId),
status = Submitted,
execId = exec.id,
result = req.result,
state = req.state,
events = req.events
).also(reqCmdRepository::queue).let(responseHandler)
}
override fun <T : Any> invoke(execId: ExecId, req: ExecFailReq, responseHandler: (ExecFailSubmitted) -> T): T {
val exec = execQueryRepository.get(execId)
return ExecFailSubmitted(
id = generateDomainId(::ReqId),
status = Submitted,
execId = exec.id,
result = req.result
).also(reqCmdRepository::queue).let(responseHandler)
}
}
| 26
|
Kotlin
|
0
| 0
|
90345f7663444dc8f067861e9ba72ec16350757d
| 2,734
|
hamal
|
Creative Commons Zero v1.0 Universal
|
petblocks-bukkit-plugin/src/main/kotlin/com/github/shynixn/petblocks/bukkit/logic/business/pathfinder/PathfinderAmbientSound.kt
|
Archeri2000
| 215,716,277
| true
|
{"Kotlin": 1612042, "Shell": 4631, "TSQL": 2140, "Dockerfile": 424}
|
package com.github.shynixn.petblocks.bukkit.logic.business.pathfinder
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PetProxy
import com.github.shynixn.petblocks.api.business.service.LoggingService
import com.github.shynixn.petblocks.api.business.service.SoundService
import com.github.shynixn.petblocks.api.persistence.entity.AIAmbientSound
import com.github.shynixn.petblocks.core.logic.business.pathfinder.BasePathfinder
import org.bukkit.GameMode
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
class PathfinderAmbientSound(
private val pet: PetProxy,
private val aiAmbientSound: AIAmbientSound,
private val livingEntity: LivingEntity,
private val player: Player
) : BasePathfinder(aiAmbientSound) {
private val soundService = PetBlocksApi.resolve(SoundService::class.java)
private val loggingService = PetBlocksApi.resolve(LoggingService::class.java)
/**
* Should the goal be executed.
*/
override fun shouldGoalBeExecuted(): Boolean {
return !livingEntity.isDead && player.gameMode != GameMode.SPECTATOR
}
/**
* On execute.
*/
override fun onExecute() {
try {
if (!pet.meta.soundEnabled) {
return
}
val value = Math.random()
if (value > 0.98) {
soundService.playSound(livingEntity.location, aiAmbientSound.sound, player)
}
} catch (e: Exception) {
loggingService.warn("Failed to execute PathfinderAmbientSound.", e)
}
}
}
| 0
| null |
0
| 0
|
0e462655ab755a7c7ad291010915f41daaef776d
| 1,621
|
PetBlocks
|
Apache License 2.0
|
simplified-books-controller/src/main/java/org/nypl/simplified/books/controller/BookBorrowFailedDismissTask.kt
|
ray-lee
| 292,624,474
| true
|
{"Git Config": 1, "Gradle": 107, "Java Properties": 5, "Shell": 4, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 99, "EditorConfig": 1, "XML": 388, "INI": 96, "Kotlin": 780, "HTML": 9, "JSON": 57, "Java": 165, "CSS": 2, "JavaScript": 2, "YAML": 2, "Gradle Kotlin DSL": 1, "Gemfile.lock": 1, "Ruby": 2}
|
package org.nypl.simplified.books.controller
import com.io7m.jfunctional.Some
import org.nypl.simplified.books.api.BookID
import org.nypl.simplified.books.book_database.api.BookDatabaseType
import org.nypl.simplified.books.book_registry.BookRegistryType
import org.nypl.simplified.books.book_registry.BookStatus
import org.nypl.simplified.books.book_registry.BookWithStatus
import org.slf4j.LoggerFactory
import java.util.concurrent.Callable
/**
* A task that dismisses a download.
*/
class BookBorrowFailedDismissTask(
private val bookRegistry: BookRegistryType,
private val id: BookID,
private val bookDatabase: BookDatabaseType
) : Callable<Unit> {
private val logger =
LoggerFactory.getLogger(BookBorrowFailedDismissTask::class.java)
override fun call() {
this.logger.debug("acknowledging download of book {}", this.id)
val statusOpt = this.bookRegistry.bookStatus(this.id)
if (statusOpt is Some<BookStatus>) {
val status = statusOpt.get()
this.logger.debug("status of book {} is currently {}", this.id, status)
val entry = this.bookDatabase.entry(this.id)
val book = entry.book
this.bookRegistry.update(BookWithStatus(book, BookStatus.fromBook(book)))
}
}
}
| 1
|
Kotlin
|
0
| 0
|
d832b391188c86858158ef702f308c6b507ddb61
| 1,233
|
Simplified-Android-Core
|
Apache License 2.0
|
app/src/main/java/io/github/gmathi/novellibrary/network/AndroidCookieJar.kt
|
gmathi
| 92,864,511
| false
| null |
package io.github.gmathi.novellibrary.network
import android.webkit.CookieManager
import io.github.gmathi.novellibrary.util.DataCenter
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import uy.kohesive.injekt.injectLazy
import java.net.URL
class AndroidCookieJar : CookieJar {
private val manager = CookieManager.getInstance()
private val dataCenter: DataCenter by injectLazy()
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
val urlString = url.toString()
cookies.forEach { manager.setCookie(urlString, it.toString()) }
}
fun saveFromResponse(urlString: String, cookiesStrings: List<String>) {
cookiesStrings.forEach { manager.setCookie(urlString, it) }
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
return get(url)
}
fun get(url: HttpUrl): List<Cookie> {
val cookies = manager.getCookie(url.toString())
return if (cookies != null && cookies.isNotEmpty()) {
cookies.split(";").mapNotNull { Cookie.parse(url, it) }
} else {
emptyList()
}
}
fun remove(url: HttpUrl, cookieNames: List<String>? = null, maxAge: Int = -1) {
val urlString = url.toString()
val cookies = manager.getCookie(urlString) ?: return
fun List<String>.filterNames(): List<String> {
return if (cookieNames != null) {
this.filter { it in cookieNames }
} else {
this
}
}
cookies.split(";")
.map { it.substringBefore("=") }
.filterNames()
.onEach { manager.setCookie(urlString, "$it=;Max-Age=$maxAge") }
}
fun removeAll() {
manager.removeAllCookies {}
}
// Old methods copied here
fun saveLoginCookies(hostName: String, lookupRegex: Regex?): Boolean {
val pureHost = hostName.replace("www.", "").replace("m.", "")
val general = saveLoginCookiesInternal(pureHost, lookupRegex)
val www = saveLoginCookiesInternal("www.$pureHost", lookupRegex)
val mobile = saveLoginCookiesInternal("m.$pureHost", lookupRegex)
return general || www || mobile;
}
private fun saveLoginCookiesInternal(hostName: String, lookup: Regex?): Boolean {
val cookies = CookieManager.getInstance().getCookie("https://$hostName/").trim()
val parts = cookies.split(";".toRegex()).dropLastWhile { it.isEmpty() }.filter {
lookup?.containsMatchIn(it) ?: false
}
return if (parts.count() != 0) {
dataCenter.setLoginCookiesString(hostName, parts.joinToString(";"))
true
} else {
false
}
}
fun clearCookies(hostName: String) {
val cookieManager = CookieManager.getInstance()
val cookieString = cookieManager.getCookie(".$hostName")
if (cookieString != null) {
val cookies = cookieString.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (cookie in cookies) {
val cookieParts = cookie.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
cookieManager.setCookie(".$hostName", cookieParts[0].trim { it <= ' ' } + "=; Expires=Wed, 31 Dec 2025 23:59:59 GMT")
}
}
}
private fun populateCookieMap(hostName: String, map: HashMap<String, String>) {
dataCenter.getLoginCookiesString(hostName).split(";".toRegex()).dropLastWhile { it.isEmpty() }.forEach {
val idx = it.indexOf('=')
map[it.substring(0, idx)] = it.substring(idx + 1)
}
}
fun getCookieMap(url: URL?): Map<String, String> {
val map = HashMap<String, String>()
if (url?.host == null) return map
val hostName = url.host.replace("www.", "").replace("m.", "").trim()
populateCookieMap(hostName, map)
populateCookieMap("www.$hostName", map)
populateCookieMap("m.$hostName", map)
return map
}
}
| 20
| null |
22
| 96
|
ff35dc386834db35e761c87089ef595957a6fa86
| 4,052
|
NovelLibrary
|
Apache License 2.0
|
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/BackgroundType.kt
|
InsanusMokrassar
| 163,152,024
| false
|
{"Kotlin": 3243076, "Shell": 373}
|
package dev.inmo.tgbotapi.types
import dev.inmo.micro_utils.common.Progress
import dev.inmo.tgbotapi.types.files.DocumentFile
import dev.inmo.tgbotapi.utils.IntProgress100Serializer
import dev.inmo.tgbotapi.utils.decodeDataAndJson
import dev.inmo.tgbotapi.utils.internal.ClassCastsIncluded
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonElement
@ClassCastsIncluded
@Serializable(BackgroundType.Companion::class)
sealed interface BackgroundType {
val type: String
sealed interface Movable : BackgroundType {
val isMoving: Boolean
}
sealed interface Dimmable : BackgroundType {
val darkThemeDimming: Progress
}
sealed interface Fillable : BackgroundType {
val fill: BackgroundFill
}
sealed interface WithDocument : BackgroundType {
val document: DocumentFile
}
@Serializable
data class Fill(
@SerialName(fillField)
override val fill: BackgroundFill,
@SerialName(darkThemeDimmingField)
@Serializable(IntProgress100Serializer::class)
override val darkThemeDimming: Progress
) : Fillable, Dimmable {
@EncodeDefault
@SerialName(typeField)
override val type: String = Companion.type
companion object {
const val type: String = "fill"
}
}
@Serializable
data class Wallpaper(
@SerialName(documentField)
override val document: DocumentFile,
@SerialName(darkThemeDimmingField)
@Serializable(IntProgress100Serializer::class)
override val darkThemeDimming: Progress,
@SerialName(isBlurredField)
val isBlurred: Boolean = false,
@SerialName(isMovingField)
override val isMoving: Boolean = false
) : WithDocument, Dimmable, Movable {
@EncodeDefault
@SerialName(typeField)
override val type: String = Companion.type
companion object {
const val type: String = "wallpaper"
}
}
@Serializable
data class Pattern(
@SerialName(documentField)
override val document: DocumentFile,
@SerialName(fillField)
override val fill: BackgroundFill,
@SerialName(intensityField)
@Serializable(IntProgress100Serializer::class)
val intensity: Progress,
@SerialName(isInvertedField)
val isInverted: Boolean = false,
@SerialName(isMovingField)
override val isMoving: Boolean = false
) : WithDocument, Fillable, Movable {
@EncodeDefault
@SerialName(typeField)
override val type: String = Companion.type
companion object {
const val type: String = "pattern"
}
}
@Serializable
data class ChatTheme(
@SerialName(themeNameField)
val themeName: String
): BackgroundType {
@EncodeDefault
@SerialName(typeField)
override val type: String = Companion.type
companion object {
const val type: String = "chat_theme"
}
}
@Serializable
data class Unknown(
@SerialName(typeField)
override val type: String,
val raw: JsonElement?
): BackgroundType
companion object : KSerializer<BackgroundType> {
@Serializable
data class RawBackgroundType(
val type: String,
@SerialName(fillField)
val fill: BackgroundFill? = null,
@SerialName(darkThemeDimmingField)
@Serializable(IntProgress100Serializer::class)
val darkThemeDimming: Progress? = null,
@SerialName(documentField)
val document: DocumentFile? = null,
@SerialName(isBlurredField)
val isBlurred: Boolean = false,
@SerialName(isMovingField)
val isMoving: Boolean = false,
@SerialName(intensityField)
@Serializable(IntProgress100Serializer::class)
val intensity: Progress? = null,
@SerialName(isInvertedField)
val isInverted: Boolean = false,
@SerialName(themeNameField)
val themeName: String? = null
)
override val descriptor: SerialDescriptor
get() = RawBackgroundType.serializer().descriptor
override fun deserialize(decoder: Decoder): BackgroundType {
val (raw, json) = decoder.decodeDataAndJson(RawBackgroundType.serializer())
val unknown by lazy { Unknown(raw.type, json) }
return when (raw.type) {
Fill.type -> Fill(
raw.fill ?: return unknown,
raw.darkThemeDimming ?: return unknown
)
Wallpaper.type -> Wallpaper(
document = raw.document ?: return unknown,
darkThemeDimming = raw.darkThemeDimming ?: return unknown,
isBlurred = raw.isBlurred,
isMoving = raw.isMoving
)
Pattern.type -> Pattern(
document = raw.document ?: return unknown,
fill = raw.fill ?: return unknown,
intensity = raw.intensity ?: return unknown,
isInverted = raw.isInverted,
isMoving = raw.isMoving
)
ChatTheme.type -> ChatTheme(
raw.themeName ?: return unknown
)
else -> unknown
}
}
override fun serialize(encoder: Encoder, value: BackgroundType) {
when (value) {
is ChatTheme -> ChatTheme.serializer().serialize(encoder, value)
is Fill -> Fill.serializer().serialize(encoder, value)
is Wallpaper -> Wallpaper.serializer().serialize(encoder, value)
is Pattern -> Pattern.serializer().serialize(encoder, value)
is Unknown -> value.raw ?.also {
JsonElement.serializer().serialize(encoder, it)
} ?: Unknown.serializer().serialize(encoder, value)
}
}
}
}
| 13
|
Kotlin
|
29
| 358
|
482c375327b7087699a4cb8bb06cb09869f07630
| 6,415
|
ktgbotapi
|
Apache License 2.0
|
data/src/desktopMain/kotlin/di/MovieDatabase.kt
|
rovargas15
| 767,866,342
| false
|
{"Kotlin": 113842, "HTML": 1086, "Swift": 722, "CSS": 102}
|
package di
import androidx.room.Room.databaseBuilder
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import local.database.MovieDatabase
import java.io.File
fun createDatabase(): MovieDatabase {
val dbFile = File(System.getProperty("java.io.tmpdir"), MovieDatabase.DB_FILE_NAME)
return databaseBuilder<MovieDatabase>(
name = dbFile.absolutePath,
).setDriver(BundledSQLiteDriver()).build()
}
| 0
|
Kotlin
|
0
| 0
|
0e860ea7116b0f208f3ac3c0cd82db71015724c1
| 423
|
Movie-kmp
|
Apache License 2.0
|
News_App/NewsBreeze/app/src/main/java/com/shaun/newsbreeze/presentation/components/BreezeImage.kt
|
aadityamp01
| 275,898,636
| false
|
{"Dart": 325447, "Kotlin": 293294, "Java": 124887, "C++": 79060, "CMake": 57342, "HTML": 9428, "Swift": 4398, "C": 4275, "Objective-C": 190}
|
package com.shaun.newsbreeze.presentation.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.shaun.newsbreeze.R
@Composable
fun BreezeImage(height:Int,imageUrl:String?) {
// val painter = rememberim(imageUrl, fadeIn = true)
//
// Image(
// painter = painter, contentDescription = null,
// modifier = Modifier
// .height(height = height.dp)
// .fillMaxSize(1f),
// contentScale = ContentScale.FillWidth
//
// )
// when (painter.loadState) {
// is ImageLoadState.Loading -> {
//
// ShimmerItem(
// size = 200,
// showBottomLine = false,
// paddingStart = 0,
// paddingEnd = 0,
// paddingTop = 0
// )
// }
// is ImageLoadState.Error -> {
//
// Image(
// painter = painterResource(id = R.drawable.failed),
// null,
// Modifier.height(200.dp).fillMaxWidth()
// )
// }
// }
}
| 1
|
Dart
|
57
| 76
|
d047d5b4c3321df85c6523c0725028986c898b14
| 1,438
|
Androapps
|
MIT License
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/market/metrics/MarketMetricsViewModel.kt
|
horizontalsystems
| 142,825,178
| false
| null |
package io.horizontalsystems.bankwallet.modules.market.metrics
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.Clearable
import io.horizontalsystems.bankwallet.core.subscribeIO
import io.horizontalsystems.bankwallet.entities.DataState
import io.horizontalsystems.bankwallet.modules.metricchart.MetricsType
import io.horizontalsystems.bankwallet.ui.extensions.MetricData
import io.horizontalsystems.chartview.ChartData
import io.horizontalsystems.chartview.ChartDataFactory
import io.horizontalsystems.chartview.models.ChartPoint
import io.horizontalsystems.core.SingleLiveEvent
import io.reactivex.disposables.CompositeDisposable
import java.math.BigDecimal
class MarketMetricsViewModel(
private val service: MarketMetricsService,
private val clearables: List<Clearable>
) : ViewModel() {
val marketMetricsLiveData = MutableLiveData<MarketMetricsWrapper?>(null)
val toastLiveData = SingleLiveEvent<String>()
val showGlobalMarketMetricsPage = SingleLiveEvent<MetricsType>()
private var metricsWrapper: MarketMetricsWrapper? = null
set(value) {
field = value
marketMetricsLiveData.postValue(value)
}
private val disposables = CompositeDisposable()
init {
service.marketMetricsObservable
.subscribeIO {
syncMarketMetrics(it)
}
.let {
disposables.add(it)
}
}
fun refresh() {
service.refresh()
}
private fun syncMarketMetrics(dataState: DataState<MarketMetricsItem>) {
var loading = false
val metricsNotSet = metricsWrapper?.marketMetrics == null
if (metricsNotSet) {
loading = dataState.loading
}
var showSyncError = false
if (dataState is DataState.Error) {
if (metricsNotSet) {
showSyncError = true
} else {
toastLiveData.postValue(convertErrorMessage(dataState.error))
}
}
var metrics = metricsWrapper?.marketMetrics
if (dataState is DataState.Success) {
val marketMetricsItem = dataState.data
val btcDominanceFormatted = App.numberFormatter.format(marketMetricsItem.btcDominance, 0, 2, suffix = "%")
val marketMetrics = MarketMetrics(
totalMarketCap = MetricData(formatFiatShortened(marketMetricsItem.marketCap.value, marketMetricsItem.marketCap.currency.symbol), marketMetricsItem.marketCapDiff24h, null),
btcDominance = MetricData(btcDominanceFormatted, marketMetricsItem.btcDominanceDiff24h, getChartData(marketMetricsItem.btcDominancePoints)),
volume24h = MetricData(formatFiatShortened(marketMetricsItem.volume24h.value, marketMetricsItem.volume24h.currency.symbol), marketMetricsItem.volume24hDiff24h, getChartData(marketMetricsItem.volume24Points)),
defiCap = MetricData(formatFiatShortened(marketMetricsItem.defiMarketCap.value, marketMetricsItem.defiMarketCap.currency.symbol), marketMetricsItem.defiMarketCapDiff24h, getChartData(marketMetricsItem.defiMarketCapPoints)),
defiTvl = MetricData(formatFiatShortened(marketMetricsItem.defiTvl.value, marketMetricsItem.defiTvl.currency.symbol), marketMetricsItem.defiTvlDiff24h, getChartData(marketMetricsItem.defiTvlPoints)),
)
metrics = marketMetrics
}
metricsWrapper = MarketMetricsWrapper(metrics, loading, showSyncError)
}
private fun getChartData(marketMetricsPoints: List<MarketMetricsPoint>): ChartData {
val startTimestamp = marketMetricsPoints.first().timestamp
val endTimestamp = marketMetricsPoints.last().timestamp
val points = marketMetricsPoints.map { ChartPoint(it.value.toFloat(), null, it.timestamp) }
return ChartDataFactory.build(points, startTimestamp, endTimestamp, false)
}
private fun formatFiatShortened(value: BigDecimal, symbol: String): String {
val (shortenValue, suffix) = App.numberFormatter.shortenValue(value)
return App.numberFormatter.formatFiat(shortenValue, symbol, 0, 2) + " $suffix"
}
private fun convertErrorMessage(it: Throwable): String {
return it.message ?: it.javaClass.simpleName
}
override fun onCleared() {
clearables.forEach(Clearable::clear)
disposables.clear()
}
fun onBtcDominanceClick() {
showGlobalMarketMetricsPage.postValue(MetricsType.BtcDominance)
}
fun on24VolumeClick() {
showGlobalMarketMetricsPage.postValue(MetricsType.Volume24h)
}
fun onDefiCapClick() {
showGlobalMarketMetricsPage.postValue(MetricsType.DefiCap)
}
fun onTvlInDefiClick() {
showGlobalMarketMetricsPage.postValue(MetricsType.TvlInDefi)
}
}
data class MarketMetrics(
val totalMarketCap: MetricData,
val btcDominance: MetricData,
val volume24h: MetricData,
val defiCap: MetricData,
val defiTvl: MetricData,
)
| 128
|
Kotlin
|
141
| 260
|
e6baef3c8530608ad7ed33a8b104382c7a54d55e
| 5,192
|
unstoppable-wallet-android
|
MIT License
|
AtomicKotlin/Functional Programming/Local Functions/Examples/src/CustomLabel.kt
|
fatiq123
| 726,462,263
| false
|
{"Kotlin": 370528, "HTML": 6544, "JavaScript": 5252, "Java": 4416, "CSS": 3780, "Assembly": 94}
|
// LocalFunctions/CustomLabel.kt
import atomictest.eq
fun main() {
val list = listOf(1, 2, 3, 4, 5)
val value = 3
var result = ""
list.forEach tag@{ // [1]
result += "$it"
if (it == value) return@tag // [2]
}
result eq "12345"
}
| 0
|
Kotlin
|
0
| 0
|
3d351652ebe1dd7ef5f93e054c8f2692c89a144e
| 262
|
AtomicKotlinCourse
|
MIT License
|
data-class-fragment/src/main/kotlin/sims/michael/gitkspr/dataclassfragment/GenerateDataClassFragmentDataClass.kt
|
MichaelSims
| 632,202,406
| false
|
{"Kotlin": 378943, "Shell": 1665}
|
package sims.michael.gitkspr.dataclassfragment
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class GenerateDataClassFragmentDataClass(
val testDataDslFactoryFunctionName: String = "",
) {
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class TestDataDslName(val name: String = "")
}
| 7
|
Kotlin
|
1
| 0
|
b7a4a8fa9443d47491c40b019e5b6d9b34ea984c
| 375
|
git-kspr
|
MIT License
|
library/core/src/commonMain/kotlin/com/attafitamim/kabin/core/converters/mappers/legacy/StringMapper.kt
|
tamimattafi
| 702,197,843
| false
|
{"Kotlin": 340835}
|
package com.attafitamim.kabin.core.converters.mappers.legacy
import app.cash.sqldelight.db.SqlCursor
import com.attafitamim.kabin.core.table.KabinMapper
object StringMapper : KabinMapper<String> {
override fun map(cursor: SqlCursor): String =
cursor.getString(0) ?: ""
}
| 0
|
Kotlin
|
3
| 50
|
b35fd487f1342b354c89dc3557a0e1cfd613d6bf
| 285
|
kabin
|
Apache License 2.0
|
src/main/kotlin/club/pisquad/uiharu/github/GithubConfiguration.kt
|
ThePiSquad
| 761,755,140
| false
|
{"Kotlin": 34139, "Dockerfile": 320}
|
package club.pisquad.uiharu.github
import club.pisquad.uiharu.AppConfiguration
import com.typesafe.config.Config
object GithubConfiguration : Config by AppConfiguration.getConfig("github") {
}
| 2
|
Kotlin
|
0
| 0
|
7b0be059b83142c128720a17a49721910d443752
| 194
|
uiharu
|
MIT License
|
src/main/kotlin/me/serce/solidity/lang/completion/keywords.kt
|
intellij-solidity
| 82,682,728
| false
| null |
package me.serce.solidity.lang.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.util.ProcessingContext
const val KEYWORD_PRIORITY = 10.0
class SolKeywordCompletionProvider(private vararg val keywords: String) : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet
) {
keywords
.map { LookupElementBuilder.create(it) }
.forEach { result.addElement(it.keywordPrioritised()) }
}
}
class SolKeywordCompletionContributor : CompletionContributor(), DumbAware {
init {
extend(
CompletionType.BASIC, rootDeclaration(),
SolKeywordCompletionProvider("pragma ", "import ", "contract ", "library "))
extend(CompletionType.BASIC, rootDeclaration(), object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val pragmaBuilder = LookupElementBuilder
.create("pragma solidity")
.bold()
.withTailText(" ^...")
.withInsertHandler { ctx, _ ->
ctx.document.insertString(ctx.selectionEndOffset, " ^0.6.0;")
EditorModificationUtil.moveCaretRelatively(ctx.editor, 9)
}
result.addElement(PrioritizedLookupElement.withPriority(pragmaBuilder, KEYWORD_PRIORITY - 5))
}
})
extend(CompletionType.BASIC, insideContract().andNot(inMemberAccess()), SolKeywordCompletionProvider("this"))
}
}
| 65
| null |
87
| 990
|
e417a9f279b8d39bec8d9c68cb19fb23d4c3cddb
| 1,751
|
intellij-solidity
|
MIT License
|
src/main/kotlin/com/sbl/sulmun2yong/survey/domain/reward/ByUserRewardInfo.kt
|
SUIN-BUNDANG-LINE
| 819,257,518
| false
|
{"Kotlin": 269239}
|
package com.sbl.sulmun2yong.survey.domain.reward
/** 사용자 설정(사용자가 직접 추첨 or 추첨을 진행하지 않음) */
data class ByUserRewardInfo(
override val rewards: List<Reward>,
) : RewardInfo {
override val targetParticipantCount = null
override val isImmediateDraw = false
}
| 0
|
Kotlin
|
1
| 3
|
cf5258613f242199b73d8b5d31b14a2a8b095ebd
| 267
|
Backend
|
MIT License
|
src/docs/cookbook/monitoring/example_tracing.kt
|
danschultz
| 118,152,914
| true
|
{"Kotlin": 770332, "JavaScript": 133258, "Java": 49492, "Shell": 6237, "HTML": 2067, "CSS": 568}
|
package cookbook.monitoring
import org.http4k.client.ApacheClient
import org.http4k.core.HttpHandler
import org.http4k.core.HttpMessage
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.filter.ClientFilters
import org.http4k.filter.ResponseFilters
import org.http4k.filter.ServerFilters
import org.http4k.server.SunHttp
import org.http4k.server.asServer
fun main(args: Array<String>) {
fun HttpMessage.logHeader(name: String) = "\n\t\t$name=${header(name)}"
fun HttpMessage.traces() = logHeader("x-b3-traceid") + logHeader("x-b3-spanid") + logHeader("x-b3-parentspanid")
fun audit(name: String) = ResponseFilters.ReportLatency { req, resp, _ ->
println("$name: ${req.uri}\n\trequest:${req.traces()}\n\tresponse:${resp.traces()}")
}
// a simple proxy to another app
fun proxy(name: String, port: Int): HttpHandler {
val proxyClient = ClientFilters.RequestTracing()
.then(ClientFilters.SetHostFrom(Uri.of("http://localhost:$port")))
.then(audit("$name-client"))
.then(ApacheClient())
return ServerFilters.RequestTracing().then(audit("$name-server")).then { proxyClient(Request(GET, it.uri)) }
}
// provides a simple ping
fun ping(): HttpHandler = ServerFilters.RequestTracing().then(audit("ping-server")).then { Response(OK).body("pong") }
val proxy1 = proxy("proxy1", 8001).asServer(SunHttp(8000)).start()
val proxy2 = proxy("proxy2", 8002).asServer(SunHttp(8001)).start()
val server3 = ping().asServer(SunHttp(8002)).start()
audit("client").then(ApacheClient())(Request(GET, "http://localhost:8000/ping"))
proxy1.stop()
proxy2.stop()
server3.stop()
}
| 0
|
Kotlin
|
0
| 0
|
7ea0046f8a4d256fe490de5d44ea6c5fc3ad2aa6
| 1,849
|
http4k
|
Apache License 2.0
|
lib/src/main/kotlin/it/scoppelletti/spaceship/ads/AdsExt.kt
|
dscoppelletti
| 395,695,274
| false
| null |
/*
* Copyright (C) 2018 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier")
package it.scoppelletti.spaceship.ads
import android.os.Bundle
import androidx.annotation.StringRes
import com.google.ads.mediation.admob.AdMobAdapter
import com.google.android.gms.ads.AdRequest
import it.scoppelletti.spaceship.ads.consent.ConsentStatus
/**
* Operations for Google Ads.
*
* @since 1.0.0
*/
public object AdsExt {
/**
* Client platform.
*/
public const val API_PLATFORM = "android"
/**
* Consent API version.
*/
public const val API_VERSION = "1.0.7"
/**
* Name of the `HttpClient` dependency.
*/
public const val DEP_HTTPCLIENT = "it.scoppelletti.spaceship.ads.1"
/**
* Name of the `Retrofit` dependency.
*/
public const val DEP_RETROFIT = "it.scoppelletti.spaceship.ads.2"
/**
* Property indicating whether an activity has been launched as a settings
* activity.
*/
public const val PROP_SETTINGS = "it.scoppelletti.spaceship.ads.2"
/**
* Property indicating that the user has not consented to receive
* personalized advertising.
*
* @see it.scoppelletti.spaceship.ads.AdsExt.NPA_TRUE
*/
public const val PROP_NPA = "npa"
/**
* Value indicating that the user has not consented to receive personalized
* advertising.
*
* @see it.scoppelletti.spaceship.ads.AdsExt.PROP_NPA
*/
public const val NPA_TRUE = "1"
/**
* Property indicating that the User is Under the Age of Consent in Europe.
*
* * [Users under the age of consent](http://developers.google.com/admob/android/targeting#users_under_the_age_of_consent)
*/
public const val PROP_TFUA = "tag_for_under_age_of_consent"
}
/**
* Returns the message corresponding to an error code.
*
* @param errorCode The error code.
* @return The message as a string resource ID.
* @since 1.0.0
*/
@StringRes
@Suppress("unused")
public fun adsErrorCodeToMessageId(errorCode: Int): Int =
when (errorCode) {
AdRequest.ERROR_CODE_INTERNAL_ERROR ->
R.string.it_scoppelletti_ads_err_internal
AdRequest.ERROR_CODE_INVALID_REQUEST ->
R.string.it_scoppelletti_ads_err_invalid_request
AdRequest.ERROR_CODE_NETWORK_ERROR ->
R.string.it_scoppelletti_ads_err_network
AdRequest.ERROR_CODE_NO_FILL ->
R.string.it_scoppelletti_ads_err_no_fill
else -> R.string.it_scoppelletti_ads_err_unknown
}
/**
* Creates a new `AdRequest.Builder` instance.
*
* @param consentStatus Consent status.
* @return The new object.
* @since 1.0.0
*/
public fun adRequestBuilder(consentStatus: ConsentStatus): AdRequest.Builder {
val adBuilder: AdRequest.Builder
val extra: Bundle
adBuilder = AdRequest.Builder()
when (consentStatus) {
ConsentStatus.NON_PERSONALIZED -> {
extra = Bundle()
extra.putString(AdsExt.PROP_NPA, AdsExt.NPA_TRUE)
adBuilder.addNetworkExtrasBundle(AdMobAdapter::class.java,
extra)
}
ConsentStatus.UNDER_AGE_OF_CONSENT -> {
extra = Bundle()
extra.putBoolean(AdsExt.PROP_TFUA, true)
adBuilder.addNetworkExtrasBundle(AdMobAdapter::class.java,
extra)
}
else -> {
// ConsentStatus.PERSONALIZED, ConsentStatus.NOT_IN_EEA
}
}
return adBuilder
}
| 0
|
Kotlin
|
0
| 0
|
37a4f832df4aba3a9f7dbd7b5b79c3aacd9aebea
| 4,207
|
spaceship-ads
|
Apache License 2.0
|
compiler/testData/codegen/box/multiplatform/k2/basic/expectActualFakeOverrides.kt
|
JetBrains
| 3,432,266
| false
| null |
// IGNORE_BACKEND_K1: JS, JS_IR, JS_IR_ES6, NATIVE, WASM
// !LANGUAGE: +MultiPlatformProjects
// MODULE: common
// TARGET_PLATFORM: Common
// FILE: commonMain.kt
expect class A() {
fun foo(s: String): String
val bar: String
}
fun test(s: String): String {
val a = A()
return a.foo(s) + a.bar
}
// MODULE: platform()()(common)
// FILE: platform.kt
open class B {
fun foo(s: String) = s
val bar: String = "K"
}
actual class A : B()
fun box() = test("O")
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 484
|
kotlin
|
Apache License 2.0
|
app/storage/src/main/java/com/fsck/k9/storage/messages/K9MessageStoreFactory.kt
|
poldi171254
| 365,734,747
| true
|
{"Java": 3240976, "Kotlin": 1707188, "Shell": 3108}
|
package com.fsck.k9.storage.messages
import com.fsck.k9.Account
import com.fsck.k9.mailstore.LocalStoreProvider
import com.fsck.k9.mailstore.MessageStore
import com.fsck.k9.mailstore.MessageStoreFactory
import com.fsck.k9.mailstore.NotifierMessageStore
import com.fsck.k9.mailstore.StorageManager
import com.fsck.k9.message.extractors.BasicPartInfoExtractor
class K9MessageStoreFactory(
private val localStoreProvider: LocalStoreProvider,
private val storageManager: StorageManager,
private val basicPartInfoExtractor: BasicPartInfoExtractor
) : MessageStoreFactory {
override fun create(account: Account): MessageStore {
val localStore = localStoreProvider.getInstance(account)
val messageStore = K9MessageStore(localStore.database, storageManager, basicPartInfoExtractor, account.uuid)
return NotifierMessageStore(messageStore, localStore)
}
}
| 0
|
Java
|
0
| 0
|
9508c19b2a9c4d1cf9ae32d38c73d46ff44e6b0c
| 892
|
k-9
|
Apache License 2.0
|
src/main/kotlin/com/blr19c/falowp/bot/system/plugin/Plugin.kt
|
falowp-bot
| 736,172,318
| false
|
{"Kotlin": 229423, "HTML": 3910}
|
package com.blr19c.falowp.bot.system.plugin
import com.blr19c.falowp.bot.system.api.ApiAuth
import com.blr19c.falowp.bot.system.api.BotApi
import com.blr19c.falowp.bot.system.api.MessageTypeEnum
import com.blr19c.falowp.bot.system.plugin.hook.HookJoinPoint
import com.blr19c.falowp.bot.system.plugin.hook.HookTypeEnum
import com.blr19c.falowp.bot.system.scheduling.api.SchedulingBotApi
import com.blr19c.falowp.bot.system.scheduling.cron.ApplicationInitTrigger
import com.blr19c.falowp.bot.system.scheduling.cron.CronTrigger
import com.blr19c.falowp.bot.system.scheduling.cron.PeriodicTrigger
import kotlinx.coroutines.channels.Channel
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
annotation class Plugin(
/**
* 插件名称
*/
val name: String,
/**
* 插件描述(支持html)
*/
val desc: String = "",
/**
* 标签(相同标签的插件在默认的帮助展示时会放在一起)
*/
val tag: String = "其他",
/**
* 是否启用
*/
val enable: Boolean = true,
/**
* 是否隐藏
*/
val hidden: Boolean = false,
) {
/**
* 监听器
*/
interface Listener {
/**
* 事件
*/
interface Event {
companion object {
/**
* 订阅事件(内部事件注册)
*/
inline fun <reified T : Event> eventListener(noinline block: suspend BotApi.(T) -> Unit): Register {
return EventPluginRegister(T::class, block)
}
}
}
/**
* 在执行期间注入
*/
interface Hook {
companion object {
/**
* 钩子
* @param hookType 类型
* @param order 顺序
* @param block 执行内容
*/
inline fun <reified T : Hook> hook(
hookType: HookTypeEnum,
order: Int = 0,
match: HookPluginRegisterMatch = HookPluginRegisterMatch.allMatch(),
noinline block: suspend HookJoinPoint.(T) -> Unit
): Register {
return HookPluginRegister(order, T::class, hookType, match, block)
}
/**
* 前置
*/
inline fun <reified T : Hook> beforeHook(
order: Int = 0,
match: HookPluginRegisterMatch = HookPluginRegisterMatch.allMatch(),
noinline block: suspend HookJoinPoint.(T) -> Unit
): Register {
return hook<T>(HookTypeEnum.BEFORE, order, match, block)
}
/**
* 后置
*/
inline fun <reified T : Hook> afterReturningHook(
order: Int = 0,
match: HookPluginRegisterMatch = HookPluginRegisterMatch.allMatch(),
noinline block: suspend HookJoinPoint.(T) -> Unit
): Register {
return hook<T>(HookTypeEnum.AFTER_RETURNING, order, match, block)
}
/**
* 异常通知
*/
inline fun <reified T : Hook> afterThrowingHook(
order: Int = 0,
match: HookPluginRegisterMatch = HookPluginRegisterMatch.allMatch(),
noinline block: suspend HookJoinPoint.(T) -> Unit
): Register {
return hook<T>(HookTypeEnum.AFTER_THROWING, order, match, block)
}
/**
* 最终通知
*/
inline fun <reified T : Hook> afterFinallyHook(
order: Int = 0,
match: HookPluginRegisterMatch = HookPluginRegisterMatch.allMatch(),
noinline block: suspend HookJoinPoint.(T) -> Unit
): Register {
return hook<T>(HookTypeEnum.AFTER_FINALLY, order, match, block)
}
/**
* 环绕
*/
inline fun <reified T : Hook> aroundHook(
order: Int = 0,
match: HookPluginRegisterMatch = HookPluginRegisterMatch.allMatch(),
noinline block: suspend HookJoinPoint.(T) -> Unit
): Register {
return hook<T>(HookTypeEnum.AROUND, order, match, block)
}
}
}
}
object Task {
/**
* cron表达式执行任务
* @param cron cron表达式
* @param useGreeting 跟随系统的闲时状态执行定时
* @param block 执行内容
*/
fun cronScheduling(
cron: String,
useGreeting: Boolean = true,
block: suspend SchedulingBotApi.() -> Unit
): Register {
return TaskPluginRegister(CronTrigger(cron, useGreeting), block)
}
/**
* 周期执行任务
*
* @param period 执行周期
* @param initialDelay 首次执行延时时间
* @param fixedRate 是否为固定速率执行
* @param useGreeting 跟随系统的闲时状态执行定时
* @param block 执行内容
*/
fun periodicScheduling(
period: Duration,
initialDelay: Duration = 0.seconds,
fixedRate: Boolean = false,
useGreeting: Boolean = true,
block: suspend SchedulingBotApi.() -> Unit
): Register {
return TaskPluginRegister(PeriodicTrigger(fixedRate, period, initialDelay, useGreeting), block)
}
/**
* 在程序完全启动之后执行
*
* @param useGreeting 跟随系统的闲时状态执行定时
* @param block 执行内容
*/
fun applicationInitScheduling(
useGreeting: Boolean = true,
block: suspend SchedulingBotApi.() -> Unit
): Register {
return TaskPluginRegister(ApplicationInitTrigger(useGreeting), block)
}
}
object Message {
/**
* 戳一戳
*
* @param terminateEvent 执行完终止事件传播
* @param block 执行内容
*/
fun poke(
order: Int = 0,
auth: ApiAuth = ApiAuth.ORDINARY_MEMBER,
terminateEvent: Boolean = true,
block: suspend BotApi.(args: Array<String>) -> Unit
): Register {
return MessagePluginRegister(
order,
MessagePluginRegisterMatch(messageType = MessageTypeEnum.POKE, auth = auth, atMe = true),
terminateEvent,
block
)
}
/**
* 消息
*
* @param regex 正则匹配
* @param auth 权限
* @param terminateEvent 执行完终止事件传播
* @param block 执行内容
*/
fun message(
regex: Regex,
order: Int = 0,
auth: ApiAuth = ApiAuth.ORDINARY_MEMBER,
terminateEvent: Boolean = true,
block: suspend BotApi.(args: Array<String>) -> Unit
): Register {
return MessagePluginRegister(
order,
MessagePluginRegisterMatch(regex, auth),
terminateEvent,
block
)
}
/**
* 消息
*
* @param match 匹配规则
* @param terminateEvent 执行完终止事件传播
* @param block 执行内容
*/
fun message(
match: MessagePluginRegisterMatch = MessagePluginRegisterMatch.allMatch(),
order: Int = 0,
terminateEvent: Boolean = true,
block: suspend BotApi.(args: Array<String>) -> Unit
): Register {
return MessagePluginRegister(
order,
match,
terminateEvent,
block
)
}
/**
* 队列消息
*
* @param regex 正则匹配
* @param auth 权限
* @param terminateEvent 执行完终止事件传播
* @param block 执行内容
* @param queueCapacity 队列长度限制(默认无限)
*/
fun queueMessage(
regex: Regex,
order: Int = 0,
auth: ApiAuth = ApiAuth.ORDINARY_MEMBER,
terminateEvent: Boolean = true,
queueCapacity: Int = Channel.RENDEZVOUS,
block: suspend BotApi.(args: Array<String>) -> Unit
): Register {
return queueMessage(
MessagePluginRegisterMatch(regex, auth),
order,
terminateEvent,
queueCapacity,
block = block
)
}
/**
* 队列消息
*
* @param match 匹配规则
* @param terminateEvent 执行完终止事件传播
* @param block 执行内容
* @param queueCapacity 队列长度限制(默认无限)
* @param onSuccess 成功进入队列时的回调
* @param onOverFlow 队列已满时回调
*/
fun queueMessage(
match: MessagePluginRegisterMatch = MessagePluginRegisterMatch.allMatch(),
order: Int = 0,
terminateEvent: Boolean = true,
queueCapacity: Int = Channel.RENDEZVOUS,
onSuccess: suspend BotApi.(queueIndex: Int) -> Unit = { queueIndex ->
if (queueIndex > 0) this.sendReply(
"已成功进入队列,当前位于第${queueIndex}位,请耐心等待",
reference = true
)
},
onOverFlow: suspend BotApi.() -> Unit = {
this.sendReply("当前功能请求人数较多,请稍后再试")
},
block: suspend BotApi.(args: Array<String>) -> Unit
): Register {
return QueueMessagePluginRegister(
message(match, order, terminateEvent, block) as MessagePluginRegister,
queueCapacity,
onSuccess,
onOverFlow
)
}
}
}
| 0
|
Kotlin
|
0
| 6
|
4dfb4620ce2ef529bcf27bc1b719587eb668b56e
| 9,757
|
falowp-bot-system
|
Apache License 2.0
|
app/src/main/java/com/afauzi/bangungkota/presentation/ui/event/CreateEventActivity.kt
|
A-fauzi
| 687,105,360
| false
|
{"Kotlin": 105462}
|
package com.afauzi.bangungkota.presentation.ui.event
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.res.ResourcesCompat
import com.afauzi.bangungkota.R
import com.afauzi.bangungkota.databinding.ActivityCreateEventBinding
import com.afauzi.bangungkota.domain.model.Event
import com.afauzi.bangungkota.presentation.ui.main.MainActivity
import com.afauzi.bangungkota.presentation.viewmodels.EventViewModel
import com.afauzi.bangungkota.utils.Constant.RC_IMAGE_GALLERY
import com.afauzi.bangungkota.utils.CustomViews.toast
import com.afauzi.bangungkota.utils.UniqueIdGenerator
import com.afauzi.bangungkota.utils.UniqueIdGenerator.generateUniqueId
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.textfield.TextInputLayout
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.skydoves.transformationlayout.TransformationActivity
import com.skydoves.transformationlayout.TransformationAppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
import java.text.SimpleDateFormat
import java.util.*
@AndroidEntryPoint
class CreateEventActivity : TransformationAppCompatActivity() {
private lateinit var binding: ActivityCreateEventBinding
private lateinit var filePathImageGallery: Uri
private val eventViewModel: EventViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCreateEventBinding.inflate(layoutInflater)
setContentView(binding.root)
setViewAppBar()
setViewFormTextField()
onClickViews()
}
private fun onClickViews() {
binding.cvUploadImage.setOnClickListener {
getImageFromGalerry()
}
binding.eventDate.outlinedTextFieldEvent.setEndIconOnClickListener {
val datePicker = MaterialDatePicker.Builder.datePicker()
.setTitleText("Select date event 📅")
.setSelection(MaterialDatePicker.todayInUtcMilliseconds())
.build()
datePicker.show(supportFragmentManager, "17:00")
datePicker.addOnPositiveButtonClickListener {
val selectDate = Date(it)
val formattedDate =
SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(selectDate)
binding.eventDate.outlinedTextFieldEvent.editText?.setText(formattedDate)
binding.eventDate.editTextCreateEvent.setTextColor(resources.getColor(R.color.black))
}
}
binding.eventTime.outlinedTextFieldEvent.setEndIconOnClickListener {
val picker =
MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_12H)
.setHour(12)
.setMinute(10)
.setTitleText("Select time event ⏲")
.build()
picker.show(supportFragmentManager, "time")
picker.addOnPositiveButtonClickListener {
val selectedHour = picker.hour
val selectedMinute = picker.minute
val formattedTime = String.format("%02d:%02d", selectedHour, selectedMinute)
binding.eventTime.outlinedTextFieldEvent.editText?.setText(formattedTime)
binding.eventTime.editTextCreateEvent.setTextColor(resources.getColor(R.color.black))
}
}
binding.btnCreateEvent.setOnClickListener {
val auth = FirebaseAuth.getInstance()
val user = auth.currentUser
val data = Event(
id = generateUniqueId(),
title = binding.eventName.editTextCreateEvent.text.toString(),
address = binding.eventLocation.editTextCreateEvent.text.toString(),
date = binding.eventDate.editTextCreateEvent.text.toString(),
time = binding.eventTime.editTextCreateEvent.text.toString(),
createdBy = user?.uid.toString(),
description = binding.etDescription.text.toString()
)
if (this::filePathImageGallery.isInitialized) {
// JIka semua validasi pada create event sudah memenuhi
binding.btnCreateEvent.visibility = View.GONE
binding.progressbar.visibility = View.VISIBLE
enabledStateForm(false)
eventViewModel.createEvent(filePathImageGallery, data) { isSuccessfullyTransactionDb ->
if (isSuccessfullyTransactionDb) {
val intent = Intent(this@CreateEventActivity, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
finish()
overridePendingTransition(R.animator.slide_in_right, R.animator.slide_out_left)
} else {
toast(this, "Operasi gagal, ada kesalahan😥")
binding.btnCreateEvent.visibility = View.VISIBLE
binding.progressbar.visibility = View.GONE
}
}
} else {
toast(this, "Upload Gambar dulu 🤦♂️")
}
}
}
private fun enabledStateForm(state: Boolean) {
binding.eventName.outlinedTextFieldEvent.isEnabled = state
binding.eventLocation.outlinedTextFieldEvent.isEnabled = state
binding.outlinedTextFieldEventDesc.isEnabled = state
}
private fun getImageFromGalerry() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, RC_IMAGE_GALLERY)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == RC_IMAGE_GALLERY) {
try {
if (data != null) {
filePathImageGallery = data.data!!
binding.tvSetFillPath.text = filePathImageGallery.path.toString()
} else {
toast(this, "Data photo is null")
}
} catch (e: Exception) {
e.printStackTrace()
toast(this, e.message)
}
}
}
private fun setViewAppBar() {
binding.appBarLayout.topAppBar.title = "Create Event"
binding.appBarLayout.topAppBar.menu.findItem(R.id.user).isVisible = false
binding.appBarLayout.topAppBar.navigationIcon = ResourcesCompat.getDrawable(resources, R.drawable.ic_angle_left, null)
binding.appBarLayout.topAppBar.setNavigationOnClickListener {
onBackPressed()
}
}
private fun setViewFormTextField() {
binding.eventLocation.tvInputName.text = getString(R.string.choose_location)
binding.eventDate.tvInputName.text = getString(R.string.set_data_event)
binding.eventTime.tvInputName.text = getString(R.string.set_time_event)
binding.eventName.tvInputName.text = getString(R.string.event_name)
binding.eventLocation.editTextCreateEvent.hint = "Bekasi, Jawabarat"
binding.eventName.editTextCreateEvent.hint = "Charity child people"
binding.eventDate.editTextCreateEvent.hint = "2023-08-31"
binding.eventTime.editTextCreateEvent.hint = "18:10"
binding.eventLocation.outlinedTextFieldEvent.endIconMode = TextInputLayout.END_ICON_CUSTOM
binding.eventDate.outlinedTextFieldEvent.endIconMode = TextInputLayout.END_ICON_CUSTOM
binding.eventTime.outlinedTextFieldEvent.endIconMode = TextInputLayout.END_ICON_CUSTOM
binding.eventLocation.outlinedTextFieldEvent.endIconDrawable =
ResourcesCompat.getDrawable(resources, R.drawable.map_marker_filled, null)
binding.eventDate.outlinedTextFieldEvent.endIconDrawable =
ResourcesCompat.getDrawable(resources, R.drawable.ic_calendar, null)
binding.eventTime.outlinedTextFieldEvent.endIconDrawable =
ResourcesCompat.getDrawable(resources, R.drawable.ic_clock, null)
binding.eventTime.editTextCreateEvent.isEnabled = false
binding.eventDate.editTextCreateEvent.isEnabled = false
}
}
| 0
|
Kotlin
|
0
| 1
|
ac498b2dbebb595d6db77738bfa89399196042b8
| 8,744
|
NewBangungKota
|
MIT License
|
src/main/kotlin/de/sambalmueslie/openevent/api/MailAPI.kt
|
Black-Forrest-Development
| 542,810,521
| false
| null |
package de.sambalmueslie.openevent.api
import de.sambalmueslie.openevent.infrastructure.mail.api.MailJob
import de.sambalmueslie.openevent.infrastructure.mail.api.MailJobHistoryEntry
import io.micronaut.data.model.Page
import io.micronaut.data.model.Pageable
import io.micronaut.security.authentication.Authentication
interface MailAPI {
companion object {
const val PERMISSION_READ = "openevent.mail.read"
const val PERMISSION_WRITE = "openevent.mail.write"
}
fun getJobs(auth: Authentication, pageable: Pageable): Page<MailJob>
fun getFailedJobs(auth: Authentication, pageable: Pageable): Page<MailJob>
fun getJobHistory(auth: Authentication, jobId: Long, pageable: Pageable): Page<MailJobHistoryEntry>
}
| 0
|
Kotlin
|
0
| 1
|
170c860ce1ac4499a8e7ee63cf4134fb38d29924
| 747
|
open-event
|
Apache License 2.0
|
dist/src/main/kotlin/kr/toxicity/hud/manager/DatabaseManagerImpl.kt
|
toxicity188
| 766,189,896
| false
|
{"Kotlin": 151540, "Java": 35638}
|
package kr.toxicity.hud.manager
import kr.toxicity.hud.api.database.HudDatabase
import kr.toxicity.hud.api.database.HudDatabaseConnector
import kr.toxicity.hud.api.hud.Hud
import kr.toxicity.hud.api.manager.DatabaseManager
import kr.toxicity.hud.api.player.HudPlayer
import kr.toxicity.hud.api.popup.Popup
import kr.toxicity.hud.player.HudPlayerImpl
import kr.toxicity.hud.resource.GlobalResource
import kr.toxicity.hud.util.*
import org.bukkit.configuration.MemoryConfiguration
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.entity.Player
import java.io.File
import java.sql.DriverManager
object DatabaseManagerImpl: BetterHudManager, DatabaseManager {
private val defaultConnector = HudDatabaseConnector {
object : HudDatabase {
private fun getFile(player: Player): File {
return DATA_FOLDER
.subFolder(".users")
.subFile("${player.uniqueId}.yml")
}
override fun close() {
}
override fun load(player: Player): HudPlayer {
val yaml = getFile(player).toYaml()
return HudPlayerImpl(
player,
yaml.getStringList("huds").mapNotNull {
HudManagerImpl.getHud(it)
}.filter {
!it.isDefault
}.toMutableSet(),
yaml.getStringList("popups").mapNotNull {
PopupManagerImpl.getPopup(it)
}.filter {
!it.isDefault
}.toMutableSet()
)
}
override fun save(player: HudPlayer): Boolean {
YamlConfiguration().run {
set("popups", player.popups.filter {
!it.isDefault
}.map {
it.name
}.toTypedArray())
set("huds", player.huds.filter {
!it.isDefault
}.map {
it.name
}.toTypedArray())
save(getFile(player.bukkitPlayer))
}
return true
}
}
}
private val connectionMap = mapOf(
"yml" to defaultConnector,
"mysql" to HudDatabaseConnector {
val host = it.getString("host").ifNull("unable to find the host value.")
val database = it.getString("database").ifNull("unable to find the database value.")
val name = it.getString("name").ifNull("unable to find the name value.")
val password = it.getString("password").ifNull("unable to find the password value.")
val mysql = DriverManager.getConnection("jdbc:mysql://$host/$database?autoReconnect=true&useSSL=false&cmaxReconnets=5&initialTimeout=1", name, password).apply {
createStatement().use { s ->
s.execute("CREATE TABLE IF NOT EXISTS enabled_hud(uuid CHAR(36) NOT NULL, type VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL);")
}
}
object: HudDatabase {
override fun close() {
mysql.close()
}
override fun load(player: Player): HudPlayer {
val uuid = player.uniqueId.toString()
val huds = HashSet<Hud>()
val popups = HashSet<Popup>()
mysql.prepareStatement("SELECT type, name FROM enabled_hud WHERE uuid = '$uuid';").use { s ->
val result = s.executeQuery()
while (result.next()) {
when (result.getString("type")) {
"hud" -> HudManagerImpl.getHud(result.getString("name"))?.let { h ->
if (!h.isDefault) huds.add(h)
}
"popup" -> PopupManagerImpl.getPopup(result.getString("popup"))?.let { p ->
if (!p.isDefault) popups.add(p)
}
}
}
}
return HudPlayerImpl(player, huds, popups)
}
override fun save(player: HudPlayer): Boolean {
val uuid = player.bukkitPlayer.uniqueId.toString()
mysql.run {
prepareStatement("DELETE FROM enabled_hud WHERE uuid = '$uuid';").use { s ->
s.executeUpdate()
}
player.huds.filter { h ->
!h.isDefault
}.forEach { h ->
prepareStatement("INSERT INTO enabled_hud(uuid, type, name) VALUES(?, ?, ?);").use { s ->
s.setString(1, uuid)
s.setString(2, "hud")
s.setString(3, h.name)
s.executeUpdate()
}
}
player.popups.filter { p ->
!p.isDefault
}.forEach { p ->
prepareStatement("INSERT INTO enabled_hud(uuid, type, name) VALUES(?, ?, ?);").use { s ->
s.setString(1, uuid)
s.setString(2, "popup")
s.setString(3, p.name)
s.executeUpdate()
}
}
}
return true
}
}
}
)
private var current = defaultConnector.connect(MemoryConfiguration())
override fun start() {
}
override fun getCurrentDatabase(): HudDatabase = current
override fun reload(resource: GlobalResource) {
runCatching {
current.close()
val db = File(DATA_FOLDER, "database.yml").apply {
if (!exists()) PLUGIN.saveResource("database.yml", false)
}.toYaml()
val type = db.getString("type").ifNull("type value not set.")
val info = db.getConfigurationSection("info").ifNull("info configuration not set.")
current = connectionMap[type].ifNull("this database doesn't exist: $type").connect(info)
}.onFailure { e ->
current = defaultConnector.connect(MemoryConfiguration())
warn("Unable to connect the database.")
warn("Reason: ${e.message}")
}
}
override fun end() {
}
}
| 2
|
Kotlin
|
6
| 32
|
ab70cc1a23b85381ab3fb806de5738e931a8a93c
| 6,794
|
BetterHud
|
MIT License
|
src/main/kotlin/icu/windea/pls/core/library/ParadoxLibraryType.kt
|
DragonKnightOfBreeze
| 328,104,626
| false
| null |
package icu.windea.pls.core.library
import com.intellij.openapi.project.*
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.libraries.*
import com.intellij.openapi.roots.libraries.ui.*
import com.intellij.openapi.vfs.*
import icu.windea.pls.*
import icu.windea.pls.model.*
import javax.swing.*
class ParadoxLibraryType : LibraryType<ParadoxLibraryProperties>(ParadoxLibraryKind) {
override fun getCreateActionName() = "Paradox"
override fun getIcon(properties: ParadoxLibraryProperties?) = PlsIcons.Library
override fun getExternalRootTypes() = arrayOf(OrderRootType.SOURCES)
override fun createPropertiesEditor(editorComponent: LibraryEditorComponent<ParadoxLibraryProperties>) = null
override fun createNewLibrary(parentComponent: JComponent, contextDirectory: VirtualFile?, project: Project): NewLibraryConfiguration? {
//必须是一个文件夹,且必须包含descriptor.mod或launcher-settings.json
//TODO 兼容压缩包
val dialog = ParadoxCreateNewLibraryDialog(project, contextDirectory)
if(dialog.showAndGet()) {
val rootFile = dialog.rootFile
val rootInfo = dialog.rootInfo
val descriptorInfo = rootInfo?.descriptorInfo
if(rootFile != null && rootInfo != null && descriptorInfo != null) {
//基于descriptor.mod或launcher-settings.json得到库的名字,由于此文件可能发生变更,不保存库的属性
val libraryName = getLibraryName(rootInfo, descriptorInfo)
val libraryProperties = ParadoxLibraryProperties
return ParadoxNewLibraryConfiguration(libraryName, this, rootFile, libraryProperties)
}
}
return null
}
private fun getLibraryName(rootInfo: ParadoxRootInfo, descriptorInfo: ParadoxDescriptorInfo): String {
//FIXME 这里的名字和版本基于描述符文件,可能会过时
return buildString {
val rootType = rootInfo.rootType
append("Paradox/").append(rootInfo.gameType.description).append(" ").append(rootType.description)
val version = descriptorInfo.version
if(rootType == ParadoxRootType.Mod) append(": ").append(descriptorInfo.name)
if(version != null) append("@").append(version)
}
}
}
| 2
| null |
2
| 7
|
037b9b4ba467ed49ea221b99efb0a26cd630bb67
| 1,999
|
Paradox-Language-Support
|
MIT License
|
app/src/main/java/com/dedsec_x47/trainer/exercisePages/MiniGames.kt
|
Karthick47v2
| 406,409,965
| false
| null |
package com.dedsec_x47.trainer.exercisePages
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.dedsec_x47.trainer.databinding.ActivityMiniGamesBinding
import com.unity3d.player.UnityPlayerActivity
class MiniGames : AppCompatActivity() {
private lateinit var activityMiniGamesBinding : ActivityMiniGamesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMiniGamesBinding = ActivityMiniGamesBinding.inflate(layoutInflater)
setContentView(activityMiniGamesBinding.root)
activityMiniGamesBinding.cardGame1MG.setOnClickListener(){
val intent = Intent(this, UnityPlayerActivity::class.java)
startActivity(intent)
}
activityMiniGamesBinding.cardComingSoonMG.setOnClickListener(){
// val intent = Intent(this, ::class.java)
// startActivity(intent)
}
}
}
| 1
|
Kotlin
|
5
| 5
|
87b08726d35780477c8e00f68ae8a4f1d162d715
| 981
|
trAIner
|
MIT License
|
src/main/kotlin/no/nav/pensjon/kalkulator/tp/client/esb/EsbTjenestepensjonClient.kt
|
navikt
| 596,104,195
| false
| null |
package no.nav.pensjon.kalkulator.tp.client.esb
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import mu.KotlinLogging
import no.nav.pensjon.kalkulator.person.Pid
import no.nav.pensjon.kalkulator.tech.security.egress.EgressAccess
import no.nav.pensjon.kalkulator.tech.security.egress.config.EgressService
import no.nav.pensjon.kalkulator.tech.security.egress.config.GatewayUsage
import no.nav.pensjon.kalkulator.tech.security.egress.token.unt.client.UsernameTokenClient
import no.nav.pensjon.kalkulator.tp.client.esb.dto.EnvelopeDto
import no.nav.pensjon.kalkulator.tech.web.CustomHttpHeaders
import no.nav.pensjon.kalkulator.tech.web.EgressException
import no.nav.pensjon.kalkulator.tp.client.TjenestepensjonClient
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpHeaders
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClientResponseException
import java.util.*
@Component
class EsbTjenestepensjonClient(
@Value("\${tp.url}") private val baseUrl: String,
private val usernameTokenClient: UsernameTokenClient,
@Qualifier("soap") private val webClient: WebClient,
private val xmlMapper: XmlMapper
) : TjenestepensjonClient {
private val log = KotlinLogging.logger {}
override fun harTjenestepensjonsforhold(pid: Pid): Boolean {
val responseXml = fetchTjenestepensjonsforholdXml(pid)
return try {
val dto = xmlMapper.readValue(responseXml, EnvelopeDto::class.java)
isForholdDefined(dto)
} catch (e: JsonProcessingException) {
log.error(e) { "Failed to process XML: $responseXml" }
false
}
}
private fun fetchTjenestepensjonsforholdXml(pid: Pid): String {
val uri = "$baseUrl$PATH"
val body = soapEnvelope(pid.value, soapBody(pid))
log.debug { "POST to URI: '$uri' with body '$body'" }
try {
return webClient
.post()
.uri(uri)
.headers(::setHeaders)
.bodyValue(body)
.retrieve()
.bodyToMono(String::class.java)
.block()
?: ""
} catch (e: WebClientResponseException) {
throw EgressException(e.responseBodyAsString, e)
} catch (e: RuntimeException) { // e.g. when connection broken
throw EgressException("Failed to GET $uri: ${e.message}", e)
}
}
private fun soapEnvelope(userId: String, body: String): String {
return """<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
${soapHeader(userId)}
$body
</soapenv:Envelope>"""
}
private fun soapHeader(userId: String): String {
val callId = callId()
return """<soapenv:Header>
<callId xmlns="uri:no.nav.applikasjonsrammeverk">$callId</callId>
<sc:StelvioContext xmlns="" xmlns:sc="http://www.nav.no/StelvioContextPropagation">
<applicationId>$APPLICATION_USER_ID</applicationId>
<correlationId>$callId</correlationId>
<userId>$userId</userId>
</sc:StelvioContext>
${usernameToken()}
</soapenv:Header>"""
}
private fun usernameToken() = usernameTokenClient.fetchUsernameToken().token
companion object {
private const val PATH = "/nav-cons-pen-pselv-tjenestepensjonWeb/sca/PSELVTjenestepensjonWSEXP"
// PP01 is the old service user ID for pensjon (replaced by srvpensjon/srvpselv in most apps)
private const val APPLICATION_USER_ID = "PP01"
private val service = EgressService.TJENESTEPENSJONSFORHOLD
private fun callId() = UUID.randomUUID().toString()
private fun setHeaders(headers: HttpHeaders) {
if (service.gatewayUsage == GatewayUsage.INTERNAL) {
headers.setBearerAuth(EgressAccess.token(service).value)
}
headers[CustomHttpHeaders.CALL_ID] = callId()
}
private fun soapBody(pid: Pid): String {
return """<soapenv:Body>
${specXml(pid)}
</soapenv:Body>"""
}
private fun specXml(pid: Pid): String {
return """<inf:finnTjenestepensjonForhold xmlns:inf="http://nav-cons-pen-pselv-tjenestepensjon/no/nav/inf">
<finnTjenestepensjonForholdRequest>
<hentSamhandlerInfo>true</hentSamhandlerInfo>
<fnr>${pid.value}</fnr>
</finnTjenestepensjonForholdRequest>
</inf:finnTjenestepensjonForhold>"""
}
private fun isForholdDefined(dto: EnvelopeDto?) =
dto?.body?.wrapper?.response?.forhold != null
}
}
| 0
|
Kotlin
|
0
| 0
|
0ca9756e794ebfa1ce12db2e9e05c944ab89e52e
| 4,921
|
pensjonskalkulator-backend
|
MIT License
|
core/src/main/kotlin/net/corda/core/crypto/internal/ProviderMap.kt
|
corda
| 70,137,417
| false
| null |
package net.corda.core.crypto.internal
import net.corda.core.DeleteForDJVM
import net.corda.core.crypto.CordaSecurityProvider
import net.corda.core.crypto.Crypto.EDDSA_ED25519_SHA512
import net.corda.core.crypto.Crypto.decodePrivateKey
import net.corda.core.crypto.Crypto.decodePublicKey
import net.corda.core.internal.X509EdDSAEngine
import net.i2p.crypto.eddsa.EdDSAEngine
import net.i2p.crypto.eddsa.EdDSASecurityProvider
import org.bouncycastle.asn1.ASN1ObjectIdentifier
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
import org.bouncycastle.jcajce.provider.asymmetric.ec.AlgorithmParametersSpi
import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider
import java.security.SecureRandom
import java.security.Security
val cordaSecurityProvider = CordaSecurityProvider().also {
// Among the others, we should register [CordaSecurityProvider] as the first provider, to ensure that when invoking [SecureRandom()]
// the [platformSecureRandom] is returned (which is registered in CordaSecurityProvider).
// Note that internally, [SecureRandom()] will look through all registered providers.
// Then it returns the first PRNG algorithm of the first provider that has registered a SecureRandom
// implementation (in our case [CordaSecurityProvider]), or null if none of the registered providers supplies
// a SecureRandom implementation.
Security.insertProviderAt(it, 1) // The position is 1-based.
}
// OID taken from https://tools.ietf.org/html/draft-ietf-curdle-pkix-00
val `id-Curve25519ph` = ASN1ObjectIdentifier("1.3.101.112")
val cordaBouncyCastleProvider = BouncyCastleProvider().apply {
putAll(EdDSASecurityProvider())
// Override the normal EdDSA engine with one which can handle X509 keys.
put("Signature.${EdDSAEngine.SIGNATURE_ALGORITHM}", X509EdDSAEngine::class.java.name)
addKeyInfoConverter(`id-Curve25519ph`, object : AsymmetricKeyInfoConverter {
override fun generatePublic(keyInfo: SubjectPublicKeyInfo) = decodePublicKey(EDDSA_ED25519_SHA512, keyInfo.encoded)
override fun generatePrivate(keyInfo: PrivateKeyInfo) = decodePrivateKey(EDDSA_ED25519_SHA512, keyInfo.encoded)
})
// Required due to [X509CRL].verify() reported issues in network-services after BC 1.60 update.
put("AlgorithmParameters.SHA256WITHECDSA", AlgorithmParametersSpi::class.java.name)
}.also {
// This registration is needed for reading back EdDSA key from java keystore.
// TODO: Find a way to make JKS work with bouncy castle provider or implement our own provide so we don't have to register bouncy castle provider.
Security.addProvider(it)
}
val bouncyCastlePQCProvider = BouncyCastlePQCProvider().apply {
require(name == "BCPQC") { "Invalid PQCProvider name" }
}.also {
Security.addProvider(it)
}
// This map is required to defend against users that forcibly call Security.addProvider / Security.removeProvider
// that could cause unexpected and suspicious behaviour.
// i.e. if someone removes a Provider and then he/she adds a new one with the same name.
// The val is private to avoid any harmful state changes.
val providerMap = listOf(cordaBouncyCastleProvider, cordaSecurityProvider, bouncyCastlePQCProvider).map { it.name to it }.toMap()
@DeleteForDJVM
fun platformSecureRandomFactory(): SecureRandom = platformSecureRandom() // To minimise diff of CryptoUtils against open-source.
| 59
| null |
1090
| 3,971
|
318990cfd90aab455311cc6256d11dc98c26d1df
| 3,572
|
corda
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/HailSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/HailSharp")
package mui.icons.material
@JsName("default")
external val HailSharp: SvgIconComponent
| 12
| null |
5
| 983
|
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 182
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/com/baulsupp/oksocial/services/transferwise/TransferwiseTestAuthInterceptor.kt
|
MaTriXy
| 129,725,910
| true
|
{"Kotlin": 426653, "Shell": 9764}
|
package com.baulsupp.oksocial.services.transferwise
import com.baulsupp.oksocial.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.oksocial.completion.ApiCompleter
import com.baulsupp.oksocial.completion.BaseUrlCompleter
import com.baulsupp.oksocial.completion.CompletionVariableCache
import com.baulsupp.oksocial.completion.UrlList
import com.baulsupp.oksocial.credentials.CredentialsStore
import com.baulsupp.oksocial.credentials.Token
import okhttp3.OkHttpClient
class TransferwiseTestAuthInterceptor : TransferwiseAuthInterceptor() {
override fun host(): String {
return "test-restgw.transferwise.com"
}
override fun serviceDefinition(): Oauth2ServiceDefinition {
return Oauth2ServiceDefinition(host(), "Transferwise Test API", "transferwise-test",
"https://api-docs.transferwise.com/",
"https://api-docs.transferwise.com/api-explorer/transferwise-api/versions/v1/")
}
override fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
val urlList = UrlList.fromResource("transferwise")!!
val testUrls = urlList.getUrls("")
.map { s -> s.replace("api.transferwise.com", host()) }
return BaseUrlCompleter(UrlList(UrlList.Match.SITE, testUrls), hosts(), completionVariableCache)
}
}
| 0
|
Kotlin
|
0
| 0
|
c4da9b2858cb9477b96fabb36b31a60f716e3e86
| 1,396
|
oksocial
|
Apache License 2.0
|
frontend/src/jsMain/kotlin/com/monkopedia/konstructor/frontend/koin/KonstructionScope.kt
|
Monkopedia
| 418,215,448
| false
|
{"Kotlin": 507651, "JavaScript": 159882, "HTML": 1015}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.monkopedia.konstructor.frontend.koin
import com.monkopedia.konstructor.frontend.model.KonstructionModel
import com.monkopedia.konstructor.frontend.model.RenderModel
import org.koin.core.qualifier.named
import org.koin.core.scope.Scope
import org.koin.dsl.ScopeDSL
class KonstructionScope(private val workspaceScope: WorkspaceScope, val konstructionId: String) :
CoroutineKoinScope() {
override fun onScopeCreated(scope: Scope) {
scope.linkTo(workspaceScope.scope)
}
companion object {
val konstructionId = named("konstruction.id")
fun ScopeDSL.initScope() {
scoped {
get<KonstructionScope>().coroutineScope
}
scoped(konstructionId) {
get<KonstructionScope>().konstructionId
}
scoped {
KonstructionModel(get(), get(), get(konstructionId), get(),)
}
scoped {
RenderModel(get(), get())
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
38f0c0d9adeba659e5cb7bf6b88a6995a3c7546f
| 1,614
|
Konstructor
|
Apache License 2.0
|
app/src/main/java/com/ably/tracking/demo/subscriber/presentation/screen/orderarrived/OrderArrivedScreen.kt
|
ably
| 497,981,253
| false
| null |
package com.ably.tracking.demo.subscriber.presentation.screen.orderarrived
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ably.tracking.demo.subscriber.R
import com.ably.tracking.demo.subscriber.presentation.theme.AATSubscriberDemoTheme
import com.ably.tracking.demo.subscriber.presentation.widget.AATAppBar
import com.ably.tracking.demo.subscriber.presentation.widget.StyledTextButton
import org.koin.androidx.compose.getViewModel
@Composable
@Preview
fun OrderArrivedScreen(viewModel: OrderArrivedViewModel = getViewModel()) = AATSubscriberDemoTheme {
Scaffold(
topBar = { AATAppBar() }
) {
CreateOrderScreenContent(viewModel)
}
}
@Composable
fun CreateOrderScreenContent(viewModel: OrderArrivedViewModel) = AATSubscriberDemoTheme {
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
modifier = Modifier.padding(8.dp),
text = stringResource(id = R.string.order_arrived_message)
)
StyledTextButton(
text = R.string.order_arrived_button_text,
onClick = viewModel::onCreateNewOrderClick
)
}
}
| 0
|
Kotlin
|
1
| 1
|
5fc1375679f84889d1e292df344ae174a06ecc1b
| 1,746
|
asset-tracking-android-customer-app-demo
|
Apache License 2.0
|
app/src/androidTest/java/com/hydrofish/app/RegisterInstrumentedTest.kt
|
HydroFish-Waterloo
| 748,731,716
| false
|
{"Kotlin": 273974}
|
package com.hydrofish.app
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hydrofish.app.api.ApiService
import com.hydrofish.app.api.AuthSuccess
import com.hydrofish.app.api.RegisterRequest
import com.hydrofish.app.ui.composables.unauthenticated.registration.RegistrationScreen
import com.hydrofish.app.ui.composables.unauthenticated.registration.RegistrationViewModel
import com.hydrofish.app.utils.IUserSessionRepository
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.test.runTest
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.mockito.Mockito.mock
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
@RunWith(AndroidJUnit4::class)
class RegisterInstrumentedTest {
private fun setupMockFailResponse(errorJson: String, registerRequest: RegisterRequest): Pair<IUserSessionRepository, ApiService> {
val errorResponseBody = errorJson.toResponseBody("application/json".toMediaTypeOrNull())
val mockErrorResponse = Response.error<AuthSuccess>(400, errorResponseBody)
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val mockCall: Call<AuthSuccess> = mock(Call::class.java) as Call<AuthSuccess>
Mockito.`when`(mockApiService.registerUser(registerRequest)).thenReturn(mockCall)
Mockito.doAnswer { invocation ->
val callback: Callback<AuthSuccess> = invocation.getArgument(0)
callback.onResponse(mockCall, mockErrorResponse)
null
}.`when`(mockCall).enqueue(ArgumentMatchers.any())
return Pair(mockUserSessionRepository, mockApiService)
}
private fun setupUi(userSessionRepository: IUserSessionRepository, apiService: ApiService) {
val viewModel = RegistrationViewModel(userSessionRepository, apiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = {},
userSessionRepository = userSessionRepository,
registrationViewModel = viewModel
)
}
}
private fun fillRegistrationForm(username: String, mobile: String, password: String, confirmPassword: String) {
composeTestRule.onNodeWithTag("username").performTextInput(username)
composeTestRule.onNodeWithTag("mobile").performTextInput(mobile)
composeTestRule.onNodeWithTag("password").performTextInput(password)
composeTestRule.onNodeWithTag("confirm password").performTextInput(confirmPassword)
}
private fun performRegistration() {
composeTestRule.onNodeWithText("Register").performClick()
}
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun registerFailByUserName() = runTest {
val errorJson = """
{
"username": ["A user with that username already exists."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "password", password2 = "password")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "password")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("A user with that username already exists.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByUserNamePassword1() = runTest {
val errorJson = """
{
"username": ["A user with that username already exists."],
"password1": ["The password is too similar to the username."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "password", password2 = "password")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "password")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("A user with that username already exists.").fetchSemanticsNodes()
.isNotEmpty()
}
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("The password is too similar to the username.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByUserNamePassword2() = runTest {
val errorJson = """
{
"username": ["A user with that username already exists."],
"password2": ["The password is too similar to the username."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "password", password2 = "password")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "password")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("A user with that username already exists.").fetchSemanticsNodes()
.isNotEmpty()
}
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("The password is too similar to the username.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByUserNamePassword12() = runTest {
val errorJson = """
{
"username": ["A user with that username already exists."],
"password1": ["This password is too common."],
"password2": ["The password is too similar to the username."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "password", password2 = "<PASSWORD>")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "<PASSWORD>")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("A user with that username already exists.").fetchSemanticsNodes()
.isNotEmpty()
}
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("This password is too common.").fetchSemanticsNodes()
.isNotEmpty()
}
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("The password is too similar to the username.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByPassword1() = runTest {
val errorJson = """
{
"password1": ["This password is too common."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "<PASSWORD>", password2 = "<PASSWORD>")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "<PASSWORD>")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("This password is too common.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByPassword2() = runTest {
val errorJson = """
{
"password2": ["The password is too similar to the username."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "<PASSWORD>", password2 = "<PASSWORD>")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "<PASSWORD>")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("The password is too similar to the username.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByPassword12() = runTest {
val errorJson = """
{
"password1": ["This password is too common."],
"password2": ["The password is too similar to the username."]
}
""".trimIndent()
val wrongRegisterRequest = RegisterRequest(username = "wrong", password1 = "<PASSWORD>", password2 = "<PASSWORD>")
val (userSessionRepository, apiService) = setupMockFailResponse(errorJson, wrongRegisterRequest)
setupUi(userSessionRepository, apiService)
fillRegistrationForm("wrong", "1235479633", "password", "<PASSWORD>")
performRegistration()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("This password is too common.").fetchSemanticsNodes()
.isNotEmpty()
}
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("The password is too similar to the username.").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerSuccess() = runTest {
var isOnNavigateCalled = false
val onNavigateToAuthenticatedRoute = {
isOnNavigateCalled = true
}
val mockSuccessResponse = Response.success(
AuthSuccess(
token = "6d2eee5b621aa765c1d5e7f201de347026be7309",
username = "testtttt"
)
)
val correctRegisterRequest = RegisterRequest(username = "correct", password1 = "<PASSWORD>", password2 = "<PASSWORD>")
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val mockCall: Call<AuthSuccess> = mock(Call::class.java) as Call<AuthSuccess>
Mockito.`when`(mockApiService.registerUser(correctRegisterRequest)).thenReturn(mockCall)
Mockito.doAnswer { invocation ->
val callback: Callback<AuthSuccess> = invocation.getArgument(0)
callback.onResponse(mockCall, mockSuccessResponse)
null
}.`when`(mockCall).enqueue(ArgumentMatchers.any())
val viewModel = RegistrationViewModel(userSessionRepository = mockUserSessionRepository, apiService = mockApiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = onNavigateToAuthenticatedRoute,
userSessionRepository = mockUserSessionRepository,
registrationViewModel = viewModel
)
}
composeTestRule.onNodeWithTag("username").performTextInput("correct")
composeTestRule.onNodeWithTag("mobile").performTextInput("1235479633")
composeTestRule.onNodeWithTag("password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithTag("confirm password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithText("Register").performClick()
composeTestRule.waitForIdle()
assertTrue(isOnNavigateCalled)
}
@Test
fun registerFailByEmptyUserName() = runTest {
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val viewModel = RegistrationViewModel(userSessionRepository = mockUserSessionRepository, apiService = mockApiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = {},
userSessionRepository = mockUserSessionRepository,
registrationViewModel = viewModel
)
}
composeTestRule.onNodeWithTag("username").performTextInput(" ")
composeTestRule.onNodeWithTag("mobile").performTextInput("1235479633")
composeTestRule.onNodeWithTag("password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithTag("confirm password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithText("Register").performClick()
composeTestRule.waitForIdle()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("Please enter your user name").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByEmptyMobile() = runTest {
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val viewModel = RegistrationViewModel(userSessionRepository = mockUserSessionRepository, apiService = mockApiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = {},
userSessionRepository = mockUserSessionRepository,
registrationViewModel = viewModel
)
}
composeTestRule.onNodeWithTag("username").performTextInput("wrong")
composeTestRule.onNodeWithTag("mobile").performTextInput("")
composeTestRule.onNodeWithTag("password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithTag("confirm password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithText("Register").performClick()
composeTestRule.waitForIdle()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("Please enter your mobile number").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByEmptyPassword1() = runTest {
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val viewModel = RegistrationViewModel(userSessionRepository = mockUserSessionRepository, apiService = mockApiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = {},
userSessionRepository = mockUserSessionRepository,
registrationViewModel = viewModel
)
}
composeTestRule.onNodeWithTag("username").performTextInput("wrong")
composeTestRule.onNodeWithTag("mobile").performTextInput("1235479633")
composeTestRule.onNodeWithTag("password").performTextInput("")
composeTestRule.onNodeWithTag("confirm password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithText("Register").performClick()
composeTestRule.waitForIdle()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("Please enter your password").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByEmptyPassword2() = runTest {
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val viewModel = RegistrationViewModel(userSessionRepository = mockUserSessionRepository, apiService = mockApiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = {},
userSessionRepository = mockUserSessionRepository,
registrationViewModel = viewModel
)
}
composeTestRule.onNodeWithTag("username").performTextInput("wrong")
composeTestRule.onNodeWithTag("mobile").performTextInput("1235479633")
composeTestRule.onNodeWithTag("password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithTag("confirm password").performTextInput("")
composeTestRule.onNodeWithText("Register").performClick()
composeTestRule.waitForIdle()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("Please confirm your password").fetchSemanticsNodes()
.isNotEmpty()
}
}
@Test
fun registerFailByMismatch() = runTest {
val mockUserSessionRepository = Mockito.mock(IUserSessionRepository::class.java)
val mockApiService = mock(ApiService::class.java)
val viewModel = RegistrationViewModel(userSessionRepository = mockUserSessionRepository, apiService = mockApiService)
composeTestRule.setContent {
RegistrationScreen(
onNavigateBack = {},
onNavigateToAuthenticatedRoute = {},
userSessionRepository = mockUserSessionRepository,
registrationViewModel = viewModel
)
}
composeTestRule.onNodeWithTag("username").performTextInput("wrong")
composeTestRule.onNodeWithTag("mobile").performTextInput("1235479633")
composeTestRule.onNodeWithTag("password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithTag("confirm password").performTextInput("<PASSWORD>")
composeTestRule.onNodeWithText("Register").performClick()
composeTestRule.waitForIdle()
composeTestRule.waitUntil(timeoutMillis = 1000) {
composeTestRule.onAllNodesWithText("Please enter the same password here as above").fetchSemanticsNodes()
.isNotEmpty()
}
}
}
| 3
|
Kotlin
|
0
| 0
|
eadfc258a70804250726e316fcbde37f50265d5a
| 18,840
|
HydroFish
|
MIT License
|
app/src/main/kotlin/com/hyperdevs/arch_example/ui/components/commons/StatusBarDisposableEffect.kt
|
hyperdevs-team
| 449,757,130
| false
| null |
/*
* Copyright 2022 Babelia
*
* 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.babelia.fansyn.ui.components.commons
import androidx.compose.material.BottomNavigationDefaults
import androidx.compose.material.LocalElevationOverlay
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import com.google.accompanist.systemuicontroller.rememberSystemUiController
/**
* [DisposableEffect] in charge of showing dark or light icons in the system bars and restore them when
* disposing the Composable.
*/
@Composable
fun StatusBarDisposableEffect(darkIcons: Boolean = true) {
val systemUiController = rememberSystemUiController()
val oldStatusBarColor = remember { systemUiController.statusBarDarkContentEnabled }
val oldNavigationBarColor = remember { systemUiController.navigationBarDarkContentEnabled }
val backgroundColor = MaterialTheme.colors.background
val elevatedBackgroundColor = LocalElevationOverlay.current?.apply(
color = backgroundColor, elevation = BottomNavigationDefaults.Elevation
)
DisposableEffect(Unit) {
systemUiController.setSystemBarsColor(color = Color.Transparent, darkIcons = darkIcons)
onDispose {
systemUiController.setStatusBarColor(color = Color.Transparent, darkIcons = oldStatusBarColor)
systemUiController.setNavigationBarColor(
color = elevatedBackgroundColor ?: backgroundColor,
darkIcons = oldNavigationBarColor
)
}
}
}
| 0
| null |
0
| 1
|
4d799865d975b2aba73e88d625fe9a7585e1c9e1
| 2,194
|
android-architecture-example
|
Apache License 2.0
|
src/main/kotlin/no/nav/pensjon/simulator/core/out/OutputPrivatAfp.kt
|
navikt
| 753,551,695
| false
|
{"Kotlin": 1608776, "Java": 48078, "Dockerfile": 144}
|
package no.nav.pensjon.simulator.core.out
data class OutputPrivatAfp(
val alder: Int,
val beloep: Int
)
| 2
|
Kotlin
|
0
| 0
|
32ef34837491247c078a5052e9124fed6e99517d
| 113
|
pensjonssimulator
|
MIT License
|
proj1/src/main/kotlin/it/gualtierotesta/playwithkotlin/Hello.kt
|
gualtierotesta
| 129,613,223
| false
|
{"Text": 1, "Ignore List": 1, "EditorConfig": 4, "Markdown": 1, "Maven POM": 2, "Kotlin": 28, "Gradle": 4, "Shell": 2, "Batchfile": 2, "INI": 2, "Java": 2, "Java Properties": 1}
|
package it.gualtierotesta.playwithkotlin
fun main(args: Array<String>) {
val msg1 = CustomMessage("Ciao")
val msg2 = msg1.copy()
val msg3 = msg1.copy(error = false)
println(msg1)
println(msg2)
println(msg3)
println(msg1 == msg2)
println(msg1 == msg3)
var msg4 = CustomMessage("ciao 4")
println(msg4)
// println(CustomMessage("Ciao"))
// println(CustomMessage("Ciao", true))
// println(CustomMessage(message = "Ciao", error = true))
// println(CustomMessage(error = true, message = "Ciao"))
// println(CustomMessage("Ciao", true).copy(error = false))
}
| 0
|
Kotlin
|
0
| 0
|
8366bb3aed765fff7fb5203abce9a20177529a8e
| 615
|
PlayWithKotlin
|
Apache License 2.0
|
enslig-forsorger/src/main/kotlin/no/nav/familie/kontrakter/ef/søknad/Vedlegg.kt
|
navikt
| 206,793,193
| false
|
{"Kotlin": 269594}
|
package no.nav.familie.kontrakter.ef.søknad
data class Vedlegg(val id: String, val navn: String, val tittel: String)
| 3
|
Kotlin
|
0
| 2
|
0271887ca8cfff51135c4f65e543bb06bf7d7f54
| 118
|
familie-kontrakter
|
MIT License
|
src/main/kotlin/com/skillw/rpgmaker/RPGMakerInstance.kt
|
q210520993
| 802,703,847
| false
|
{"Kotlin": 210609, "Java": 73654}
|
package com.skillw.rpgmaker
import com.skillw.rpgmaker.core.map.KeyMap
import com.skillw.rpgmaker.core.manager.Manager
import com.skillw.rpgmaker.core.manager.ManagerData
import com.skillw.rpgmaker.util.safe
import net.luckperms.api.LuckPerms
import taboolib.common5.cbool
import taboolib.module.configuration.Configuration
object RPGMakerInstance {
@JvmStatic
lateinit var rpgMaker: RPGMaker
@JvmStatic
lateinit var luckPerms: LuckPerms
@JvmStatic
lateinit var serverConf: Configuration
@JvmStatic
lateinit var option: Configuration
val allManagers = KeyMap<String, ManagerData>()
internal fun Manager.reg() {
rpgMaker.managerData.register(this)
}
private val debug: Boolean
get() = serverConf.getBoolean("server.debug")
internal fun debug(runnable: Runnable) {
if (!debug) return
runnable.run()
}
internal fun reload() {
safe {
rpgMaker.managerData.reload()
}
}
}
| 0
|
Kotlin
|
0
| 4
|
17d24b9a7c5134a733636e0965f892850f445666
| 1,002
|
RPGMaker
|
MIT License
|
app/src/androidTest/kotlin/com/amsavarthan/tally/data/source/local/AccountDaoTest.kt
|
amsavarthan
| 592,784,968
| false
|
{"Kotlin": 232629, "HTML": 5928}
|
package com.amsavarthan.tally.data.source.local
import android.database.sqlite.SQLiteConstraintException
import com.amsavarthan.tally.domain.entity.Account
import com.amsavarthan.tally.domain.entity.AccountType
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
internal class AccountDaoTest {
@get:Rule
val hiltRule = HiltAndroidRule(this)
@Inject
lateinit var database: TallyDatabase
private lateinit var accountDao: AccountDao
@Before
fun setUp() {
hiltRule.inject()
accountDao = database.accountDao()
}
@Test
fun insertsAccountWithSameNameButDifferentType() = runTest {
val debitAccount = Account(
id = 0,
name = "test-account",
limit = 100.0,
type = AccountType.DebitCard
)
val creditAccount = Account(
id = 1,
name = "test-account",
limit = 100.0,
type = AccountType.CreditCard
)
//Inserting an account
accountDao.insertAccount(debitAccount)
accountDao.insertAccount(creditAccount)
//Checking if the list contains the account
val accounts = accountDao.getAccountEntities().first()
assertThat(accounts).containsExactly(debitAccount, creditAccount)
}
@Test
fun failsToInsertsAccountWithSameNameAndType() = runTest {
val debitAccount = Account(
id = 0,
name = "test-account",
limit = 100.0,
type = AccountType.DebitCard
)
val anotherDebitAccount = Account(
id = 1,
name = "test-account",
limit = 100.0,
type = AccountType.DebitCard
)
//Inserting an account
accountDao.insertAccount(debitAccount)
//Should fail
try {
accountDao.insertAccount(anotherDebitAccount)
} catch (e: SQLiteConstraintException) {
assertThat(e).isInstanceOf(SQLiteConstraintException::class.java)
}
}
@Test
fun getAccountsOrderedAlphabetically() = runTest {
//Dummy account list
val accountItems = listOf(
Account(
name = "b",
limit = 100.0,
type = AccountType.DebitCard
), Account(
name = "A",
limit = 100.0,
type = AccountType.DebitCard
)
)
//Inserting the account
accountItems.forEach { account ->
accountDao.insertAccount(account)
}
//Checking if the returned list is sorted by name (lowercase)
val accounts = accountDao.getAccountEntities().first()
assertThat(accounts[0].name).isLessThan(accounts[1].name)
}
@After
fun tearDown() {
database.close()
}
}
| 0
|
Kotlin
|
0
| 4
|
3d5209573aeb755f3ce3f899add6075a28224c9c
| 3,252
|
tally
|
MIT License
|
service/src/postgresComponentTest/kotlin/com/lsdconsulting/generatorui/ComponentTestBase.kt
|
lsd-consulting
| 418,193,928
| false
|
{"Kotlin": 46320, "HTML": 23164, "Shell": 1724}
|
package com.lsdconsulting.generatorui
import com.github.dockerjava.api.model.ExposedPort
import com.github.dockerjava.api.model.HostConfig
import com.github.dockerjava.api.model.PortBinding
import com.github.dockerjava.api.model.Ports
import com.lsdconsulting.generatorui.repository.TestRepository
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import io.lsdconsulting.lsd.distributed.connector.model.InteractionType
import io.lsdconsulting.lsd.distributed.connector.model.InterceptedInteraction
import io.lsdconsulting.lsd.distributed.postgres.config.LibraryConfig
import org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT
import org.springframework.context.annotation.Import
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.test.context.ActiveProfiles
import org.testcontainers.containers.PostgreSQLContainer
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.*
private const val POSTGRES_PORT = 5432
private const val POSTGRES_IMAGE = "postgres:15.3-alpine3.18"
private const val TABLE_NAME = "lsd_database"
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = [LsdGeneratorUiApplication::class])
@ActiveProfiles("test")
@Import(LibraryConfig::class)
class ComponentTestBase {
@Value("\${lsd.dist.connectionString}")
private lateinit var dbConnectionString: String
@Autowired
lateinit var testRepository: TestRepository
@BeforeEach
fun setupDb() {
val config = HikariConfig()
config.jdbcUrl = dbConnectionString
config.driverClassName = "org.postgresql.Driver"
testRepository.createTable(HikariDataSource(config))
testRepository.clearTable(HikariDataSource(config))
}
companion object {
private var postgreSQLContainer: PostgreSQLContainer<*> = PostgreSQLContainer(POSTGRES_IMAGE)
.withDatabaseName(TABLE_NAME)
.withUsername("sa")
.withPassword("sa")
.withExposedPorts(POSTGRES_PORT)
.withCreateContainerCmdModifier { cmd ->
cmd.withHostConfig(
HostConfig().withPortBindings(
PortBinding(
Ports.Binding.bindPort(POSTGRES_PORT), ExposedPort(
POSTGRES_PORT
)
)
)
)
}
@BeforeAll
@JvmStatic
internal fun beforeAll() {
postgreSQLContainer.start()
}
@AfterAll
@JvmStatic
internal fun afterAll() {
postgreSQLContainer.stop()
}
}
internal fun buildInterceptedInteraction() = InterceptedInteraction(
traceId = randomAlphanumeric(10),
body = randomAlphanumeric(100),
requestHeaders = mapOf(),
responseHeaders = mapOf(),
serviceName = randomAlphanumeric(30),
target = randomAlphanumeric(30),
path = randomAlphanumeric(100),
httpStatus = HttpStatus.entries[Random().nextInt(0, HttpStatus.entries.size - 1)].name,
httpMethod = HttpMethod.values()[Random().nextInt(0, HttpMethod.values().size - 1)].name(),
interactionType = InteractionType.entries[Random().nextInt(0, InteractionType.entries.size - 1)],
profile = randomAlphanumeric(20),
elapsedTime = Random().nextLong(),
createdAt = ZonedDateTime.now(ZoneId.of("UTC"))
)
}
| 3
|
Kotlin
|
0
| 1
|
2dc37beb7f238f1fd2b02dc7bd36f24b8140b3a8
| 3,907
|
lsd-distributed-generator-ui
|
MIT License
|
sudoemail/src/main/java/com/sudoplatform/sudoemail/util/Rfc822MessageParser.kt
|
sudoplatform
| 303,299,846
| false
|
{"Kotlin": 1052952}
|
/*
* Copyright © 2024 <NAME>, Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.sudoplatform.sudoemail.util
import android.os.Parcelable
import com.sudoplatform.sudoemail.types.EmailAttachment
import com.sudoplatform.sudoemail.types.EncryptionStatus
import jakarta.activation.DataHandler
import jakarta.mail.Message
import jakarta.mail.MessagingException
import jakarta.mail.Part
import jakarta.mail.Session
import jakarta.mail.internet.InternetAddress
import jakarta.mail.internet.MimeBodyPart
import jakarta.mail.internet.MimeMessage
import jakarta.mail.internet.MimeMultipart
import jakarta.mail.util.ByteArrayDataSource
import kotlinx.parcelize.Parcelize
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.Properties
@Parcelize
data class SimplifiedEmailMessage(
val from: List<String>,
val to: List<String>,
val cc: List<String>,
val bcc: List<String>,
val subject: String?,
val body: String?,
) : Parcelable
private const val EMAIL_HEADER_NAME_ENCRYPTION = "X-Sudoplatform-Encryption"
private const val PLATFORM_ENCRYPTION = "sudoplatform"
private const val CANNED_TEXT_BODY = "Encrypted message attached"
/**
* A class which handles the encoding and parsing of the RFC 822 compatible email message content.
*/
object Rfc822MessageParser {
private val session = Session.getInstance(Properties())
@Throws(MessagingException::class, IOException::class)
fun encodeToRfc822Data(
from: String,
to: List<String>,
cc: List<String>? = null,
bcc: List<String>? = null,
subject: String? = null,
body: String? = null,
attachments: List<EmailAttachment>? = null,
inlineAttachments: List<EmailAttachment>? = null,
encryptionStatus: EncryptionStatus = EncryptionStatus.UNENCRYPTED,
): ByteArray {
val message = MimeMessage(session)
message.setFrom(InternetAddress(from))
to.map { if (it.isNotBlank()) message.addRecipient(Message.RecipientType.TO, InternetAddress(it)) }
cc?.map { if (it.isNotBlank()) message.addRecipient(Message.RecipientType.CC, InternetAddress(it)) }
bcc?.map { if (it.isNotBlank()) message.addRecipient(Message.RecipientType.BCC, InternetAddress(it)) }
message.subject = subject
// Check if encrypted then add a custom header
if (encryptionStatus == EncryptionStatus.ENCRYPTED) {
message.setHeader(EMAIL_HEADER_NAME_ENCRYPTION, PLATFORM_ENCRYPTION)
}
val topMultiPart = MimeMultipart() // The top level-multipart of the email
val messageBodyPart = MimeBodyPart() // The body-part which holds the message body text
// The related multi-part contains the message body and any inline attachments
val relatedWrapper = MimeBodyPart()
val relatedMultipart = MimeMultipart("related")
relatedWrapper.setContent(relatedMultipart)
val bodyText = body ?: ""
when (encryptionStatus) {
EncryptionStatus.ENCRYPTED -> {
messageBodyPart.setText(CANNED_TEXT_BODY, "UTF-8")
topMultiPart.addBodyPart(messageBodyPart)
}
else -> {
messageBodyPart.setText(bodyText, "UTF-8")
messageBodyPart.setHeader("Content-Transfer-Encoding", "QUOTED-PRINTABLE")
messageBodyPart.setHeader("Content-Disposition", "inline")
messageBodyPart.setHeader("Content-Type", "text/plain")
relatedMultipart.addBodyPart(messageBodyPart)
topMultiPart.addBodyPart(relatedWrapper)
}
}
attachments?.forEach { attachment ->
val attachmentBodyPart = MimeBodyPart()
attachmentBodyPart.disposition = Part.ATTACHMENT
attachmentBodyPart.fileName = attachment.fileName
attachmentBodyPart.dataHandler = DataHandler(ByteArrayDataSource(attachment.data, attachment.mimeType))
attachmentBodyPart.contentID = "<${attachment.contentId}>"
// Add normal attachments to the top level multi-part
topMultiPart.addBodyPart(attachmentBodyPart)
}
inlineAttachments?.forEach { inlineAttachment ->
val attachmentBodyPart = MimeBodyPart()
attachmentBodyPart.disposition = Part.INLINE
attachmentBodyPart.fileName = inlineAttachment.fileName
attachmentBodyPart.dataHandler = DataHandler(ByteArrayDataSource(inlineAttachment.data, inlineAttachment.mimeType))
attachmentBodyPart.contentID = "<${inlineAttachment.contentId}>"
// Add inline attachments to the "related" multipart
relatedMultipart.addBodyPart(attachmentBodyPart)
}
message.setContent(topMultiPart)
val byteOutputStream = ByteArrayOutputStream()
message.writeTo(byteOutputStream)
return byteOutputStream.toByteArray()
}
/**
* Parse and RFC 822 compatible email message.
*/
@Throws(MessagingException::class, IOException::class)
fun parseRfc822Data(rfc822Data: ByteArray): SimplifiedEmailMessage {
val rfc822Input = ByteArrayInputStream(rfc822Data)
val javaMailMessage = LocalMimeMessage(session, rfc822Input)
return toSimplifiedEmailMessage(javaMailMessage)
}
private class LocalMimeMessage(
session: Session,
rfc822Input: InputStream,
) : MimeMessage(session, rfc822Input) {
override fun toString(): String {
val from = from?.map { it.toString() } ?: emptyList()
val to = getRecipients(Message.RecipientType.TO)?.map { it.toString() } ?: emptyList()
val cc = getRecipients(Message.RecipientType.CC)?.map { it.toString() } ?: emptyList()
val bcc = getRecipients(Message.RecipientType.BCC)?.map { it.toString() } ?: emptyList()
return buildString {
if (dataHandler.dataSource.contentType.contains("text/plain")) {
appendLine(dataHandler.content)
} else {
appendLine("MimeMessage [")
appendLine(" From: $from")
appendLine(" To: $to")
appendLine(" Cc: $cc")
appendLine(" Bcc: $bcc")
appendLine(" Subject: $subject")
appendLine(" Received: $receivedDate")
appendLine(" ContentType: $contentType")
appendLine(" Description: $description")
appendLine(" Encoding: $encoding")
appendLine(" Size: $size")
val multipart = MimeMultipart(dataHandler.dataSource)
appendLine(" Preamble: ${multipart.preamble}")
for (i in 0 until multipart.count) {
val bodyPart = multipart.getBodyPart(i)
appendLine(" Body Part $i [")
appendLine(" ContentType: ${bodyPart.contentType}")
appendLine(" Description: ${bodyPart.description}")
appendLine(" Size: ${bodyPart.size}")
if (bodyPart.contentType.contains("text/plain")) {
appendLine(" Content: ${bodyPart.content}")
}
appendLine(" ]")
}
appendLine("]")
}
}
}
}
@Throws(MessagingException::class, IOException::class)
private fun toSimplifiedEmailMessage(message: Message): SimplifiedEmailMessage {
val from = message.from?.map { it.toString() } ?: emptyList()
val to = message.getRecipients(Message.RecipientType.TO)?.map { it.toString() } ?: emptyList()
val cc = message.getRecipients(Message.RecipientType.CC)?.map { it.toString() } ?: emptyList()
val bcc = message.getRecipients(Message.RecipientType.BCC)?.map { it.toString() } ?: emptyList()
val body: String
if (message.isMimeType("text/plain")) {
body = buildString { append(message) }
} else {
val multipart = MimeMultipart(message.dataHandler.dataSource)
body = buildString {
for (i in 0 until multipart.count) {
val bodyPart = multipart.getBodyPart(i)
if (bodyPart.isMimeType("text/plain")) {
append(bodyPart.content)
} else if (bodyPart.isMimeType("multipart/*")) {
val mimeMultipart = bodyPart.content as MimeMultipart
for (j in 0 until mimeMultipart.count) {
val mimeBodyPart = mimeMultipart.getBodyPart(j)
if (mimeBodyPart.isMimeType("text/plain")) {
append(mimeBodyPart.content)
}
}
}
}
}
}
return SimplifiedEmailMessage(
from,
to,
cc,
bcc,
message.subject,
body,
)
}
}
| 0
|
Kotlin
|
0
| 1
|
039e7fd806ad34d5a6b2c563cee2dd4dea69ebcf
| 9,324
|
sudo-email-android
|
Apache License 2.0
|
api/src/main/kotlin/com/wnsgml972/strada/security/OAuth2SecuritySpec.kt
|
Coffee-Street
| 289,485,814
| false
|
{"Kotlin": 267923, "Shell": 2546, "Dockerfile": 174}
|
package com.wnsgml972.strada.security
import org.springframework.security.config.annotation.web.builders.HttpSecurity
class OAuth2SecuritySpec {
fun configure(http: HttpSecurity) {
http.csrf().disable()
.formLogin().disable()
.logout().disable()
.httpBasic().disable()
.exceptionHandling()
}
}
| 2
|
Kotlin
|
2
| 2
|
24422867afe6c7f547a93f98083f655ecb80c0ed
| 360
|
strada
|
MIT License
|
sample/src/main/java/com/storage/sample/activity/SettingsActivity.kt
|
durgav62
| 397,616,572
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Proguard": 1, "Kotlin": 53, "XML": 19, "Java": 2}
|
package com.storage.sample.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.storage.sample.fragment.SettingsFragment
/**
* Created on 08/08/21
* @author <NAME>
*/
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, SettingsFragment())
.commit()
}
}
| 1
| null |
1
| 1
|
1c91d5b36585fcfe989ad87ee930898462881c13
| 502
|
scoped-storage
|
Apache License 2.0
|
app/src/main/java/com/example/tambolaGame/presentation/fragments/ParticipantsWalletFragment.kt
|
pranmar93
| 266,756,980
| false
| null |
package com.example.tambolaGame.presentation.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.tambolaGame.MainActivity
import com.example.tambolaGame.MainActivity.Companion.myDevice
import com.example.tambolaGame.MainActivity.Companion.tambolaMembers
import com.example.tambolaGame.R
import com.example.tambolaGame.models.UserDevice
import com.example.tambolaGame.presentation.adapters.ParticipantsWalletAdapter
import kotlinx.android.synthetic.main.fragment_participants_wallet.view.*
class ParticipantsWalletFragment: Fragment() {
private lateinit var root: View
private lateinit var type: String
private lateinit var participantsWalletAdapter: ParticipantsWalletAdapter
private lateinit var adapterList: List<UserDevice>
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
root = inflater.inflate(R.layout.fragment_participants_wallet, container, false)
refreshView(arguments!!.getString("TYPE")!!)
arguments!!.remove("TYPE")
return root
}
fun refreshView(Type: String) {
type = Type
adapterList = if (type == "Wallet") {
(activity as MainActivity).supportActionBar!!.title = "Money Holder - " + myDevice.userId.toString()
tambolaMembers.filter { user -> user.walletMoney > 0 }
} else {
(activity as MainActivity).supportActionBar!!.title = "Joined Members - " + myDevice.userId.toString()
tambolaMembers
}
participantsWalletAdapter = ParticipantsWalletAdapter(context!!, type, adapterList)
root.members_rv.adapter = participantsWalletAdapter
}
fun getType(): String {
return type
}
}
| 0
|
Kotlin
|
0
| 1
|
ee93c61b85b896a3745fc2acd9d9e058eaef4224
| 1,897
|
TambolaGame
|
MIT License
|
core/src/commonMain/kotlin/com/littlekt/math/geom/Angle.kt
|
littlektframework
| 442,309,478
| false
|
{"Kotlin": 2170511, "Java": 1717152, "C": 111391}
|
@file:Suppress("NOTHING_TO_INLINE", "EXTENSION_SHADOWED_BY_MEMBER")
package com.lehaine.littlekt.math.geom
import com.lehaine.littlekt.math.*
import com.lehaine.littlekt.util.internal.umod
import kotlin.jvm.JvmInline
import kotlin.math.absoluteValue
import kotlin.math.atan2
@PublishedApi
internal const val MAX_DEGREES = 360f
@PublishedApi
internal const val MAX_RADIANS = PI2_F
@PublishedApi
internal const val HALF_DEGREES = MAX_DEGREES / 2f
@PublishedApi
internal const val HALF_RADIANS = MAX_RADIANS / 2f
@PublishedApi
internal fun Angle_shortDistanceTo(from: Angle, to: Angle): Angle {
val r0 = from.radians umod MAX_RADIANS
val r1 = to.radians umod MAX_RADIANS
val diff = (r1 - r0 + HALF_RADIANS) % MAX_RADIANS - HALF_RADIANS
return if (diff < -HALF_RADIANS) Angle(diff + MAX_RADIANS) else Angle(diff)
}
@PublishedApi
internal fun Angle_longDistanceTo(from: Angle, to: Angle): Angle {
val short = Angle_shortDistanceTo(from, to)
return when {
short == Angle.ZERO -> Angle.ZERO
short < Angle.ZERO -> 360.degrees + short
else -> (-360).degrees + short
}
}
@PublishedApi
internal fun Angle_between(x0: Float, y0: Float, x1: Float, y1: Float): Angle {
val angle = atan2(y1 - y0, x1 - x0)
return if (angle < 0) Angle(angle + PI2_F) else Angle(angle)
}
// https://github.com/korlibs/korge-next/blob/master/korma/src/commonMain/kotlin/com/soywiz/korma/geom/Angle.kt
@JvmInline
value class Angle(val radians: Float) : Comparable<Angle> {
override fun toString(): String = "$degrees.degrees"
operator fun times(scale: Float): Angle = Angle(this.radians * scale)
operator fun div(scale: Float): Angle = Angle(this.radians / scale)
operator fun times(scale: Double): Angle = this * scale.toFloat()
operator fun div(scale: Double): Angle = this / scale.toFloat()
operator fun times(scale: Int): Angle = this * scale.toFloat()
operator fun div(scale: Int): Angle = this / scale.toFloat()
operator fun div(other: Angle): Float = this.radians / other.radians // Ratio
operator fun plus(other: Angle): Angle = Angle(this.radians + other.radians)
operator fun minus(other: Angle): Angle = Angle(this.radians - other.radians)
operator fun unaryMinus(): Angle = Angle(-radians)
operator fun unaryPlus(): Angle = Angle(+radians)
@Suppress("MemberVisibilityCanBePrivate")
companion object {
inline val ZERO get() = Angle(0f)
inline fun fromRadians(radians: Float) = Angle(radians)
inline fun fromDegrees(degrees: Float) = Angle(degreesToRadians(degrees))
inline fun fromRadians(radians: Double) = fromRadians(radians.toFloat())
inline fun fromDegrees(degrees: Double) = fromDegrees(degrees.toFloat())
inline fun fromRadians(radians: Int) = fromRadians(radians.toDouble())
inline fun fromDegrees(degrees: Int) = fromDegrees(degrees.toDouble())
inline fun cos01(ratio: Double) = kotlin.math.cos(PI2 * ratio)
inline fun sin01(ratio: Double) = kotlin.math.sin(PI2 * ratio)
inline fun tan01(ratio: Double) = kotlin.math.tan(PI2 * ratio)
inline fun degreesToRadians(degrees: Float): Float = (degrees.toRad())
inline fun radiansToDegrees(radians: Float): Float = (radians.toDeg())
inline fun shortDistanceTo(from: Angle, to: Angle): Angle = Angle_shortDistanceTo(from, to)
inline fun longDistanceTo(from: Angle, to: Angle): Angle = Angle_longDistanceTo(from, to)
inline fun between(x0: Float, y0: Float, x1: Float, y1: Float): Angle = Angle_between(x0, y0, x1, y1)
inline fun between(x0: Int, y0: Int, x1: Int, y1: Int): Angle =
between(x0.toDouble(), y0.toDouble(), x1.toDouble(), y1.toDouble())
inline fun between(x0: Double, y0: Double, x1: Double, y1: Double): Angle =
between(x0.toFloat(), y0.toFloat(), x1.toFloat(), y1.toFloat())
}
override fun compareTo(other: Angle): Int {
val left = this.radians
val right = other.radians
if (left < right) return -1
if (left > right) return +1
return 0
}
}
inline fun cos(angle: Angle): Float = kotlin.math.cos(angle.radians)
inline fun sin(angle: Angle): Float = kotlin.math.sin(angle.radians)
inline fun tan(angle: Angle): Float = kotlin.math.tan(angle.radians)
inline fun abs(angle: Angle): Angle = Angle.fromRadians(angle.radians.absoluteValue)
val Angle.cosine get() = cos(this)
val Angle.sine get() = sin(this)
val Angle.tangent get() = tan(this)
val Angle.degrees get() = Angle.radiansToDegrees(radians)
val Angle.absoluteValue: Angle get() = Angle.fromRadians(radians.absoluteValue)
fun Angle.shortDistanceTo(other: Angle): Angle = Angle.shortDistanceTo(this, other)
fun Angle.longDistanceTo(other: Angle): Angle = Angle.longDistanceTo(this, other)
infix fun Angle.until(other: Angle) = OpenRange(this, other)
fun Angle.inBetweenInclusive(min: Angle, max: Angle): Boolean = inBetween(min, max, inclusive = true)
fun Angle.inBetweenExclusive(min: Angle, max: Angle): Boolean = inBetween(min, max, inclusive = false)
infix fun Angle.inBetween(range: ClosedRange<Angle>): Boolean =
inBetween(range.start, range.endInclusive, inclusive = true)
infix fun Angle.inBetween(range: OpenRange<Angle>): Boolean =
inBetween(range.start, range.endExclusive, inclusive = false)
fun Angle.inBetween(min: Angle, max: Angle, inclusive: Boolean): Boolean {
val nthis = this.normalized
val nmin = min.normalized
val nmax = max.normalized
@Suppress("ConvertTwoComparisonsToRangeCheck")
return when {
nmin > nmax -> nthis >= nmin || (if (inclusive) nthis <= nmax else nthis < nmax)
else -> nthis >= nmin && (if (inclusive) nthis <= nmax else nthis < nmax)
}
}
operator fun Float.times(angle: Angle): Angle = Angle(this * angle.radians)
operator fun Float.div(angle: Angle): Angle = Angle(this / angle.radians)
operator fun Double.times(angle: Angle): Angle = this.toFloat() * angle
operator fun Double.div(angle: Angle): Angle = this.toFloat() / angle
operator fun Int.times(angle: Angle): Angle = this.toFloat() * angle
operator fun Int.div(angle: Angle): Angle = this.toFloat() / angle
val Double.degrees get() = Angle.fromDegrees(this)
val Double.radians get() = Angle.fromRadians(this)
val Int.degrees get() = Angle.fromDegrees(this)
val Int.radians get() = Angle.fromRadians(this)
val Float.degrees get() = Angle.fromDegrees(this)
val Float.radians get() = Angle.fromRadians(this)
val Angle.normalized get() = Angle(radians umod MAX_RADIANS)
fun Double.interpolate(l: Angle, r: Angle): Angle = this.interpolate(l.radians, r.radians).radians
| 14
|
Kotlin
|
9
| 316
|
100c37feefcfd65038a9cba4886aeb4a7d5632dc
| 6,667
|
littlekt
|
Apache License 2.0
|
app/src/main/java/com/breezehungrybee/features/nearbyshops/api/updateaddress/ShopAddressUpdateRepo.kt
|
DebashisINT
| 863,346,668
| false
|
{"Kotlin": 15849418, "Java": 1029592}
|
package com.breezehungrybee.features.nearbyshops.api.updateaddress
import com.breezehungrybee.base.BaseResponse
import com.breezehungrybee.features.nearbyshops.model.updateaddress.AddressUpdateRequest
import io.reactivex.Observable
/**
* Created by Pratishruti on 05-02-2018.
*/
class ShopAddressUpdateRepo (val apiService: ShopAddressUpdateApi) {
fun getShopAddressUpdate(shopAddressUpdate:AddressUpdateRequest): Observable<BaseResponse> {
return apiService.getShopAddressUpdate(shopAddressUpdate)
}
}
| 0
|
Kotlin
|
0
| 0
|
c76e59331c57a9188c840b52c72dec40164db090
| 522
|
HungryBee
|
Apache License 2.0
|
base/src/main/java/com/theone/mvvm/base/IViewBinding.kt
|
Theoneee
| 473,409,123
| false
|
{"Kotlin": 616409, "Java": 410498}
|
package com.theone.mvvm.base
import android.util.SparseArray
import androidx.annotation.NonNull
import androidx.viewbinding.ViewBinding
import com.theone.mvvm.BR
import com.theone.mvvm.ext.getClazz
// ┏┓ ┏┓
//┏┛┻━━━┛┻┓
//┃ ┃
//┃ ━ ┃
//┃ ┳┛ ┗┳ ┃
//┃ ┃
//┃ ┻ ┃
//┃ ┃
//┗━┓ ┏━┛
// ┃ ┃ 神兽保佑
// ┃ ┃ 永无BUG!
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛
/**
* @author The one
* @date 2021-03-31 15:04
* @describe DataBinding基类相关
* @email <EMAIL>
* @remark
*/
interface IViewBinding<VB:ViewBinding> {
/**
* 获取ViewBinding,供子类调用
* @return DB
*/
fun getViewBinding():VB
/**
* ViewBinding在泛型中的位置
* @return Int
* @remark 如果子类中没有了VB泛型,则需要重写[getViewBindingClass]直接指定Class
* 例:很多界面都用的是一个DB,那么可以指定这个VB进行封装,子类重写后是没有VB的
*/
fun getViewBindingIndex():Int = 0
/**
* DataBinding的class
* @return Class<*>
*/
fun getViewBindingClass():Class<VB> = getClazz()
}
| 0
|
Kotlin
|
4
| 6
|
66e7dd671635352c8039bc3bf47a715620347448
| 1,062
|
QMUI-MVVM
|
Apache License 2.0
|
idea/testData/resolve/partialBodyResolve/IfNotIsReturn.kt
|
JakeWharton
| 99,388,807
| false
| null |
fun foo(p: Any?) {
if (p !is String) {
if (p == null) {
print("null")
return
}
else {
return
}
}
println(<caret>p.length())
}
| 0
| null |
30
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 205
|
kotlin
|
Apache License 2.0
|
backend/src/main/kotlin/org/gridiron/backend/persistence/Users.kt
|
domnikl
| 282,521,529
| false
| null |
package org.gridiron.backend.persistence
import org.jetbrains.exposed.sql.Table
object Users : Table(name = "users") {
val uuid = uuid("uuid")
val email = varchar("email", 180).uniqueIndex()
val username = varchar("login", 70).uniqueIndex()
val password = varchar("password", 100)
val roles = varchar("roles", 255).default("")
val score = integer("score").default(0)
override val primaryKey = PrimaryKey(uuid)
}
| 15
|
Kotlin
|
0
| 2
|
baae7a92fe6610139e2473276ad1ac599f041165
| 443
|
gridiron
|
Apache License 2.0
|
exact-numbers/src/test/kotlin/xyz/lbres/exactnumbers/exactfraction/binaryMinusTests.kt
|
lbressler13
| 491,698,766
| false
| null |
package xyz.lbres.exactnumbers.exactfraction
import kotlin.test.assertEquals
internal fun runMinusTests() {
// zero
var first = ExactFraction(0)
var second = ExactFraction(0)
var expected = ExactFraction(0, 1)
assertEquals(expected, first - second)
first = ExactFraction(4)
second = ExactFraction(0)
expected = ExactFraction(4, 1)
assertEquals(expected, first - second)
first = ExactFraction(-4)
second = ExactFraction(0)
expected = ExactFraction(-4, 1)
assertEquals(expected, first - second)
first = ExactFraction(0)
second = ExactFraction(4)
expected = ExactFraction(-4, 1)
assertEquals(expected, first - second)
first = ExactFraction(0)
second = ExactFraction(-4)
expected = ExactFraction(4, 1)
assertEquals(expected, first - second)
// whole numbers
first = ExactFraction(4)
second = ExactFraction(1)
expected = ExactFraction(3, 1)
assertEquals(expected, first - second)
first = ExactFraction(-12)
second = ExactFraction(33)
expected = ExactFraction(-45, 1)
assertEquals(expected, first - second)
first = ExactFraction(12)
second = ExactFraction(-33)
expected = ExactFraction(45, 1)
assertEquals(expected, first - second)
first = ExactFraction(-12)
second = ExactFraction(-6)
expected = ExactFraction(-6, 1)
assertEquals(expected, first - second)
// same denominator
first = ExactFraction(5, 3)
second = ExactFraction(-6, 3)
expected = ExactFraction(11, 3)
assertEquals(expected, first - second)
first = ExactFraction(-5, 3)
second = ExactFraction(2, 3)
expected = ExactFraction(-7, 3)
assertEquals(expected, first - second)
first = ExactFraction(5, 19)
second = ExactFraction(11, 19)
expected = ExactFraction(-6, 19)
assertEquals(expected, first - second)
first = ExactFraction(-24, 19)
second = ExactFraction(-32, 19)
expected = ExactFraction(8, 19)
assertEquals(expected, first - second)
// different denominator
first = ExactFraction(5, 1)
second = ExactFraction(-4, 3)
expected = ExactFraction(19, 3)
assertEquals(expected, first - second)
first = ExactFraction(5, 2)
second = ExactFraction(7, 3)
expected = ExactFraction(1, 6)
assertEquals(expected, first - second)
first = ExactFraction(-5, 12)
second = ExactFraction(3, 11)
expected = ExactFraction(-91, 132)
assertEquals(expected, first - second)
first = ExactFraction(-4, 8)
second = ExactFraction(-1, 3)
expected = ExactFraction(-4, 24)
assertEquals(expected, first - second)
// BigInteger
var ef = ExactFraction(0, 1) - 3.toBigInteger()
expected = ExactFraction(-3)
assertEquals(ef, expected)
ef = ExactFraction(-6) - 20.toBigInteger()
expected = ExactFraction(-26)
assertEquals(ef, expected)
ef = ExactFraction(3) - 5.toBigInteger()
expected = ExactFraction(-2L)
assertEquals(ef, expected)
ef = ExactFraction(3, 7) - 4.toBigInteger()
expected = ExactFraction(-25, 7)
assertEquals(ef, expected)
// Int
ef = ExactFraction(0, 1) - 3
expected = ExactFraction(-3)
assertEquals(ef, expected)
ef = ExactFraction(-6) - 20
expected = ExactFraction(-26)
assertEquals(ef, expected)
ef = ExactFraction(3) - 5
expected = ExactFraction(-2L)
assertEquals(ef, expected)
ef = ExactFraction(3, 7) - 4
expected = ExactFraction(-25, 7)
assertEquals(ef, expected)
// Long
ef = ExactFraction(0, 1) - 3L
expected = ExactFraction(-3)
assertEquals(ef, expected)
ef = ExactFraction(-6) - 20L
expected = ExactFraction(-26)
assertEquals(ef, expected)
ef = ExactFraction(3) - 5L
expected = ExactFraction(-2L)
assertEquals(ef, expected)
ef = ExactFraction(3, 7) - 4L
expected = ExactFraction(-25, 7)
assertEquals(ef, expected)
}
| 0
|
Kotlin
|
0
| 2
|
b839a77a73599b2e156b80ef81defbcd2e4e8a89
| 3,940
|
exact-numbers
|
MIT License
|
compose-ui/src/commonMain/kotlin/ru/blays/ficbookReader/ui_components/CustomToolbar/CustomToolbarScrollBehavior.kt
|
B1ays
| 710,470,973
| false
| null |
package com.istu.schedule.ui.components.toolbar
import androidx.compose.animation.core.AnimationState
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDecay
import androidx.compose.animation.core.animateTo
import androidx.compose.animation.core.spring
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.runtime.Composable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.unit.Velocity
import kotlin.math.abs
class CustomToolbarScrollBehavior(
val state: CustomToolbarScrollState,
val flingAnimationSpec: DecayAnimationSpec<Float>?
) {
val nestedScrollConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// Don't intercept if scrolling down.
if (available.y > 0f) return Offset.Zero
val prevHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + available.y
return if (prevHeightOffset != state.heightOffset) {
// We're in the middle of top app bar collapse or expand.
// Consume only the scroll on the Y axis.
available.copy(x = 0f)
} else {
Offset.Zero
}
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
state.contentOffset += consumed.y
if (available.y < 0f || consumed.y < 0f) {
// When scrolling up, just update the state's height offset.
val oldHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + consumed.y
return Offset(0f, state.heightOffset - oldHeightOffset)
}
if (consumed.y == 0f && available.y > 0) {
// Reset the total content offset to zero when scrolling all the way down. This
// will eliminate some float precision inaccuracies.
state.contentOffset = 0f
}
if (available.y > 0f) {
// Adjust the height offset in case the consumed delta Y is less than what was
// recorded as available delta Y in the pre-scroll.
val oldHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + available.y
return Offset(0f, state.heightOffset - oldHeightOffset)
}
return Offset.Zero
}
override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
var result = super.onPostFling(consumed, available)
// Check if the app bar is partially collapsed/expanded.
// Note that we don't check for 0f due to float precision with the collapsedFraction
// calculation.
if (state.collapsedFraction > 0.01f && state.collapsedFraction < 1f) {
result += flingToolbar(
state = state,
initialVelocity = available.y,
flingAnimationSpec = flingAnimationSpec
)
snapToolbar(state)
}
return result
}
}
}
private suspend fun flingToolbar(
state: CustomToolbarScrollState,
initialVelocity: Float,
flingAnimationSpec: DecayAnimationSpec<Float>?
): Velocity {
var remainingVelocity = initialVelocity
// In case there is an initial velocity that was left after a previous user fling, animate to
// continue the motion to expand or collapse the app bar.
if (flingAnimationSpec != null && abs(initialVelocity) > 1f) {
var lastValue = 0f
AnimationState(
initialValue = 0f,
initialVelocity = initialVelocity
)
.animateDecay(flingAnimationSpec) {
val delta = value - lastValue
val initialHeightOffset = state.heightOffset
state.heightOffset = initialHeightOffset + delta
val consumed = abs(initialHeightOffset - state.heightOffset)
lastValue = value
remainingVelocity = this.velocity
// avoid rounding errors and stop if anything is unconsumed
if (abs(delta - consumed) > 0.5f) {
cancelAnimation()
}
}
}
return Velocity(0f, remainingVelocity)
}
private suspend fun snapToolbar(state: CustomToolbarScrollState) {
// In case the app bar motion was stopped in a state where it's partially visible, snap it to
// the nearest state.
if (state.heightOffset < 0 &&
state.heightOffset > state.heightOffsetLimit
) {
AnimationState(
initialValue = state.heightOffset
).animateTo(
targetValue = if (state.collapsedFraction < 0.5f) 0f else state.heightOffsetLimit,
animationSpec = spring(stiffness = Spring.StiffnessMediumLow)
) {
state.heightOffset = value
}
}
}
@Composable
fun rememberToolbarScrollBehavior() = CustomToolbarScrollBehavior(
state = rememberToolbarScrollState(
initialHeightOffsetLimit = -Float.MAX_VALUE
),
flingAnimationSpec = rememberSplineBasedDecay()
)
| 1
| null |
1
| 9
|
478a79286c952c7d1e001b4a0d9075e3fccd4f18
| 5,588
|
ficbook-reader
|
MIT License
|
sesame-localized-string/src/main/kotlin/me/aartikov/sesame/localizedstring/TextViewExt.kt
|
aartikov
| 292,022,280
| false
| null |
package me.aartikov.sesame.localizedstring
import android.widget.TextView
/**
* Sets [LocalizedString] value to [TextView].
*/
var TextView.localizedText: LocalizedString?
get() = LocalizedString.raw(text)
set(value) {
text = value?.resolve(context)
}
| 0
|
Kotlin
|
6
| 98
|
46cca40d702d3a58f00e944836e22af042b048b9
| 276
|
Sesame
|
MIT License
|
src/main/kotlin/xyz/magentaize/dynamicdata/list/internal/Switch.kt
|
Magentaize
| 290,133,754
| false
| null |
package xyz.magentaize.dynamicdata.list.internal
import xyz.magentaize.dynamicdata.kernel.subscribeBy
import xyz.magentaize.dynamicdata.list.ChangeSet
import xyz.magentaize.dynamicdata.list.SourceList
import xyz.magentaize.dynamicdata.list.clear
import xyz.magentaize.dynamicdata.list.populateInto
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.internal.functions.Functions
import xyz.magentaize.dynamicdata.kernel.ObservableEx
internal class Switch<T>(
private var _source: Observable<Observable<ChangeSet<T>>>
) {
fun run(): Observable<ChangeSet<T>> =
ObservableEx.create { emitter ->
val dest = SourceList<T>()
val populator = _source
.doOnEach { dest.clear() }
.switchMap(Functions.identity())
.populateInto(dest)
val publisher = dest.connect().subscribeBy(emitter)
return@create CompositeDisposable(dest, populator, publisher)
}
}
| 0
|
Kotlin
|
0
| 3
|
dda522f335a6ab3847cc90ff56e8429c15834800
| 1,046
|
dynamicdata-kotlin
|
MIT License
|
src/ad/kata/aoc2021/day05/Point.kt
|
andrej-dyck
| 433,401,789
| false
|
{"Kotlin": 161613}
|
package ad.kata.aoc2021.day05
import ad.kata.aoc2021.extensions.splitTrim
data class Point(val x: Int, val y: Int)
data class Vector(val x: Int, val y: Int)
internal operator fun Point.plus(vector: Vector) =
copy(x = x + vector.x, y = y + vector.y)
internal fun String.toPoint() =
removeSurrounding("(", ")")
.splitTrim(',')
.let { (x, y) -> Point(x.toInt(), y.toInt()) }
| 0
|
Kotlin
|
0
| 0
|
28d374fee4178e5944cb51114c1804d0c55d1052
| 400
|
advent-of-code-2021
|
MIT License
|
mobile/src/main/java/com/damn/anotherglass/extensions/notifications/Converter.kt
|
inckie
| 291,422,816
| false
|
{"Git Config": 1, "Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "XML": 46, "Java": 38, "Kotlin": 24, "YAML": 1, "INI": 1}
|
package com.damn.anotherglass.extensions.notifications
import android.app.Notification
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.service.notification.StatusBarNotification
import com.applicaster.xray.core.Logger
import com.damn.anotherglass.logging.ALog
import com.damn.anotherglass.shared.notifications.NotificationData
import java.io.ByteArrayOutputStream
import java.io.IOException
object Converter {
private const val TAG = "IconConverter"
private val log = ALog(Logger.get(TAG))
fun convert(
context: Context,
acton: NotificationData.Action,
sbn: StatusBarNotification
): NotificationData {
val data = NotificationData()
data.action = acton
// parse basic data
data.id = sbn.id
data.packageName = sbn.packageName
data.postedTime = sbn.postTime
data.isOngoing = sbn.isOngoing
// todo: code below this point is not really needed for NotificationData.Action.Removed
// todo: extract app name
// parse Notification data
val notification = sbn.notification
data.title = notification.extras.getString(Notification.EXTRA_TITLE)
data.text = notification.extras.getString(Notification.EXTRA_TEXT)
// todo: https://stackoverflow.com/questions/29363770/how-to-get-text-of-stacked-notifications-in-android/29364414
if (null != notification.tickerText) {
data.tickerText = notification.tickerText.toString()
}
try {
extractIcon(context, data, notification)
} catch (e: Exception) {
// todo: new Android version do not allow that, add required permission
log.e(TAG, "Failed to extract icon from notification: " + e.message, e)
}
return data
}
private fun extractIcon(
context: Context,
data: NotificationData,
notification: Notification
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
var icon = notification.getLargeIcon()
if (null == icon) icon = notification.smallIcon
if (null != icon) {
val drawable = icon.loadDrawable(context)
if (null != drawable) {
val bitmap = drawableToBitmap(drawable)
setIconData(data, bitmap)
}
}
}
if (null != data.icon) return
if (null != notification.largeIcon) setIconData(data, notification.largeIcon)
if (null != data.icon) return
// todo: retrieve default icon from the package
}
private fun setIconData(data: NotificationData, bitmap: Bitmap) {
try {
ByteArrayOutputStream().use { memoryStream ->
bitmap.compress(Bitmap.CompressFormat.PNG, 0, memoryStream)
data.icon = memoryStream.toByteArray()
}
} catch (e: IOException) {
log.e(TAG, "Failed to compress icon bitmap: " + e.message, e)
}
}
fun drawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
if (null != drawable.bitmap) {
return drawable.bitmap
}
}
val bitmap: Bitmap = if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
// Single color bitmap will be created of 1x1 pixel
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
} else {
Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
}
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
}
| 0
|
Java
|
0
| 12
|
0732a42e1ffe0e7e0ae86eaf68829b8c2adca7cd
| 3,977
|
AnotherGlass
|
MIT License
|
transport-eta-android/sms/src/prod/java/com/joaquimley/transporteta/sms/SmsBroadcastReceiverImpl.kt
|
JoaquimLey
| 93,657,822
| false
| null |
package com.joaquimley.transporteta.sms
import android.content.Context
import android.content.Intent
import android.provider.Telephony
import javax.inject.Inject
/**
* A broadcast receiver who listens for incoming SMS
*/
class SmsBroadcastReceiverImpl @Inject constructor(serviceNumber: String, serviceSmsCondition: String)
: SmsBroadcastReceiver(serviceNumber, serviceSmsCondition) {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {
var smsBody = ""
var smsSender = ""
for (smsMessage in Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.displayOriginatingAddress
smsBody += smsMessage.messageBody
}
if (smsSender == serviceNumber && smsBody.startsWith(serviceSmsCondition)) {
broadcastServiceSms.onNext(smsBody)
}
}
}
}
| 34
|
Kotlin
|
45
| 224
|
7c841a3b4e7f296e5b5e53eab6c7a9e84c2b3c61
| 980
|
transport-eta
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ui/chart/ChartScreen.kt
|
piappstudio
| 696,508,694
| false
|
{"Kotlin": 145998, "Swift": 941, "Shell": 228}
|
package ui.chart
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import co.touchlab.kermit.Logger
import com.aay.compose.barChart.BarChart
import com.aay.compose.barChart.model.BarParameters
import com.biggboss.shared.MR
import dev.icerock.moko.resources.compose.stringResource
import di.getScreenModel
import io.github.aakira.napier.Napier
import model.ParticipantItem
import model.generateRandomColorExcludingWhite
import ui.theme.Dimens
class ChartScreen(
private val title: String,
val url: String,
val trendUrl: String,
val startDate: String
) :
Screen {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val detailModel = getScreenModel<ChartViewModel>()
val state by detailModel.episodeUiData.collectAsState()
LaunchedEffect(url) {
if (state.showDetail == null) {
detailModel.fetchShowDetails(url, startDate)
detailModel.fetchTrends(trendUrl)
}
}
Scaffold(topBar = {
TopAppBar(title = {
Text(title)
}, navigationIcon = {
IconButton(onClick = {
navigator.pop()
}) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back Button")
}
})
}) { it ->
LazyColumn(Modifier.padding(it).padding(Dimens.space)) {
item {
val sbh = stringResource(MR.strings.title_sbh)
RenderTitle("Weekly Small Boss House Trending")
state.showDetail?.participants?.let { lstParticipants ->
val allParticipantItem = lstParticipants.associate { participantItem ->
(participantItem.name?.subSequence(0, 4).toString()) to
(participantItem.history?.filter { historyItem ->
historyItem.notes?.contains(
sbh
) == true
}?.size?.toDouble() ?: 0.0)
}
val sortedEmployeeMap = allParticipantItem.toList()
.sortedByDescending { it.second }
.toMap()
val xAxisData = sortedEmployeeMap.keys.toList()
val yAxisData = sortedEmployeeMap.values.toList()
RenderBarChart(sbh, yAxisData, xAxisData, ui.theme.smallBossHouse)
}
Spacer(modifier = Modifier.height(Dimens.doubleSpace))
val nominated = stringResource(MR.strings.title_nominated)
RenderTitle("Most number of nominations")
state.showDetail?.participants?.let { lstParticipants ->
val allParticipantItem = lstParticipants.associate { participantItem ->
(participantItem.name?.subSequence(0, 4).toString()) to
(participantItem.history?.filter { historyItem ->
historyItem.notes?.contains(
nominated
) == true
}?.size?.toDouble() ?: 0.0)
}
val sortedEmployeeMap = allParticipantItem.toList()
.sortedByDescending { it.second }
.toMap()
val xAxisData = sortedEmployeeMap.keys.toList()
val yAxisData = sortedEmployeeMap.values.toList()
RenderBarChart(nominated, yAxisData, xAxisData, ui.theme.nominated)
}
// Week wise nominations
Spacer(modifier = Modifier.height(Dimens.doubleSpace))
RenderWeeklyWiseVotingChart(state.showDetail?.participants)
Spacer(modifier = Modifier.height(Dimens.doubleSpace))
// Captain
val captain = stringResource(MR.strings.title_captain)
RenderTitle("Weekly Captain Trending")
state.showDetail?.participants?.let { lstParticipants ->
val allParticipantItem = lstParticipants.associate { participantItem ->
(participantItem.name?.subSequence(0, 4).toString()) to
(participantItem.history?.filter { historyItem ->
historyItem.notes?.contains(
captain
) == true
}?.size?.toDouble() ?: 0.0)
}
val sortedEmployeeMap = allParticipantItem.toList()
.sortedByDescending { it.second }
.toMap()
val xAxisData = sortedEmployeeMap.keys.toList()
val yAxisData = sortedEmployeeMap.values.toList()
RenderBarChart(captain, yAxisData, xAxisData, ui.theme.captain)
}
}
}
}
}
@Composable
fun RenderWeeklyWiseVotingChart(participants: List<ParticipantItem>?) {
participants?.let { lstParticipants ->
val nominated = stringResource(MR.strings.title_nominated)
RenderTitle("Weekly nomination votes")
val lstBarParameter = mutableListOf<BarParameters>()
val lstWeeks =
lstParticipants.flatMap { it.history ?: emptyList() }.mapNotNull { it.week }
.distinct()
lstParticipants.forEach { participant ->
val lstVotes = mutableListOf<Double>()
for (week in lstWeeks) {
val currentWeek = participant.history?.firstOrNull { it.week == week && it.notes?.contains(nominated) == true}
if (currentWeek != null) {
Logger.d { "Week: $week, Participant: ${participant.name}, Vote: ${currentWeek.nominatedBy?.size}" }
lstVotes.add(currentWeek.nominatedBy?.size?.toDouble()?:0.0)
} else {
lstVotes.add(0.0)
}
}
lstBarParameter.add(
BarParameters(
participant.name ?: "",
data = lstVotes,
generateRandomColorExcludingWhite()
)
)
}
Box(Modifier.padding(Dimens.doubleSpace).fillMaxWidth().height(400.dp)) {
BarChart(
chartParameters = lstBarParameter,
gridColor = Color.DarkGray,
xAxisData = lstWeeks.map { "Week: ${it}" },
isShowGrid = true,
animateChart = true,
showGridWithSpacer = true,
yAxisStyle = TextStyle(
fontSize = 14.sp,
color = Color.DarkGray,
),
xAxisStyle = TextStyle(
fontSize = 14.sp,
color = Color.DarkGray,
fontWeight = FontWeight.W400
),
yAxisRange = 5,
barWidth = Dimens.doubleSpace,
spaceBetweenBars = 0.dp,
spaceBetweenGroups = Dimens.forthSpace,
)
}
}
}
}
| 0
|
Kotlin
|
3
| 9
|
22af22bd245fd0765ea95569b6a2101e40825112
| 9,138
|
BiggBoss
|
Apache License 2.0
|
apps/jvm/kotlin-console/src/main/kotlin/eu/sirotin/kotunil/currency/EuroKotlinConsoleTest.kt
|
vsirotin
| 542,600,036
| false
|
{"Kotlin": 1302807, "Java": 163060, "TypeScript": 75436, "JavaScript": 71916, "HTML": 4559}
|
package eu.sirotin.kotunil.currency
import eu.sirotin.kotunil.app.kotlin.check
import eu.sirotin.kotunil.specialunits.m3
import eu.sirotin.kotunil.core.div
import eu.sirotin.kotunil.core.times
object EuroKotlinConsoleTest {
fun kotlinConsoleTest() {
check(EUR, Euro())
check(12.EUR, Euro(12.0))
val s = EUR.unitSymbols()
check("EUR", s)
val s1 = EUR.categorySymbols()
check("`€`", s1)
val s2 = EUR.dimensions.factors.first().specification.unitSymbol
check("EUR", s2)
check(`€`, Euro())
check(123.`€`, 123.EUR)
val c = 12*m3/`€`
check("m3/EUR", c.unitSymbols())
}
}
| 14
|
Kotlin
|
4
| 95
|
2ece508f86d04d0e4fce3bc2b94b70a30d97dc33
| 680
|
si-units
|
Apache License 2.0
|
bbfgradle/tmp/results/BACKUP_DIFF/nnmzhkf_FILE.kt
|
DaniilStepanov
| 346,008,310
| false
| null |
// Bug happens on JVM , JAVA
//File: tmp/tmp0.kt
fun box() = object {}
| 1
| null |
1
| 1
|
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
| 72
|
kotlinWithFuzzer
|
Apache License 2.0
|
analysis/analysis-api/testData/symbols/symbolByPsi/destructuringDeclaration.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE
// DO_NOT_CHECK_SYMBOL_RESTORE_K1
data class P(val x: Int, val y: Int)
fun destruct(): Int {
val (l, r) = P(1, 2)
return l + r
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 177
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/flanks255/simplybackpacks/network/NetworkWrapper.kt
|
kellixon
| 166,381,768
| true
|
{"Kotlin": 33178}
|
package com.flanks255.simplybackpacks.network
import com.flanks255.simplybackpacks.simplybackpacks
import net.minecraftforge.fml.common.network.NetworkRegistry
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper
import net.minecraftforge.fml.relauncher.Side
object NetworkWrapper {
val wrapper: SimpleNetworkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel(simplybackpacks.MODID)
fun registerPackets() {
var id = 0
wrapper.registerMessage(ToggleHandler::class.java, ToggleMessage::class.java, id++, Side.SERVER)
wrapper.registerMessage(OpenHandler::class.java, OpenMessage::class.java, id++, Side.SERVER)
}
}
| 0
|
Kotlin
|
0
| 0
|
f8fa5337eb28c37f4551e9767155a67092c2f554
| 676
|
simplybackpacks
|
MIT License
|
src/main/java/com/rafaelfiume/tictactoe/console/ConsoleGameRunner.kt
|
rafaelfiume
| 46,618,701
| false
| null |
package com.rafaelfiume.tictactoe.console
import com.rafaelfiume.tictactoe.*
import com.rafaelfiume.tictactoe.TttGame.Factory.newGame
class ConsoleGameRunner(
private val game: Game,
private val input: ConsoleInputReader,
private val renderer: GameRenderer) {
fun start() {
renderer.show(game.snapshot())
while (game.gameIsOn()) {
game.playerChooses(input.readUserInput())
renderer.show(game.snapshot())
}
}
companion object {
private val BOT_MODE = "botmode"
private val TURN_DURATION_WHEN_IN_BOT_MODE_IN_SECONDS = 2
@JvmStatic fun main(args: Array<String>) {
val inputReader = if (isBotModeIn(args))
BotConsoleInputReader(TURN_DURATION_WHEN_IN_BOT_MODE_IN_SECONDS)
else
BlockingConsoleInputReader()
ConsoleGameRunner(newGame(), inputReader, ConsoleGameRenderer()).start()
}
private fun isBotModeIn(args: Array<String>): Boolean {
return args.isNotEmpty() && BOT_MODE == args[0]
}
}
}
| 4
|
Kotlin
|
0
| 1
|
e81cf93a9dc7dd033e617a5a2dd9e9531d397e64
| 1,112
|
tictactoe
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsciagcareersinductionapi/service/CIAGProfileService.kt
|
ministryofjustice
| 620,258,376
| false
|
{"Kotlin": 184763, "Dockerfile": 1191}
|
package uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.service
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.jsonprofile.CIAGProfileDTO
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.jsonprofile.CIAGProfileListDTO
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.jsonprofile.CIAGProfileRequestDTO
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.CIAGProfile
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.exceptions.NotFoundException
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.messaging.EventType
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.messaging.OutboundEventsService
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.repository.CIAGProfileRepository
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.repository.EducationAndQualificationRepository
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.repository.PreviousWorkRepository
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.repository.PrisonWorkAndEducationRepository
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.repository.SkillsAndInterestsRepository
import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.repository.WorkInterestsRepository
@Service
class CIAGProfileService(
private val ciagProfileRepository: CIAGProfileRepository,
private val educationAndQualificationRepository: EducationAndQualificationRepository,
private val previousWorkRepository: PreviousWorkRepository,
private val prisonWorkAndEducationRepository: PrisonWorkAndEducationRepository,
private val skillsAndInterestsRepository: SkillsAndInterestsRepository,
private val workInterestsRepository: WorkInterestsRepository,
private val outboundEventsService: OutboundEventsService,
) {
fun createOrUpdateCIAGInductionForOffender(
ciagProfileDTO: CIAGProfileRequestDTO,
): CIAGProfile? {
var ciagProfile = CIAGProfile(ciagProfileDTO)
var eventType: EventType = EventType.CIAG_INDUCTION_CREATED
if (ciagProfileRepository.existsById(ciagProfile.offenderId)) {
eventType = EventType.CIAG_INDUCTION_UPDATED
}
ciagProfile.skillsAndInterests?.let { skillsAndInterestsRepository.save(it) }
ciagProfile.qualificationsAndTraining?.let { educationAndQualificationRepository.save(it) }
ciagProfile.inPrisonInterests?.let { prisonWorkAndEducationRepository.save(it) }
ciagProfile.workExperience?.workInterests?.let { workInterestsRepository.save(it) }
ciagProfile.workExperience?.let { previousWorkRepository.save(it) }
ciagProfile = ciagProfileRepository.saveAndFlush(ciagProfile)
outboundEventsService.createAndPublishEventMessage(ciagProfile, eventType)
return ciagProfile
}
fun getCIAGProfileForOffender(
offenderId: String,
): CIAGProfileDTO? {
var ciagProfile = ciagProfileRepository.findById(offenderId)
if (ciagProfile == null || ciagProfile.isEmpty()) {
throw NotFoundException(offenderId)
}
return ciagProfile.let { CIAGProfileDTO(it.get()) }
}
fun getAllCIAGProfileForGivenOffenderIds(
offenderIdList: List<String>,
): CIAGProfileListDTO {
var ciagProfileMutableList = ciagProfileRepository.findAllCIAGProfilesByIdList(offenderIdList)
var ciagProfileDTOList = CIAGProfileListDTO(ciagProfileMutableList)
return ciagProfileDTOList
}
fun deleteCIAGProfile(
offenderId: String,
) {
var ciagProfile = ciagProfileRepository.findById(offenderId)
if (ciagProfile == null || ciagProfile.isEmpty()) {
throw NotFoundException(offenderId)
} else {
}
return ciagProfileRepository.deleteById(offenderId)
}
}
| 0
|
Kotlin
|
0
| 0
|
62358ea01eaa7430511ad96bf8e01a7fde6406a0
| 3,801
|
hmpps-ciag-careers-induction-api
|
MIT License
|
src/main/kotlin/net/starlegacy/feature/nations/NationsBalancing.kt
|
hafarooki
| 437,384,015
| false
| null |
package net.starlegacy.feature.nations
import net.starlegacy.SLComponent
import net.starlegacy.util.loadConfig
lateinit var NATIONS_BALANCE: NationsBalancing.Config
object NationsBalancing : SLComponent() {
data class Config(
val settlement: Config.Settlements = Settlements(),
val nation: Config.Nations = Nations(),
val capturableStation: Config.Stations = Stations()
) {
data class Settlements(
val activityDays: Int = 6,
val cityHourlyTax: Int = 125,
val cityMinActive: Int = 4,
val hourlyActivityCredits: Int = 1,
val inactivityDays: Int = 30,
val minCreateLevel: Int = 3,
val renameCost: Int = 1500,
val maxTaxPercent: Int = 12
)
data class Nations(
val minCreateLevel: Int = 12,
val minJoinLevel: Int = 7,
val hourlyActivityCredits: Int = 4,
val createCost: Int = 20000,
val renameCost: Int = 3000,
val costPerSpaceStationBlock: Double = 0.5
)
data class Stations(
val radius: Int = 1000,
val siegeMinDuration: Long = 15,
val siegeMaxDuration: Long = 60,
val siegeCost: Int = 1000,
val hourlyIncome: Int = 20,
val daysPerSiege: Double = 0.5,
val siegerXP: Int = 2000,
val siegerAllyXP: Int = 1000
)
}
override fun onEnable() {
reload()
}
fun reload() {
NATIONS_BALANCE = loadConfig(plugin.sharedDataFolder, "nations_balancing")
}
override fun supportsVanilla(): Boolean {
return true
}
}
| 0
|
Kotlin
|
5
| 4
|
c830eb40180c935e8bfff599da0f9310eeccfb5c
| 1,402
|
StarLegacy
|
MIT License
|
odinmain/src/main/kotlin/me/odinmain/features/impl/floor7/DragonCheck.kt
|
odtheking
| 657,580,559
| false
| null |
package me.odinmain.features.impl.floor7
import me.odinmain.events.impl.ChatPacketEvent
import me.odinmain.features.impl.floor7.WitherDragons.sendNotification
import me.odinmain.features.impl.floor7.WitherDragons.sendSpawned
import me.odinmain.features.impl.floor7.WitherDragons.sendTime
import me.odinmain.utils.equalsOneOf
import me.odinmain.utils.skyblock.modMessage
import net.minecraft.entity.boss.EntityDragon
import net.minecraft.util.Vec3
import net.minecraftforge.event.entity.EntityJoinWorldEvent
import net.minecraftforge.event.entity.living.LivingDeathEvent
object DragonCheck {
var lastDragonDeath = ""
fun dragonJoinWorld(event: EntityJoinWorldEvent) {
if (event.entity !is EntityDragon) return
val dragon = WitherDragonsEnum.entries.find { event.entity.positionVector.dragonCheck(it.spawnPos) } ?: return
dragon.spawning = false
dragon.particleSpawnTime = 0L
dragon.timesSpawned += 1
dragon.entity = event.entity
if (sendSpawned) modMessage("§${dragon.colorCode}${dragon.name} §fdragon spawned. This is the §${dragon.colorCode}${dragon.timesSpawned}§f time it has spawned.")
}
fun dragonLeaveWorld(event: LivingDeathEvent) {
if (event.entity !is EntityDragon) return
val dragon = WitherDragonsEnum.entries.find {it.entity?.entityId == event.entity.entityId} ?: return
if (sendTime) {
val oldPB = dragon.dragonKillPBs.value
val killTime = event.entity.ticksExisted / 20.0
if (dragon.dragonKillPBs.value < event.entity.ticksExisted / 20.0) dragon.dragonKillPBs.value = killTime
modMessage("§${dragon.colorCode}${dragon.name} §fdragon was alive for ${printSecondsWithColor(killTime, 3.5, 7.5, down = false)}${if (killTime < oldPB) " §7(§dNew PB§7)" else ""}.")
}
lastDragonDeath = dragon.name
}
fun onChatPacket(event: ChatPacketEvent) {
if (
!event.message.equalsOneOf(
"[BOSS] Wither King: Oh, this one hurts!",
"[BOSS] Wither King: I have more of those",
"[BOSS] Wither King: My soul is disposable."
)
) return
val dragon = WitherDragonsEnum.entries.find { lastDragonDeath == it.name } ?: return
if (sendNotification) modMessage("§${dragon.colorCode}${dragon.name} dragon counts.")
}
private fun Vec3.dragonCheck(vec3: Vec3): Boolean {
return this.xCoord == vec3.xCoord && this.yCoord == vec3.yCoord && this.zCoord == vec3.zCoord
}
private fun printSecondsWithColor(time1: Double, time2: Double, time3: Double, down: Boolean = true, colorCode1: String = "a", colorCode2: String = "6", colorCode3: String = "c"): String {
val colorCode = if (down) {
when {
time1 <= time2 -> colorCode3
time1 <= time3 -> colorCode2
else -> colorCode1
}
} else {
when {
time1 <= time2 -> colorCode1
time1 <= time3 -> colorCode2
else -> colorCode3
}
}
return "§$colorCode${time1}s"
}
}
| 0
| null |
9
| 29
|
31b718797d49dba5da3439080db1b576e26357f1
| 3,169
|
OdinClient
|
MIT License
|
app/src/main/java/com/jaygoo/demo/fragments/BaseFragment.kt
|
Jay-Goo
| 81,301,855
| false
| null |
package com.jaygoo.demo.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ______`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 永无BUG
* =====================================================
* 作 者:JayGoo
* 创建日期:2019-06-13
* 描 述:
* =====================================================
*/
abstract class BaseFragment: Fragment() {
abstract fun getLayoutId():Int
abstract fun initView(view: View)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return try {
inflater.inflate(getLayoutId(), container, false)
}catch (e:Exception){
super.onCreateView(inflater, container, savedInstanceState)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView(view)
}
}
| 43
| null |
382
| 2,480
|
ba46b09113d4632f4c784d44dd5caf115eea77ba
| 1,678
|
RangeSeekBar
|
Apache License 2.0
|
sample/src/main/kotlin/org/jraf/android/androidwearcolorpicker/sample/MainActivity.kt
|
BoD
| 32,235,650
| false
| null |
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2015-present <NAME>BoD<NAME> (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jraf.android.androidwearcolorpicker.sample
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.Text
import org.jraf.android.androidwearcolorpicker.ColorPickActivity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
var pickedColor: Int? by remember { mutableStateOf(null) }
val colorPickLauncher = rememberLauncherForActivityResult(contract = ColorPickActivity.Contract()) { pickedColorResult ->
if (pickedColorResult == null) {
Log.d("MainActivity", "Cancelled")
} else {
pickedColor = pickedColorResult.pickedColor
}
}
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = {
colorPickLauncher.launch(ColorPickActivity.Contract.PickRequest(pickedColor))
}
) {
Text(
modifier = Modifier.padding(horizontal = 16.dp),
text = "Pick a color"
)
}
Spacer(modifier = Modifier.size(16.dp))
Box(
modifier = Modifier
.size(48.dp)
.background(Color(pickedColor ?: 0))
)
}
}
}
}
| 0
|
Kotlin
|
13
| 52
|
c1470cefd360edff2642bab4fbc04bef24b51970
| 3,442
|
android-wear-color-picker
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/di/Module.kt
|
frantoribio
| 510,270,967
| true
|
{"Kotlin": 50332}
|
/*
* 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.di
import com.example.androiddevchallenge.data.remote.WeatherApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor()
.apply { level = HttpLoggingInterceptor.Level.BODY }
)
.build()
@Provides
@Singleton
fun provideRetrofitBuilder(okHttpClient: OkHttpClient): Retrofit.Builder =
Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
@Provides
@Singleton
fun provideWeatherApi(retrofit: Retrofit.Builder): WeatherApi =
retrofit.baseUrl(WeatherApi.BASE_URL).build().create(WeatherApi::class.java)
}
@Module
@InstallIn(ViewModelComponent::class)
class Module
| 0
| null |
0
| 1
|
69d17ab04d810d0d62f906711dd0054155e21046
| 1,913
|
Kotlin-challenge-compose-week4
|
Apache License 2.0
|
rtp/src/test/kotlin/org/jitsi/rtp/rtcp/RtcpPacketTest.kt
|
jitsi
| 9,657,943
| false
| null |
/*
* Copyright @ 2018 - present 8x8, 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.jitsi.rtp.rtcp
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.types.shouldBeInstanceOf
import org.jitsi.rtp.extensions.bytearray.byteArrayOf
class RtcpPacketTest : ShouldSpec() {
init {
context("Parsing") {
context("a valid but unsupported RTCP packet") {
val unsupportedRtcpData = byteArrayOf(
// V=2, PT=195, length = 2
0x80, 0xC3, 0x00, 0x02,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
)
should("return UnsupportedRtcpPacket") {
RtcpPacket.parse(unsupportedRtcpData, 0, unsupportedRtcpData.size)
.shouldBeInstanceOf<UnsupportedRtcpPacket>()
}
}
context("an invalid RTCP packet") {
val invalidRtcpData = byteArrayOf(
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
)
should("throw an InvalidRtcpException") {
shouldThrow<InvalidRtcpException> {
RtcpPacket.parse(invalidRtcpData, 0, invalidRtcpData.size)
}
}
}
context("a packet with invalid length") {
val invalidRtcpLengthData = byteArrayOf(
// V=2, PT=195, length = 8
0x80, 0xC3, 0x00, 0x08,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
)
should("throw an InvalidRtcpException") {
shouldThrow<InvalidRtcpException> {
RtcpPacket.parse(invalidRtcpLengthData, 0, invalidRtcpLengthData.size)
}
}
}
}
}
}
| 170
| null |
989
| 2,900
|
b7dba8242cfaa84364bf6988cc097611346505c0
| 2,602
|
jitsi-videobridge
|
Apache License 2.0
|
app/src/main/java/com/example/atomicdesign/ui/components/atom/SecondaryButton.kt
|
4mr0m3r0
| 259,181,662
| false
| null |
package com.anibalbastias.uikitcompose.components.atom
import androidx.compose.foundation.BorderStroke
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Surface
import androidx.compose.material.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.anibalbastias.uikitcompose.theme.UIKitComposeTheme
import java.util.*
@Composable
fun SecondaryButton(label: String, onClick: () -> Unit, modifier: Modifier = Modifier) {
OutlinedButton(
onClick = onClick,
border = BorderStroke(1.dp, MaterialTheme.colors.primary),
modifier = modifier
) {
Text(
text = label.uppercase(Locale.getDefault()),
color = MaterialTheme.colors.secondary
)
}
}
@Preview("SecondaryButton light mode")
@Composable
fun SecondaryButtonButtonLight() {
UIKitComposeTheme {
Surface {
SecondaryButton(label = "Secondary Button", onClick = { })
}
}
}
@Preview("SecondaryButton dark mode")
@Composable
fun SecondaryButtonButtonDark() {
UIKitComposeTheme(darkTheme = true) {
Surface {
SecondaryButton(label = "Secondary Button", onClick = { })
}
}
}
| 0
| null |
1
| 2
|
b096114948b0a7d986e788662dcef0a46e5a5823
| 1,367
|
composing-atomic-design
|
MIT License
|
Kotlin/extras/games/gameOfFifteen/GameOfFifteen.kt
|
vimalsubbiah7
| 254,466,514
| true
|
{"C++": 138303, "Java": 102500, "Python": 73097, "C": 32475, "JavaScript": 30753, "Kotlin": 26122, "Swift": 22216, "C#": 19569, "Go": 15841, "Ruby": 10824, "Haskell": 5956, "Scala": 4198, "Rust": 3485, "Perl": 1926, "Crystal": 812, "Makefile": 727, "Brainfuck": 616, "Racket": 406}
|
package games.gameOfFifteen
import board.Direction
import board.GameBoard
import board.createGameBoard
import games.game.Game
/*
* Implement the Game of Fifteen (https://en.wikipedia.org/wiki/15_puzzle).
* When you finish, you can play the game by executing 'PlayGameOfFifteen'.
*/
fun newGameOfFifteen(initializer: GameOfFifteenInitializer = RandomGameInitializer()): Game =GameOfFifteen(initializer)
class GameOfFifteen(private val initializer: GameOfFifteenInitializer) : Game {
private val board = createGameBoard<Int?>(4)
override fun initialize() {
board.addNewValue(initializer)
}
override fun canMove() = true
override fun hasWon(): Boolean {
val list = mutableListOf<Int?>()
board.getAllCells().forEach { cell ->
list.add(board[cell])
}
if (list.last() != null) return false
var value = list.first()!!
for (i in 1..list.lastIndex) {
list[i]?.let {
if (it < value) return false
value = it
}
}
return true
}
override fun processMove(direction: Direction) {
val cell = board.find { it == null }
when (direction) {
Direction.LEFT -> {
with(board) {
cell?.getNeighbour(Direction.RIGHT)?.let { neighbour ->
board[cell] = board[neighbour].also {
board[neighbour] = board[cell]
}
}
}
}
Direction.DOWN -> {
with(board) {
cell?.getNeighbour(Direction.UP)?.let { neighbour ->
board[cell] = board[neighbour].also {
board[neighbour] = board[cell]
}
}
}
}
Direction.UP -> {
with(board) {
cell?.getNeighbour(Direction.DOWN)?.let { neighbour ->
board[cell] = board[neighbour].also {
board[neighbour] = board[cell]
}
}
}
}
Direction.RIGHT -> {
with(board) {
cell?.getNeighbour(Direction.LEFT)?.let { neighbour ->
board[cell] = board[neighbour].also {
board[neighbour] = board[cell]
}
}
}
}
}
}
override fun get(i: Int, j: Int): Int? = board.run { get(getCell(i, j)) }
}
fun GameBoard<Int?>.addNewValue(initializer: GameOfFifteenInitializer) {
var index = 0
getAllCells().forEach { cell ->
if (index <= initializer.initialPermutation.lastIndex) {
this[cell] = initializer.initialPermutation[index]
}
index++
}
}
| 0
|
C++
|
0
| 0
|
1cf249e5bcabb32096ded17d0ea7216968ff7fbe
| 2,957
|
Algorithms
|
Apache License 2.0
|
app/src/main/java/arcus/app/pairing/device/customization/waterheater/WaterHeaterModelSerialNumberFragment.kt
|
arcus-smart-home
| 168,191,380
| false
| null |
/*
* Copyright 2019 Arcus 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 arcus.app.pairing.device.customization.waterheater
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import arcus.app.R
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import arcus.app.pairing.device.customization.CustomizationNavigationDelegate
import arcus.app.common.fragment.TitledFragment
import arcus.presentation.pairing.device.customization.CustomizationStep
import arcus.presentation.pairing.device.customization.CustomizationType
import arcus.presentation.pairing.device.customization.waterheater.WaterHeaterModelSerialPresenter
import arcus.presentation.pairing.device.customization.waterheater.WaterHeaterModelSerialPresenterImpl
import arcus.presentation.pairing.device.customization.waterheater.WaterHeaterModelSerialView
import com.google.android.material.textfield.TextInputLayout
import kotlin.properties.Delegates
class WaterHeaterModelSerialNumberFragment : Fragment(),
TitledFragment,
WaterHeaterModelSerialView {
private lateinit var pairingDeviceAddress: String
private lateinit var customizationStep: CustomizationStep
private lateinit var pageHeaderTitle: TextView
private lateinit var pageDescription: TextView
private lateinit var modelNumber: EditText
private lateinit var modelNumberContainer: TextInputLayout
private lateinit var serialNumber: EditText
private lateinit var serialNumberContainer: TextInputLayout
private lateinit var nextButton: Button
private lateinit var cancelButton: Button
private var callback by Delegates.notNull<CustomizationNavigationDelegate>()
private var cancelPresent: Boolean = false
private var nextButtonText: Int = R.string.pairing_next
private val presenter: WaterHeaterModelSerialPresenter =
WaterHeaterModelSerialPresenterImpl()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.run {
pairingDeviceAddress = getString(ARG_PAIRING_DEVICE_ADDRESS)!!
customizationStep = getParcelable(ARG_CUSTOMIZATION_STEP)!!
cancelPresent = getBoolean(ARG_CANCEL_PRESENT)
nextButtonText = getInt(ARG_NEXT_BUTTON_TEXT)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_water_heater_model_serial, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pageHeaderTitle = view.findViewById(R.id.header_title)
pageDescription = view.findViewById(R.id.description)
modelNumber = view.findViewById(R.id.model_number)
modelNumberContainer = view.findViewById(R.id.model_number_container)
serialNumber = view.findViewById(R.id.serial_number)
serialNumberContainer = view.findViewById(R.id.serial_number_container)
nextButton = view.findViewById(R.id.next_button)
nextButton.setText(nextButtonText)
nextButton.setOnClickListener {
presenter.saveModelAndSerialNumbersToPairingDevice(
pairingDeviceAddress,
modelNumber.text,
serialNumber.text
)
callback.navigateForwardAndComplete(CustomizationType.WATER_HEATER)
}
cancelButton = view.findViewById(R.id.cancel_button)
cancelButton.setOnClickListener { callback.cancelCustomization() }
cancelButton.visibility = if (cancelPresent) View.VISIBLE else View.GONE
}
override fun onStart() {
super.onStart()
pageHeaderTitle.text = customizationStep.title ?: getString(R.string.water_heater_assistance_title)
pageDescription.text = if (customizationStep.description.isEmpty()) {
getString(R.string.water_heater_assistance_desc)
} else {
customizationStep.description.joinToString("\n\n")
}
}
override fun onResume() {
super.onResume()
presenter.setView(this)
}
override fun onPause() {
super.onPause()
presenter.clearView()
}
override fun onAttach(context: Context) {
super.onAttach(context)
activity?.let {
callback = it as CustomizationNavigationDelegate
}
}
override fun onSaveSuccess() {
/* No-Op */
}
override fun onUnhandledError() {
/* No-Op */
}
override fun onSaveError() {
/* No-Op */
}
override fun getTitle(): String = customizationStep.header ?: resources.getString(R.string.water_heater_assistance_header)
companion object {
private const val ARG_PAIRING_DEVICE_ADDRESS = "ARG_PAIRING_DEVICE_ADDRESS"
private const val ARG_CUSTOMIZATION_STEP = "ARG_CUSTOMIZATION_STEP"
private const val ARG_CANCEL_PRESENT = "ARG_CANCEL_PRESENT"
private const val ARG_NEXT_BUTTON_TEXT = "ARG_NEXT_BUTTON_TEXT"
@JvmStatic
fun newInstance(pairingDeviceAddress: String,
step: CustomizationStep,
cancelPresent: Boolean = false,
nextButtonText: Int = R.string.pairing_next
) = WaterHeaterModelSerialNumberFragment().also { fragment ->
fragment.arguments = createArgumentBundle(
pairingDeviceAddress,
step,
cancelPresent,
nextButtonText)
fragment.retainInstance = true
}
@JvmStatic
fun createArgumentBundle(
pairingDeviceAddress: String,
step: CustomizationStep,
cancelPresent: Boolean = false,
nextButtonText: Int = R.string.pairing_next
) = Bundle().also { args ->
args.putString(ARG_PAIRING_DEVICE_ADDRESS, pairingDeviceAddress)
args.putParcelable(ARG_CUSTOMIZATION_STEP, step)
args.putBoolean(ARG_CANCEL_PRESENT, cancelPresent)
args.putInt(ARG_NEXT_BUTTON_TEXT, nextButtonText)
}
}
}
| 6
|
Java
|
27
| 27
|
845b23b6ee913c58e009914e920242e29d0b137a
| 6,866
|
arcusandroid
|
Apache License 2.0
|
app/src/main/java/com/mertoenjosh/triviaquest/adapters/SelectCategoryItemAdapter.kt
|
mertoenjosh
| 480,945,233
| false
| null |
package com.mertoenjosh.triviaquest.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mertoenjosh.triviaquest.R
class SelectCategoryItemAdapter(
private val context: Context,
private val list: ArrayList<String>,
private val icons: ArrayList<Int>,
):
RecyclerView.Adapter<SelectCategoryItemAdapter.ViewHolder>(){
private var onItemClickListener: OnItemClickListener? = null
interface OnItemClickListener {
fun onItemClick(position: Int, category: String)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_select_category, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val category = list[position]
val icon = icons[position]
holder.bind(position, category, icon)
}
override fun getItemCount(): Int = list.size
fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
this.onItemClickListener = onItemClickListener
}
inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val tvCategoryName: TextView = view.findViewById(R.id.tvCategoryName)
private val ivCategory: ImageView = view.findViewById(R.id.ivCategory)
fun bind(position: Int, category: String, icon: Int) {
tvCategoryName.text = category
ivCategory.setImageResource(icon)
this@ViewHolder.itemView.setOnClickListener {
if (onItemClickListener != null) {
onItemClickListener!!.onItemClick(position, category)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
03651369aa63c512a1c0237d527eb27b9d5b230c
| 1,969
|
TriviaQuest
|
MIT License
|
api/src/main/kotlin/io/github/dseelp/framecord/api/plugins/repository/Repository.kt
|
DSeeLP
| 378,427,319
| false
| null |
/*
* Copyright (c) 2021 DSeeLP & FrameCord contributors
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.dseelp.framecord.api.plugins.repository
interface Repository {
val url: String
val meta: RepositoryMeta
val indexes: Array<RepositoryIndex>
suspend fun updateIndexes()
fun find(groupId: String, exact: Boolean = false): Array<RepositoryIndex>
fun find(
groupId: String,
artifactId: String,
exactGroupId: Boolean = true,
exactArtifactId: Boolean = true
): Array<RepositoryIndex>
suspend fun toPackage(index: RepositoryIndex): Package<*>
}
| 1
|
Kotlin
|
0
| 0
|
489823eacbe85a88c0b8aadfcc50b5fb122f11dc
| 1,676
|
FrameCord
|
MIT License
|
app/src/main/java/com/chocolate/triviatitans/presentation/screens/category/CategoryScreen.kt
|
team-chocolate-cake
| 661,943,976
| false
| null |
package com.chocolate.triviatitans.presentation.screens.category
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.chocolate.triviatitans.R
import com.chocolate.triviatitans.presentation.screens.category.components.BottomBar
import com.chocolate.triviatitans.presentation.screens.category.components.Content
import com.chocolate.triviatitans.presentation.screens.category.components.TopBar
import com.chocolate.triviatitans.presentation.screens.category.viewmodel.CategoriesUiState
import com.chocolate.triviatitans.presentation.screens.category.viewmodel.CategoryUiState
import com.chocolate.triviatitans.presentation.screens.category.viewmodel.CategoryViewModel
import com.chocolate.triviatitans.presentation.screens.level.navigateToLevel
import com.chocolate.triviatitans.presentation.theme.TriviaTitansTheme
import com.chocolate.triviatitans.presentation.theme.customColor
@Composable
fun CategoryScreen(
navController: NavController,
viewModel: CategoryViewModel = hiltViewModel()
) {
val state by viewModel.state.collectAsState()
CategoryContent(
state = state,
onCategorySelected = viewModel::onCategorySelected,
onCategoryDeselected = viewModel::onCategoryDeselected,
onClickNext = {
val category = state.categoriesSelected.joinToString(",") { it.name }
navController.navigateToLevel(category, viewModel.categoryArgs.gameTypeName)
},
onClickBack = { navController.navigateUp() }
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CategoryContent(
state: CategoriesUiState,
onCategorySelected: (CategoryUiState) -> Unit,
onCategoryDeselected: (CategoryUiState) -> Unit,
onClickNext: () -> Unit,
onClickBack: () -> Unit
) {
val colors = MaterialTheme.customColor()
Scaffold(
modifier = Modifier.fillMaxSize(),
containerColor = colors.background,
topBar = {
TopBar(
title = stringResource(R.string.you_want_to_improve_today),
onBackClick = onClickBack,
)
},
bottomBar = {
BottomBar(
count = state.categoriesSelectedCount,
onNextClick = onClickNext,
)
}
)
{ padding ->
Content(
padding = padding,
categories = state.categories,
onCategorySelected = { category, isSelected ->
if (isSelected) onCategorySelected(category)
else onCategoryDeselected(category)
}
)
}
}
@Preview
@Composable
fun CategoryScreenPreview() {
TriviaTitansTheme {
// CategoryScreen()
}
}
| 0
|
Kotlin
|
3
| 1
|
94e74e9943f25d94a64311d898baf4b07fabfc63
| 3,204
|
TriviaTitans
|
MIT License
|
MVVMLibrary/src/main/java/com/see/mvvm/viewmodel/SeeApplication.kt
|
XiaoSeee
| 107,637,882
| false
|
{"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 3, "Markdown": 2, "Proguard": 4, "XML": 41, "Java": 13, "Kotlin": 30}
|
package com.see.mvvm.viewmodel
import android.app.Application
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
/**
* 继承 [ViewModelStoreOwner] 用来存放 [androidx.lifecycle.ViewModel]
* @author by XiaoSe on 2020/11/23.
*/
open class SeeApplication : Application(), ViewModelStoreOwner {
protected val mViewModelStore: ViewModelStore by lazy {
ViewModelStore()
}
override fun getViewModelStore(): ViewModelStore {
return mViewModelStore
}
}
| 0
|
Kotlin
|
1
| 0
|
9f0190703a474d9dc72dfb78c7a30f225c9f8b4b
| 509
|
SeeComponent
|
Apache License 2.0
|
app/src/main/java/com/example/android/architecture/blueprints/todoapp/util/EspressoIdlingResource.kt
|
nLoops
| 347,321,889
| false
| null |
package com.example.android.architecture.blueprints.todoapp.util
import androidx.test.espresso.idling.CountingIdlingResource
// How to make a NO-OP for Production code
// https://medium.com/androiddevelopers/android-testing-with-espressos-idling-resources-and-testing-fidelity-8b8647ed57f4
object EspressoIdlingResource {
private const val RESOURCE = "GLOBAL"
@JvmField
val countingIdlingResource = CountingIdlingResource(RESOURCE)
fun increment() {
countingIdlingResource.increment()
}
fun decrement() {
if (!countingIdlingResource.isIdleNow) {
countingIdlingResource.decrement()
}
}
}
inline fun <T> wrapEspressoIdlingResource(function: () -> T): T {
// Espresso does not work well with coroutines yet. See
// https://github.com/Kotlin/kotlinx.coroutines/issues/982
EspressoIdlingResource.increment() // Set app as busy.
return try {
function()
} finally {
EspressoIdlingResource.decrement() // Set app as idle.
}
}
| 0
|
Kotlin
|
0
| 0
|
c9017a31fd04cc5a48355a6b96aa21822bbd9a27
| 1,031
|
AndroidTesting
|
Apache License 2.0
|
app/src/main/java/com/lodz/android/agiledevkt/modules/rv/snap/SnapRvActivity.kt
|
LZ9
| 137,967,291
| false
|
{"Kotlin": 2174504}
|
package com.lodz.android.agiledevkt.modules.rv.snap
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lodz.android.agiledevkt.R
import com.lodz.android.agiledevkt.bean.NationBean
import com.lodz.android.agiledevkt.config.Constant
import com.lodz.android.agiledevkt.databinding.ActivitySnapBinding
import com.lodz.android.agiledevkt.modules.main.MainActivity
import com.lodz.android.pandora.base.activity.BaseActivity
import com.lodz.android.pandora.utils.viewbinding.bindingLayout
import com.lodz.android.pandora.widget.rv.snap.TabPagerSnapHelper
import com.lodz.android.pandora.widget.rv.snap.ViewPagerSnapHelper
/**
* RvSnap测试类
* Created by zhouL on 2018/12/3.
*/
class SnapRvActivity : BaseActivity() {
companion object {
fun start(context: Context) {
val intent = Intent(context, SnapRvActivity::class.java)
context.startActivity(intent)
}
}
/** 国旗 */
private val NATION_IMGS = arrayOf(
Constant.CHN_FLAG_URL,
Constant.USA_FLAG_URL,
Constant.RUS_FLAG_URL,
Constant.JPN_FLAG_URL,
Constant.KOR_FLAG_URL,
Constant.AUS_FLAG_URL,
Constant.UKR_FLAG_URL,
Constant.PRK_FLAG_URL,
Constant.BRA_FLAG_URL
)
/** 名称 */
private val NATION_NAMES = arrayOf(
"中国", "美国", "俄罗斯", "日本", "韩国", "澳大利亚", "乌克兰", "朝鲜", "巴西"
)
/** 缩写 */
private val NATION_CODES = arrayOf(
"CHN", "USA", "RUS", "JPN", "KOR", "AUS", "UKR", "PRK", "BRA"
)
private val mBinding: ActivitySnapBinding by bindingLayout(ActivitySnapBinding::inflate)
override fun getViewBindingLayout(): View = mBinding.root
override fun findViews(savedInstanceState: Bundle?) {
getTitleBarLayout().setTitleName(intent.getStringExtra(MainActivity.EXTRA_TITLE_NAME) ?: "")
initTab()
initPager()
}
private fun initTab() {
NATION_NAMES.forEachIndexed { index, name ->
mBinding.tabLayout.addTab(mBinding.tabLayout.newTab().setText(name), index == 0)
}
initTabRecyclerView()
}
private fun initTabRecyclerView() {
val layoutManager = LinearLayoutManager(getContext())
layoutManager.orientation = RecyclerView.HORIZONTAL
val adapter = SnapAdapter(getContext())
mBinding.tabRv.layoutManager = layoutManager
mBinding.tabRv.setHasFixedSize(true)
mBinding.tabRv.adapter = adapter
val snapHelper = TabPagerSnapHelper(0)
snapHelper.attachToRecyclerView(mBinding.tabRv)
snapHelper.setupWithTabLayout(mBinding.tabLayout)
adapter.setData(getNationList())
adapter.notifyDataSetChanged()
}
private fun initPager() {
val layoutManager = LinearLayoutManager(getContext())
layoutManager.orientation = RecyclerView.HORIZONTAL
val adapter = SnapAdapter(getContext())
mBinding.pagerRv.layoutManager = layoutManager
mBinding.pagerRv.setHasFixedSize(true)
mBinding.pagerRv.adapter = adapter
val snapHelper = ViewPagerSnapHelper(0)
snapHelper.attachToRecyclerView(mBinding.pagerRv)
snapHelper.setOnPageChangeListener { position ->
mBinding.pageTv.text = getString(R.string.rvsnap_page, (position + 1).toString())
}
adapter.setData(getNationList())
adapter.notifyDataSetChanged()
mBinding.pageTv.text = getString(R.string.rvsnap_page, "1")
}
override fun onClickBackBtn() {
super.onClickBackBtn()
finish()
}
override fun initData() {
super.initData()
showStatusCompleted()
}
private fun getNationList(): ArrayList<NationBean> {
val list = ArrayList<NationBean>()
for (i in NATION_IMGS.indices) {
val bean = NationBean()
bean.imgUrl = NATION_IMGS[i]
bean.name = NATION_NAMES[i]
bean.code = NATION_CODES[i]
list.add(bean)
}
return list
}
}
| 0
|
Kotlin
|
3
| 11
|
926b9f968a984c42ade94371714ef4caf3ffbccf
| 4,174
|
AgileDevKt
|
Apache License 2.0
|
app/src/main/java/com/example/weather/Presentation/MainActivity.kt
|
BrunoAnndrade
| 742,541,348
| false
|
{"Kotlin": 35695}
|
package com.example.weather.Presentation
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
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.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.example.weather.R
import com.example.weather.ui.theme.WeatherTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WeatherTheme {
WeatherScreen()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WeatherScreen() {
val viewModelWeather:WeatherViewModel by lazy {
WeatherViewModel.create()
}
val viewModelForecast by lazy {
ForecastViewModel.create()
}
val mainState = viewModelWeather.MainLiveData.observeAsState()
val weatherState = viewModelWeather.WeatherLiveData.observeAsState()
val windState = viewModelWeather.WindSpeedLiveData.observeAsState()
val mainTemp = mainState.value?.temp
val iconTemp = weatherState.value?.firstOrNull()?.icon
val descriptionTemp = weatherState.value?.firstOrNull()?.description
val mainTempMin = mainState.value?.temp_min
val mainTempMax = mainState.value?.temp_max
val feelsLike = mainState.value?.feels_like
val humidity = mainState.value?.humidity
val windSpeed = windState.value?.speed
val cityState = viewModelForecast.CityLiveData.observeAsState()
val city = cityState.value?.name
val forecastForDayState = viewModelForecast.ListElementLiveData.observeAsState()
// each array has 3 hours of differences in API
// 1 day later
val oneDayLater = 2
val tempMinForDayOne = forecastForDayState.value?.get(oneDayLater)?.main?.temp_min
val tempMaxForDayOne = forecastForDayState.value?.get(oneDayLater)?.main?.temp_max
val iconTempForDayOne = forecastForDayState.value?.get(oneDayLater)?.weather?.firstOrNull()?.icon
val dataForDayOne = forecastForDayState.value?.get(oneDayLater)?.dt_txt
// 2 days later
val twoDayLater = 10
val tempMinForDayTwo = forecastForDayState.value?.get(twoDayLater)?.main?.temp_min
val tempMaxForDayTwo = forecastForDayState.value?.get(twoDayLater)?.main?.temp_max
val iconTempForDayTwo = forecastForDayState.value?.get(twoDayLater)?.weather?.firstOrNull()?.icon
val dataForDayTwo = forecastForDayState.value?.get(twoDayLater)?.dt_txt
// 3 days later
val threeDayLater = 18
val tempMinForDayThree = forecastForDayState.value?.get(threeDayLater)?.main?.temp_min
val tempMaxForDayThree = forecastForDayState.value?.get(threeDayLater)?.main?.temp_max
val iconTempForDayThree = forecastForDayState.value?.get(threeDayLater)?.weather?.firstOrNull()?.icon
val dataForDayThree = forecastForDayState.value?.get(threeDayLater)?.dt_txt
// 4 days later
val fourDayLater = 26
val tempMinForDayFour = forecastForDayState.value?.get(fourDayLater)?.main?.temp_min
val tempMaxForDayFour = forecastForDayState.value?.get(fourDayLater)?.main?.temp_max
val iconTempForDayFour = forecastForDayState.value?.get(fourDayLater)?.weather?.firstOrNull()?.icon
val dataForDayFour = forecastForDayState.value?.get(fourDayLater)?.dt_txt
Scaffold(
topBar = {
TopAppBar(
colors = TopAppBarDefaults.mediumTopAppBarColors(
containerColor = Color.Black
), title = {
Text(
text = "Weather",
fontSize = 20.sp,
fontWeight = FontWeight.ExtraBold,
color = Color.White,
)
})
},
) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxWidth()
.fillMaxHeight()
.background(Color.White),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(1.dp))
Box(
modifier = Modifier
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color.Blue.copy(0.7f, 0.3f, 0.7f), Color.Blue.copy(0.6f)
)
),
shape = RoundedCornerShape(10.dp),
)
.width(360.dp), contentAlignment = Alignment.Center
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Text(
text = city.toString(),
fontSize = 30.sp,
style = TextStyle.Default.copy(
Color.White,
),
fontWeight = FontWeight.Bold,
)
AsyncImage(
model = "https://openweathermap.org/img/wn/$iconTemp@2x.png",
contentDescription = null,
modifier = Modifier
.width(200.dp)
.height(120.dp)
.clip(CircleShape)
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
if (mainTemp != null) {
Text(
text = mainTemp.toInt().toString() + "ºC",
fontSize = 80.sp,
modifier = Modifier,
style = TextStyle.Default.copy(
Color.White, fontWeight = FontWeight.ExtraBold
),
)
} else {
Text(
text = "",
fontSize = 100.sp,
modifier = Modifier,
style = TextStyle.Default.copy(
Color.White, fontWeight = FontWeight.ExtraBold
),
)
}
}
Text(
text = descriptionTemp.toString().uppercase(),
fontSize = 18.sp,
style = TextStyle.Default.copy(
Color.White,
),
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(5.dp))
Row(
modifier = Modifier
.fillMaxWidth()
,
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Min:",
style = TextStyle.Default.copy(
Color.White,
),
fontWeight = FontWeight.ExtraBold,
modifier = Modifier.padding(end = 5.dp),
)
if (mainTempMin != null) {
Text(
text = mainTempMin.toInt().toString() + "ºC",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
modifier = Modifier
)
}
Text(
text = "Max:",
style = TextStyle.Default.copy(
Color.White,
),
modifier = Modifier.padding(start = 10.dp, end = 2.dp),
fontWeight = FontWeight.ExtraBold,
)
if (mainTempMax != null) {
Text(
text = mainTempMax.toInt().toString() + "ºC",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
)
}
Spacer(modifier = Modifier.width(10.dp))
Text(
text = "Sensação:",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
)
Text(
text = feelsLike.toString().take(2)+"ºC",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
modifier = Modifier.padding(start = 5.dp)
)
}
Spacer(modifier = Modifier.height(10.dp))
Row(
modifier = Modifier.padding(bottom = 10.dp)
) {
Image(
painter = painterResource(id = R.drawable.humidity_icon),
contentDescription = "humidity",
modifier = Modifier.size(20.dp)
)
Text(
text = humidity.toString()+"%",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
modifier = Modifier.padding(start = 5.dp)
)
Spacer(modifier = Modifier.width(10.dp))
Image(
painter = painterResource(id = R.drawable.wind_icon),
contentDescription = "umidity",
modifier = Modifier.size(20.dp)
)
Text(
text = windSpeed.toString()+" km",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
modifier = Modifier.padding(start = 5.dp)
)
}
}
}
Box(
modifier = Modifier
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color.Blue.copy(0.9f, 0.4f, 0.6f), Color.Blue.copy(0.6f)
)
),
shape = RoundedCornerShape(10.dp),
)
.width(360.dp), contentAlignment = Alignment.Center
) {
Column(
verticalArrangement = Arrangement.spacedBy(20.dp),
modifier = Modifier.padding(top = 10.dp)
) {
Text(
text = "Previsao para os próximos dias",
color = Color.White,
fontWeight = FontWeight.Bold,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
Row(
horizontalArrangement = Arrangement.spacedBy(45.dp),
verticalAlignment = CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp)
) {
Text(
text = viewModelForecast.getDayOfTheWeek(dataForDayOne.toString()),
modifier = Modifier.width(40.dp),
color = Color.White,
)
AsyncImage(
model = "https://openweathermap.org/img/wn/$iconTempForDayOne@2x.png",
contentDescription = "sol",
modifier = Modifier
.width(30.dp)
.height(30.dp)
.clip(CircleShape)
)
Text(
text = tempMinForDayOne.toString().take(2) + "º",
modifier = Modifier.width(40.dp),
color = Color.White,
)
Text(
text = tempMaxForDayOne.toString().take(2) + "º",
style = TextStyle.Default.copy(
color = Color.White,
)
)
}
Row(
horizontalArrangement = Arrangement.spacedBy(45.dp),
verticalAlignment = CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp)
) {
Text(
text = viewModelForecast.getDayOfTheWeek(dataForDayTwo.toString()),
modifier = Modifier.width(40.dp),
color = Color.White,
)
AsyncImage(
model = "https://openweathermap.org/img/wn/$iconTempForDayTwo@2x.png",
contentDescription = "sol",
modifier = Modifier
.width(30.dp)
.height(30.dp)
.clip(CircleShape)
)
Text(
text = tempMinForDayTwo.toString().take(2) + "º",
modifier = Modifier.width(40.dp),
color = Color.White,
)
Text(
text = tempMaxForDayTwo.toString().take(2) + "º",
style = TextStyle.Default.copy(
Color.White,
)
)
}
Row(
horizontalArrangement = Arrangement.spacedBy(45.dp),
verticalAlignment = CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp)
) {
Text(
text = viewModelForecast.getDayOfTheWeek(dataForDayThree.toString()),
modifier = Modifier.width(40.dp),
color = Color.White,
)
AsyncImage(
model = "https://openweathermap.org/img/wn/$iconTempForDayThree@2x.png",
contentDescription = "sol",
modifier = Modifier
.width(30.dp)
.height(30.dp)
.clip(CircleShape)
)
Text(
text = tempMinForDayThree.toString().take(2) + "º",
modifier = Modifier.width(40.dp),
color = Color.White,
)
Text(
text = tempMaxForDayThree.toString().take(2) + "º",
style = TextStyle.Default.copy(
Color.White,
)
)
}
Row(
horizontalArrangement = Arrangement.spacedBy(45.dp),
verticalAlignment = CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp)
) {
Text(
text = viewModelForecast.getDayOfTheWeek(dataForDayFour.toString()),
modifier = Modifier.width(40.dp),
color = Color.White,
)
AsyncImage(
model = "https://openweathermap.org/img/wn/$iconTempForDayFour@2x.png",
contentDescription = "sol",
modifier = Modifier
.width(30.dp)
.height(30.dp)
.clip(CircleShape)
)
Text(
text = tempMinForDayFour.toString().take(2) + "º",
modifier = Modifier.width(40.dp),
color = Color.White,
)
Text(
text = tempMaxForDayFour.toString().take(2) + "º",
style = TextStyle.Default.copy(
Color.White,
)
)
}
Spacer(modifier = Modifier.height(2.dp))
}
}
}
}
}
@Preview
@Composable
fun GreatingPreview() {
WeatherScreen()
}
| 0
|
Kotlin
|
0
| 0
|
ffd467f77b54341b69aa62cbd1f4e8bea424582e
| 20,014
|
weather
|
MIT License
|
feature/attraction_gallery/src/main/java/tw/com/deathhit/feature/attraction_gallery/AttractionGalleryViewModel.kt
|
Deathhit
| 748,190,483
| false
|
{"Kotlin": 197443}
|
package tw.com.deathhit.feature.attraction_gallery
import android.os.Bundle
import android.os.Parcelable
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.parcelize.Parcelize
import tw.com.deathhit.domain.AttractionImageRepository
import tw.com.deathhit.domain.AttractionRepository
import javax.inject.Inject
@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class AttractionGalleryViewModel @Inject constructor(
private val attractionImageRepository: AttractionImageRepository,
private val attractionRepository: AttractionRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val _stateFlow = MutableStateFlow<State>(savedStateHandle[KEY_STATE]!!)
val stateFlow = _stateFlow.asStateFlow()
private var state: State
get() = stateFlow.value
set(value) {
_stateFlow.update { value }
savedStateHandle[KEY_STATE] = value
}
val attractionImageListFlow = createAttractionListFlow().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(),
emptyList()
)
val attractionFlow =
createAttractionFlow().stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)
fun goBack() {
state = state.copy(actions = state.actions + State.Action.GoBack)
}
fun goToImageViewerScreen(imageUrl: String) {
state =
state.copy(
actions = state.actions + State.Action.GoToImageViewerScreen(
imageUrl = imageUrl
)
)
}
fun onAction(action: State.Action) {
state = state.copy(actions = state.actions - action)
}
private fun createAttractionFlow() = stateFlow.map { it.attractionId }.flatMapLatest {
attractionRepository.getAttractionFlow(it)
}
private fun createAttractionListFlow() = stateFlow.map { it.attractionId }.flatMapLatest {
attractionImageRepository.getAttractionImageListFlow(attractionId = it)
}
companion object {
private const val TAG = "AttractionGalleryViewModel"
private const val KEY_STATE = "$TAG.KEY_STATE"
internal fun createArgs(attractionId: String) = Bundle().apply {
putParcelable(
KEY_STATE, State(
attractionId = attractionId
)
)
}
}
@Parcelize
data class State(val actions: List<Action> = emptyList(), val attractionId: String) :
Parcelable {
sealed interface Action : Parcelable {
@Parcelize
data object GoBack : Action
@Parcelize
data class GoToImageViewerScreen(val imageUrl: String) : Action
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d76f4a3f3d3f0310e3a8b551efa11f46c3c54a30
| 3,209
|
TaipeiTour
|
Apache License 2.0
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/frauddetector/CfnDetector.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.frauddetector
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.ITaggable
import io.cloudshiftdev.awscdk.TagManager
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* Manages a detector and associated detector versions.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* CfnDetector cfnDetector = CfnDetector.Builder.create(this, "MyCfnDetector")
* .detectorId("detectorId")
* .eventType(EventTypeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .entityTypes(List.of(EntityTypeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* .eventVariables(List.of(EventVariableProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .dataSource("dataSource")
* .dataType("dataType")
* .defaultValue("defaultValue")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .variableType("variableType")
* .build()))
* .inline(false)
* .labels(List.of(LabelProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build())
* .rules(List.of(RuleProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .detectorId("detectorId")
* .expression("expression")
* .language("language")
* .lastUpdatedTime("lastUpdatedTime")
* .outcomes(List.of(OutcomeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* .ruleId("ruleId")
* .ruleVersion("ruleVersion")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* // the properties below are optional
* .associatedModels(List.of(ModelProperty.builder()
* .arn("arn")
* .build()))
* .description("description")
* .detectorVersionStatus("detectorVersionStatus")
* .ruleExecutionMode("ruleExecutionMode")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html)
*/
public open class CfnDetector(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector,
) : CfnResource(cdkObject), IInspectable, ITaggable {
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnDetectorProps,
) :
this(software.amazon.awscdk.services.frauddetector.CfnDetector(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id, props.let(CfnDetectorProps.Companion::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnDetectorProps.Builder.() -> Unit,
) : this(scope, id, CfnDetectorProps(props)
)
/**
* The models to associate with this detector.
*/
public open fun associatedModels(): Any? = unwrap(this).getAssociatedModels()
/**
* The models to associate with this detector.
*/
public open fun associatedModels(`value`: IResolvable) {
unwrap(this).setAssociatedModels(`value`.let(IResolvable.Companion::unwrap))
}
/**
* The models to associate with this detector.
*/
public open fun associatedModels(`value`: List<Any>) {
unwrap(this).setAssociatedModels(`value`.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The models to associate with this detector.
*/
public open fun associatedModels(vararg `value`: Any): Unit = associatedModels(`value`.toList())
/**
* The detector ARN.
*/
public open fun attrArn(): String = unwrap(this).getAttrArn()
/**
* Timestamp of when detector was created.
*/
public open fun attrCreatedTime(): String = unwrap(this).getAttrCreatedTime()
/**
* The name of the detector.
*/
public open fun attrDetectorVersionId(): String = unwrap(this).getAttrDetectorVersionId()
/**
* The detector ARN.
*/
public open fun attrEventTypeArn(): String = unwrap(this).getAttrEventTypeArn()
/**
* Timestamp of when the detector was created.
*/
public open fun attrEventTypeCreatedTime(): String = unwrap(this).getAttrEventTypeCreatedTime()
/**
* Timestamp of when the detector was last updated.
*/
public open fun attrEventTypeLastUpdatedTime(): String =
unwrap(this).getAttrEventTypeLastUpdatedTime()
/**
* Timestamp of when detector was last updated.
*/
public open fun attrLastUpdatedTime(): String = unwrap(this).getAttrLastUpdatedTime()
/**
* The detector description.
*/
public open fun description(): String? = unwrap(this).getDescription()
/**
* The detector description.
*/
public open fun description(`value`: String) {
unwrap(this).setDescription(`value`)
}
/**
* The name of the detector.
*/
public open fun detectorId(): String = unwrap(this).getDetectorId()
/**
* The name of the detector.
*/
public open fun detectorId(`value`: String) {
unwrap(this).setDetectorId(`value`)
}
/**
* The status of the detector version.
*/
public open fun detectorVersionStatus(): String? = unwrap(this).getDetectorVersionStatus()
/**
* The status of the detector version.
*/
public open fun detectorVersionStatus(`value`: String) {
unwrap(this).setDetectorVersionStatus(`value`)
}
/**
* The event type associated with this detector.
*/
public open fun eventType(): Any = unwrap(this).getEventType()
/**
* The event type associated with this detector.
*/
public open fun eventType(`value`: IResolvable) {
unwrap(this).setEventType(`value`.let(IResolvable.Companion::unwrap))
}
/**
* The event type associated with this detector.
*/
public open fun eventType(`value`: EventTypeProperty) {
unwrap(this).setEventType(`value`.let(EventTypeProperty.Companion::unwrap))
}
/**
* The event type associated with this detector.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("ea093576b787a8e47cd555312a920e21e9d568a6c1930d5c16c16d353c1140a4")
public open fun eventType(`value`: EventTypeProperty.Builder.() -> Unit): Unit =
eventType(EventTypeProperty(`value`))
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector.Companion::unwrap))
}
/**
* The rule execution mode for the rules included in the detector version.
*/
public open fun ruleExecutionMode(): String? = unwrap(this).getRuleExecutionMode()
/**
* The rule execution mode for the rules included in the detector version.
*/
public open fun ruleExecutionMode(`value`: String) {
unwrap(this).setRuleExecutionMode(`value`)
}
/**
* The rules to include in the detector version.
*/
public open fun rules(): Any = unwrap(this).getRules()
/**
* The rules to include in the detector version.
*/
public open fun rules(`value`: IResolvable) {
unwrap(this).setRules(`value`.let(IResolvable.Companion::unwrap))
}
/**
* The rules to include in the detector version.
*/
public open fun rules(`value`: List<Any>) {
unwrap(this).setRules(`value`.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The rules to include in the detector version.
*/
public open fun rules(vararg `value`: Any): Unit = rules(`value`.toList())
/**
* Tag Manager which manages the tags for this resource.
*/
public override fun tags(): TagManager = unwrap(this).getTags().let(TagManager::wrap)
/**
* An array of key-value pairs to apply to this resource.
*/
public open fun tagsRaw(): List<CfnTag> = unwrap(this).getTagsRaw()?.map(CfnTag::wrap) ?:
emptyList()
/**
* An array of key-value pairs to apply to this resource.
*/
public open fun tagsRaw(`value`: List<CfnTag>) {
unwrap(this).setTagsRaw(`value`.map(CfnTag.Companion::unwrap))
}
/**
* An array of key-value pairs to apply to this resource.
*/
public open fun tagsRaw(vararg `value`: CfnTag): Unit = tagsRaw(`value`.toList())
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.frauddetector.CfnDetector].
*/
@CdkDslMarker
public interface Builder {
/**
* The models to associate with this detector.
*
* You must provide the ARNs of all the models you want to associate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-associatedmodels)
* @param associatedModels The models to associate with this detector.
*/
public fun associatedModels(associatedModels: IResolvable)
/**
* The models to associate with this detector.
*
* You must provide the ARNs of all the models you want to associate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-associatedmodels)
* @param associatedModels The models to associate with this detector.
*/
public fun associatedModels(associatedModels: List<Any>)
/**
* The models to associate with this detector.
*
* You must provide the ARNs of all the models you want to associate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-associatedmodels)
* @param associatedModels The models to associate with this detector.
*/
public fun associatedModels(vararg associatedModels: Any)
/**
* The detector description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-description)
* @param description The detector description.
*/
public fun description(description: String)
/**
* The name of the detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-detectorid)
* @param detectorId The name of the detector.
*/
public fun detectorId(detectorId: String)
/**
* The status of the detector version.
*
* If a value is not provided for this property, AWS CloudFormation assumes `DRAFT` status.
*
* Valid values: `ACTIVE | DRAFT`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-detectorversionstatus)
* @param detectorVersionStatus The status of the detector version.
*/
public fun detectorVersionStatus(detectorVersionStatus: String)
/**
* The event type associated with this detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-eventtype)
* @param eventType The event type associated with this detector.
*/
public fun eventType(eventType: IResolvable)
/**
* The event type associated with this detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-eventtype)
* @param eventType The event type associated with this detector.
*/
public fun eventType(eventType: EventTypeProperty)
/**
* The event type associated with this detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-eventtype)
* @param eventType The event type associated with this detector.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1908bdf3c79730411659f2ed378d0a4ec38565e5f69568f793a845c4056359a0")
public fun eventType(eventType: EventTypeProperty.Builder.() -> Unit)
/**
* The rule execution mode for the rules included in the detector version.
*
* Valid values: `FIRST_MATCHED | ALL_MATCHED` Default value: `FIRST_MATCHED`
*
* You can define and edit the rule mode at the detector version level, when it is in draft
* status.
*
* If you specify `FIRST_MATCHED` , Amazon Fraud Detector evaluates rules sequentially, first to
* last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for
* that single rule.
*
* If you specifiy `ALL_MATCHED` , Amazon Fraud Detector evaluates all rules and returns the
* outcomes for all matched rules.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-ruleexecutionmode)
* @param ruleExecutionMode The rule execution mode for the rules included in the detector
* version.
*/
public fun ruleExecutionMode(ruleExecutionMode: String)
/**
* The rules to include in the detector version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-rules)
* @param rules The rules to include in the detector version.
*/
public fun rules(rules: IResolvable)
/**
* The rules to include in the detector version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-rules)
* @param rules The rules to include in the detector version.
*/
public fun rules(rules: List<Any>)
/**
* The rules to include in the detector version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-rules)
* @param rules The rules to include in the detector version.
*/
public fun rules(vararg rules: Any)
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-tags)
* @param tags An array of key-value pairs to apply to this resource.
*/
public fun tags(tags: List<CfnTag>)
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-tags)
* @param tags An array of key-value pairs to apply to this resource.
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.frauddetector.CfnDetector.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.Builder.create(scope, id)
/**
* The models to associate with this detector.
*
* You must provide the ARNs of all the models you want to associate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-associatedmodels)
* @param associatedModels The models to associate with this detector.
*/
override fun associatedModels(associatedModels: IResolvable) {
cdkBuilder.associatedModels(associatedModels.let(IResolvable.Companion::unwrap))
}
/**
* The models to associate with this detector.
*
* You must provide the ARNs of all the models you want to associate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-associatedmodels)
* @param associatedModels The models to associate with this detector.
*/
override fun associatedModels(associatedModels: List<Any>) {
cdkBuilder.associatedModels(associatedModels.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The models to associate with this detector.
*
* You must provide the ARNs of all the models you want to associate.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-associatedmodels)
* @param associatedModels The models to associate with this detector.
*/
override fun associatedModels(vararg associatedModels: Any): Unit =
associatedModels(associatedModels.toList())
/**
* The detector description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-description)
* @param description The detector description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* The name of the detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-detectorid)
* @param detectorId The name of the detector.
*/
override fun detectorId(detectorId: String) {
cdkBuilder.detectorId(detectorId)
}
/**
* The status of the detector version.
*
* If a value is not provided for this property, AWS CloudFormation assumes `DRAFT` status.
*
* Valid values: `ACTIVE | DRAFT`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-detectorversionstatus)
* @param detectorVersionStatus The status of the detector version.
*/
override fun detectorVersionStatus(detectorVersionStatus: String) {
cdkBuilder.detectorVersionStatus(detectorVersionStatus)
}
/**
* The event type associated with this detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-eventtype)
* @param eventType The event type associated with this detector.
*/
override fun eventType(eventType: IResolvable) {
cdkBuilder.eventType(eventType.let(IResolvable.Companion::unwrap))
}
/**
* The event type associated with this detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-eventtype)
* @param eventType The event type associated with this detector.
*/
override fun eventType(eventType: EventTypeProperty) {
cdkBuilder.eventType(eventType.let(EventTypeProperty.Companion::unwrap))
}
/**
* The event type associated with this detector.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-eventtype)
* @param eventType The event type associated with this detector.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1908bdf3c79730411659f2ed378d0a4ec38565e5f69568f793a845c4056359a0")
override fun eventType(eventType: EventTypeProperty.Builder.() -> Unit): Unit =
eventType(EventTypeProperty(eventType))
/**
* The rule execution mode for the rules included in the detector version.
*
* Valid values: `FIRST_MATCHED | ALL_MATCHED` Default value: `FIRST_MATCHED`
*
* You can define and edit the rule mode at the detector version level, when it is in draft
* status.
*
* If you specify `FIRST_MATCHED` , Amazon Fraud Detector evaluates rules sequentially, first to
* last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for
* that single rule.
*
* If you specifiy `ALL_MATCHED` , Amazon Fraud Detector evaluates all rules and returns the
* outcomes for all matched rules.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-ruleexecutionmode)
* @param ruleExecutionMode The rule execution mode for the rules included in the detector
* version.
*/
override fun ruleExecutionMode(ruleExecutionMode: String) {
cdkBuilder.ruleExecutionMode(ruleExecutionMode)
}
/**
* The rules to include in the detector version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-rules)
* @param rules The rules to include in the detector version.
*/
override fun rules(rules: IResolvable) {
cdkBuilder.rules(rules.let(IResolvable.Companion::unwrap))
}
/**
* The rules to include in the detector version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-rules)
* @param rules The rules to include in the detector version.
*/
override fun rules(rules: List<Any>) {
cdkBuilder.rules(rules.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The rules to include in the detector version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-rules)
* @param rules The rules to include in the detector version.
*/
override fun rules(vararg rules: Any): Unit = rules(rules.toList())
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-tags)
* @param tags An array of key-value pairs to apply to this resource.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-frauddetector-detector.html#cfn-frauddetector-detector-tags)
* @param tags An array of key-value pairs to apply to this resource.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.frauddetector.CfnDetector =
cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.frauddetector.CfnDetector.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnDetector {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnDetector(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector):
CfnDetector = CfnDetector(cdkObject)
internal fun unwrap(wrapped: CfnDetector):
software.amazon.awscdk.services.frauddetector.CfnDetector = wrapped.cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector
}
/**
* The entity type details.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* EntityTypeProperty entityTypeProperty = EntityTypeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html)
*/
public interface EntityTypeProperty {
/**
* The entity type ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp of when the entity type was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-createdtime)
*/
public fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The entity type description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts the
* create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these Variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-inline)
*/
public fun `inline`(): Any? = unwrap(this).getInline()
/**
* Timestamp of when the entity type was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-lastupdatedtime)
*/
public fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The entity type name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-name)
*/
public fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [EntityTypeProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The entity type ARN.
*/
public fun arn(arn: String)
/**
* @param createdTime Timestamp of when the entity type was created.
*/
public fun createdTime(createdTime: String)
/**
* @param description The entity type description.
*/
public fun description(description: String)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these Variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: Boolean)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these Variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: IResolvable)
/**
* @param lastUpdatedTime Timestamp of when the entity type was last updated.
*/
public fun lastUpdatedTime(lastUpdatedTime: String)
/**
* @param name The entity type name.
*/
public fun name(name: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty.builder()
/**
* @param arn The entity type ARN.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
/**
* @param createdTime Timestamp of when the entity type was created.
*/
override fun createdTime(createdTime: String) {
cdkBuilder.createdTime(createdTime)
}
/**
* @param description The entity type description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these Variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: Boolean) {
cdkBuilder.`inline`(`inline`)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these Variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: IResolvable) {
cdkBuilder.`inline`(`inline`.let(IResolvable.Companion::unwrap))
}
/**
* @param lastUpdatedTime Timestamp of when the entity type was last updated.
*/
override fun lastUpdatedTime(lastUpdatedTime: String) {
cdkBuilder.lastUpdatedTime(lastUpdatedTime)
}
/**
* @param name The entity type name.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build():
software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty,
) : CdkObject(cdkObject), EntityTypeProperty {
/**
* The entity type ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp of when the entity type was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-createdtime)
*/
override fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The entity type description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts
* the create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these Variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-inline)
*/
override fun `inline`(): Any? = unwrap(this).getInline()
/**
* Timestamp of when the entity type was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-lastupdatedtime)
*/
override fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The entity type name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-name)
*/
override fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-entitytype.html#cfn-frauddetector-detector-entitytype-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): EntityTypeProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty):
EntityTypeProperty = CdkObjectWrappers.wrap(cdkObject) as? EntityTypeProperty ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: EntityTypeProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.EntityTypeProperty
}
}
/**
* The event type details.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* EventTypeProperty eventTypeProperty = EventTypeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .entityTypes(List.of(EntityTypeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* .eventVariables(List.of(EventVariableProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .dataSource("dataSource")
* .dataType("dataType")
* .defaultValue("defaultValue")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .variableType("variableType")
* .build()))
* .inline(false)
* .labels(List.of(LabelProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html)
*/
public interface EventTypeProperty {
/**
* The entity type ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp of when the event type was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-createdtime)
*/
public fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The event type description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* The event type entity types.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-entitytypes)
*/
public fun entityTypes(): Any? = unwrap(this).getEntityTypes()
/**
* The event type event variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-eventvariables)
*/
public fun eventVariables(): Any? = unwrap(this).getEventVariables()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts the
* create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the Variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-inline)
*/
public fun `inline`(): Any? = unwrap(this).getInline()
/**
* The event type labels.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-labels)
*/
public fun labels(): Any? = unwrap(this).getLabels()
/**
* Timestamp of when the event type was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-lastupdatedtime)
*/
public fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The event type name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-name)
*/
public fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [EventTypeProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The entity type ARN.
*/
public fun arn(arn: String)
/**
* @param createdTime Timestamp of when the event type was created.
*/
public fun createdTime(createdTime: String)
/**
* @param description The event type description.
*/
public fun description(description: String)
/**
* @param entityTypes The event type entity types.
*/
public fun entityTypes(entityTypes: IResolvable)
/**
* @param entityTypes The event type entity types.
*/
public fun entityTypes(entityTypes: List<Any>)
/**
* @param entityTypes The event type entity types.
*/
public fun entityTypes(vararg entityTypes: Any)
/**
* @param eventVariables The event type event variables.
*/
public fun eventVariables(eventVariables: IResolvable)
/**
* @param eventVariables The event type event variables.
*/
public fun eventVariables(eventVariables: List<Any>)
/**
* @param eventVariables The event type event variables.
*/
public fun eventVariables(vararg eventVariables: Any)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the Variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: Boolean)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the Variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: IResolvable)
/**
* @param labels The event type labels.
*/
public fun labels(labels: IResolvable)
/**
* @param labels The event type labels.
*/
public fun labels(labels: List<Any>)
/**
* @param labels The event type labels.
*/
public fun labels(vararg labels: Any)
/**
* @param lastUpdatedTime Timestamp of when the event type was last updated.
*/
public fun lastUpdatedTime(lastUpdatedTime: String)
/**
* @param name The event type name.
*/
public fun name(name: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty.builder()
/**
* @param arn The entity type ARN.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
/**
* @param createdTime Timestamp of when the event type was created.
*/
override fun createdTime(createdTime: String) {
cdkBuilder.createdTime(createdTime)
}
/**
* @param description The event type description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param entityTypes The event type entity types.
*/
override fun entityTypes(entityTypes: IResolvable) {
cdkBuilder.entityTypes(entityTypes.let(IResolvable.Companion::unwrap))
}
/**
* @param entityTypes The event type entity types.
*/
override fun entityTypes(entityTypes: List<Any>) {
cdkBuilder.entityTypes(entityTypes.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param entityTypes The event type entity types.
*/
override fun entityTypes(vararg entityTypes: Any): Unit = entityTypes(entityTypes.toList())
/**
* @param eventVariables The event type event variables.
*/
override fun eventVariables(eventVariables: IResolvable) {
cdkBuilder.eventVariables(eventVariables.let(IResolvable.Companion::unwrap))
}
/**
* @param eventVariables The event type event variables.
*/
override fun eventVariables(eventVariables: List<Any>) {
cdkBuilder.eventVariables(eventVariables.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param eventVariables The event type event variables.
*/
override fun eventVariables(vararg eventVariables: Any): Unit =
eventVariables(eventVariables.toList())
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the Variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: Boolean) {
cdkBuilder.`inline`(`inline`)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the Variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: IResolvable) {
cdkBuilder.`inline`(`inline`.let(IResolvable.Companion::unwrap))
}
/**
* @param labels The event type labels.
*/
override fun labels(labels: IResolvable) {
cdkBuilder.labels(labels.let(IResolvable.Companion::unwrap))
}
/**
* @param labels The event type labels.
*/
override fun labels(labels: List<Any>) {
cdkBuilder.labels(labels.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param labels The event type labels.
*/
override fun labels(vararg labels: Any): Unit = labels(labels.toList())
/**
* @param lastUpdatedTime Timestamp of when the event type was last updated.
*/
override fun lastUpdatedTime(lastUpdatedTime: String) {
cdkBuilder.lastUpdatedTime(lastUpdatedTime)
}
/**
* @param name The event type name.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build():
software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty,
) : CdkObject(cdkObject), EventTypeProperty {
/**
* The entity type ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp of when the event type was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-createdtime)
*/
override fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The event type description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* The event type entity types.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-entitytypes)
*/
override fun entityTypes(): Any? = unwrap(this).getEntityTypes()
/**
* The event type event variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-eventvariables)
*/
override fun eventVariables(): Any? = unwrap(this).getEventVariables()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts
* the create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the Variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-inline)
*/
override fun `inline`(): Any? = unwrap(this).getInline()
/**
* The event type labels.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-labels)
*/
override fun labels(): Any? = unwrap(this).getLabels()
/**
* Timestamp of when the event type was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-lastupdatedtime)
*/
override fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The event type name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-name)
*/
override fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventtype.html#cfn-frauddetector-detector-eventtype-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): EventTypeProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty):
EventTypeProperty = CdkObjectWrappers.wrap(cdkObject) as? EventTypeProperty ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: EventTypeProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.EventTypeProperty
}
}
/**
* The event type variable for the detector.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* EventVariableProperty eventVariableProperty = EventVariableProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .dataSource("dataSource")
* .dataType("dataType")
* .defaultValue("defaultValue")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .variableType("variableType")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html)
*/
public interface EventVariableProperty {
/**
* The event variable ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp for when the event variable was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-createdtime)
*/
public fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The data source of the event variable.
*
* Valid values: `EVENT | EXTERNAL_MODEL_SCORE`
*
* When defining a variable within a detector, you can only use the `EVENT` value for DataSource
* when the *Inline* property is set to true. If the *Inline* property is set false, you can use
* either `EVENT` or `MODEL_SCORE` for DataSource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-datasource)
*/
public fun dataSource(): String? = unwrap(this).getDataSource()
/**
* The data type of the event variable.
*
* Valid values: `STRING | INTEGER | BOOLEAN | FLOAT`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-datatype)
*/
public fun dataType(): String? = unwrap(this).getDataType()
/**
* The default value of the event variable.
*
* This is required if you are providing the details of your variables instead of the ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-defaultvalue)
*/
public fun defaultValue(): String? = unwrap(this).getDefaultValue()
/**
* The description of the event variable.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts the
* create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-inline)
*/
public fun `inline`(): Any? = unwrap(this).getInline()
/**
* Timestamp for when the event variable was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-lastupdatedtime)
*/
public fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The name of the event variable.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-name)
*/
public fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* The type of event variable.
*
* For more information, see [Variable
* types](https://docs.aws.amazon.com/frauddetector/latest/ug/create-a-variable.html#variable-types)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-variabletype)
*/
public fun variableType(): String? = unwrap(this).getVariableType()
/**
* A builder for [EventVariableProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The event variable ARN.
*/
public fun arn(arn: String)
/**
* @param createdTime Timestamp for when the event variable was created.
*/
public fun createdTime(createdTime: String)
/**
* @param dataSource The data source of the event variable.
* Valid values: `EVENT | EXTERNAL_MODEL_SCORE`
*
* When defining a variable within a detector, you can only use the `EVENT` value for
* DataSource when the *Inline* property is set to true. If the *Inline* property is set false,
* you can use either `EVENT` or `MODEL_SCORE` for DataSource.
*/
public fun dataSource(dataSource: String)
/**
* @param dataType The data type of the event variable.
* Valid values: `STRING | INTEGER | BOOLEAN | FLOAT`
*/
public fun dataType(dataType: String)
/**
* @param defaultValue The default value of the event variable.
* This is required if you are providing the details of your variables instead of the ARN.
*/
public fun defaultValue(defaultValue: String)
/**
* @param description The description of the event variable.
*/
public fun description(description: String)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: Boolean)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: IResolvable)
/**
* @param lastUpdatedTime Timestamp for when the event variable was last updated.
*/
public fun lastUpdatedTime(lastUpdatedTime: String)
/**
* @param name The name of the event variable.
*/
public fun name(name: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
/**
* @param variableType The type of event variable.
* For more information, see [Variable
* types](https://docs.aws.amazon.com/frauddetector/latest/ug/create-a-variable.html#variable-types)
* .
*/
public fun variableType(variableType: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty.builder()
/**
* @param arn The event variable ARN.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
/**
* @param createdTime Timestamp for when the event variable was created.
*/
override fun createdTime(createdTime: String) {
cdkBuilder.createdTime(createdTime)
}
/**
* @param dataSource The data source of the event variable.
* Valid values: `EVENT | EXTERNAL_MODEL_SCORE`
*
* When defining a variable within a detector, you can only use the `EVENT` value for
* DataSource when the *Inline* property is set to true. If the *Inline* property is set false,
* you can use either `EVENT` or `MODEL_SCORE` for DataSource.
*/
override fun dataSource(dataSource: String) {
cdkBuilder.dataSource(dataSource)
}
/**
* @param dataType The data type of the event variable.
* Valid values: `STRING | INTEGER | BOOLEAN | FLOAT`
*/
override fun dataType(dataType: String) {
cdkBuilder.dataType(dataType)
}
/**
* @param defaultValue The default value of the event variable.
* This is required if you are providing the details of your variables instead of the ARN.
*/
override fun defaultValue(defaultValue: String) {
cdkBuilder.defaultValue(defaultValue)
}
/**
* @param description The description of the event variable.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: Boolean) {
cdkBuilder.`inline`(`inline`)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: IResolvable) {
cdkBuilder.`inline`(`inline`.let(IResolvable.Companion::unwrap))
}
/**
* @param lastUpdatedTime Timestamp for when the event variable was last updated.
*/
override fun lastUpdatedTime(lastUpdatedTime: String) {
cdkBuilder.lastUpdatedTime(lastUpdatedTime)
}
/**
* @param name The name of the event variable.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
/**
* @param variableType The type of event variable.
* For more information, see [Variable
* types](https://docs.aws.amazon.com/frauddetector/latest/ug/create-a-variable.html#variable-types)
* .
*/
override fun variableType(variableType: String) {
cdkBuilder.variableType(variableType)
}
public fun build():
software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty,
) : CdkObject(cdkObject), EventVariableProperty {
/**
* The event variable ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp for when the event variable was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-createdtime)
*/
override fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The data source of the event variable.
*
* Valid values: `EVENT | EXTERNAL_MODEL_SCORE`
*
* When defining a variable within a detector, you can only use the `EVENT` value for
* DataSource when the *Inline* property is set to true. If the *Inline* property is set false,
* you can use either `EVENT` or `MODEL_SCORE` for DataSource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-datasource)
*/
override fun dataSource(): String? = unwrap(this).getDataSource()
/**
* The data type of the event variable.
*
* Valid values: `STRING | INTEGER | BOOLEAN | FLOAT`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-datatype)
*/
override fun dataType(): String? = unwrap(this).getDataType()
/**
* The default value of the event variable.
*
* This is required if you are providing the details of your variables instead of the ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-defaultvalue)
*/
override fun defaultValue(): String? = unwrap(this).getDefaultValue()
/**
* The description of the event variable.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts
* the create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-inline)
*/
override fun `inline`(): Any? = unwrap(this).getInline()
/**
* Timestamp for when the event variable was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-lastupdatedtime)
*/
override fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The name of the event variable.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-name)
*/
override fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* The type of event variable.
*
* For more information, see [Variable
* types](https://docs.aws.amazon.com/frauddetector/latest/ug/create-a-variable.html#variable-types)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-eventvariable.html#cfn-frauddetector-detector-eventvariable-variabletype)
*/
override fun variableType(): String? = unwrap(this).getVariableType()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): EventVariableProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty):
EventVariableProperty = CdkObjectWrappers.wrap(cdkObject) as? EventVariableProperty ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: EventVariableProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty = (wrapped
as CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.EventVariableProperty
}
}
/**
* The label details.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* LabelProperty labelProperty = LabelProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html)
*/
public interface LabelProperty {
/**
* The label ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp of when the event type was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-createdtime)
*/
public fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The label description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts the
* create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-inline)
*/
public fun `inline`(): Any? = unwrap(this).getInline()
/**
* Timestamp of when the label was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-lastupdatedtime)
*/
public fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The label name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-name)
*/
public fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [LabelProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The label ARN.
*/
public fun arn(arn: String)
/**
* @param createdTime Timestamp of when the event type was created.
*/
public fun createdTime(createdTime: String)
/**
* @param description The label description.
*/
public fun description(description: String)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: Boolean)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: IResolvable)
/**
* @param lastUpdatedTime Timestamp of when the label was last updated.
*/
public fun lastUpdatedTime(lastUpdatedTime: String)
/**
* @param name The label name.
*/
public fun name(name: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty.builder()
/**
* @param arn The label ARN.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
/**
* @param createdTime Timestamp of when the event type was created.
*/
override fun createdTime(createdTime: String) {
cdkBuilder.createdTime(createdTime)
}
/**
* @param description The label description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: Boolean) {
cdkBuilder.`inline`(`inline`)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: IResolvable) {
cdkBuilder.`inline`(`inline`.let(IResolvable.Companion::unwrap))
}
/**
* @param lastUpdatedTime Timestamp of when the label was last updated.
*/
override fun lastUpdatedTime(lastUpdatedTime: String) {
cdkBuilder.lastUpdatedTime(lastUpdatedTime)
}
/**
* @param name The label name.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty,
) : CdkObject(cdkObject), LabelProperty {
/**
* The label ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp of when the event type was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-createdtime)
*/
override fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The label description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts
* the create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-inline)
*/
override fun `inline`(): Any? = unwrap(this).getInline()
/**
* Timestamp of when the label was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-lastupdatedtime)
*/
override fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The label name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-name)
*/
override fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-label.html#cfn-frauddetector-detector-label-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): LabelProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty):
LabelProperty = CdkObjectWrappers.wrap(cdkObject) as? LabelProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: LabelProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.LabelProperty
}
}
/**
* The model.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* ModelProperty modelProperty = ModelProperty.builder()
* .arn("arn")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-model.html)
*/
public interface ModelProperty {
/**
* The ARN of the model.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-model.html#cfn-frauddetector-detector-model-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* A builder for [ModelProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The ARN of the model.
*/
public fun arn(arn: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty.builder()
/**
* @param arn The ARN of the model.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
public fun build(): software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty,
) : CdkObject(cdkObject), ModelProperty {
/**
* The ARN of the model.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-model.html#cfn-frauddetector-detector-model-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): ModelProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty):
ModelProperty = CdkObjectWrappers.wrap(cdkObject) as? ModelProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: ModelProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.ModelProperty
}
}
/**
* The outcome.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* OutcomeProperty outcomeProperty = OutcomeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html)
*/
public interface OutcomeProperty {
/**
* The outcome ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* The timestamp when the outcome was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-createdtime)
*/
public fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The outcome description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts the
* create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-inline)
*/
public fun `inline`(): Any? = unwrap(this).getInline()
/**
* The timestamp when the outcome was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-lastupdatedtime)
*/
public fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The outcome name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-name)
*/
public fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [OutcomeProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The outcome ARN.
*/
public fun arn(arn: String)
/**
* @param createdTime The timestamp when the outcome was created.
*/
public fun createdTime(createdTime: String)
/**
* @param description The outcome description.
*/
public fun description(description: String)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: Boolean)
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
public fun `inline`(`inline`: IResolvable)
/**
* @param lastUpdatedTime The timestamp when the outcome was last updated.
*/
public fun lastUpdatedTime(lastUpdatedTime: String)
/**
* @param name The outcome name.
*/
public fun name(name: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty.builder()
/**
* @param arn The outcome ARN.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
/**
* @param createdTime The timestamp when the outcome was created.
*/
override fun createdTime(createdTime: String) {
cdkBuilder.createdTime(createdTime)
}
/**
* @param description The outcome description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: Boolean) {
cdkBuilder.`inline`(`inline`)
}
/**
* @param inline Indicates whether the resource is defined within this CloudFormation template
* and impacts the create, update, and delete behavior of the stack.
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*/
override fun `inline`(`inline`: IResolvable) {
cdkBuilder.`inline`(`inline`.let(IResolvable.Companion::unwrap))
}
/**
* @param lastUpdatedTime The timestamp when the outcome was last updated.
*/
override fun lastUpdatedTime(lastUpdatedTime: String) {
cdkBuilder.lastUpdatedTime(lastUpdatedTime)
}
/**
* @param name The outcome name.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty
= cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty,
) : CdkObject(cdkObject), OutcomeProperty {
/**
* The outcome ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
/**
* The timestamp when the outcome was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-createdtime)
*/
override fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The outcome description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* Indicates whether the resource is defined within this CloudFormation template and impacts
* the create, update, and delete behavior of the stack.
*
* If the value is `true` , CloudFormation will create/update/delete the resource when
* creating/updating/deleting the stack. If the value is `false` , CloudFormation will validate
* that the object exists and then use it within the resource without making changes to the
* object.
*
* For example, when creating `AWS::FraudDetector::Detector` you must define at least two
* variables. You can set `Inline=true` for these variables and CloudFormation will
* create/update/delete the variables as part of stack operations. However, if you set
* `Inline=false` , CloudFormation will associate the variables to your detector but not execute
* any changes to the variables.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-inline)
*/
override fun `inline`(): Any? = unwrap(this).getInline()
/**
* The timestamp when the outcome was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-lastupdatedtime)
*/
override fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The outcome name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-name)
*/
override fun name(): String? = unwrap(this).getName()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-outcome.html#cfn-frauddetector-detector-outcome-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): OutcomeProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty):
OutcomeProperty = CdkObjectWrappers.wrap(cdkObject) as? OutcomeProperty ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: OutcomeProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.OutcomeProperty
}
}
/**
* A rule.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.frauddetector.*;
* RuleProperty ruleProperty = RuleProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .detectorId("detectorId")
* .expression("expression")
* .language("language")
* .lastUpdatedTime("lastUpdatedTime")
* .outcomes(List.of(OutcomeProperty.builder()
* .arn("arn")
* .createdTime("createdTime")
* .description("description")
* .inline(false)
* .lastUpdatedTime("lastUpdatedTime")
* .name("name")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build()))
* .ruleId("ruleId")
* .ruleVersion("ruleVersion")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html)
*/
public interface RuleProperty {
/**
* The rule ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-arn)
*/
public fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp for when the rule was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-createdtime)
*/
public fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The rule description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* The detector for which the rule is associated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-detectorid)
*/
public fun detectorId(): String? = unwrap(this).getDetectorId()
/**
* The rule expression.
*
* A rule expression captures the business logic. For more information, see [Rule language
* reference](https://docs.aws.amazon.com/frauddetector/latest/ug/rule-language-reference.html) .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-expression)
*/
public fun expression(): String? = unwrap(this).getExpression()
/**
* The rule language.
*
* Valid Value: DETECTORPL
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-language)
*/
public fun language(): String? = unwrap(this).getLanguage()
/**
* Timestamp for when the rule was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-lastupdatedtime)
*/
public fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The rule outcome.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-outcomes)
*/
public fun outcomes(): Any? = unwrap(this).getOutcomes()
/**
* The rule ID.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-ruleid)
*/
public fun ruleId(): String? = unwrap(this).getRuleId()
/**
* The rule version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-ruleversion)
*/
public fun ruleVersion(): String? = unwrap(this).getRuleVersion()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [RuleProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param arn The rule ARN.
*/
public fun arn(arn: String)
/**
* @param createdTime Timestamp for when the rule was created.
*/
public fun createdTime(createdTime: String)
/**
* @param description The rule description.
*/
public fun description(description: String)
/**
* @param detectorId The detector for which the rule is associated.
*/
public fun detectorId(detectorId: String)
/**
* @param expression The rule expression.
* A rule expression captures the business logic. For more information, see [Rule language
* reference](https://docs.aws.amazon.com/frauddetector/latest/ug/rule-language-reference.html) .
*/
public fun expression(expression: String)
/**
* @param language The rule language.
* Valid Value: DETECTORPL
*/
public fun language(language: String)
/**
* @param lastUpdatedTime Timestamp for when the rule was last updated.
*/
public fun lastUpdatedTime(lastUpdatedTime: String)
/**
* @param outcomes The rule outcome.
*/
public fun outcomes(outcomes: IResolvable)
/**
* @param outcomes The rule outcome.
*/
public fun outcomes(outcomes: List<Any>)
/**
* @param outcomes The rule outcome.
*/
public fun outcomes(vararg outcomes: Any)
/**
* @param ruleId The rule ID.
*/
public fun ruleId(ruleId: String)
/**
* @param ruleVersion The rule version.
*/
public fun ruleVersion(ruleVersion: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty.Builder =
software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty.builder()
/**
* @param arn The rule ARN.
*/
override fun arn(arn: String) {
cdkBuilder.arn(arn)
}
/**
* @param createdTime Timestamp for when the rule was created.
*/
override fun createdTime(createdTime: String) {
cdkBuilder.createdTime(createdTime)
}
/**
* @param description The rule description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param detectorId The detector for which the rule is associated.
*/
override fun detectorId(detectorId: String) {
cdkBuilder.detectorId(detectorId)
}
/**
* @param expression The rule expression.
* A rule expression captures the business logic. For more information, see [Rule language
* reference](https://docs.aws.amazon.com/frauddetector/latest/ug/rule-language-reference.html) .
*/
override fun expression(expression: String) {
cdkBuilder.expression(expression)
}
/**
* @param language The rule language.
* Valid Value: DETECTORPL
*/
override fun language(language: String) {
cdkBuilder.language(language)
}
/**
* @param lastUpdatedTime Timestamp for when the rule was last updated.
*/
override fun lastUpdatedTime(lastUpdatedTime: String) {
cdkBuilder.lastUpdatedTime(lastUpdatedTime)
}
/**
* @param outcomes The rule outcome.
*/
override fun outcomes(outcomes: IResolvable) {
cdkBuilder.outcomes(outcomes.let(IResolvable.Companion::unwrap))
}
/**
* @param outcomes The rule outcome.
*/
override fun outcomes(outcomes: List<Any>) {
cdkBuilder.outcomes(outcomes.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param outcomes The rule outcome.
*/
override fun outcomes(vararg outcomes: Any): Unit = outcomes(outcomes.toList())
/**
* @param ruleId The rule ID.
*/
override fun ruleId(ruleId: String) {
cdkBuilder.ruleId(ruleId)
}
/**
* @param ruleVersion The rule version.
*/
override fun ruleVersion(ruleVersion: String) {
cdkBuilder.ruleVersion(ruleVersion)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty,
) : CdkObject(cdkObject), RuleProperty {
/**
* The rule ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-arn)
*/
override fun arn(): String? = unwrap(this).getArn()
/**
* Timestamp for when the rule was created.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-createdtime)
*/
override fun createdTime(): String? = unwrap(this).getCreatedTime()
/**
* The rule description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* The detector for which the rule is associated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-detectorid)
*/
override fun detectorId(): String? = unwrap(this).getDetectorId()
/**
* The rule expression.
*
* A rule expression captures the business logic. For more information, see [Rule language
* reference](https://docs.aws.amazon.com/frauddetector/latest/ug/rule-language-reference.html) .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-expression)
*/
override fun expression(): String? = unwrap(this).getExpression()
/**
* The rule language.
*
* Valid Value: DETECTORPL
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-language)
*/
override fun language(): String? = unwrap(this).getLanguage()
/**
* Timestamp for when the rule was last updated.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-lastupdatedtime)
*/
override fun lastUpdatedTime(): String? = unwrap(this).getLastUpdatedTime()
/**
* The rule outcome.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-outcomes)
*/
override fun outcomes(): Any? = unwrap(this).getOutcomes()
/**
* The rule ID.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-ruleid)
*/
override fun ruleId(): String? = unwrap(this).getRuleId()
/**
* The rule version.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-ruleversion)
*/
override fun ruleVersion(): String? = unwrap(this).getRuleVersion()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-frauddetector-detector-rule.html#cfn-frauddetector-detector-rule-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): RuleProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty):
RuleProperty = CdkObjectWrappers.wrap(cdkObject) as? RuleProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: RuleProperty):
software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.frauddetector.CfnDetector.RuleProperty
}
}
}
| 3
| null |
0
| 4
|
e15f2e27e08adeb755ad44b2424c195521a6f5ba
| 135,743
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
web/src/main/kotlin/no/nav/su/se/bakover/web/routes/søknadsbehandling/vilkårOgGrunnlag/LeggTilGrunnlagBosituasjonRoutes.kt
|
navikt
| 227,366,088
| false
|
{"Kotlin": 9236522, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800}
|
package no.nav.su.se.bakover.web.routes.søknadsbehandling.vilkårOgGrunnlag
import arrow.core.flatMap
import arrow.core.getOrElse
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.call
import io.ktor.server.routing.Route
import io.ktor.server.routing.post
import no.nav.su.se.bakover.common.audit.AuditLogEvent
import no.nav.su.se.bakover.common.brukerrolle.Brukerrolle
import no.nav.su.se.bakover.common.infrastructure.web.Resultat
import no.nav.su.se.bakover.common.infrastructure.web.audit
import no.nav.su.se.bakover.common.infrastructure.web.authorize
import no.nav.su.se.bakover.common.infrastructure.web.sikkerlogg
import no.nav.su.se.bakover.common.infrastructure.web.suUserContext
import no.nav.su.se.bakover.common.infrastructure.web.svar
import no.nav.su.se.bakover.common.infrastructure.web.withBehandlingId
import no.nav.su.se.bakover.common.infrastructure.web.withBody
import no.nav.su.se.bakover.common.infrastructure.web.withSakId
import no.nav.su.se.bakover.common.serialize
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingId
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService
import no.nav.su.se.bakover.web.routes.grunnlag.LeggTilBosituasjonJsonRequest
import no.nav.su.se.bakover.web.routes.grunnlag.tilResultat
import no.nav.su.se.bakover.web.routes.søknadsbehandling.SØKNADSBEHANDLING_PATH
import no.nav.su.se.bakover.web.routes.søknadsbehandling.toJson
import vilkår.formue.domain.FormuegrenserFactory
internal fun Route.leggTilGrunnlagBosituasjonRoutes(
søknadsbehandlingService: SøknadsbehandlingService,
formuegrenserFactory: FormuegrenserFactory,
) {
post("$SØKNADSBEHANDLING_PATH/{behandlingId}/grunnlag/bosituasjon") {
authorize(Brukerrolle.Saksbehandler) {
call.withSakId { sakId ->
call.withBehandlingId { behandlingId ->
call.withBody<LeggTilBosituasjonJsonRequest> { json ->
call.svar(
json.toService(
SøknadsbehandlingId(behandlingId),
)
.mapLeft { it }
.flatMap {
søknadsbehandlingService.leggTilBosituasjongrunnlag(
it,
call.suUserContext.saksbehandler,
)
.mapLeft { it.tilResultat() }
.map { søknadsbehandling ->
call.audit(
søknadsbehandling.fnr,
AuditLogEvent.Action.UPDATE,
søknadsbehandling.id.value,
)
call.sikkerlogg("Lagret bosituasjon for søknadsbehandling $behandlingId på $sakId")
Resultat.json(
HttpStatusCode.OK,
serialize(søknadsbehandling.toJson(formuegrenserFactory)),
)
}
}.getOrElse { it },
)
}
}
}
}
}
}
| 9
|
Kotlin
|
1
| 1
|
f187a366e1b4ec73bf18f4ebc6a68109494f1c1b
| 3,520
|
su-se-bakover
|
MIT License
|
scheduler/src/test/kotlin/tech/cuda/woden/scheduler/tracker/JobTrackerTest.kt
|
cuda-tech
| 234,125,581
| false
|
{"Kotlin": 532433, "JavaScript": 97771, "Vue": 95927, "CSS": 10200, "Dockerfile": 267, "HTML": 208}
|
/*
* 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 tech.cuda.woden.scheduler.tracker
import io.kotest.matchers.shouldBe
import tech.cuda.woden.scheduler.TestWithDistribution
import tech.cuda.woden.common.service.JobService
import tech.cuda.woden.common.service.po.dtype.JobStatus
import java.time.LocalDateTime
/**
* @author <NAME> <<EMAIL>>
* @since 0.1.0
*/
class JobTrackerTest : TestWithDistribution("job", "task", "container") {
/**
* 各调度格式的任务数
* 周调度:1:6个, 2:9个, 3:7个, 4:5个, 5:10个, 6:6个, 7:6个
* 天调度:73个
* 小时调度: 48个
*
* 2010-08-06: 周五(10) + MONTH(1) + DAY(73) + HOUR(48*24) = 1236
* 2010-08-07: 周六(6) + MONTH(2) + DAY(73) + HOUR(48*24) = 1233
* 2010-08-08: 周日(6) + YEAR(1) + MONTH(1) + DAY(73) + HOUR(48*24) = 1233
* 2010-08-09: 周一(6) + ONCE(1) + MONTH(1) + DAY(73) + HOUR(48*24) = 1233
* 2010-08-10: 周二(9) + ONCE(1) + MONTH(4) + DAY(73) + HOUR(48*24) = 1239
* 2010-08-11: 周三(7) + MONTH(2) + DAY(73) + HOUR(48*24) = 1234
* 2010-08-12: 周四(5) + MONTH(1) + DAY(73) + HOUR(48*24) = 1231
*/
@Test
@Ignore
fun testGenerateJob() {
val expectCount = listOf(1236, 1233, 1233, 1233, 1239, 1234, 1231)
(6..12).forEachIndexed { index, day ->
supposeNowIs(2010, 8, day, 0, 1) {
val now = LocalDateTime.now()
JobService.listing(1, 10, status = JobStatus.INIT, after = now, before = now)
.second shouldBe 0
val jobTracker = JobTracker(afterJobGenerated = {
JobService.listing(1, 10, status = JobStatus.INIT, after = now, before = now)
.second shouldBe expectCount[index]
it.cancel()
})
jobTracker.start()
jobTracker.join()
}
}
}
/**
* Init: 周五(10) + MONTH(1) + DAY(73) + HOUR(48*24) = 1236
* Ready: 2010-08-06: 周五(10) + MONTH(1) + DAY(73) + HOUR(48*1) = 1236
*/
@Test
fun testMakeReadyForInitedJob() = supposeNowIs(2010, 8, 6, 0, 1) {
val now = LocalDateTime.now()
println(now)
JobService.listing(1, 10, status = JobStatus.INIT, after = now, before = now).second shouldBe 0
JobService.listing(1, 10, status = JobStatus.READY, after = now, before = now).second shouldBe 0
val jobTracker = JobTracker(
afterJobGenerated = {
val jobs = JobService.listing(1, 10000, status = JobStatus.INIT, after = now, before = now).first
jobs.size shouldBe 1236
jobs.forEach { it.containerId shouldBe null }
},
afterMakeReady = { tracker ->
// JobService.listing(1, 10, status = JobStatus.INIT, after = now, before = now)
// .second shouldBe 0
val jobs = JobService.listing(1, 10000, status = JobStatus.READY, after = now, before = now).first
jobs.size shouldBe 1236
println(jobs.size)
jobs.forEach { it.containerId shouldBe null }
tracker.cancel()
}
)
jobTracker.start()
jobTracker.join()
}
@Test
@Ignore
fun testMakeRunningForReadyJob() {
val jobTracker = JobTracker(afterMakeRunning = {
it.cancel()
})
jobTracker.start()
jobTracker.join()
}
@Test
@Ignore
fun testCheckInstanceOfRunningJob() {
val jobTracker = JobTracker(afterInstanceCheck = {
it.cancel()
})
jobTracker.start()
jobTracker.join()
}
@Test
@Ignore
fun testRetryForFailedJob() {
val jobTracker = JobTracker(afterRetry = {
it.cancel()
})
jobTracker.start()
jobTracker.join()
}
}
| 0
|
Kotlin
|
0
| 0
|
2efc2de1cad2646ea129637752b15d868ca13c7d
| 4,342
|
woden-deprecated
|
Apache License 2.0
|
platform/lvcs-impl/src/com/intellij/history/integration/ui/models/RevisionData.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.history.integration.ui.models
import com.intellij.history.core.LocalHistoryFacade
import com.intellij.history.core.RevisionsCollector
import com.intellij.history.core.changes.ChangeSet
import com.intellij.history.core.changes.ChangeVisitor
import com.intellij.history.core.changes.StructuralChange
import com.intellij.history.core.revisions.CurrentRevision
import com.intellij.history.core.revisions.Revision
import com.intellij.history.core.tree.RootEntry
import com.intellij.history.integration.IdeaGateway
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PairProcessor
import com.intellij.util.concurrency.annotations.RequiresReadLock
import java.util.*
data class RevisionData(val currentRevision: Revision, val revisions: List<RevisionItem>)
val RevisionData.allRevisions get() = listOf(currentRevision) + revisions.map { it.revision }
internal fun collectRevisionData(project: Project,
gateway: IdeaGateway,
facade: LocalHistoryFacade,
file: VirtualFile,
filter: String? = null,
before: Boolean = true): RevisionData {
return runReadAction {
gateway.registerUnsavedDocuments(facade)
val root = gateway.createTransientRootEntry()
val path = gateway.getPathOrUrl(file)
val revisionItems = collectRevisionItems(project, facade, root, path, filter, before)
RevisionData(CurrentRevision(root, path), revisionItems)
}
}
internal fun collectRevisionItems(project: Project,
gateway: IdeaGateway,
facade: LocalHistoryFacade,
file: VirtualFile,
filter: String?,
before: Boolean): List<RevisionItem> {
return runReadAction {
gateway.registerUnsavedDocuments(facade)
return@runReadAction collectRevisionItems(project, facade, gateway.createTransientRootEntry(), gateway.getPathOrUrl(file), filter, before)
}
}
@RequiresReadLock
private fun collectRevisionItems(project: Project,
facade: LocalHistoryFacade,
root: RootEntry,
path: String,
filter: String?,
before: Boolean): List<RevisionItem> {
return mergeLabelsWithRevisions(RevisionsCollector(facade, root, path, project.getLocationHash(), filter, before).result)
}
private fun mergeLabelsWithRevisions(revisions: List<Revision>): List<RevisionItem> {
val result = mutableListOf<RevisionItem>()
for (revision in revisions.asReversed()) {
if (revision.isLabel && !result.isEmpty()) {
result.last().labels.addFirst(revision)
}
else {
result.add(RevisionItem(revision))
}
}
return result.asReversed()
}
fun LocalHistoryFacade.filterContents(gateway: IdeaGateway, file: VirtualFile, revisions: List<RevisionItem>, filter: String,
before: Boolean): Set<Long> {
val result = mutableSetOf<Long>()
processContents(gateway, file, revisions, before) { revision, content ->
if (Thread.currentThread().isInterrupted) return@processContents false
if (content?.contains(filter, true) == true) {
val id = revision.changeSetId
if (id != null) result.add(id)
}
true
}
return result
}
internal fun LocalHistoryFacade.processContents(gateway: IdeaGateway, file: VirtualFile, revisions: List<RevisionItem>, before: Boolean,
processor: PairProcessor<in Revision, in String?>) {
val revisionMap = revisions.associate { it.revision.changeSetId to it.revision }
if (revisionMap.isEmpty()) return
val root = revisionMap.values.first().root.copy()
var path: String? = gateway.getPathOrUrl(file)
accept(object : ChangeVisitor() {
init {
processContent(revisionMap[null])
}
private fun processContent(revision: Revision?): Boolean {
if (revision == null) return true
val entry = root.findEntry(path)
val content = entry?.content
val text = content?.getString(entry, gateway)
return processor.process(revision, text)
}
override fun begin(c: ChangeSet) {
ProgressManager.checkCanceled()
if (Thread.currentThread().isInterrupted) {
throw ProcessCanceledException()
}
if (!before && !processContent(revisionMap[c.id])) stop()
}
@Throws(StopVisitingException::class)
override fun end(c: ChangeSet) {
if (before && !processContent(revisionMap[c.id])) stop()
}
override fun visit(c: StructuralChange) {
if (c.affectsPath(path)) {
c.revertOn(root, false)
path = c.revertPath(path)
}
}
})
}
| 251
| null |
5079
| 16,158
|
831d1a4524048aebf64173c1f0b26e04b61c6880
| 5,247
|
intellij-community
|
Apache License 2.0
|
goblin-rpc/src/main/java/org/goblinframework/rpc/module/config/RpcRegistryConfigMXBean.kt
|
xiaohaiz
| 206,246,434
| false
| null |
package org.goblinframework.rpc.module.config
import org.goblinframework.api.core.SerializerMode
import java.lang.management.PlatformManagedObject
interface RpcRegistryConfigMXBean : PlatformManagedObject {
fun getZookeeper(): String
fun getConnectionTimeout(): Int
fun getSessionTimeout(): Int
fun getSerializer(): SerializerMode
}
| 0
| null |
6
| 9
|
b1db234912ceb23bdd81ac66a3bf61933b717d0b
| 347
|
goblinframework
|
Apache License 2.0
|
src/main/kotlin/com/casadodev/interfaces/api/api.package.kt
|
casadodev
| 380,860,209
| false
| null |
package com.casadodev.interfaces.api
/**
* Interface protocolo HTTP
*/
| 1
|
Kotlin
|
0
| 1
|
2e7d6ad9c5a457667a0d290d951cb52f137cca7e
| 73
|
bot-twitch-kotlin
|
MIT License
|
app/src/main/java/com/example/lessons_schedule/subjects/components/DeleteSubjectDialog.kt
|
RUD0MIR
| 597,636,190
| false
|
{"Kotlin": 75382}
|
package com.example.lessons_schedule.subjects.components
import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import com.example.lessons_schedule.R
import com.example.lessons_schedule.data.model.Subject
import com.example.lessons_schedule.subjects.SubjectsViewModel
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import java.text.FieldPosition
class DeleteSubjectDialog(
private val subject: Subject
): DialogFragment() {
private val model: SubjectsViewModel by activityViewModels()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = MaterialAlertDialogBuilder(requireContext())
.setTitle(resources.getString(R.string.delete_subject_dialog_title))
.setNeutralButton(resources.getString(R.string.cancel_option)) { _, _ -> }
.setPositiveButton(resources.getString(R.string.delete_option)) { _, _ ->
model.deleteSubject(subject)
}
.create()
dialog.setCanceledOnTouchOutside(false)
return dialog
}
companion object {
const val TAG = "DeleteSubjectDialog"
}
}
| 0
|
Kotlin
|
0
| 0
|
b4ff2a5d4c09e0b4fef40264d5e2ff324c75c507
| 1,232
|
lessons-schedule-manager-app
|
MIT License
|
telegram-bot/src/commonMain/kotlin/eu/vendeli/tgbot/types/MessageId.kt
|
vendelieu
| 496,567,172
| false
| null |
package eu.vendeli.tgbot.types
import eu.vendeli.tgbot.interfaces.MultipleResponse
import kotlinx.serialization.Serializable
/**
* This object represents a unique message identifier.
* @property messageId Unique message identifier
* Api reference: https://core.telegram.org/bots/api#messageid
*/
@Serializable
data class MessageId(val messageId: Long) : MultipleResponse
| 6
| null |
9
| 165
|
c1ddf4a42c577410af31249dc650858320668263
| 376
|
telegram-bot
|
Apache License 2.0
|
app/src/main/java/com/degree106/flashlight/MainActivity.kt
|
degree106
| 350,258,735
| false
| null |
package com.degree106.flashlight
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageButton
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
private var hasFlash: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
hasFlash = applicationContext.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
setButton()
}
private fun setButton () {
val button = findViewById(R.id.btn_main) as ImageButton
button.setOnClickListener{view ->
Snackbar.make(view, "Hello", Snackbar.LENGTH_SHORT).show()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d35b114589230f2b67f03e00ca20b33e917605ef
| 859
|
flashlight
|
Apache License 2.0
|
src/main/kotlin/org/vitrivr/cottontail/database/queries/planning/nodes/logical/transform/DistanceLogicalOperatorNode.kt
|
vitrivr
| 160,775,368
| false
| null |
package org.vitrivr.cottontail.database.queries.planning.nodes.logical.transform
import org.vitrivr.cottontail.database.column.ColumnDef
import org.vitrivr.cottontail.database.queries.OperatorNode
import org.vitrivr.cottontail.database.queries.planning.nodes.logical.UnaryLogicalOperatorNode
import org.vitrivr.cottontail.database.queries.planning.nodes.physical.transform.DistancePhysicalOperatorNode
import org.vitrivr.cottontail.database.queries.predicates.knn.KnnPredicate
import org.vitrivr.cottontail.utilities.math.KnnUtilities
/**
* A [UnaryLogicalOperatorNode] that represents calculating the distance of a certain [ColumnDef] to a certain
* query vector (expressed by a [KnnPredicate]).
*
* This can be used for late population, which can lead to optimized performance for kNN queries
*
* @author Ralph Gasser
* @version 2.1.0
*/
class DistanceLogicalOperatorNode(input: OperatorNode.Logical? = null, val predicate: KnnPredicate) : UnaryLogicalOperatorNode(input) {
companion object {
private const val NODE_NAME = "Distance"
}
/** The name of this [DistanceLogicalOperatorNode]. */
override val name: String
get() = NODE_NAME
/** The [DistanceLogicalOperatorNode] returns the [ColumnDef] of its input + a distance column. */
override val columns: Array<ColumnDef<*>>
get() = (this.input?.columns ?: emptyArray()) + KnnUtilities.distanceColumnDef(this.predicate.column.name.entity())
/** The [DistanceLogicalOperatorNode] requires all [ColumnDef]s used in the [KnnPredicate]. */
override val requires: Array<ColumnDef<*>> = arrayOf(this.predicate.column)
/**
* Creates and returns a copy of this [LimitLogicalOperatorNode] without any children or parents.
*
* @return Copy of this [LimitLogicalOperatorNode].
*/
override fun copy() = DistanceLogicalOperatorNode(predicate = this.predicate)
/**
* Returns a [DistancePhysicalOperatorNode] representation of this [DistanceLogicalOperatorNode]
*
* @return [DistancePhysicalOperatorNode]
*/
override fun implement(): Physical = DistancePhysicalOperatorNode(this.input?.implement(), this.predicate)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is DistanceLogicalOperatorNode) return false
if (predicate != other.predicate) return false
return true
}
/** Generates and returns a [String] representation of this [DistanceLogicalOperatorNode]. */
override fun hashCode(): Int = this.predicate.hashCode()
}
| 8
|
Kotlin
|
11
| 14
|
bd2a7fc1b6add25d43d98e7b5c4187adc758ffb2
| 2,578
|
cottontaildb
|
MIT License
|
feature-single-note/src/main/java/com/stslex/feature_single_note/ui/SingleNoteRoute.kt
|
stslex
| 475,504,690
| false
|
{"Kotlin": 235179}
|
package com.stslex.feature_single_note.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import com.stslex.core.ValueState
import com.stslex.core_model.model.NoteUI
@Composable
fun SingleNoteRoute(popBackStack: () -> Unit, viewModel: SingleNoteViewModel) {
SingleNoteScreen(
modifier = Modifier.windowInsetsPadding(WindowInsets.safeDrawing),
viewModel = viewModel,
popBackStack = popBackStack
)
}
@Composable
fun SingleNoteScreen(
modifier: Modifier = Modifier,
popBackStack: () -> Unit,
viewModel: SingleNoteViewModel
) {
val noteState: State<ValueState<NoteUI>> = viewModel.note.collectAsState()
when (val result = noteState.value) {
is ValueState.Success -> {
val note = remember {
mutableStateOf(result.data)
}
SingleNoteContent(
modifier = modifier,
noteState = note
)
BackHandler(onBack = onBackHandler(note.value, viewModel::updateNote, popBackStack))
}
is ValueState.Failure -> Unit
is ValueState.Loading -> Unit
}
}
private inline fun onBackHandler(
noteUI: NoteUI,
crossinline updateNote: (noteUI: NoteUI) -> Unit,
crossinline popBackStack: () -> Unit
): () -> Unit = {
if (noteUI.getContent().value.isNotEmpty() || noteUI.getTitle().value.isNotEmpty()) {
val createdNote = noteUI.copy(timestamp = System.currentTimeMillis())
updateNote(createdNote)
}
popBackStack()
}
| 4
|
Kotlin
|
0
| 1
|
c3e1e1aeebfdbe014af58117e7293ec38af29bfb
| 1,758
|
CNotes
|
Apache License 2.0
|
tinyarbrowser/src/main/java/com/kkaun/tinyarbrowser/paintables/GpsSymbol.kt
|
kkaun
| 127,122,428
| false
| null |
package com.kkaun.tinyarbrowser.paintables
import android.graphics.Canvas
class GpsSymbol(radius: Float, strokeWidth: Float, fill: Boolean, color: Int) : CommonPaintable() {
private var radius = 0f
private var mStrokeWidth = 0f
private var mFill = false
private var mColor = 0
init { set(radius, strokeWidth, fill, color) }
operator fun set(radius: Float, strokeWidth: Float, fill: Boolean, color: Int) {
this.radius = radius
this.mStrokeWidth = strokeWidth
this.mFill = fill
this.mColor = color
}
override fun paint(canvas: Canvas) {
setStrokeWidth(mStrokeWidth)
setFill(mFill)
setColor(mColor)
paintCircle(canvas, 0f, 0f, radius)
}
override fun getWidth(): Float = radius * 2
override fun getHeight(): Float = radius * 2
}
| 0
|
Kotlin
|
1
| 1
|
f43e4ceaed545ce47a40723b4e45abb4b158151a
| 839
|
tiny_ar_browser
|
MIT License
|
data/RF02081/rnartist.kts
|
fjossinet
| 449,239,232
| false
|
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF02081"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
15 to 18
144 to 147
}
value = "#d171ec"
}
color {
location {
20 to 21
142 to 143
}
value = "#9f7885"
}
color {
location {
23 to 24
32 to 33
}
value = "#dad1e0"
}
color {
location {
35 to 39
136 to 140
}
value = "#d366f5"
}
color {
location {
48 to 50
107 to 109
}
value = "#a954c7"
}
color {
location {
55 to 60
65 to 70
}
value = "#4eafe4"
}
color {
location {
88 to 92
102 to 106
}
value = "#8964e2"
}
color {
location {
113 to 115
128 to 130
}
value = "#7dcbe6"
}
color {
location {
158 to 162
209 to 213
}
value = "#c2885c"
}
color {
location {
165 to 169
176 to 180
}
value = "#3be62c"
}
color {
location {
187 to 189
203 to 205
}
value = "#4d4b2a"
}
color {
location {
192 to 193
199 to 200
}
value = "#f07c3b"
}
color {
location {
255 to 256
324 to 325
}
value = "#8c7831"
}
color {
location {
287 to 289
296 to 298
}
value = "#ef846e"
}
color {
location {
19 to 19
144 to 143
}
value = "#4f920e"
}
color {
location {
22 to 22
34 to 34
141 to 141
}
value = "#22ba23"
}
color {
location {
25 to 31
}
value = "#7b0914"
}
color {
location {
40 to 47
110 to 112
131 to 135
}
value = "#cba763"
}
color {
location {
51 to 54
71 to 87
107 to 106
}
value = "#cdd706"
}
color {
location {
61 to 64
}
value = "#28d839"
}
color {
location {
93 to 101
}
value = "#d710df"
}
color {
location {
116 to 127
}
value = "#95cc8c"
}
color {
location {
163 to 164
181 to 186
206 to 208
}
value = "#60d4bc"
}
color {
location {
170 to 175
}
value = "#c44a94"
}
color {
location {
190 to 191
201 to 202
}
value = "#49517d"
}
color {
location {
194 to 198
}
value = "#58ea5f"
}
color {
location {
257 to 286
299 to 323
}
value = "#fc1fd4"
}
color {
location {
290 to 295
}
value = "#e727b1"
}
color {
location {
1 to 14
}
value = "#738388"
}
color {
location {
148 to 157
}
value = "#f6d350"
}
color {
location {
214 to 254
}
value = "#9e751c"
}
color {
location {
326 to 409
}
value = "#35a447"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3016050675602d506a0e308f07d071abf1524b67
| 4,820
|
Rfam-for-RNArtist
|
MIT License
|
src/main/kotlin/no/nav/familie/ef/sak/opplysninger/søknad/domain/Søknadsverdier.kt
|
navikt
| 206,805,010
| false
| null |
package no.nav.familie.ef.sak.opplysninger.søknad.domain
import java.time.LocalDateTime
import java.time.YearMonth
data class Søknadsverdier(
val barn: Set<SøknadBarn>,
val fødselsnummer: String,
val medlemskap: Medlemskap,
val sivilstandsplaner: Sivilstandsplaner?,
val bosituasjon: Bosituasjon,
val sivilstand: Sivilstand,
val aktivitet: Aktivitet? = null, // Gjelder: OS og BT
val situasjon: Situasjon? = null, // Gjelder: OS
val datoMottatt: LocalDateTime,
val søkerFra: YearMonth? = null,
)
fun SøknadsskjemaSkolepenger.tilSøknadsverdier() = Søknadsverdier(
aktivitet = Aktivitet(underUtdanning = this.utdanning, tidligereUtdanninger = this.tidligereUtdanninger),
barn = this.barn,
fødselsnummer = this.fødselsnummer,
medlemskap = this.medlemskap,
sivilstand = this.sivilstand,
sivilstandsplaner = this.sivilstandsplaner,
bosituasjon = this.bosituasjon,
situasjon = null,
datoMottatt = this.datoMottatt,
)
fun SøknadsskjemaBarnetilsyn.tilSøknadsverdier() = Søknadsverdier(
aktivitet = this.aktivitet,
barn = this.barn,
fødselsnummer = this.fødselsnummer,
medlemskap = this.medlemskap,
sivilstand = this.sivilstand,
sivilstandsplaner = this.sivilstandsplaner,
bosituasjon = this.bosituasjon,
situasjon = null,
datoMottatt = this.datoMottatt,
søkerFra = this.søkerFra,
)
fun SøknadsskjemaOvergangsstønad.tilSøknadsverdier() = Søknadsverdier(
aktivitet = this.aktivitet,
barn = this.barn,
fødselsnummer = this.fødselsnummer,
medlemskap = this.medlemskap,
sivilstand = this.sivilstand,
sivilstandsplaner = this.sivilstandsplaner,
bosituasjon = this.bosituasjon,
situasjon = this.situasjon,
datoMottatt = this.datoMottatt,
søkerFra = this.søkerFra
)
| 8
|
Kotlin
|
2
| 0
|
826996ddfeb9a0ec01a8b3525cb5841bd41bd7dd
| 1,813
|
familie-ef-sak
|
MIT License
|
app/src/main/java/com/example/gowalk/presentation/navigation/screen.kt
|
moemaair
| 711,874,379
| false
|
{"Kotlin": 53906}
|
package com.example.gowalk.presentation.navigation
sealed class Screen (val route: String){
object Home: Screen(route = "Home")
object StartWalking : Screen(route = "StartWalking")
}
| 0
|
Kotlin
|
0
| 1
|
f7ec78165e469a20b9f2f201b472f051d1cf6467
| 191
|
Gowalk
|
MIT License
|
src/main/kotlin/dev/moru3/compsql/datatype/types/numeric/unsigned/USMALLINT.kt
|
moru348
| 386,672,322
| false
| null |
package dev.moru3.compsql.datatype.types.numeric.unsigned
import dev.moru3.compsql.datatype.BaseDataType
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Types
/**
* SmallInt 0 から 65535 までの整数を格納できるSQLの型です。
* これ以上大きな型が必要な場合は INTEGER, UINTEGER を使用します。
* Unsigned: USMALLINT, Non-Unsigned: SMALLINT
* 注意: numeric系のプロパティは"最大数"ではなく"最大桁数"なのでお間違えなく。
*/
open class USMALLINT(property: Byte): USmallIntBase<Int>(property) {
override val from: Class<Int> = Int::class.javaObjectType
override fun get(resultSet: ResultSet, id: String): Int? = resultSet.getInt(id)
}
abstract class USmallIntBase<F>(val property: Byte): BaseDataType<F, Int> {
final override val typeName: String = "SMALLINT"
final override val type: Class<Int> = Int::class.javaObjectType
final override val sqlType: Int = Types.SMALLINT
final override val allowPrimaryKey: Boolean = true
final override val allowNotNull: Boolean = true
final override val allowUnique: Boolean = true
final override val isUnsigned: Boolean = true
final override val allowZeroFill: Boolean = true
final override val allowAutoIncrement: Boolean = true
override val allowDefault: Boolean = true
override val defaultProperty: String = "$property"
override val priority: Int = 10
override fun set(ps: PreparedStatement, index: Int, any: Any?) {
check(any is Number?) { "The type of \"${if(any!=null) any::class.javaObjectType.simpleName else "null"}\" is different from \"Number\"." }
super.set(ps, index, any?.toInt())
}
}
| 0
|
Kotlin
|
0
| 2
|
5788ede9874caa407729342904a5d05a085194da
| 1,573
|
CompSQL
|
MIT License
|
sample/src/main/kotlin/io/github/ilyapavlovskii/feature/toggle/sample/compose/MenuItemVerticalGrid.kt
|
IlyaPavlovskii
| 580,842,175
| false
| null |
package io.github.ilyapavlovskii.feature.toggle.sample.compose
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.runtime.Composable
import io.github.ilyapavlovskii.feature.toggle.sample.model.MenuItem
import io.github.ilyapavlovskii.feature.toggle.sample.toggles.MenuItemFeatureToggle
@Composable
internal fun MenuItemVerticalGrid(
featureToggle: MenuItemFeatureToggle,
items: List<MenuItem>,
) {
LazyVerticalGrid(columns = GridCells.Fixed(count = featureToggle.gridCount)) {
items(items) { item: MenuItem ->
MenuItemCard(featureToggle = featureToggle, item = item)
}
}
}
| 0
|
Kotlin
|
0
| 7
|
eccf7715f3da43cd168567e65180a1c142315ee6
| 759
|
FeatureToggle
|
Apache License 2.0
|
feature_profile/api/src/main/java/com/example/feature_profile/api/domain/models/Connection.kt
|
powerINcode
| 299,091,005
| false
| null |
package com.example.feature_profile.api.domain.models
data class Connection(val name: String, val value: String)
| 0
|
Kotlin
|
0
| 0
|
51de029c527f8c5668a3c6dc69c1fc783ddcc962
| 113
|
MviCurrencyTracker
|
Apache License 2.0
|
app/src/main/java/com/ibashkimi/cryptomarket/data/Result.kt
|
indritbashkimi
| 237,490,799
| false
|
{"Kotlin": 75293, "Java": 331}
|
package com.ibashkimi.cryptomarket.data
sealed class ApiResponse<T> {
class Success<T>(val result: T) : ApiResponse<T>()
class Failure<T>(val error: Any? = null) : ApiResponse<T>()
}
| 1
|
Kotlin
|
1
| 1
|
f55204467e3d466ab5d735281b40957a7c2f2b8e
| 192
|
CryptoPare
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.