path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/app/src/main/java/com/ingjuanocampo/enfila/android/home/ActivityLobby.kt
ingjuanocampo
387,043,993
false
{"Kotlin": 240432}
package com.ingjuanocampo.enfila.android.home import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.bottomnavigation.LabelVisibilityMode.LABEL_VISIBILITY_SELECTED import com.ingjuanocampo.enfila.android.R import com.ingjuanocampo.enfila.android.home.clients.FragmentClientList import com.ingjuanocampo.enfila.android.home.home.FragmentHome import com.ingjuanocampo.enfila.android.home.profile.FragmentProfile import com.ingjuanocampo.enfila.android.home.shift_pager.FragmentShiftPager import com.ingjuanocampo.enfila.android.home.tips.FragmentTips import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ActivityLobby : AppCompatActivity() { /* private val bottomNavBuilder by lazy { BottomMenuBuilder() .appendItem( fragmentFactory = { FragmentTips.newInstance() }, icon = getDrawable(R.drawable.ic_tips_and_updates), title = "Tips" ) .appendItem( fragmentFactory = { FragmentShiftPager.newInstance() }, icon = getDrawable(R.drawable.ic_format_list), title = "Turnos" ) .appendItem( fragmentFactory = { FragmentHome.newInstance() }, icon = getDrawable(R.drawable.ic_home), title = "Panel", default = true ) .appendItem( fragmentFactory = { FragmentClientList.newInstance() }, icon = getDrawable(R.drawable.ic_groups_48px), title = "Clientes" ) .appendItem( fragmentFactory = { FragmentProfile.newInstance() }, icon = getDrawable(R.drawable.ic_account), title = "Profile" ) } */ private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) /* val toolbar = findViewById<Toolbar>(R.id.toolbarWidget) setSupportActionBar(toolbar) var bottomNav: BottomNavigationView = findViewById(R.id.bottomNav) bottomNav.labelVisibilityMode = LABEL_VISIBILITY_SELECTED bottomNavBuilder.attachMenu(bottomNav, this)*/ navController = findNavController(R.id.nav_host_fragment) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNav) bottomNavigationView.setupWithNavController(navController) val appBarConfiguration = AppBarConfiguration(navController.graph) findViewById<Toolbar>(R.id.toolbarWidget) .setupWithNavController(navController, appBarConfiguration) } }
0
Kotlin
0
0
decebb226be191ec6382a7d60a97c5598d3f1bdf
3,071
EnFila-Android
MIT License
compiler/testData/codegen/box/jvmField/checkNoAccessors.kt
JakeWharton
99,388,807
false
null
import kotlin.test.assertFalse @JvmField public val field = "OK"; class A { @JvmField public val field = "OK"; companion object { @JvmField public val cfield = "OK"; } } object Object { @JvmField public val field = "OK"; } fun box(): String { var result = A().field checkNoAccessors(A::class.java) checkNoAccessors(A.Companion::class.java) checkNoAccessors(Object::class.java) checkNoAccessors(Class.forName("CheckNoAccessorsKt")) return "OK" } public fun checkNoAccessors(clazz: Class<*>) { clazz.declaredMethods.forEach { assertFalse(it.name.startsWith("get") || it.name.startsWith("set"), "Class ${clazz.name} has accessor '${it.name}'" ) } }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
742
kotlin
Apache License 2.0
app/src/main/kotlin/by/anegin/vkdiscover/core/util/FragmentEx.kt
eugene-kirzhanov
159,214,166
false
{"Kotlin": 72538}
package by.anegin.vkdiscover.core.util import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders inline fun <reified T : ViewModel> Fragment.getViewModel(viewModelFactory: ViewModelProvider.Factory): T { return ViewModelProviders.of(this, viewModelFactory)[T::class.java] }
0
Kotlin
0
0
0b7ad65c5e54eefc00673d6fb0171e22bddf0b09
382
vk-mobile-challenge-18
MIT License
teqanydb/src/main/java/com/teqanyco/teqanydb/PasswordFiled.kt
teqanyco
421,897,417
false
{"Kotlin": 17126}
package com.teqanyco.teqanyjetpack.textfield import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import com.teqanyco.teqanyjetpack.R @Composable fun PasswordTextField() { var text by rememberSaveable { mutableStateOf("") } var visible by rememberSaveable { mutableStateOf(false) } val icon = if (visible) painterResource(id = R.drawable.ic_baseline_visibility_off_24) else painterResource(id = R.drawable.ic_baseline_visibility_24) OutlinedTextField( value = text, onValueChange = { text = it }, placeholder = { Text(text = "Password here") }, label = { Text(text = "Password") }, trailingIcon = { IconButton(onClick = { visible = !visible }) { Icon( painter = icon, contentDescription = "password" ) } }, visualTransformation = if (visible) VisualTransformation.None else PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password ), singleLine = true ) }
0
Kotlin
0
0
c105182dd9a91c6ec12e40e04077a20f2c1cfdca
1,756
teqanyjetback
MIT License
domain/src/main/java/com/semicolon/domain/entity/users/FetchUserHealthEntity.kt
Walkhub
443,006,389
false
null
package com.semicolon.domain.entity.users data class FetchUserHealthEntity( val height: Double, val weight: Double, val sex: String )
5
Kotlin
1
29
5070c2c33365f2db6f57975078e1ecd7594f66fa
147
walkhub_android
MIT License
detekt-watcher/src/test/resources/Default.kt
hcknl
158,261,983
true
{"Kotlin": 1062676, "Groovy": 3620, "Shell": 1710, "HTML": 698}
@Suppress("unused") private val x = 0
0
Kotlin
0
1
565d86d780c15ade77b5468a9e342ba334181333
38
detekt
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/CirclePhoneFlip.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.CirclePhoneFlip: ImageVector get() { if (_circlePhoneFlip != null) { return _circlePhoneFlip!! } _circlePhoneFlip = Builder(name = "CirclePhoneFlip", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 24.0f) curveTo(5.383f, 24.0f, 0.0f, 18.617f, 0.0f, 12.0f) reflectiveCurveTo(5.383f, 0.0f, 12.0f, 0.0f) reflectiveCurveToRelative(12.0f, 5.383f, 12.0f, 12.0f) reflectiveCurveToRelative(-5.383f, 12.0f, -12.0f, 12.0f) close() moveTo(12.0f, 3.0f) curveTo(7.038f, 3.0f, 3.0f, 7.038f, 3.0f, 12.0f) reflectiveCurveToRelative(4.038f, 9.0f, 9.0f, 9.0f) reflectiveCurveToRelative(9.0f, -4.038f, 9.0f, -9.0f) reflectiveCurveTo(16.962f, 3.0f, 12.0f, 3.0f) close() moveTo(6.0f, 15.827f) lineToRelative(1.378f, 1.378f) curveToRelative(0.539f, 0.54f, 1.249f, 0.795f, 1.957f, 0.795f) curveToRelative(3.634f, 0.0f, 8.666f, -4.752f, 8.666f, -8.666f) curveToRelative(0.0f, -0.708f, -0.256f, -1.418f, -0.795f, -1.957f) lineToRelative(-1.378f, -1.378f) lineToRelative(-2.712f, 2.712f) lineToRelative(1.775f, 1.775f) curveToRelative(-0.882f, 2.195f, -2.376f, 3.629f, -4.403f, 4.403f) lineToRelative(-1.775f, -1.775f) lineToRelative(-2.712f, 2.712f) close() } } .build() return _circlePhoneFlip!! } private var _circlePhoneFlip: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,588
icons
MIT License
libs/DocumentScanner/src/main/java/com/zynksoftware/documentscanner/ui/camerascreen/CameraScreenFragment.kt
instructure
179,290,947
false
null
/** Copyright 2021 Krobys 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 com.krobys.documentscanner.ui.camerascreen import android.Manifest import android.app.Activity import android.content.Intent import android.graphics.BitmapFactory import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.tbruyelle.rxpermissions3.RxPermissions import com.krobys.documentscanner.R import com.krobys.documentscanner.common.extensions.hide import com.krobys.documentscanner.common.extensions.show import com.krobys.documentscanner.common.utils.FileUriUtils import com.krobys.documentscanner.manager.SessionManager import com.krobys.documentscanner.model.DocumentScannerErrorModel import com.krobys.documentscanner.ui.base.BaseFragment import com.krobys.documentscanner.ui.components.scansurface.ScanSurfaceListener import com.krobys.documentscanner.ui.scan.InternalScanActivity import id.zelory.compressor.determineImageRotation import kotlinx.android.synthetic.main.fragment_camera_screen.* import java.io.File import java.io.FileNotFoundException internal class CameraScreenFragment: BaseFragment(), ScanSurfaceListener { companion object { private const val GALLERY_REQUEST_CODE = 878 private val TAG = CameraScreenFragment::class.simpleName fun newInstance(): CameraScreenFragment { return CameraScreenFragment() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_camera_screen, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) scanSurfaceView.lifecycleOwner = this scanSurfaceView.listener = this scanSurfaceView.originalImageFile = getScanActivity().originalImageFile checkForCameraPermissions() initListeners() // settings val sessionManager = SessionManager(getScanActivity()) galleryButton.visibility = if (sessionManager.isGalleryEnabled()) View.VISIBLE else View.GONE autoButton.visibility = if (sessionManager.isCaptureModeButtonEnabled()) View.VISIBLE else View.GONE scanSurfaceView.isAutoCaptureOn = sessionManager.isAutoCaptureEnabledByDefault() scanSurfaceView.isLiveDetectionOn = sessionManager.isLiveDetectionEnabled() } override fun onDestroy() { super.onDestroy() if(getScanActivity().shouldCallOnClose) { getScanActivity().onClose() } } override fun onResume() { super.onResume() getScanActivity().reInitOriginalImageFile() scanSurfaceView.originalImageFile = getScanActivity().originalImageFile } private fun initListeners() { cameraCaptureButton.setOnClickListener { takePhoto() } cancelButton.setOnClickListener { finishActivity() } flashButton.setOnClickListener { switchFlashState() } galleryButton.setOnClickListener { checkForStoragePermissions() } autoButton.setOnClickListener { toggleAutoManualButton() } } private fun toggleAutoManualButton() { scanSurfaceView.isAutoCaptureOn = !scanSurfaceView.isAutoCaptureOn scanSurfaceView.isLiveDetectionOn = scanSurfaceView.isAutoCaptureOn if (scanSurfaceView.isAutoCaptureOn) { autoButton.text = getString(R.string.zdc_auto) } else { autoButton.text = getString(R.string.zdc_manual) } } private fun checkForCameraPermissions() { RxPermissions(this) .requestEach(Manifest.permission.CAMERA) .subscribe { permission -> when { permission.granted -> { startCamera() } permission.shouldShowRequestPermissionRationale -> { onError(DocumentScannerErrorModel(DocumentScannerErrorModel.ErrorMessage.CAMERA_PERMISSION_REFUSED_WITHOUT_NEVER_ASK_AGAIN)) } else -> { onError(DocumentScannerErrorModel(DocumentScannerErrorModel.ErrorMessage.CAMERA_PERMISSION_REFUSED_GO_TO_SETTINGS)) } } } } private fun checkForStoragePermissions() { RxPermissions(this) .requestEach(Manifest.permission.READ_EXTERNAL_STORAGE) .subscribe { permission -> when { permission.granted -> { selectImageFromGallery() } permission.shouldShowRequestPermissionRationale -> { onError(DocumentScannerErrorModel(DocumentScannerErrorModel.ErrorMessage.STORAGE_PERMISSION_REFUSED_WITHOUT_NEVER_ASK_AGAIN)) } else -> { onError(DocumentScannerErrorModel(DocumentScannerErrorModel.ErrorMessage.STORAGE_PERMISSION_REFUSED_GO_TO_SETTINGS)) } } } } private fun startCamera() { scanSurfaceView.start() } private fun takePhoto() { scanSurfaceView.takePicture() } private fun getScanActivity(): InternalScanActivity { return (requireActivity() as InternalScanActivity) } private fun finishActivity() { getScanActivity().finish() } private fun switchFlashState() { scanSurfaceView.switchFlashState() } override fun showFlash() { flashButton?.show() } override fun hideFlash() { flashButton?.hide() } private fun selectImageFromGallery() { val photoPickerIntent = Intent(Intent.ACTION_OPEN_DOCUMENT) photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE) photoPickerIntent.type = "image/*" startActivityForResult(photoPickerIntent, GALLERY_REQUEST_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && requestCode == GALLERY_REQUEST_CODE) { try { val imageUri = data?.data if (imageUri != null) { val realPath = FileUriUtils.getRealPath(getScanActivity(), imageUri) if (realPath != null) { getScanActivity().reInitOriginalImageFile() getScanActivity().originalImageFile = File(realPath) gotoNext() } else { Log.e(TAG, DocumentScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR.error) onError(DocumentScannerErrorModel( DocumentScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR, null)) } } else { Log.e(TAG, DocumentScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR.error) onError(DocumentScannerErrorModel( DocumentScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR, null)) } } catch (e: FileNotFoundException) { Log.e(TAG, "FileNotFoundException", e) onError(DocumentScannerErrorModel( DocumentScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR, e)) } } } override fun scanSurfacePictureTaken() { gotoNext() } private fun gotoNext() { if (isAdded) { if (SessionManager(getScanActivity()).isCropperEnabled()) { getScanActivity().showImageCropFragment() } else { val sourceBitmap = BitmapFactory.decodeFile(getScanActivity().originalImageFile.absolutePath) if (sourceBitmap != null) { getScanActivity().croppedImage = determineImageRotation(getScanActivity().originalImageFile, sourceBitmap) getScanActivity().showImageProcessingFragment() } else { Log.e(TAG, DocumentScannerErrorModel.ErrorMessage.INVALID_IMAGE.error) onError(DocumentScannerErrorModel(DocumentScannerErrorModel.ErrorMessage.INVALID_IMAGE)) Handler(Looper.getMainLooper()).post{ finishActivity() } } } } } override fun scanSurfaceShowProgress() { showProgressBar() } override fun scanSurfaceHideProgress() { hideProgressBar() } override fun onError(error: DocumentScannerErrorModel) { if(isAdded) { getScanActivity().onError(error) } } override fun showFlashModeOn() { flashButton.setImageResource(R.drawable.zdc_flash_on) } override fun showFlashModeOff() { flashButton.setImageResource(R.drawable.zdc_flash_off) } }
9
null
85
99
1bac9958504306c03960bdce7fbb87cc63bc6845
10,331
canvas-android
Apache License 2.0
player/events/src/main/java/com/tidal/sdk/player/events/model/VideoPlaybackSession.kt
tidal-music
806,866,286
false
{"Kotlin": 1775374, "Shell": 9881, "Python": 7380, "Mustache": 911}
package com.tidal.sdk.player.events.model import androidx.annotation.Keep import com.google.gson.annotations.SerializedName import com.tidal.sdk.player.common.model.AssetPresentation import com.tidal.sdk.player.common.model.ProductType import com.tidal.sdk.player.common.model.VideoQuality import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import java.util.UUID @Keep data class VideoPlaybackSession @AssistedInject internal constructor( @Assisted override val ts: Long, @Assisted override val uuid: UUID, @Assisted override val user: User, @Assisted override val client: Client, @Assisted override val payload: Payload, @Assisted override val extras: Map<String, String?>?, ) : PlaybackSession<VideoPlaybackSession.Payload>() { @Keep data class Payload( override val playbackSessionId: UUID, override val startTimestamp: Long, @SerializedName("startAssetPosition") override val startAssetPositionSeconds: Double, override val requestedProductId: String, override val actualProductId: String, override val actualAssetPresentation: AssetPresentation, override val actualQuality: VideoQuality, override val sourceType: String?, override val sourceId: String?, override val actions: List<PlaybackSession.Payload.Action>, override val endTimestamp: Long, @SerializedName("endAssetPosition") override val endAssetPositionSeconds: Double, ) : PlaybackSession.Payload { override val productType = ProductType.VIDEO override val isPostPaywall = true override val actualAudioMode = null } @AssistedFactory internal interface Factory { @Suppress("LongParameterList") fun create( ts: Long, uuid: UUID, user: User, client: Client, payload: Payload, extras: Map<String, String?>?, ): VideoPlaybackSession } }
33
Kotlin
0
23
1f654552133ef7794fe9bb7677bc7fc94c713aa3
2,045
tidal-sdk-android
Apache License 2.0
compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/builder/FirErrorImportBuilder.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:Suppress("DuplicatedCode") package org.jetbrains.kotlin.fir.declarations.builder import kotlin.contracts.* import org.jetbrains.kotlin.KtSourceElement import org.jetbrains.kotlin.fir.builder.FirBuilderDsl import org.jetbrains.kotlin.fir.declarations.FirErrorImport import org.jetbrains.kotlin.fir.declarations.FirImport import org.jetbrains.kotlin.fir.declarations.impl.FirErrorImportImpl import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic import org.jetbrains.kotlin.fir.visitors.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name /* * This file was generated automatically * DO NOT MODIFY IT MANUALLY */ @FirBuilderDsl class FirErrorImportBuilder { var aliasSource: KtSourceElement? = null lateinit var diagnostic: ConeDiagnostic lateinit var delegate: FirImport fun build(): FirErrorImport { return FirErrorImportImpl( aliasSource, diagnostic, delegate, ) } } @OptIn(ExperimentalContracts::class) inline fun buildErrorImport(init: FirErrorImportBuilder.() -> Unit): FirErrorImport { contract { callsInPlace(init, kotlin.contracts.InvocationKind.EXACTLY_ONCE) } return FirErrorImportBuilder().apply(init).build() }
34
null
5686
46,039
f98451e38169a833f60b87618db4602133e02cf2
1,472
kotlin
Apache License 2.0
projects/core/src/main/kotlin/site/siredvin/peripheralium/common/items/DescriptiveBlockItem.kt
SirEdvin
489,457,802
false
{"Kotlin": 479164, "Java": 13590}
package site.siredvin.peripheralium.common.items import net.minecraft.network.chat.Component import net.minecraft.network.chat.MutableComponent import net.minecraft.network.chat.contents.TranslatableContents import net.minecraft.world.item.BlockItem import net.minecraft.world.item.ItemStack import net.minecraft.world.item.TooltipFlag import net.minecraft.world.level.Level import net.minecraft.world.level.block.Block import site.siredvin.peripheralium.util.itemTooltip open class DescriptiveBlockItem(block: Block, properties: Properties) : BlockItem(block, properties) { private val extraDescription: MutableComponent by lazy { return@lazy itemTooltip(this.descriptionId) } override fun appendHoverText( itemStack: ItemStack, level: Level?, list: MutableList<Component>, tooltipFlag: TooltipFlag, ) { super.appendHoverText(itemStack, level, list, tooltipFlag) val keyContents = extraDescription.contents as TranslatableContents if (keyContents.key != extraDescription.string) { list.add(extraDescription) } } }
2
Kotlin
3
2
94a9b51913723e792c3403f5a5ba347bc84c7987
1,123
Peripheralium
MIT License
app/src/main/java/fm/weigl/refsberlin/di/ActivityComponent.kt
asco33
92,974,118
false
null
package fm.weigl.refsberlin.di import dagger.Component import fm.weigl.refsberlin.abouttheapp.view.AboutTheAppFragment import fm.weigl.refsberlin.gameslist.view.GamesListFragment import fm.weigl.refsberlin.main.view.MainActivity import fm.weigl.refsberlin.settings.view.SettingsFragment @ActivityScope @Component(modules = arrayOf(ActivityModule::class), dependencies = arrayOf(AppComponent::class)) interface ActivityComponent { fun inject(activity: MainActivity) fun inject(fragment: GamesListFragment) fun inject(fragment: AboutTheAppFragment) fun inject(fragment: SettingsFragment) }
2
null
1
1
7b0c7b8641206624c3d2df235eb47341130e98f1
605
refsberlin
Apache License 2.0
server/src/main/kotlin/com/kamelia/hedera/database/Connection.kt
Black-Kamelia
492,280,011
false
null
package com.kamelia.hedera.database import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import java.sql.Connection import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync object Connection { private lateinit var dataSource: HikariDataSource private lateinit var database: Database val connection: Connection get() = dataSource.connection fun init() { dataSource = hikari() database = Database.connect(dataSource) } private fun hikari(): HikariDataSource { val config = HikariConfig("/hikari.properties") config.validate() return HikariDataSource(config) } suspend fun <T> transaction( dispatcher: CoroutineDispatcher = Dispatchers.IO, block: suspend Transaction.() -> T, ): T = suspendedTransactionAsync(dispatcher, database) { block() }.await() }
3
Kotlin
0
9
23b16a0000769665d1d97a54dc8459935edfdb50
1,087
Hedera
Apache License 2.0
z2-core/src/commonMain/kotlin/hu/simplexion/z2/adaptive/entry.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1586446, "CSS": 166528, "Java": 12046, "HTML": 1560, "JavaScript": 975}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.z2.adaptive /** * Entry point of a Adaptive component tree. * * **IMPORTANT** variables declared outside the block are **NOT** reactive */ fun adaptive(block: (adaptiveAdapter: AdaptiveAdapter<*>) -> Unit) { block(AdaptiveAdapterRegistry.adapterFor()) } /** * Entry point of a Adaptive component tree with a specific adapter. The adapter * registry is not accessed in this case but the components will use the * adapter passed. * * **IMPORTANT** variables declared outside the block are **NOT** reactive */ fun <BT> adaptive(adaptiveAdapter: AdaptiveAdapter<BT>, block: (adaptiveAdapter: AdaptiveAdapter<BT>) -> Unit) { block(adaptiveAdapter) }
5
Kotlin
0
1
a7213ad95437796bc87674dd9530a95e1528901e
820
z2
Apache License 2.0
backend/services/UserService/src/main/kotlin/com/arconsis/domain/users/UsersService.kt
arconsis
506,954,248
false
{"Kotlin": 284198, "HCL": 70387, "HTML": 27287, "Dockerfile": 10124, "Go": 8432, "TypeScript": 7350, "PLpgSQL": 3157, "JavaScript": 2138, "Shell": 1891, "Smarty": 1371, "Java": 697}
package com.arconsis.domain.users import com.arconsis.data.outboxevents.OutboxEventsRepository import com.arconsis.data.users.UsersRepository import com.arconsis.presentation.http.dto.UserCreate import com.fasterxml.jackson.databind.ObjectMapper import io.smallrye.mutiny.Uni import org.hibernate.reactive.mutiny.Mutiny import java.util.* import javax.enterprise.context.ApplicationScoped @ApplicationScoped class UsersService( private val usersRepository: UsersRepository, private val outboxEventsRepository: OutboxEventsRepository, private val sessionFactory: Mutiny.SessionFactory, private val objectMapper: ObjectMapper ) { fun createUser(userCreate: UserCreate): Uni<User> { return sessionFactory.withTransaction { session, _ -> usersRepository.createUser(userCreate, session) .createOutboxEvent(session) } } fun getUser(userId: UUID): Uni<User?> { return usersRepository.getUser(userId) } fun getUserBySub(sub: String): Uni<User?> { return usersRepository.getUserBySub(sub) } private fun Uni<User>.createOutboxEvent(session: Mutiny.Session) = flatMap { user -> val createOutboxEvent = user.toCreateOutboxEvent(objectMapper) outboxEventsRepository.createEvent(createOutboxEvent, session).map { user } } }
9
Kotlin
1
3
384eb68907ef2e975904bf392a9ece9d0d0754f8
1,359
ecommerce
Apache License 2.0
src/test/kotlin/no/nav/medlemskap/cucumber/steps/RegelFraDatagrunnlagJsonSteps.kt
navikt
225,422,169
false
{"Kotlin": 943408, "Gherkin": 426906, "Shell": 151, "Dockerfile": 147}
package no.nav.medlemskap.cucumber.steps import io.cucumber.java8.No import junit.framework.TestCase.assertEquals import no.nav.medlemskap.cucumber.DomenespråkParser import no.nav.medlemskap.domene.Datagrunnlag import no.nav.medlemskap.regler.assertDelresultat import no.nav.medlemskap.regler.common.RegelId.REGEL_2 import no.nav.medlemskap.regler.common.Resultat import no.nav.medlemskap.regler.personer.Personleser import no.nav.medlemskap.regler.v1.ReglerService class RegelFraDatagrunnlagJsonSteps : No { private var resultat: Resultat? = null private var datagrunnlag: Datagrunnlag? = null private val domenespråkParser = DomenespråkParser init { Gitt("følgende datagrunnlag json") { docString: String? -> datagrunnlag = Personleser.dataGrunnlagFraJson(docString!!) } Når("lovvalg og medlemskap beregnes fra datagrunnlag json") { resultat = ReglerService.kjørRegler(datagrunnlag!!) } Så("skal delresultat {string} være {string}") { regelIdStr: String, forventetSvar: String? -> val regelId = domenespråkParser.parseRegelId(regelIdStr) assertDelresultat(regelId, domenespråkParser.parseSvar(forventetSvar!!), resultat!!) } Så("omfattet av grunnforordningen være {string}") { forventetSvar: String? -> assertDelresultat(REGEL_2, domenespråkParser.parseSvar(forventetSvar!!), resultat!!) } Så("skal medlemskap i Folketrygden være {string}") { forventetVerdi: String -> val forventetSvar = domenespråkParser.parseSvar(forventetVerdi) assertEquals(forventetSvar, resultat!!.svar) } } }
10
Kotlin
1
0
ef1d25c3b042bfec4fc2f235fb658e97f94479d6
1,690
medlemskap-oppslag
MIT License
feature/photo-api/src/main/java/com/mldz/feature/photo/PhotoEntry.kt
MaximZubarev
729,033,741
false
{"Kotlin": 156400}
package com.mldz.feature.photo import androidx.compose.runtime.Composable abstract class PhotoEntry { val photoIdArg = "photoIdArg" val canNavigateToProfileArg = "canNavigateToProfileArg" val featureRoute = "photo_route/" val featureRouteArg = "photo_route/{$photoIdArg}/{$canNavigateToProfileArg}" @Composable abstract fun Start( navigateBack: () -> Unit, navigateToProfile: (String) -> Unit ) }
0
Kotlin
0
0
fb0d2d62f5e09034e204348ba6d0818521a178ff
445
unsplash_app
The Unlicense
compiler/testData/diagnostics/tests/multimodule/AnonymousFunctionParametersOfInaccessibleTypes.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}
// LATEST_LV_DIFFERENCE // MODULE: start // FILE: start.kt interface InaccessibleConcreteType interface InaccessibleGenericType<T> // MODULE: middle(start) // FILE: middle.kt fun withConcreteParameter(arg: (InaccessibleConcreteType) -> Unit) {} fun withGenericParameter(arg: (InaccessibleGenericType<*>) -> Unit) {} // MODULE: end(middle) // FILE: end.kt fun test() { withConcreteParameter(fun(arg) {}) withGenericParameter(fun(arg) {}) withConcreteParameter(fun(arg: <!UNRESOLVED_REFERENCE!>InaccessibleConcreteType<!>) {}) withGenericParameter(fun(arg: <!UNRESOLVED_REFERENCE!>InaccessibleGenericType<!><*>) {}) }
182
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
638
kotlin
Apache License 2.0
src/main/kotlin/CommandManager.kt
somichev-dev
768,722,264
false
{"Kotlin": 2591}
import org.bukkit.block.CommandBlock import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.command.TabCompleter class CommandManager(private val plugin: SMMW) : CommandExecutor, TabCompleter { override fun onCommand( sender: CommandSender, command: Command, alias: String, args: Array<out String>, ): Boolean { if (sender is CommandBlock) return true if (args.size !in 1..2) { sender.sendMessage( "/smmw view - see current whitelist message" + "\n/smmw set [message] - set new whitelist message", ) return true } val op = args[0] if (op == "view") { sender.sendMessage(plugin.whitelistMessage) } else if (op == "set" && args.size == 2) { plugin.config.set("message", args[1]) return true } sender.sendMessage( "/smmw view - see current whitelist message" + "\n/smmw set [message] - set new whitelist message", ) return true } override fun onTabComplete( sender: CommandSender, command: Command, alias: String, args: Array<out String>, ): MutableList<String>? { if (args.size == 1) { return mutableListOf("view", "set") } return null } }
0
Kotlin
0
0
353585b8140cd6e847370cd41f3913d227aeec21
1,459
SimpleMiniMessageForWhitelist
MIT License
src/commonMain/kotlin/com/arcnor/miniscript/MiniscriptLexer.kt
Arcnor
205,708,705
false
null
package com.arcnor.miniscript class MiniscriptLexer { class Token( var type: Type = Type.Unknown, // may be null for things like operators, whose text is fixed var text: String? = null ) { enum class Type { Unknown, Keyword, Number, String, Identifier, OpAssign, OpPlus, OpMinus, OpTimes, OpDivide, OpMod, OpPower, OpEqual, OpNotEqual, OpGreater, OpGreatEqual, OpLesser, OpLessEqual, LParen, RParen, LSquare, RSquare, LCurly, RCurly, AddressOf, Comma, Dot, Colon, Comment, EOL } var afterSpace: Boolean = false override fun toString(): String { if (text == null) return type.toString(); return "$type($text)"; } companion object { val EOL: Token = Token(type = Type.EOL) } } class Lexer(private val input: String) { var lineNum = 1 // start at 1, so we report 1-based line numbers private val inputLength = input.length; private var position = 0; private var pending = mutableListOf<Token>() val AtEnd: Boolean get() = position >= inputLength && pending.isEmpty() fun Peek(): Token { if (pending.isEmpty()) { if (AtEnd) return Token.EOL pending.add(Dequeue()) } return pending[0] } fun Dequeue(): Token { if (pending.isNotEmpty()) return pending.removeAt(0); val oldPos = position; SkipWhitespaceAndComment(); if (AtEnd) return Token.EOL; var result = Token(); result.afterSpace = (position > oldPos); var startPos = position; var c = input[position++]; // Handle two-character operators first. if (!AtEnd) { val c2 = input [position]; if (c == '=' && c2 == '=') result.type = Token.Type.OpEqual; if (c == '!' && c2 == '=') result.type = Token.Type.OpNotEqual; if (c == '>' && c2 == '=') result.type = Token.Type.OpGreatEqual; if (c == '<' && c2 == '=') result.type = Token.Type.OpLessEqual; if (result.type != Token.Type.Unknown) { position++; return result; } } // Then, handle more extended tokens. result.type = when (c) { '+' -> Token.Type.OpPlus '-' -> Token.Type.OpMinus '*' -> Token.Type.OpTimes '/' -> Token.Type.OpDivide '%' -> Token.Type.OpMod '^' -> Token.Type.OpPower '(' -> Token.Type.LParen ')' -> Token.Type.RParen '[' -> Token.Type.LSquare ']' -> Token.Type.RSquare '{' -> Token.Type.LCurly '}' -> Token.Type.RCurly ',' -> Token.Type.Comma ':' -> Token.Type.Colon '=' -> Token.Type.OpAssign '<' -> Token.Type.OpLesser '>' -> Token.Type.OpGreater '@' -> Token.Type.AddressOf ';', '\n' -> { result.text = if (c == ';') ";" else "\n" if (c != ';') lineNum++; Token.Type.EOL; } '\r' -> { // Careful; DOS may use \r\n, so we need to check for that too. if (position < inputLength && input[position] == '\n') { position++; result.text = "\r\n"; } else { result.text = "\r"; } lineNum++; Token.Type.EOL; } else -> { Token.Type.Unknown } } if (result.type != Token.Type.Unknown) return result; // Then, handle more extended tokens. if (c == '.') { // A token that starts with a dot is just Type.Dot, UNLESS // it is followed by a number, in which case it's a decimal number. if (position >= inputLength || !IsNumeric(input[position])) { result.type = Token.Type.Dot; return result; } } if (c == '.' || IsNumeric(c)) { result.type = Token.Type.Number; while (position < inputLength) { val lastc = c; c = input[position]; if (IsNumeric(c) || c == '.' || c == 'E' || c == 'e' || (c == '-' && (lastc == 'E' || lastc == 'e'))) { position++; } else break; } } else if (IsIdentifier(c)) { while (position < inputLength) { if (IsIdentifier(input[position])) position++; else break; } result.text = input.substring(startPos, position); result.type = (if (Keywords.IsKeyword(result.text!!)) Token.Type.Keyword else Token.Type.Identifier); if (result.text == "end") { // As a special case: when we see "end", grab the next keyword (after whitespace) // too, and conjoin it, so our token is "end if", "end function", etc. val nextWord = Dequeue(); if (nextWord != null && nextWord.type == Token.Type.Keyword) { result.text = result.text + " " + nextWord.text; } else { // Oops, didn't find another keyword. User error. throw LexerException("'end' without following keyword ('if', 'function', etc.)"); } } else if (result.text == "else") { // And similarly, conjoin an "if" after "else" (to make "else if"). val p = position; val nextWord = Dequeue(); if (nextWord != null && nextWord.text == "if") result.text = "else if"; else position = p; } return result; } else if (c == '"') { // Lex a string... to the closing ", but skipping (and singling) a doubled double quote ("") result.type = Token.Type.String; var haveDoubledQuotes = false; startPos = position; var gotEndQuote = false; while (position < inputLength) { c = input[position++]; if (c == '"') { if (position < inputLength && input[position] == '"') { // This is just a doubled quote. haveDoubledQuotes = true; position++; } else { // This is the closing quote, marking the end of the string. gotEndQuote = true; break; } } } if (!gotEndQuote) throw LexerException("missing closing quote (\")"); result.text = input.substring(startPos, position-1); if (haveDoubledQuotes) result.text = result.text!!.replace("\"\"", "\""); return result; } else { result.type = Token.Type.Unknown; } result.text = input.substring(startPos, position); return result; } private fun SkipWhitespaceAndComment() { while (!AtEnd && IsWhitespace(input[position])) { position++ } if (position < input.length - 1 && input[position] === '/' && input[position + 1] === '/') { // Comment. Skip to end of line. position += 2 while (!AtEnd && input[position] !== '\n') position++ } } /** * Caution: ignores queue, and uses only current position */ fun IsAtWhitespace() = AtEnd || IsWhitespace(input[position]) companion object { fun IsNumeric(c: Char) = c in '0'..'9' fun IsIdentifier(c: Char) = (c == '_' || c in 'a'..'z' || c in 'A'..'Z' || c in '0'..'9' || c > '\u009F') fun IsWhitespace(c: Char) = c == ' ' || c == '\t' fun IsInStringLiteral(charPos: Int, source: String, startPos: Int = 0): Boolean { var inString = false; for (i in startPos until charPos) { if (source[i] == '"') inString = !inString; } return inString; } fun CommentStartPos(source: String, startPos: Int): Int { // Find the first occurrence of "//" in this line that // is not within a string literal. var commentStart = startPos - 2 while (true) { commentStart = source.indexOf("//", commentStart + 2) if (commentStart < 0) break // no comment found if (!IsInStringLiteral(commentStart, source, startPos)) break // valid comment } return commentStart } fun TrimComment(source: String): String { val startPos = source.lastIndexOf('\n') + 1 val commentStart = CommentStartPos(source, startPos) // TODO: Check if the trimming is being done properly return if (commentStart >= 0) source.substring(startPos, commentStart) else source } // Find the last token in the given source, ignoring any whitespace // or comment at the end of that line. fun LastToken(source: String): Token { // Start by finding the start and logical end of the last line. val startPos = source.lastIndexOf('\n') + 1 val commentStart = CommentStartPos(source, startPos) // Walk back from end of string or start of comment, skipping whitespace. var endPos = if (commentStart >= 0) commentStart - 1 else source.length - 1 while (endPos >= 0 && IsWhitespace(source[endPos])) endPos-- if (endPos < 0) return Token.EOL // Find the start of that last token. // There are several cases to consider here. var tokStart = endPos val c = source[endPos] if (IsIdentifier(c)) { while (tokStart > startPos && IsIdentifier(source[tokStart - 1])) tokStart-- } else if (c == '"') { var inQuote = true while (tokStart > startPos) { tokStart-- if (source[tokStart] === '"') { inQuote = !inQuote if (!inQuote && tokStart > startPos && source[tokStart - 1] !== '"') break } } } else if (c == '=' && tokStart > startPos) { val c2 = source[tokStart - 1] if (c2 == '>' || c2 == '<' || c2 == '=' || c2 == '!') tokStart-- } // Now use the standard lexer to grab just that bit. val lex = Lexer(source) lex.position = tokStart return lex.Dequeue() } fun RunUnitTests() { } } } }
0
Kotlin
1
5
c0ab5c46f1a441ebaf3a3fc7138d6e109cb8c4a9
9,041
miniscript-kt
MIT License
src/commonMain/kotlin/com/arcnor/miniscript/MiniscriptLexer.kt
Arcnor
205,708,705
false
null
package com.arcnor.miniscript class MiniscriptLexer { class Token( var type: Type = Type.Unknown, // may be null for things like operators, whose text is fixed var text: String? = null ) { enum class Type { Unknown, Keyword, Number, String, Identifier, OpAssign, OpPlus, OpMinus, OpTimes, OpDivide, OpMod, OpPower, OpEqual, OpNotEqual, OpGreater, OpGreatEqual, OpLesser, OpLessEqual, LParen, RParen, LSquare, RSquare, LCurly, RCurly, AddressOf, Comma, Dot, Colon, Comment, EOL } var afterSpace: Boolean = false override fun toString(): String { if (text == null) return type.toString(); return "$type($text)"; } companion object { val EOL: Token = Token(type = Type.EOL) } } class Lexer(private val input: String) { var lineNum = 1 // start at 1, so we report 1-based line numbers private val inputLength = input.length; private var position = 0; private var pending = mutableListOf<Token>() val AtEnd: Boolean get() = position >= inputLength && pending.isEmpty() fun Peek(): Token { if (pending.isEmpty()) { if (AtEnd) return Token.EOL pending.add(Dequeue()) } return pending[0] } fun Dequeue(): Token { if (pending.isNotEmpty()) return pending.removeAt(0); val oldPos = position; SkipWhitespaceAndComment(); if (AtEnd) return Token.EOL; var result = Token(); result.afterSpace = (position > oldPos); var startPos = position; var c = input[position++]; // Handle two-character operators first. if (!AtEnd) { val c2 = input [position]; if (c == '=' && c2 == '=') result.type = Token.Type.OpEqual; if (c == '!' && c2 == '=') result.type = Token.Type.OpNotEqual; if (c == '>' && c2 == '=') result.type = Token.Type.OpGreatEqual; if (c == '<' && c2 == '=') result.type = Token.Type.OpLessEqual; if (result.type != Token.Type.Unknown) { position++; return result; } } // Then, handle more extended tokens. result.type = when (c) { '+' -> Token.Type.OpPlus '-' -> Token.Type.OpMinus '*' -> Token.Type.OpTimes '/' -> Token.Type.OpDivide '%' -> Token.Type.OpMod '^' -> Token.Type.OpPower '(' -> Token.Type.LParen ')' -> Token.Type.RParen '[' -> Token.Type.LSquare ']' -> Token.Type.RSquare '{' -> Token.Type.LCurly '}' -> Token.Type.RCurly ',' -> Token.Type.Comma ':' -> Token.Type.Colon '=' -> Token.Type.OpAssign '<' -> Token.Type.OpLesser '>' -> Token.Type.OpGreater '@' -> Token.Type.AddressOf ';', '\n' -> { result.text = if (c == ';') ";" else "\n" if (c != ';') lineNum++; Token.Type.EOL; } '\r' -> { // Careful; DOS may use \r\n, so we need to check for that too. if (position < inputLength && input[position] == '\n') { position++; result.text = "\r\n"; } else { result.text = "\r"; } lineNum++; Token.Type.EOL; } else -> { Token.Type.Unknown } } if (result.type != Token.Type.Unknown) return result; // Then, handle more extended tokens. if (c == '.') { // A token that starts with a dot is just Type.Dot, UNLESS // it is followed by a number, in which case it's a decimal number. if (position >= inputLength || !IsNumeric(input[position])) { result.type = Token.Type.Dot; return result; } } if (c == '.' || IsNumeric(c)) { result.type = Token.Type.Number; while (position < inputLength) { val lastc = c; c = input[position]; if (IsNumeric(c) || c == '.' || c == 'E' || c == 'e' || (c == '-' && (lastc == 'E' || lastc == 'e'))) { position++; } else break; } } else if (IsIdentifier(c)) { while (position < inputLength) { if (IsIdentifier(input[position])) position++; else break; } result.text = input.substring(startPos, position); result.type = (if (Keywords.IsKeyword(result.text!!)) Token.Type.Keyword else Token.Type.Identifier); if (result.text == "end") { // As a special case: when we see "end", grab the next keyword (after whitespace) // too, and conjoin it, so our token is "end if", "end function", etc. val nextWord = Dequeue(); if (nextWord != null && nextWord.type == Token.Type.Keyword) { result.text = result.text + " " + nextWord.text; } else { // Oops, didn't find another keyword. User error. throw LexerException("'end' without following keyword ('if', 'function', etc.)"); } } else if (result.text == "else") { // And similarly, conjoin an "if" after "else" (to make "else if"). val p = position; val nextWord = Dequeue(); if (nextWord != null && nextWord.text == "if") result.text = "else if"; else position = p; } return result; } else if (c == '"') { // Lex a string... to the closing ", but skipping (and singling) a doubled double quote ("") result.type = Token.Type.String; var haveDoubledQuotes = false; startPos = position; var gotEndQuote = false; while (position < inputLength) { c = input[position++]; if (c == '"') { if (position < inputLength && input[position] == '"') { // This is just a doubled quote. haveDoubledQuotes = true; position++; } else { // This is the closing quote, marking the end of the string. gotEndQuote = true; break; } } } if (!gotEndQuote) throw LexerException("missing closing quote (\")"); result.text = input.substring(startPos, position-1); if (haveDoubledQuotes) result.text = result.text!!.replace("\"\"", "\""); return result; } else { result.type = Token.Type.Unknown; } result.text = input.substring(startPos, position); return result; } private fun SkipWhitespaceAndComment() { while (!AtEnd && IsWhitespace(input[position])) { position++ } if (position < input.length - 1 && input[position] === '/' && input[position + 1] === '/') { // Comment. Skip to end of line. position += 2 while (!AtEnd && input[position] !== '\n') position++ } } /** * Caution: ignores queue, and uses only current position */ fun IsAtWhitespace() = AtEnd || IsWhitespace(input[position]) companion object { fun IsNumeric(c: Char) = c in '0'..'9' fun IsIdentifier(c: Char) = (c == '_' || c in 'a'..'z' || c in 'A'..'Z' || c in '0'..'9' || c > '\u009F') fun IsWhitespace(c: Char) = c == ' ' || c == '\t' fun IsInStringLiteral(charPos: Int, source: String, startPos: Int = 0): Boolean { var inString = false; for (i in startPos until charPos) { if (source[i] == '"') inString = !inString; } return inString; } fun CommentStartPos(source: String, startPos: Int): Int { // Find the first occurrence of "//" in this line that // is not within a string literal. var commentStart = startPos - 2 while (true) { commentStart = source.indexOf("//", commentStart + 2) if (commentStart < 0) break // no comment found if (!IsInStringLiteral(commentStart, source, startPos)) break // valid comment } return commentStart } fun TrimComment(source: String): String { val startPos = source.lastIndexOf('\n') + 1 val commentStart = CommentStartPos(source, startPos) // TODO: Check if the trimming is being done properly return if (commentStart >= 0) source.substring(startPos, commentStart) else source } // Find the last token in the given source, ignoring any whitespace // or comment at the end of that line. fun LastToken(source: String): Token { // Start by finding the start and logical end of the last line. val startPos = source.lastIndexOf('\n') + 1 val commentStart = CommentStartPos(source, startPos) // Walk back from end of string or start of comment, skipping whitespace. var endPos = if (commentStart >= 0) commentStart - 1 else source.length - 1 while (endPos >= 0 && IsWhitespace(source[endPos])) endPos-- if (endPos < 0) return Token.EOL // Find the start of that last token. // There are several cases to consider here. var tokStart = endPos val c = source[endPos] if (IsIdentifier(c)) { while (tokStart > startPos && IsIdentifier(source[tokStart - 1])) tokStart-- } else if (c == '"') { var inQuote = true while (tokStart > startPos) { tokStart-- if (source[tokStart] === '"') { inQuote = !inQuote if (!inQuote && tokStart > startPos && source[tokStart - 1] !== '"') break } } } else if (c == '=' && tokStart > startPos) { val c2 = source[tokStart - 1] if (c2 == '>' || c2 == '<' || c2 == '=' || c2 == '!') tokStart-- } // Now use the standard lexer to grab just that bit. val lex = Lexer(source) lex.position = tokStart return lex.Dequeue() } fun RunUnitTests() { } } } }
0
Kotlin
1
5
c0ab5c46f1a441ebaf3a3fc7138d6e109cb8c4a9
9,041
miniscript-kt
MIT License
android/versioned-abis/expoview-abi48_0_0/src/main/java/abi48_0_0/expo/modules/image/ImageViewWrapperTarget.kt
betomoedano
462,599,485
false
null
package abi48_0_0.expo.modules.image import android.graphics.drawable.Drawable import android.util.Log import com.bumptech.glide.RequestManager import com.bumptech.glide.request.ThumbnailRequestCoordinator import com.bumptech.glide.request.transition.Transition import abi48_0_0.expo.modules.core.utilities.ifNull import abi48_0_0.expo.modules.image.enums.ContentFit import java.lang.ref.WeakReference /** * A custom target to provide a smooth transition between multiple drawables. * It delegates images to the [ExpoImageViewWrapper], where we handle the loaded [Drawable]. * When the target is cleared, we don't do anything. The [ExpoImageViewWrapper] is responsible for * clearing bitmaps before freeing targets. That may be error-prone, but that is the only way * of implementing the transition between bitmaps. */ class ImageViewWrapperTarget( private val imageViewHolder: WeakReference<ExpoImageViewWrapper>, ) : com.bumptech.glide.request.target.CustomTarget<Drawable>(SIZE_ORIGINAL, SIZE_ORIGINAL) { var hasSource = false var isUsed = false var placeholderContentFit: ContentFit? = null override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { // The image view should always be valid. When the view is deallocated, all targets should be // canceled. Therefore that code shouldn't be called in that case. Instead of crashing, we // decided to ignore that. val imageView = imageViewHolder.get().ifNull { Log.w("ExpoImage", "The `ExpoImageViewWrapper` was deallocated, but the target wasn't canceled in time.") return } // The thumbnail and full request are handled in the same way by Glide. // Here we're checking if the provided resource is the final bitmap or a thumbnail. val isPlaceholder = if (request is ThumbnailRequestCoordinator) { (request as? ThumbnailRequestCoordinator) ?.getPrivateFullRequest() ?.isComplete != true } else { false } imageView.onResourceReady(this, resource, isPlaceholder) } override fun onLoadCleared(placeholder: Drawable?) = Unit fun clear(requestManager: RequestManager) { requestManager.clear(this) } }
1
null
1
4
52d6405570a39a87149648d045d91098374f4423
2,197
expo
MIT License
domain/src/test/java/org/watsi/domain/relations/EncounterWithExtrasTest.kt
Meso-Health
227,514,539
false
{"Gradle": 7, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 4, "Markdown": 1, "Proguard": 2, "JSON": 25, "Kotlin": 419, "YAML": 3, "XML": 153, "Java": 1}
package org.watsi.domain.relations import org.junit.Assert.assertEquals import org.junit.Test import org.watsi.domain.factories.BillableFactory import org.watsi.domain.factories.BillableWithPriceScheduleFactory import org.watsi.domain.factories.EncounterItemFactory import org.watsi.domain.factories.PriceScheduleFactory class EncounterWithExtrasTest { @Test fun price_noStockouts() { val encounterItem1 = EncounterItemFactory.build(quantity = 1) val encounterItem2 = EncounterItemFactory.build(quantity = 2) val encounterItem3 = EncounterItemFactory.build(quantity = 3) val billable1 = BillableFactory.build() val billable2 = BillableFactory.build() val billable3 = BillableFactory.build() val priceSchedule1 = PriceScheduleFactory.build(billableId = billable1.id, price = 10) val priceSchedule2 = PriceScheduleFactory.build(billableId = billable2.id, price = 25) val priceSchedule3 = PriceScheduleFactory.build(billableId = billable3.id, price = 100) val billableWithPriceSchedule1 = BillableWithPriceScheduleFactory.build(billable1, priceSchedule1) val billableWithPriceSchedule2 = BillableWithPriceScheduleFactory.build(billable2, priceSchedule2) val billableWithPriceSchedule3 = BillableWithPriceScheduleFactory.build(billable3, priceSchedule3) val encounterRelationList = listOf( EncounterItemWithBillableAndPrice(encounterItem1, billableWithPriceSchedule1, null), EncounterItemWithBillableAndPrice(encounterItem2, billableWithPriceSchedule2, null), EncounterItemWithBillableAndPrice(encounterItem3, billableWithPriceSchedule3, null) ) assertEquals(360, EncounterWithExtras.price(encounterRelationList)) } @Test fun price_withStockouts() { val encounterItem1 = EncounterItemFactory.build(quantity = 1, stockout = false) val encounterItem2 = EncounterItemFactory.build(quantity = 2, stockout = false) val encounterItem3 = EncounterItemFactory.build(quantity = 3, stockout = true) val billable1 = BillableFactory.build() val billable2 = BillableFactory.build() val priceSchedule1 = PriceScheduleFactory.build(billableId = billable1.id, price = 10) val priceSchedule2 = PriceScheduleFactory.build(billableId = billable2.id, price = 25) val billableWithPriceSchedule1 = BillableWithPriceScheduleFactory.build(billable1, priceSchedule1) val billableWithPriceSchedule2 = BillableWithPriceScheduleFactory.build(billable2, priceSchedule2) val encounterRelationList = listOf( EncounterItemWithBillableAndPrice(encounterItem1, billableWithPriceSchedule1, null), EncounterItemWithBillableAndPrice(encounterItem2, billableWithPriceSchedule2, null), EncounterItemWithBillableAndPrice(encounterItem3, billableWithPriceSchedule2, null) ) assertEquals(60, EncounterWithExtras.price(encounterRelationList)) } }
2
Kotlin
3
6
6e1da182073088f28230fe60a2e09d6f38aab957
3,082
meso-clinic
Apache License 2.0
presentation/src/main/java/com/nemesis/rio/presentation/profile/overview/character/mplus/ranks/MythicPlusOverallRanksItemsFactory.kt
N3-M3-S1S
370,791,918
false
null
package com.nemesis.rio.presentation.profile.overview.character.mplus.ranks import com.nemesis.rio.domain.mplus.ranks.MythicPlusRanksScope import com.nemesis.rio.domain.mplus.ranks.usecase.GetOverallMythicPlusRanksForCurrentSeason import com.nemesis.rio.domain.profile.Character import com.nemesis.rio.presentation.R import com.nemesis.rio.presentation.profile.character.attributes.iconResId import com.nemesis.rio.presentation.profile.character.attributes.stringResId import com.nemesis.rio.presentation.ranks.list.RanksListItem import splitties.resources.appStr class MythicPlusOverallRanksItemsFactory( private val getOverallMythicPlusRanksForCurrentSeason: GetOverallMythicPlusRanksForCurrentSeason ) : MythicPlusRanksItemsFactory { override suspend fun getRanksItems( character: Character, scope: MythicPlusRanksScope ): List<RanksListItem> { val overallRanks = getOverallMythicPlusRanksForCurrentSeason(character, scope) val overallRanksItems = mutableListOf<RanksListItem>() val overallRanksItem = RanksListItem( appStr(R.string.character_mplus_ranks_all_classes_and_roles), overallRanks.overallRanks, R.drawable.role_overall ) overallRanksItems.add(overallRanksItem) overallRanks.overallRoleRanks.mapTo(overallRanksItems) { (role, ranks) -> RanksListItem( appStr(role.stringResId), ranks, role.iconResId ) } return overallRanksItems } }
0
Kotlin
0
0
62dc309a7b4b80ff36ea624bacfa7b00b5d8607e
1,560
rio
MIT License
android/app/src/main/kotlin/com/lior/translation_cards/MainActivity.kt
liorgeren
320,936,715
false
{"Dart": 4843, "Swift": 404, "Kotlin": 131, "Objective-C": 38}
package com.lior.translation_cards import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
1
0
ab275a4841042c2371abbda1df28323a185d84b8
131
flutter-flash-cards
Apache License 2.0
app/src/main/java/com/smarttoolfactory/composecropper/MainActivity.kt
SmartToolFactory
529,241,895
false
{"Kotlin": 262869}
package com.smarttoolfactory.composecropper import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.smarttoolfactory.composecropper.demo.ImageCropDemo import com.smarttoolfactory.composecropper.ui.theme.ComposeCropperTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeCropperTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column { ImageCropDemo() } } } } } }
15
Kotlin
51
358
ac45140384d16c6d1ddfa539a100a92e44b70221
1,108
Compose-Cropper
MIT License
src/main/kotlin/me/fzzyhmstrs/amethyst_core/boost/base/FireAspectBoost.kt
fzzyhmstrs
507,177,454
false
null
package me.fzzyhmstrs.amethyst_core.boost.base import me.fzzyhmstrs.amethyst_core.AC import me.fzzyhmstrs.amethyst_core.boost.BoostConsumers import me.fzzyhmstrs.amethyst_core.boost.EnchantmentAugmentBoost import me.fzzyhmstrs.amethyst_core.modifier.AugmentConsumer import me.fzzyhmstrs.amethyst_core.modifier.AugmentEffect import net.minecraft.enchantment.Enchantments import net.minecraft.util.Identifier class FireAspectBoost: EnchantmentAugmentBoost(AC.identity("fire_aspect_boost"), Enchantments.FIRE_ASPECT, 2) { companion object{ val CONSUMER = AugmentConsumer.createAndRegisterConsumer(AC.identity("fire_aspect_boost_consumer"),BoostConsumers.FIRE_ASPECT_CONSUMER, AugmentConsumer.Type.HARMFUL) } override val boostEffect: AugmentEffect get() = super.boostEffect.withConsumers(CONSUMER) }
2
Kotlin
1
0
c5b7e4f17ef534c525b4a41f38a547ef46f10e13
829
ac
MIT License
src/test/kotlin/no/nav/bidrag/arbeidsflyt/hendelse/featuretoggle/FeatureToggleOpprettOppgave.kt
navikt
295,692,779
false
null
package no.nav.bidrag.arbeidsflyt.hendelse import no.nav.bidrag.arbeidsflyt.dto.OppgaveData import no.nav.bidrag.arbeidsflyt.dto.OppgaveStatus import no.nav.bidrag.arbeidsflyt.dto.Oppgavestatuskategori import no.nav.bidrag.arbeidsflyt.service.BehandleOppgaveHendelseService import no.nav.bidrag.arbeidsflyt.utils.AKTOER_ID import no.nav.bidrag.arbeidsflyt.utils.JOURNALPOST_ID_1 import no.nav.bidrag.arbeidsflyt.utils.OPPGAVETYPE_JFR import no.nav.bidrag.arbeidsflyt.utils.OPPGAVE_ID_1 import no.nav.bidrag.arbeidsflyt.utils.PERSON_IDENT_1 import no.nav.bidrag.arbeidsflyt.utils.createOppgaveHendelse import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.TestPropertySource @TestPropertySource(properties = ["FEATURE_ENABLED=KAFKA_OPPGAVE"]) class FeatureToggleOpprettOppgave: AbstractBehandleHendelseTest() { @Autowired lateinit var behandleOppgaveHendelseService: BehandleOppgaveHendelseService @Test fun `skal ikke opprette oppgave nar oppgave ferdigstilt men journalpost status er mottatt når feature toggle av`(){ stubHentOppgave(listOf( OppgaveData( id = OPPGAVE_ID_1, versjon = 1, journalpostId = JOURNALPOST_ID_1, aktoerId = AKTOER_ID, oppgavetype = "BEH_SAK", tema = "BID", tildeltEnhetsnr = "4833" ) )) val oppgaveHendelse = createOppgaveHendelse(OPPGAVE_ID_1, journalpostId = JOURNALPOST_ID_1, fnr = PERSON_IDENT_1, status = OppgaveStatus.FERDIGSTILT, statuskategori = Oppgavestatuskategori.AVSLUTTET) behandleOppgaveHendelseService.behandleEndretOppgave(oppgaveHendelse) verifyOppgaveNotOpprettet() } }
3
Kotlin
0
1
9c999650de179ec26ec7298b7922b97caf707dd5
1,805
bidrag-arbeidsflyt
MIT License
AstroYoga/astroyoga/src/main/java/com/shushant/astroyoga/di/AppModule.kt
ShushantTiwari-ashu
667,410,698
false
null
package com.shushant.astroyoga.di import com.shushant.astroyoga.data.utils.AppCoroutineDispatchers import com.shushant.astroyoga.operator.DefaultAppCoroutineDispatchers import com.shushant.astroyoga.ui.MainViewModel import com.shushant.common.compose.utils.ActivityProvider import com.shushant.resource.ResourceProvider import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val appModule = module { viewModel { MainViewModel(get(), get(), get(), get()) } single(createdAtStart = true) { ActivityProvider(get()) } single<AppCoroutineDispatchers> { DefaultAppCoroutineDispatchers() } single { ResourceProvider(get()) } }
0
Kotlin
0
0
9882d51d4a1d975249109c097da0c7b141e6ff69
658
AstroYoga-Full-kotlin-stack-App
Apache License 2.0
shared/src/commonMain/kotlin/com/lightningkite/lightningdb/HasIdFields.kt
lightningkite
512,032,499
false
{"Kotlin": 2373037, "TypeScript": 38628, "JavaScript": 118}
package com.lightningkite.lightningdb import com.lightningkite.serialization.SerializableProperty import com.lightningkite.serialization.serializableProperties import kotlinx.serialization.KSerializer import kotlin.jvm.JvmName @Suppress("UNCHECKED_CAST") fun <Model: HasId<ID>, ID> KSerializer<Model>._id() = serializableProperties!!.find { it.name == "_id" }!! as SerializableProperty<Model, ID> @Suppress("UNCHECKED_CAST") fun <Model: HasEmail> KSerializer<Model>.email() = serializableProperties!!.find { it.name == "email" }!! as SerializableProperty<Model, String> @Suppress("UNCHECKED_CAST") fun <Model: HasPhoneNumber> KSerializer<Model>.phoneNumber() = serializableProperties!!.find { it.name == "phoneNumber" }!! as SerializableProperty<Model, String> @JvmName("emailMaybe") @Suppress("UNCHECKED_CAST") fun <Model: HasMaybeEmail> KSerializer<Model>.email() = serializableProperties!!.find { it.name == "email" }!! as SerializableProperty<Model, String?> @JvmName("phoneNumberMaybe") @Suppress("UNCHECKED_CAST") fun <Model: HasMaybePhoneNumber> KSerializer<Model>.phoneNumber() = serializableProperties!!.find { it.name == "phoneNumber" }!! as SerializableProperty<Model, String?> @Suppress("UNCHECKED_CAST") fun <Model: HasPassword> KSerializer<Model>.hashedPassword() = serializableProperties!!.find { it.name == "hashedPassword" }!! as SerializableProperty<Model, String>
2
Kotlin
1
5
b061fe6b89860f0381a184e6b7fcca7736fad4a4
1,390
lightning-server
MIT License
app/src/main/java/com/example/shrinecompose/MainActivity.kt
c5inco
388,989,613
false
null
package com.example.shrinecompose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.example.shrinecompose.ui.theme.ShrineComposeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ShrineComposeTheme { Cart() } } } } @Preview(showBackground = true) @Composable fun AppPreview() { ShrineComposeTheme { Cart() } }
0
Kotlin
1
5
2275e7332f7d2eacb24dcc10dc6c21e98f4cdb97
666
Shrine-Compose-Stream
Apache License 2.0
androidlibrary/src/main/java/io/supportgenie/androidlibrary/view/main/ChatActivityFragment.kt
himmat-rana
206,965,643
false
null
package io.supportgenie.androidlibrary.view.main import android.Manifest import android.app.Activity.RESULT_OK import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.graphics.LightingColorFilter import android.graphics.Typeface import android.graphics.drawable.ColorDrawable import android.net.ConnectivityManager import androidx.fragment.app.Fragment import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.amazonaws.auth.CognitoCachingCredentialsProvider import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver import com.amazonaws.mobileconnectors.s3.transferutility.TransferState import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility import com.amazonaws.regions.Region import com.amazonaws.regions.Regions import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.AmazonS3Client import com.github.kittinunf.fuel.Fuel import com.github.kittinunf.fuel.core.FuelManager import io.supportgenie.androidlibrary.* import io.supportgenie.androidlibrary.model.* import io.supportgenie.androidlibrary.view.common.getViewModel import io.supportgenie.androidlibrary.view.common.onSubmit import io.supportgenie.androidlibrary.viewmodel.ChatMessagesViewModel import kotlinx.android.synthetic.main.fragment_chat.* import kotlinx.android.synthetic.main.rv_chat_doc_item.* import kotlinx.android.synthetic.main.rv_chat_image_item.* import kotlinx.android.synthetic.main.rv_chat_video_item.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.io.IOException import java.util.* /** * A placeholder fragment containing a simple view. */ private const val GALLERY = 1 class ChatActivityFragment(private val sessionId: String, private val companyId: String) : Fragment() { private lateinit var chatMessagesViewModel: ChatMessagesViewModel private lateinit var imagePath: String private lateinit var videoPath: String private lateinit var pdfFullPath: String private lateinit var fileName: String private lateinit var pdfFileName: String private lateinit var msgPng: String private lateinit var msgJpg: String private lateinit var msgPdf: String private lateinit var msgMp4: String private lateinit var s3Client: AmazonS3 private var bucket = "supportgeniemedia" private lateinit var transferUtility: TransferUtility override fun onAttach(context: Context?) { super.onAttach(context) chatMessagesViewModel = getViewModel(ChatMessagesViewModel::class) FuelManager.instance.basePath = "https://staging-webservice.supportgenie.io/v3" s3credentialsProvider() setTransferUtility() val uniqueID = UUID.randomUUID().toString() println("uniqueID By UUID--->$uniqueID") } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_chat, container, false) } private fun sendTextMessage() { val message = etSendMessage.text.toString() println("send text message is $message") if (message.isNotEmpty()) { println("send text message $message for session $sessionId company $companyId") this.context?.let { sendTextMessage(message, sessionId, companyId, it) } etSendMessage.setText("") rvChatMessages.adapter?.itemCount?.let { //rvChatMessages.scrollToPosition(it - 1) } } } private fun sendPngImage() { val message = msgPng println("send png image is $message") if (message.isNotEmpty()) { println("send png image $message for session $sessionId company $companyId") this.context?.let { sendPngImage(message, sessionId, companyId, it) } rvChatMessages.adapter?.itemCount?.let { //rvChatMessages.scrollToPosition(it - 1) } } } private fun sendJpgImage() { val message = msgJpg println("send jpg image is $message") if (message.isNotEmpty()) { println("send jpg image $message for session $sessionId company $companyId") this.context?.let { sendJpgImage(message, sessionId, companyId, it) } rvChatMessages.adapter?.itemCount?.let { //rvChatMessages.scrollToPosition(it - 1) } } } private fun sendMp4Video() { val message = msgMp4 println("send mp4 video is $message") if (message.isNotEmpty()) { println("send mp4 video $message for session $sessionId company $companyId") this.context?.let { sendMp4Video(message, sessionId, companyId, it) } rvChatMessages.adapter?.itemCount?.let { //rvChatMessages.scrollToPosition(it - 1) } } } private fun sendPdfFile() { val message = msgPdf println("send pdf file is $message") if (message.isNotEmpty()) { println("send pdf file $message for session $sessionId company $companyId") this.context?.let { sendPdfFile(message, sessionId, companyId, it) } rvChatMessages.adapter?.itemCount?.let { //rvChatMessages.scrollToPosition(it - 1) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpChatMessageRecyclerView() // Will come from MainActivity //setUpSwipeRefresh() // Implemented later observeAgentCompanies() observeSessions() observeSessionParticipants() observeMessages() btSend.setOnClickListener { sendTextMessage() } etSendMessage.onSubmit { sendTextMessage() } // ibAttach.setOnClickListener { // attachFile() // } ibAdd.setOnClickListener { attachFile() } btEndChat.setOnClickListener { endChatSession() } } private fun endChatSession() { val status = "closed" this.context?.let { endChatSession(status, sessionId, companyId, it) } activity?.onBackPressed() } private fun setUpChatMessageRecyclerView() = with(rvChatMessages) { val linearLayoutManager: LinearLayoutManager? = androidx.recyclerview.widget.LinearLayoutManager(context) //linearLayoutManager?.stackFromEnd = true layoutManager = linearLayoutManager //adapter = SessionsListAdapter(emptyList<SessionData>()) adapter = ChatListAdapter( kotlin.collections.emptyList<Agent>(), kotlin.collections.emptyList<Session>(), kotlin.collections.emptyList<SessionParticipant>(), kotlin.collections.emptyList<Company>(), kotlin.collections.emptyList<ChatMessage>(), fragmentManager ) } private fun observeAgentCompanies() = GlobalScope.launch { // Updates list when favorites change // val companyId="<KEY>" val companiesData = chatMessagesViewModel.getAgentsForCompany(companyId) withContext(Dispatchers.Main) { companiesData.observe(this@ChatActivityFragment, Observer { companies -> companies?.let { (rvChatMessages.adapter as? ChatListAdapter)?.setAgentsForCompany(companies) } }) } } private fun observeSessions() = GlobalScope.launch { // Updates list when favorites change // val sessionId="5c99ce01b662766ce5e9a68e" val sessionsData = chatMessagesViewModel.getSession(sessionId) withContext(Dispatchers.Main) { sessionsData.observe(this@ChatActivityFragment, Observer { sessions -> sessions?.let { (rvChatMessages.adapter as? ChatListAdapter)?.setSessions(sessions) val sessionStatus = sessions.status if (sessionStatus == "closed") { etSendMessage.isEnabled = false // btSend.isClickable=false // ibCamera.isClickable = false // ibAdd.isClickable=false // btEndChat.isClickable=false // ibAttach.isClickable=false btSend.isEnabled = false ibCamera.isEnabled = false ibAdd.isEnabled = false // btEndChat.isEnabled = false btEndChat.isClickable = false // ibAttach.isEnabled = false val color = Color.parseColor("#D3D3D3") // rvChatMessages.setBackgroundColor(color) // etSendMessage.setBackgroundColor(color) // ibCamera.setBackgroundColor(color) // ibAdd.setBackgroundColor(color) // btEndChat.setBackgroundColor(color) // ibAttach.setBackgroundColor(color) frag_chat.setBackgroundColor(color) btEndChat.background = null etSendMessage.setText("Chat Ended") etSendMessage.setTextColor(Color.RED) etSendMessage.setGravity(Gravity.CENTER_HORIZONTAL) // etSendMessage.setBackgroundColor(Color.WHITE) // btSend.visibility = View.GONE etSendMessage.typeface = Typeface.DEFAULT_BOLD // btSend.setBackgroundColor(Color.rgb(255, 255, 255)) // ivMessageImage?.setOnClickListener(null) // clAdaptiveCard.setBackgroundColor(color) // ivMessageImage?.isEnabled = false // tvPdfMessage?.isEnabled = false // imgThumbnail?.isEnabled = false // ivMessageImage?.isClickable = false // tvPdfMessage?.isClickable = false // imgThumbnail?.isClickable = false // ivMessageImage?.setOnClickListener { // return@setOnClickListener // } } else { btEndChat.setBackgroundColor(Color.WHITE) btEndChat.background = null ibCamera.setBackgroundColor(Color.WHITE) ibCamera.background = null ibAdd.setBackgroundColor(Color.WHITE) ibAdd.background = null } } }) } } private fun observeSessionParticipants() = GlobalScope.launch { // Updates list when favorites change // val sessionId="5c99ce01b662766ce5e9a68e" val sessionsData = chatMessagesViewModel.getSessionParticipants(sessionId) withContext(Dispatchers.Main) { sessionsData.observe(this@ChatActivityFragment, Observer { sessions -> sessions?.let { (rvChatMessages.adapter as? ChatListAdapter)?.setSessionParticipants(sessions) } }) } } private fun observeMessages() = GlobalScope.launch { // Updates list when favorites change // val sessionId="5c99ce01b662766ce5e9a68e" val messagesData = chatMessagesViewModel.getMessages(sessionId) withContext(Dispatchers.Main) { messagesData.observe(this@ChatActivityFragment, Observer { messages -> messages?.let { val chatListAdapter = rvChatMessages.adapter as? ChatListAdapter chatListAdapter?.let { println("item count before setting messages ${it.itemCount}") it.setMessages(messages) //(rvChatMessages.adapter as? ChatListAdapter)?.notifyItemInserted(it.size) //rvChatMessages.scrollToPosition(it.size) println("item count after setting messages ${it.itemCount}") rvChatMessages.smoothScrollToPosition(it.itemCount - 1) } } }) } } // code for uploading attachment to AWS S3 Bucket private fun attachFile() { showPictureDialog() } private fun showPictureDialog() { val pictureDialog = AlertDialog.Builder(context) pictureDialog.setTitle("Select Action :") // pictureDialog.getWindow().setBackgroundDrawable(ColorDrawable(Color.YELLOW)) val pictureDialogItems = arrayOf( "Select Image from Gallery", "Select Video from Gallery", "Select Pdf File from Gallery" ) pictureDialog.setItems( pictureDialogItems ) { _, which -> when (which) { 0 -> chooseImageFromGallery() 1 -> chooseVideoFromGallery() 2 -> choosePdfFromGallery() } } pictureDialog.show() } private fun chooseImageFromGallery() { if (ActivityCompat.checkSelfPermission( activity!!.applicationContext, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ) run { ActivityCompat.requestPermissions( activity!!, arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE ), 10 ) } else { val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(galleryIntent, GALLERY) } } private fun chooseVideoFromGallery() { if (ActivityCompat.checkSelfPermission( activity!!.applicationContext, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ) run { ActivityCompat.requestPermissions( activity!!, arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE ), 10 ) } else { val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) startActivityForResult(galleryIntent, GALLERY) } } private fun choosePdfFromGallery() { if (ActivityCompat.checkSelfPermission( activity!!.applicationContext, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ) run { ActivityCompat.requestPermissions( activity!!, arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE ), 10 ) } else { val intent = Intent() .setType("application/pdf") .setAction(Intent.ACTION_GET_CONTENT) startActivityForResult(Intent.createChooser(intent, "Select a File"), 2) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { // TODO Auto-generated method stub if (requestCode == GALLERY) { fileName = data.data!!.lastPathSegment!! val contentURI = data.data!! try { val filePathColumn = arrayOf(MediaStore.Images.Media.DATA) val filePathColumn1 = arrayOf(MediaStore.Video.Media.DATA) val cursor = activity!!.applicationContext.contentResolver.query( contentURI, filePathColumn, null, null, null ) val cursor1 = activity!!.applicationContext.contentResolver.query( contentURI, filePathColumn1, null, null, null ) cursor!!.moveToFirst() cursor1!!.moveToFirst() val columnIndex = cursor.getColumnIndex(filePathColumn[0]) imagePath = cursor.getString(columnIndex) cursor.close() val columnIndex1 = cursor1.getColumnIndex(filePathColumn1[0]) videoPath = cursor1.getString(columnIndex1) cursor1.close() // etSendMessage.setText(picturePath) // etSendMessage.setText(picturePath1) // etSendMessage.setText(fileName) if (imagePath.contains(".png") || imagePath.contains(".jpg") || videoPath.contains(".mp4")) { uploadToS3() } // else{ // Toast.makeText(context,"File format not supported.",Toast.LENGTH_LONG).show() // } // if (imagePath.contains(".png")) { // uploadToS3() //// etSendMessage.setText(picturePath) //// val a=".png" //// etSendMessage.setText(fileName+a) // //// etSendMessage.setText(fileName) //// etSendMessage.isEnabled = false // //// println("PNG Image Path-$imagePath") //// println("PNG Image FileName-$fileName") // } // if (imagePath.contains(".jpg")) { // uploadToS3() //// etSendMessage.setText(picturePath) //// val a=".jpg" //// etSendMessage.setText(fileName+a) // //// etSendMessage.setText(fileName) //// etSendMessage.isEnabled = false // //// println("JPG Image Path-$picturePath") //// println("JPG Image FileName-$fileName") //// img_video_upload_to_S3() // } // if (videoPath.contains(".mp4")) { // uploadToS3() //// etSendMessage.setText(picturePath1) //// val a=".mp4" //// etSendMessage.setText(fileName+a) // //// etSendMessage.setText(fileName) //// etSendMessage.isEnabled = false // //// println("MP4 Video Path-$videoPath") //// println("MP4 Video FileName-$fileName") //// img_video_upload_to_S3() // } } catch (e: IOException) { e.printStackTrace() Toast.makeText( context, "Error in Picking Image/Video from Gallery.", Toast.LENGTH_LONG ).show() } // uploadToS3() // etSendMessage.text?.clear() // etSendMessage.isEnabled = true } if (requestCode == 2 && resultCode == RESULT_OK) { val selectedFile = data.data!!.lastPathSegment!! pdfFullPath = data.data!!.path!! val regex = """(.+)/(.+)\.(.+)""".toRegex() val matchResult = regex.matchEntire(selectedFile) if (matchResult != null) { val (directory, fileName, extension) = matchResult.destructured // println("dir: $directory | fileName: $fileName | extension: $extension") pdfFileName = "$fileName.$extension" // etSendMessage.setText(selectedFile) // etSendMessage.setText(pdfFileName) // println("pdfFilePath: $pdfFullPath") // println("pdfFileName: $pdfFileName") // println("pdfSelectedFile: $selectedFile") // etSendMessage.setText(pdfFullPath) //// etSendMessage.setText(selectedFile) // etSendMessage.isEnabled = false } if (isOnline()) { // etSendMessage.setText(selectedFile) // etSendMessage.isEnabled = false if (selectedFile.isEmpty()) { Toast.makeText(context, "Please select a PDF File.", Toast.LENGTH_LONG).show() return } if (selectedFile.trim().isNotEmpty()) { if (selectedFile.contains(".pdf")) { val uploadToS3 = File(selectedFile) try { val transferObserver = transferUtility.upload( bucket, pdfFileName, uploadToS3 ) transferObserverListener(transferObserver) val a = "https://s3-us-west-1.amazonaws.com/supportgeniemedia/" val b = pdfFileName // val msg = a.plus(b) msgPdf = a.plus(b) val uniqueID = UUID.randomUUID().toString() println("uniqueID--->$uniqueID") // Fuel.post( // "/message/send", listOf( // "id" to uniqueID, // "message" to msgPdf, // "sender" to "5c99cdfd830f78365845f193", // "senderType" to "customer", // "sessionId" to "5c99ce01b662766ce5e9a68e", // "mimeType" to "application/pdf" // ) // ).response { _, _, _ -> // Toast.makeText( // context, // "Please open the App again to see changes.", // Toast.LENGTH_LONG // ) // .show() // } // if (msgPdf.isNotEmpty()) { // println("send pdf file $msgPdf for session $sessionId company $companyId") // this.context?.let { // sendPdfFile(msgPdf, sessionId, companyId, it) // } // } sendPdfFile() } catch (e: Exception) { Toast.makeText( context, "Error in Uploading PDF File.", Toast.LENGTH_LONG ).show() } } } // etSendMessage.text?.clear() // etSendMessage.isEnabled = true } else { Toast.makeText(context, "You are not connected to Internet.", Toast.LENGTH_LONG) .show() AlertDialog.Builder(context).setTitle("No Internet Connection.") .setMessage("Please check your internet connection and try again later!") .setPositiveButton(android.R.string.ok) { _, _ -> // finish() // startActivity(intent) } .setIcon(android.R.drawable.ic_dialog_alert).show() } } } private fun uploadToS3() { if (isOnline()) { val uploadToS3 = File(imagePath) val uploadToS31 = File(videoPath) if (imagePath.isEmpty() || videoPath.isEmpty()) { return@uploadToS3 } if (imagePath.trim().isNotEmpty() || videoPath.trim().isNotEmpty()) { if (imagePath.contains(".png")) { try { val transferObserver = transferUtility.upload( bucket, fileName, uploadToS3 ) transferObserverListener(transferObserver) val a = "https://s3-us-west-1.amazonaws.com/supportgeniemedia/" val b = fileName // val msg = a.plus(b) msgPng = a.plus(b) val uniqueID = UUID.randomUUID().toString() println("uniqueID--->$uniqueID") // Fuel.post( // "/message/send", listOf( // "id" to uniqueID, // "message" to msgPng, // "sender" to "5c99cdfd830f78365845f193", // "senderType" to "customer", // "sessionId" to "5c99ce01b662766ce5e9a68e", // "mimeType" to "image/png" // ) // ).response { _, _, _ -> // Toast.makeText( // context, // "Please open the App again to see changes.", // Toast.LENGTH_LONG // ) // .show() // } // if (msgPng.isNotEmpty()) { // println("send png image $msgPng for session $sessionId company $companyId") // this.context?.let { // sendPngImage(msgPng, sessionId, companyId, it) // } // } sendPngImage() } catch (e: Exception) { Toast.makeText(context, "Error in Uploading PNG Image.", Toast.LENGTH_LONG) .show() } } else if (imagePath.contains(".jpg")) { try { val transferObserver = transferUtility.upload( bucket, fileName, uploadToS3 ) transferObserverListener(transferObserver) val a = "https://s3-us-west-1.amazonaws.com/supportgeniemedia/" val b = fileName // val msg = a.plus(b) msgJpg = a.plus(b) val uniqueID = UUID.randomUUID().toString() println("uniqueID--->$uniqueID") // Fuel.post( // "/message/send", listOf( // "id" to uniqueID, // "message" to msgJpg, // "sender" to "5c99cdfd830f78365845f193", // "senderType" to "customer", // "sessionId" to "5c99ce01b662766ce5e9a68e", // "mimeType" to "image/jpg" // ) // ).response { _, _, _ -> // Toast.makeText( // context, // "Please open the App again to see changes.", // Toast.LENGTH_LONG // ) // .show() // } // if (msgJpg.isNotEmpty()) { // println("send jpg image $msgJpg for session $sessionId company $companyId") // this.context?.let { // sendJpgImage(msgJpg, sessionId, companyId, it) // } // } sendJpgImage() } catch (e: Exception) { Toast.makeText(context, "Error in Uploading JPG Image.", Toast.LENGTH_LONG) .show() } } else if (videoPath.contains(".mp4")) { try { val transferObserver = transferUtility.upload( bucket, fileName, uploadToS31 ) transferObserverListener(transferObserver) val a = "https://s3-us-west-1.amazonaws.com/supportgeniemedia/" val b = fileName // val msg = a.plus(b) msgMp4 = a.plus(b) val uniqueID = UUID.randomUUID().toString() println("uniqueID--->$uniqueID") // Fuel.post( // "/message/send", listOf( // "id" to uniqueID, // "message" to msgMp4, // "sender" to "5c99cdfd830f78365845f193", // "senderType" to "customer", // "sessionId" to "5c99ce01b662766ce5e9a68e", // "mimeType" to "video/mp4" // ) // ).response { _, _, _ -> // Toast.makeText( // context, // "Please open the App again to see changes.", // Toast.LENGTH_LONG // ) // .show() // } // if (msgMp4.isNotEmpty()) { // println("send mp4 video $msgMp4 for session $sessionId company $companyId") // this.context?.let { // sendMp4Video(msgMp4, sessionId, companyId, it) // } // } sendMp4Video() } catch (e: Exception) { Toast.makeText(context, "Error in Uploading MP4 Video.", Toast.LENGTH_LONG) .show() } } else { Toast.makeText( context, "Please select : jpg/png/mp4 Files only.", Toast.LENGTH_LONG ).show() return@uploadToS3 } } // etSendMessage.text?.clear() // etSendMessage.isEnabled = true } else { Toast.makeText(context, "You are not connected to Internet.", Toast.LENGTH_LONG).show() AlertDialog.Builder(context).setTitle("No Internet Connection.") .setMessage("Please check your internet connection and try again later!") .setPositiveButton(android.R.string.ok) { _, _ -> // finish() // startActivity(intent) } .setIcon(android.R.drawable.ic_dialog_alert).show() } } private fun transferObserverListener(transferObserver: TransferObserver) { transferObserver.setTransferListener(object : TransferListener { override fun onStateChanged(id: Int, state: TransferState) { Toast.makeText(context, "Upload Status: $state", Toast.LENGTH_LONG).show() } override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) { val percentage = (bytesCurrent / bytesTotal * 100).toInt() Toast.makeText(context, "Upload Percentage : $percentage %", Toast.LENGTH_LONG) .show() } override fun onError(id: Int, ex: Exception) { Log.e("Error", "Error") } }) } private fun s3credentialsProvider() { val cognitoCachingCredentialsProvider: CognitoCachingCredentialsProvider = CognitoCachingCredentialsProvider( context, "us-east-1:fdcd1af0-7e51-49fc-b23b-79139735c1f2", Regions.US_EAST_1 ) createAmazonS3Client(cognitoCachingCredentialsProvider) } private fun createAmazonS3Client(credentialsProvider: CognitoCachingCredentialsProvider) { s3Client = AmazonS3Client(credentialsProvider) s3Client.setRegion(Region.getRegion(Regions.US_EAST_1)) } private fun setTransferUtility() { transferUtility = TransferUtility(s3Client, context) } private fun isOnline(): Boolean { val cm = activity?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = cm.activeNetworkInfo return netInfo != null && netInfo.isConnectedOrConnecting } }
1
null
1
1
2fa640e9d281f849a8c25620d640c68aa2e53a91
34,084
AndroidSDK
Apache License 2.0
state/src/main/java/me/rei_m/hyakuninisshu/state/question/model/QuestionResult.kt
rei-m
68,487,243
false
{"Kotlin": 446709, "HTML": 1416}
/* * Copyright (c) 2020. <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package me.rei_m.hyakuninisshu.domain.question.model import me.rei_m.hyakuninisshu.domain.ValueObject import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaNo /** * 問題の正誤判定. * * @param karutaNo 問題の対象となった歌の番号 * @param isCorrect 正解かどうか */ data class QuestionJudgement( val karutaNo: KarutaNo, val isCorrect: Boolean ) : ValueObject
0
Kotlin
1
11
d88621799d19fb55443c14748870a85c063026e3
930
android_hyakuninisshu
Apache License 2.0
src/jvmMain/kotlin/com/rodev/jbpkmp/domain/compiler/BlueprintCompiler.kt
r0astPiGGy
665,522,977
false
null
package com.rodev.jbpkmp.domain.compiler import com.rodev.jbpkmp.domain.compiler.exception.BlueprintCompileException import com.rodev.jbpkmp.domain.model.Blueprint import com.rodev.jbpkmp.domain.repository.NodeDataSource import kotlin.jvm.Throws class BlueprintCompiler( private val nodeDataSource: NodeDataSource ) { @Throws(BlueprintCompileException::class) suspend fun compile(blueprint: Blueprint): String { return BlueprintCompilerHelper(nodeDataSource, blueprint).compile() } }
0
Kotlin
0
3
11dfc41d60c3482fb100ed8d2a8e5f77569836b2
511
JustBlueprints
MIT License
sdk/src/main/kotlin/io/github/wulkanowy/sdk/mapper/MessagesMapper.kt
wulkanowy
138,756,468
false
null
package io.github.wulkanowy.sdk.mapper import io.github.wulkanowy.sdk.normalizeRecipient import io.github.wulkanowy.sdk.pojo.Folder import io.github.wulkanowy.sdk.pojo.Message import io.github.wulkanowy.sdk.pojo.MessageAttachment import io.github.wulkanowy.sdk.pojo.MessageDetails import io.github.wulkanowy.sdk.pojo.MessageReplayDetails import io.github.wulkanowy.sdk.toLocalDateTime import java.time.ZoneId import io.github.wulkanowy.sdk.mobile.messages.Message as ApiMessage import io.github.wulkanowy.sdk.scrapper.messages.MessageDetails as ScrapperDetailsMessage import io.github.wulkanowy.sdk.scrapper.messages.MessageMeta as ScrapperMessageMeta import io.github.wulkanowy.sdk.scrapper.messages.MessageReplayDetails as ScrapperReplayDetailsMessage @JvmName("mapApiMessages") fun List<ApiMessage>.mapMessages(zoneId: ZoneId) = map { Message( globalKey = it.messageId.toString(), id = it.messageId, readBy = it.read?.toInt(), unreadBy = it.unread?.toInt(), unread = it.folder == "Odebrane" && it.readDateTime == null, recipients = it.recipients?.map { recipient -> recipient.copy(name = recipient.name.normalizeRecipient()) }?.mapFromMobileToRecipients().orEmpty(), correspondents = "", mailbox = "", folderId = when (it.folder) { "Odebrane" -> 1 "Wyslane" -> 2 else -> 1 }, content = it.content, dateZoned = it.sentDateTime.toLocalDateTime().atZone(zoneId), subject = it.subject, hasAttachments = false, ) } fun List<ScrapperMessageMeta>.mapMessages(zoneId: ZoneId, folderId: Folder) = map { Message( globalKey = it.apiGlobalKey, id = it.id, mailbox = it.mailbox, subject = it.subject, dateZoned = it.date.atZone(zoneId), content = null, folderId = folderId.id, recipients = emptyList(), correspondents = it.correspondents, unread = !it.isRead, unreadBy = it.readUnreadBy?.substringBefore("/")?.toIntOrNull(), readBy = it.readUnreadBy?.substringAfter("/")?.toIntOrNull(), hasAttachments = it.isAttachments, ) } fun ScrapperDetailsMessage.mapScrapperMessage() = MessageDetails( content = content, apiGlobalKey = apiGlobalKey, date = date, sender = sender, recipients = recipients, subject = subject, id = id, attachments = attachments.map { MessageAttachment( url = it.url, filename = it.filename, ) }, ) fun ScrapperReplayDetailsMessage.mapScrapperMessage() = MessageReplayDetails( content = content, apiGlobalKey = apiGlobalKey, date = date, mailboxId = mailboxId, senderMailboxId = senderMailboxId, senderMailboxName = senderMailboxName, sender = sender.mapToRecipient(), recipients = recipients.mapRecipients(), subject = subject, id = id, attachments = attachments.map { MessageAttachment( url = it.url, filename = it.filename, ) }, )
5
Kotlin
5
22
cd3b738e8173907cc6ba81fe968e93c11eeca0cf
3,081
sdk
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/main/UsbDeviceAddedDetails.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package electron.main typealias UsbDeviceAddedDetails = electron.core.UsbDeviceAddedDetails
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
94
kotlin-wrappers
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/synthetics/CfnCanary.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.synthetics 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.Deprecated import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.collections.Map import kotlin.jvm.JvmName import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * Creates or updates a canary. * * Canaries are scripts that monitor your endpoints and APIs from the outside-in. Canaries help you * check the availability and latency of your web services and troubleshoot anomalies by investigating * load time data, screenshots of the UI, logs, and metrics. You can set up a canary to run * continuously or just once. * * To create canaries, you must have the `CloudWatchSyntheticsFullAccess` policy. If you are * creating a new IAM role for the canary, you also need the the `iam:CreateRole` , `iam:CreatePolicy` * and `iam:AttachRolePolicy` permissions. For more information, see [Necessary Roles and * Permissions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Roles) * . * * Do not include secrets or proprietary information in your canary names. The canary name makes up * part of the Amazon Resource Name (ARN) for the canary, and the ARN is included in outbound calls * over the internet. For more information, see [Security Considerations for Synthetics * Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html) * . * * 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.synthetics.*; * CfnCanary cfnCanary = CfnCanary.Builder.create(this, "MyCfnCanary") * .artifactS3Location("artifactS3Location") * .code(CodeProperty.builder() * .handler("handler") * // the properties below are optional * .s3Bucket("s3Bucket") * .s3Key("s3Key") * .s3ObjectVersion("s3ObjectVersion") * .script("script") * .sourceLocationArn("sourceLocationArn") * .build()) * .executionRoleArn("executionRoleArn") * .name("name") * .runtimeVersion("runtimeVersion") * .schedule(ScheduleProperty.builder() * .expression("expression") * // the properties below are optional * .durationInSeconds("durationInSeconds") * .build()) * // the properties below are optional * .artifactConfig(ArtifactConfigProperty.builder() * .s3Encryption(S3EncryptionProperty.builder() * .encryptionMode("encryptionMode") * .kmsKeyArn("kmsKeyArn") * .build()) * .build()) * .deleteLambdaResourcesOnCanaryDeletion(false) * .failureRetentionPeriod(123) * .runConfig(RunConfigProperty.builder() * .activeTracing(false) * .environmentVariables(Map.of( * "environmentVariablesKey", "environmentVariables")) * .memoryInMb(123) * .timeoutInSeconds(123) * .build()) * .startCanaryAfterCreation(false) * .successRetentionPeriod(123) * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .visualReference(VisualReferenceProperty.builder() * .baseCanaryRunId("baseCanaryRunId") * // the properties below are optional * .baseScreenshots(List.of(BaseScreenshotProperty.builder() * .screenshotName("screenshotName") * // the properties below are optional * .ignoreCoordinates(List.of("ignoreCoordinates")) * .build())) * .build()) * .vpcConfig(VPCConfigProperty.builder() * .securityGroupIds(List.of("securityGroupIds")) * .subnetIds(List.of("subnetIds")) * // the properties below are optional * .vpcId("vpcId") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html) */ public open class CfnCanary( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary, ) : CfnResource(cdkObject), IInspectable, ITaggable { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnCanaryProps, ) : this(software.amazon.awscdk.services.synthetics.CfnCanary(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap), id, props.let(CfnCanaryProps.Companion::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnCanaryProps.Builder.() -> Unit, ) : this(scope, id, CfnCanaryProps(props) ) /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ public open fun artifactConfig(): Any? = unwrap(this).getArtifactConfig() /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ public open fun artifactConfig(`value`: IResolvable) { unwrap(this).setArtifactConfig(`value`.let(IResolvable.Companion::unwrap)) } /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ public open fun artifactConfig(`value`: ArtifactConfigProperty) { unwrap(this).setArtifactConfig(`value`.let(ArtifactConfigProperty.Companion::unwrap)) } /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("f3cb1704f83216a2bfdfbf7cf9496a1793bed3dbae1788e8a7e3f5fd09fa6932") public open fun artifactConfig(`value`: ArtifactConfigProperty.Builder.() -> Unit): Unit = artifactConfig(ArtifactConfigProperty(`value`)) /** * The location in Amazon S3 where Synthetics stores artifacts from the runs of this canary. */ public open fun artifactS3Location(): String = unwrap(this).getArtifactS3Location() /** * The location in Amazon S3 where Synthetics stores artifacts from the runs of this canary. */ public open fun artifactS3Location(`value`: String) { unwrap(this).setArtifactS3Location(`value`) } /** * `Ref` returns the ARN of the Lambda layer where Synthetics stores the canary script code. */ public open fun attrCodeSourceLocationArn(): String = unwrap(this).getAttrCodeSourceLocationArn() /** * The ID of the canary. */ public open fun attrId(): String = unwrap(this).getAttrId() /** * The state of the canary. * * For example, `RUNNING` . */ public open fun attrState(): String = unwrap(this).getAttrState() /** * Use this structure to input your script code for the canary. */ public open fun code(): Any = unwrap(this).getCode() /** * Use this structure to input your script code for the canary. */ public open fun code(`value`: IResolvable) { unwrap(this).setCode(`value`.let(IResolvable.Companion::unwrap)) } /** * Use this structure to input your script code for the canary. */ public open fun code(`value`: CodeProperty) { unwrap(this).setCode(`value`.let(CodeProperty.Companion::unwrap)) } /** * Use this structure to input your script code for the canary. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("4fc5bd083f88ecc4e8524b58bfdd35b15084318d123150fd624c972b2f2b24dc") public open fun code(`value`: CodeProperty.Builder.() -> Unit): Unit = code(CodeProperty(`value`)) /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * @deprecated this property has been deprecated */ @Deprecated(message = "deprecated in CDK") public open fun deleteLambdaResourcesOnCanaryDeletion(): Any? = unwrap(this).getDeleteLambdaResourcesOnCanaryDeletion() /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * @deprecated this property has been deprecated */ @Deprecated(message = "deprecated in CDK") public open fun deleteLambdaResourcesOnCanaryDeletion(`value`: Boolean) { unwrap(this).setDeleteLambdaResourcesOnCanaryDeletion(`value`) } /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * @deprecated this property has been deprecated */ @Deprecated(message = "deprecated in CDK") public open fun deleteLambdaResourcesOnCanaryDeletion(`value`: IResolvable) { unwrap(this).setDeleteLambdaResourcesOnCanaryDeletion(`value`.let(IResolvable.Companion::unwrap)) } /** * The ARN of the IAM role to be used to run the canary. */ public open fun executionRoleArn(): String = unwrap(this).getExecutionRoleArn() /** * The ARN of the IAM role to be used to run the canary. */ public open fun executionRoleArn(`value`: String) { unwrap(this).setExecutionRoleArn(`value`) } /** * The number of days to retain data about failed runs of this canary. */ public open fun failureRetentionPeriod(): Number? = unwrap(this).getFailureRetentionPeriod() /** * The number of days to retain data about failed runs of this canary. */ public open fun failureRetentionPeriod(`value`: Number) { unwrap(this).setFailureRetentionPeriod(`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 name for this canary. */ public open fun name(): String = unwrap(this).getName() /** * The name for this canary. */ public open fun name(`value`: String) { unwrap(this).setName(`value`) } /** * A structure that contains input information for a canary run. */ public open fun runConfig(): Any? = unwrap(this).getRunConfig() /** * A structure that contains input information for a canary run. */ public open fun runConfig(`value`: IResolvable) { unwrap(this).setRunConfig(`value`.let(IResolvable.Companion::unwrap)) } /** * A structure that contains input information for a canary run. */ public open fun runConfig(`value`: RunConfigProperty) { unwrap(this).setRunConfig(`value`.let(RunConfigProperty.Companion::unwrap)) } /** * A structure that contains input information for a canary run. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("eb98029d262fc07236f6cc9512e890ef821f4ee256e72cd14c3ea90d56df3429") public open fun runConfig(`value`: RunConfigProperty.Builder.() -> Unit): Unit = runConfig(RunConfigProperty(`value`)) /** * Specifies the runtime version to use for the canary. */ public open fun runtimeVersion(): String = unwrap(this).getRuntimeVersion() /** * Specifies the runtime version to use for the canary. */ public open fun runtimeVersion(`value`: String) { unwrap(this).setRuntimeVersion(`value`) } /** * A structure that contains information about how often the canary is to run, and when these runs * are to stop. */ public open fun schedule(): Any = unwrap(this).getSchedule() /** * A structure that contains information about how often the canary is to run, and when these runs * are to stop. */ public open fun schedule(`value`: IResolvable) { unwrap(this).setSchedule(`value`.let(IResolvable.Companion::unwrap)) } /** * A structure that contains information about how often the canary is to run, and when these runs * are to stop. */ public open fun schedule(`value`: ScheduleProperty) { unwrap(this).setSchedule(`value`.let(ScheduleProperty.Companion::unwrap)) } /** * A structure that contains information about how often the canary is to run, and when these runs * are to stop. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("93aeb981857476ec769a7a2742025af40fef3205942257c7d9ce1c2c6b0c3570") public open fun schedule(`value`: ScheduleProperty.Builder.() -> Unit): Unit = schedule(ScheduleProperty(`value`)) /** * Specify TRUE to have the canary start making runs immediately after it is created. */ public open fun startCanaryAfterCreation(): Any? = unwrap(this).getStartCanaryAfterCreation() /** * Specify TRUE to have the canary start making runs immediately after it is created. */ public open fun startCanaryAfterCreation(`value`: Boolean) { unwrap(this).setStartCanaryAfterCreation(`value`) } /** * Specify TRUE to have the canary start making runs immediately after it is created. */ public open fun startCanaryAfterCreation(`value`: IResolvable) { unwrap(this).setStartCanaryAfterCreation(`value`.let(IResolvable.Companion::unwrap)) } /** * The number of days to retain data about successful runs of this canary. */ public open fun successRetentionPeriod(): Number? = unwrap(this).getSuccessRetentionPeriod() /** * The number of days to retain data about successful runs of this canary. */ public open fun successRetentionPeriod(`value`: Number) { unwrap(this).setSuccessRetentionPeriod(`value`) } /** * Tag Manager which manages the tags for this resource. */ public override fun tags(): TagManager = unwrap(this).getTags().let(TagManager::wrap) /** * The list of key-value pairs that are associated with the canary. */ public open fun tagsRaw(): List<CfnTag> = unwrap(this).getTagsRaw()?.map(CfnTag::wrap) ?: emptyList() /** * The list of key-value pairs that are associated with the canary. */ public open fun tagsRaw(`value`: List<CfnTag>) { unwrap(this).setTagsRaw(`value`.map(CfnTag.Companion::unwrap)) } /** * The list of key-value pairs that are associated with the canary. */ public open fun tagsRaw(vararg `value`: CfnTag): Unit = tagsRaw(`value`.toList()) /** * If this canary performs visual monitoring by comparing screenshots, this structure contains the * ID of the canary run to use as the baseline for screenshots, and the coordinates of any parts of * the screen to ignore during the visual monitoring comparison. */ public open fun visualReference(): Any? = unwrap(this).getVisualReference() /** * If this canary performs visual monitoring by comparing screenshots, this structure contains the * ID of the canary run to use as the baseline for screenshots, and the coordinates of any parts of * the screen to ignore during the visual monitoring comparison. */ public open fun visualReference(`value`: IResolvable) { unwrap(this).setVisualReference(`value`.let(IResolvable.Companion::unwrap)) } /** * If this canary performs visual monitoring by comparing screenshots, this structure contains the * ID of the canary run to use as the baseline for screenshots, and the coordinates of any parts of * the screen to ignore during the visual monitoring comparison. */ public open fun visualReference(`value`: VisualReferenceProperty) { unwrap(this).setVisualReference(`value`.let(VisualReferenceProperty.Companion::unwrap)) } /** * If this canary performs visual monitoring by comparing screenshots, this structure contains the * ID of the canary run to use as the baseline for screenshots, and the coordinates of any parts of * the screen to ignore during the visual monitoring comparison. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("97e7c35ac5fac3fde2721d515323f2bf59afca8fb0695744278bdb75b635c8ea") public open fun visualReference(`value`: VisualReferenceProperty.Builder.() -> Unit): Unit = visualReference(VisualReferenceProperty(`value`)) /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. */ public open fun vpcConfig(): Any? = unwrap(this).getVpcConfig() /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. */ public open fun vpcConfig(`value`: IResolvable) { unwrap(this).setVpcConfig(`value`.let(IResolvable.Companion::unwrap)) } /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. */ public open fun vpcConfig(`value`: VPCConfigProperty) { unwrap(this).setVpcConfig(`value`.let(VPCConfigProperty.Companion::unwrap)) } /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("2c745b5b442c7930b15a62104ceadf907406274b133cbac468889dd9ce9dde37") public open fun vpcConfig(`value`: VPCConfigProperty.Builder.() -> Unit): Unit = vpcConfig(VPCConfigProperty(`value`)) /** * A fluent builder for [io.cloudshiftdev.awscdk.services.synthetics.CfnCanary]. */ @CdkDslMarker public interface Builder { /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig) * @param artifactConfig A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ public fun artifactConfig(artifactConfig: IResolvable) /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig) * @param artifactConfig A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ public fun artifactConfig(artifactConfig: ArtifactConfigProperty) /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig) * @param artifactConfig A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b23f001e2dd8a6cfb00b3131af1425ae09f30fc4cbc4fc44e8f860e9febcc135") public fun artifactConfig(artifactConfig: ArtifactConfigProperty.Builder.() -> Unit) /** * The location in Amazon S3 where Synthetics stores artifacts from the runs of this canary. * * Artifacts include the log file, screenshots, and HAR files. Specify the full location path, * including `s3://` at the beginning of the path. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifacts3location) * @param artifactS3Location The location in Amazon S3 where Synthetics stores artifacts from * the runs of this canary. */ public fun artifactS3Location(artifactS3Location: String) /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version * are also included. If the script is passed into the canary directly, the script code is * contained in the value of `Script` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code) * @param code Use this structure to input your script code for the canary. */ public fun code(code: IResolvable) /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version * are also included. If the script is passed into the canary directly, the script code is * contained in the value of `Script` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code) * @param code Use this structure to input your script code for the canary. */ public fun code(code: CodeProperty) /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version * are also included. If the script is passed into the canary directly, the script code is * contained in the value of `Script` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code) * @param code Use this structure to input your script code for the canary. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("5c812154cd31e9058f9a59ba258f53c8ba550d96607d8ec454c71346200d4796") public fun code(code: CodeProperty.Builder.() -> Unit) /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * Default is False * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-deletelambdaresourcesoncanarydeletion) * @deprecated this property has been deprecated * @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by * Synthetics if set to True. */ @Deprecated(message = "deprecated in CDK") public fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: Boolean) /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * Default is False * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-deletelambdaresourcesoncanarydeletion) * @deprecated this property has been deprecated * @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by * Synthetics if set to True. */ @Deprecated(message = "deprecated in CDK") public fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: IResolvable) /** * The ARN of the IAM role to be used to run the canary. * * This role must already exist, and must include `lambda.amazonaws.com` as a principal in the * trust policy. The role must also have the following permissions: * * * `s3:PutObject` * * `s3:GetBucketLocation` * * `s3:ListAllMyBuckets` * * `cloudwatch:PutMetricData` * * `logs:CreateLogGroup` * * `logs:CreateLogStream` * * `logs:PutLogEvents` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn) * @param executionRoleArn The ARN of the IAM role to be used to run the canary. */ public fun executionRoleArn(executionRoleArn: String) /** * The number of days to retain data about failed runs of this canary. * * If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-failureretentionperiod) * @param failureRetentionPeriod The number of days to retain data about failed runs of this * canary. */ public fun failureRetentionPeriod(failureRetentionPeriod: Number) /** * The name for this canary. * * Be sure to give it a descriptive name that distinguishes it from other canaries in your * account. * * Do not include secrets or proprietary information in your canary names. The canary name makes * up part of the canary ARN, and the ARN is included in outbound calls over the internet. For more * information, see [Security Considerations for Synthetics * Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-name) * @param name The name for this canary. */ public fun name(name: String) /** * A structure that contains input information for a canary run. * * If you omit this structure, the frequency of the canary is used as canary's timeout value, up * to a maximum of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig) * @param runConfig A structure that contains input information for a canary run. */ public fun runConfig(runConfig: IResolvable) /** * A structure that contains input information for a canary run. * * If you omit this structure, the frequency of the canary is used as canary's timeout value, up * to a maximum of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig) * @param runConfig A structure that contains input information for a canary run. */ public fun runConfig(runConfig: RunConfigProperty) /** * A structure that contains input information for a canary run. * * If you omit this structure, the frequency of the canary is used as canary's timeout value, up * to a maximum of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig) * @param runConfig A structure that contains input information for a canary run. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("593ad653374326f03b8fffc50aebd3f75a0ebf23cee869b1d32c4fbc0ab76399") public fun runConfig(runConfig: RunConfigProperty.Builder.() -> Unit) /** * Specifies the runtime version to use for the canary. * * For more information about runtime versions, see [Canary Runtime * Versions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runtimeversion) * @param runtimeVersion Specifies the runtime version to use for the canary. */ public fun runtimeVersion(runtimeVersion: String) /** * A structure that contains information about how often the canary is to run, and when these * runs are to stop. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule) * @param schedule A structure that contains information about how often the canary is to run, * and when these runs are to stop. */ public fun schedule(schedule: IResolvable) /** * A structure that contains information about how often the canary is to run, and when these * runs are to stop. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule) * @param schedule A structure that contains information about how often the canary is to run, * and when these runs are to stop. */ public fun schedule(schedule: ScheduleProperty) /** * A structure that contains information about how often the canary is to run, and when these * runs are to stop. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule) * @param schedule A structure that contains information about how often the canary is to run, * and when these runs are to stop. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("0fd52bf09f0ec9f283e051ca56ffb048645d905bc4e602bd1a3c9395b5b79ddb") public fun schedule(schedule: ScheduleProperty.Builder.() -> Unit) /** * Specify TRUE to have the canary start making runs immediately after it is created. * * A canary that you create using CloudFormation can't be used to monitor the CloudFormation * stack that creates the canary or to roll back that stack if there is a failure. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-startcanaryaftercreation) * @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately * after it is created. */ public fun startCanaryAfterCreation(startCanaryAfterCreation: Boolean) /** * Specify TRUE to have the canary start making runs immediately after it is created. * * A canary that you create using CloudFormation can't be used to monitor the CloudFormation * stack that creates the canary or to roll back that stack if there is a failure. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-startcanaryaftercreation) * @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately * after it is created. */ public fun startCanaryAfterCreation(startCanaryAfterCreation: IResolvable) /** * The number of days to retain data about successful runs of this canary. * * If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-successretentionperiod) * @param successRetentionPeriod The number of days to retain data about successful runs of this * canary. */ public fun successRetentionPeriod(successRetentionPeriod: Number) /** * The list of key-value pairs that are associated with the canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-tags) * @param tags The list of key-value pairs that are associated with the canary. */ public fun tags(tags: List<CfnTag>) /** * The list of key-value pairs that are associated with the canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-tags) * @param tags The list of key-value pairs that are associated with the canary. */ public fun tags(vararg tags: CfnTag) /** * If this canary performs visual monitoring by comparing screenshots, this structure contains * the ID of the canary run to use as the baseline for screenshots, and the coordinates of any * parts of the screen to ignore during the visual monitoring comparison. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference) * @param visualReference If this canary performs visual monitoring by comparing screenshots, * this structure contains the ID of the canary run to use as the baseline for screenshots, and the * coordinates of any parts of the screen to ignore during the visual monitoring comparison. */ public fun visualReference(visualReference: IResolvable) /** * If this canary performs visual monitoring by comparing screenshots, this structure contains * the ID of the canary run to use as the baseline for screenshots, and the coordinates of any * parts of the screen to ignore during the visual monitoring comparison. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference) * @param visualReference If this canary performs visual monitoring by comparing screenshots, * this structure contains the ID of the canary run to use as the baseline for screenshots, and the * coordinates of any parts of the screen to ignore during the visual monitoring comparison. */ public fun visualReference(visualReference: VisualReferenceProperty) /** * If this canary performs visual monitoring by comparing screenshots, this structure contains * the ID of the canary run to use as the baseline for screenshots, and the coordinates of any * parts of the screen to ignore during the visual monitoring comparison. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference) * @param visualReference If this canary performs visual monitoring by comparing screenshots, * this structure contains the ID of the canary run to use as the baseline for screenshots, and the * coordinates of any parts of the screen to ignore during the visual monitoring comparison. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("0bbb4cbb9894123c40e44079dc0cc74d2f61a18097234b42c75576546fef8718") public fun visualReference(visualReference: VisualReferenceProperty.Builder.() -> Unit) /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig) * @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. */ public fun vpcConfig(vpcConfig: IResolvable) /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig) * @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. */ public fun vpcConfig(vpcConfig: VPCConfigProperty) /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig) * @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("42466e6db317ff4a78574c685c398063fd03f17ed16764eba50d382eca61f3d6") public fun vpcConfig(vpcConfig: VPCConfigProperty.Builder.() -> Unit) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.Builder.create(scope, id) /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig) * @param artifactConfig A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ override fun artifactConfig(artifactConfig: IResolvable) { cdkBuilder.artifactConfig(artifactConfig.let(IResolvable.Companion::unwrap)) } /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig) * @param artifactConfig A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ override fun artifactConfig(artifactConfig: ArtifactConfigProperty) { cdkBuilder.artifactConfig(artifactConfig.let(ArtifactConfigProperty.Companion::unwrap)) } /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifactconfig) * @param artifactConfig A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b23f001e2dd8a6cfb00b3131af1425ae09f30fc4cbc4fc44e8f860e9febcc135") override fun artifactConfig(artifactConfig: ArtifactConfigProperty.Builder.() -> Unit): Unit = artifactConfig(ArtifactConfigProperty(artifactConfig)) /** * The location in Amazon S3 where Synthetics stores artifacts from the runs of this canary. * * Artifacts include the log file, screenshots, and HAR files. Specify the full location path, * including `s3://` at the beginning of the path. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-artifacts3location) * @param artifactS3Location The location in Amazon S3 where Synthetics stores artifacts from * the runs of this canary. */ override fun artifactS3Location(artifactS3Location: String) { cdkBuilder.artifactS3Location(artifactS3Location) } /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version * are also included. If the script is passed into the canary directly, the script code is * contained in the value of `Script` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code) * @param code Use this structure to input your script code for the canary. */ override fun code(code: IResolvable) { cdkBuilder.code(code.let(IResolvable.Companion::unwrap)) } /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version * are also included. If the script is passed into the canary directly, the script code is * contained in the value of `Script` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code) * @param code Use this structure to input your script code for the canary. */ override fun code(code: CodeProperty) { cdkBuilder.code(code.let(CodeProperty.Companion::unwrap)) } /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version * are also included. If the script is passed into the canary directly, the script code is * contained in the value of `Script` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-code) * @param code Use this structure to input your script code for the canary. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("5c812154cd31e9058f9a59ba258f53c8ba550d96607d8ec454c71346200d4796") override fun code(code: CodeProperty.Builder.() -> Unit): Unit = code(CodeProperty(code)) /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * Default is False * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-deletelambdaresourcesoncanarydeletion) * @deprecated this property has been deprecated * @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by * Synthetics if set to True. */ @Deprecated(message = "deprecated in CDK") override fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: Boolean) { cdkBuilder.deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion) } /** * (deprecated) Deletes associated lambda resources created by Synthetics if set to True. * * Default is False * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-deletelambdaresourcesoncanarydeletion) * @deprecated this property has been deprecated * @param deleteLambdaResourcesOnCanaryDeletion Deletes associated lambda resources created by * Synthetics if set to True. */ @Deprecated(message = "deprecated in CDK") override fun deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion: IResolvable) { cdkBuilder.deleteLambdaResourcesOnCanaryDeletion(deleteLambdaResourcesOnCanaryDeletion.let(IResolvable.Companion::unwrap)) } /** * The ARN of the IAM role to be used to run the canary. * * This role must already exist, and must include `lambda.amazonaws.com` as a principal in the * trust policy. The role must also have the following permissions: * * * `s3:PutObject` * * `s3:GetBucketLocation` * * `s3:ListAllMyBuckets` * * `cloudwatch:PutMetricData` * * `logs:CreateLogGroup` * * `logs:CreateLogStream` * * `logs:PutLogEvents` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn) * @param executionRoleArn The ARN of the IAM role to be used to run the canary. */ override fun executionRoleArn(executionRoleArn: String) { cdkBuilder.executionRoleArn(executionRoleArn) } /** * The number of days to retain data about failed runs of this canary. * * If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-failureretentionperiod) * @param failureRetentionPeriod The number of days to retain data about failed runs of this * canary. */ override fun failureRetentionPeriod(failureRetentionPeriod: Number) { cdkBuilder.failureRetentionPeriod(failureRetentionPeriod) } /** * The name for this canary. * * Be sure to give it a descriptive name that distinguishes it from other canaries in your * account. * * Do not include secrets or proprietary information in your canary names. The canary name makes * up part of the canary ARN, and the ARN is included in outbound calls over the internet. For more * information, see [Security Considerations for Synthetics * Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-name) * @param name The name for this canary. */ override fun name(name: String) { cdkBuilder.name(name) } /** * A structure that contains input information for a canary run. * * If you omit this structure, the frequency of the canary is used as canary's timeout value, up * to a maximum of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig) * @param runConfig A structure that contains input information for a canary run. */ override fun runConfig(runConfig: IResolvable) { cdkBuilder.runConfig(runConfig.let(IResolvable.Companion::unwrap)) } /** * A structure that contains input information for a canary run. * * If you omit this structure, the frequency of the canary is used as canary's timeout value, up * to a maximum of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig) * @param runConfig A structure that contains input information for a canary run. */ override fun runConfig(runConfig: RunConfigProperty) { cdkBuilder.runConfig(runConfig.let(RunConfigProperty.Companion::unwrap)) } /** * A structure that contains input information for a canary run. * * If you omit this structure, the frequency of the canary is used as canary's timeout value, up * to a maximum of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runconfig) * @param runConfig A structure that contains input information for a canary run. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("593ad653374326f03b8fffc50aebd3f75a0ebf23cee869b1d32c4fbc0ab76399") override fun runConfig(runConfig: RunConfigProperty.Builder.() -> Unit): Unit = runConfig(RunConfigProperty(runConfig)) /** * Specifies the runtime version to use for the canary. * * For more information about runtime versions, see [Canary Runtime * Versions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-runtimeversion) * @param runtimeVersion Specifies the runtime version to use for the canary. */ override fun runtimeVersion(runtimeVersion: String) { cdkBuilder.runtimeVersion(runtimeVersion) } /** * A structure that contains information about how often the canary is to run, and when these * runs are to stop. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule) * @param schedule A structure that contains information about how often the canary is to run, * and when these runs are to stop. */ override fun schedule(schedule: IResolvable) { cdkBuilder.schedule(schedule.let(IResolvable.Companion::unwrap)) } /** * A structure that contains information about how often the canary is to run, and when these * runs are to stop. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule) * @param schedule A structure that contains information about how often the canary is to run, * and when these runs are to stop. */ override fun schedule(schedule: ScheduleProperty) { cdkBuilder.schedule(schedule.let(ScheduleProperty.Companion::unwrap)) } /** * A structure that contains information about how often the canary is to run, and when these * runs are to stop. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-schedule) * @param schedule A structure that contains information about how often the canary is to run, * and when these runs are to stop. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("0fd52bf09f0ec9f283e051ca56ffb048645d905bc4e602bd1a3c9395b5b79ddb") override fun schedule(schedule: ScheduleProperty.Builder.() -> Unit): Unit = schedule(ScheduleProperty(schedule)) /** * Specify TRUE to have the canary start making runs immediately after it is created. * * A canary that you create using CloudFormation can't be used to monitor the CloudFormation * stack that creates the canary or to roll back that stack if there is a failure. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-startcanaryaftercreation) * @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately * after it is created. */ override fun startCanaryAfterCreation(startCanaryAfterCreation: Boolean) { cdkBuilder.startCanaryAfterCreation(startCanaryAfterCreation) } /** * Specify TRUE to have the canary start making runs immediately after it is created. * * A canary that you create using CloudFormation can't be used to monitor the CloudFormation * stack that creates the canary or to roll back that stack if there is a failure. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-startcanaryaftercreation) * @param startCanaryAfterCreation Specify TRUE to have the canary start making runs immediately * after it is created. */ override fun startCanaryAfterCreation(startCanaryAfterCreation: IResolvable) { cdkBuilder.startCanaryAfterCreation(startCanaryAfterCreation.let(IResolvable.Companion::unwrap)) } /** * The number of days to retain data about successful runs of this canary. * * If you omit this field, the default of 31 days is used. The valid range is 1 to 455 days. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-successretentionperiod) * @param successRetentionPeriod The number of days to retain data about successful runs of this * canary. */ override fun successRetentionPeriod(successRetentionPeriod: Number) { cdkBuilder.successRetentionPeriod(successRetentionPeriod) } /** * The list of key-value pairs that are associated with the canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-tags) * @param tags The list of key-value pairs that are associated with the canary. */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap)) } /** * The list of key-value pairs that are associated with the canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-tags) * @param tags The list of key-value pairs that are associated with the canary. */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) /** * If this canary performs visual monitoring by comparing screenshots, this structure contains * the ID of the canary run to use as the baseline for screenshots, and the coordinates of any * parts of the screen to ignore during the visual monitoring comparison. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference) * @param visualReference If this canary performs visual monitoring by comparing screenshots, * this structure contains the ID of the canary run to use as the baseline for screenshots, and the * coordinates of any parts of the screen to ignore during the visual monitoring comparison. */ override fun visualReference(visualReference: IResolvable) { cdkBuilder.visualReference(visualReference.let(IResolvable.Companion::unwrap)) } /** * If this canary performs visual monitoring by comparing screenshots, this structure contains * the ID of the canary run to use as the baseline for screenshots, and the coordinates of any * parts of the screen to ignore during the visual monitoring comparison. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference) * @param visualReference If this canary performs visual monitoring by comparing screenshots, * this structure contains the ID of the canary run to use as the baseline for screenshots, and the * coordinates of any parts of the screen to ignore during the visual monitoring comparison. */ override fun visualReference(visualReference: VisualReferenceProperty) { cdkBuilder.visualReference(visualReference.let(VisualReferenceProperty.Companion::unwrap)) } /** * If this canary performs visual monitoring by comparing screenshots, this structure contains * the ID of the canary run to use as the baseline for screenshots, and the coordinates of any * parts of the screen to ignore during the visual monitoring comparison. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-visualreference) * @param visualReference If this canary performs visual monitoring by comparing screenshots, * this structure contains the ID of the canary run to use as the baseline for screenshots, and the * coordinates of any parts of the screen to ignore during the visual monitoring comparison. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("0bbb4cbb9894123c40e44079dc0cc74d2f61a18097234b42c75576546fef8718") override fun visualReference(visualReference: VisualReferenceProperty.Builder.() -> Unit): Unit = visualReference(VisualReferenceProperty(visualReference)) /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig) * @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. */ override fun vpcConfig(vpcConfig: IResolvable) { cdkBuilder.vpcConfig(vpcConfig.let(IResolvable.Companion::unwrap)) } /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig) * @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. */ override fun vpcConfig(vpcConfig: VPCConfigProperty) { cdkBuilder.vpcConfig(vpcConfig.let(VPCConfigProperty.Companion::unwrap)) } /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-vpcconfig) * @param vpcConfig If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("42466e6db317ff4a78574c685c398063fd03f17ed16764eba50d382eca61f3d6") override fun vpcConfig(vpcConfig: VPCConfigProperty.Builder.() -> Unit): Unit = vpcConfig(VPCConfigProperty(vpcConfig)) public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.synthetics.CfnCanary.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnCanary { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnCanary(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary): CfnCanary = CfnCanary(cdkObject) internal fun unwrap(wrapped: CfnCanary): software.amazon.awscdk.services.synthetics.CfnCanary = wrapped.cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary } /** * A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3 . * * 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.synthetics.*; * ArtifactConfigProperty artifactConfigProperty = ArtifactConfigProperty.builder() * .s3Encryption(S3EncryptionProperty.builder() * .encryptionMode("encryptionMode") * .kmsKeyArn("kmsKeyArn") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-artifactconfig.html) */ public interface ArtifactConfigProperty { /** * A structure that contains the configuration of the encryption-at-rest settings for artifacts * that the canary uploads to Amazon S3 . * * Artifact encryption functionality is available only for canaries that use Synthetics runtime * version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-artifactconfig.html#cfn-synthetics-canary-artifactconfig-s3encryption) */ public fun s3Encryption(): Any? = unwrap(this).getS3Encryption() /** * A builder for [ArtifactConfigProperty] */ @CdkDslMarker public interface Builder { /** * @param s3Encryption A structure that contains the configuration of the encryption-at-rest * settings for artifacts that the canary uploads to Amazon S3 . * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . */ public fun s3Encryption(s3Encryption: IResolvable) /** * @param s3Encryption A structure that contains the configuration of the encryption-at-rest * settings for artifacts that the canary uploads to Amazon S3 . * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . */ public fun s3Encryption(s3Encryption: S3EncryptionProperty) /** * @param s3Encryption A structure that contains the configuration of the encryption-at-rest * settings for artifacts that the canary uploads to Amazon S3 . * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("c139218594ab3ddb52cd25fe29117d299d2b333cbade9bb9b71aa26d9e27fa73") public fun s3Encryption(s3Encryption: S3EncryptionProperty.Builder.() -> Unit) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty.builder() /** * @param s3Encryption A structure that contains the configuration of the encryption-at-rest * settings for artifacts that the canary uploads to Amazon S3 . * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . */ override fun s3Encryption(s3Encryption: IResolvable) { cdkBuilder.s3Encryption(s3Encryption.let(IResolvable.Companion::unwrap)) } /** * @param s3Encryption A structure that contains the configuration of the encryption-at-rest * settings for artifacts that the canary uploads to Amazon S3 . * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . */ override fun s3Encryption(s3Encryption: S3EncryptionProperty) { cdkBuilder.s3Encryption(s3Encryption.let(S3EncryptionProperty.Companion::unwrap)) } /** * @param s3Encryption A structure that contains the configuration of the encryption-at-rest * settings for artifacts that the canary uploads to Amazon S3 . * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("c139218594ab3ddb52cd25fe29117d299d2b333cbade9bb9b71aa26d9e27fa73") override fun s3Encryption(s3Encryption: S3EncryptionProperty.Builder.() -> Unit): Unit = s3Encryption(S3EncryptionProperty(s3Encryption)) public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty, ) : CdkObject(cdkObject), ArtifactConfigProperty { /** * A structure that contains the configuration of the encryption-at-rest settings for * artifacts that the canary uploads to Amazon S3 . * * Artifact encryption functionality is available only for canaries that use Synthetics * runtime version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting * canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-artifactconfig.html#cfn-synthetics-canary-artifactconfig-s3encryption) */ override fun s3Encryption(): Any? = unwrap(this).getS3Encryption() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): ArtifactConfigProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty): ArtifactConfigProperty = CdkObjectWrappers.wrap(cdkObject) as? ArtifactConfigProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: ArtifactConfigProperty): software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.ArtifactConfigProperty } } /** * A structure representing a screenshot that is used as a baseline during visual monitoring * comparisons made by the canary. * * 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.synthetics.*; * BaseScreenshotProperty baseScreenshotProperty = BaseScreenshotProperty.builder() * .screenshotName("screenshotName") * // the properties below are optional * .ignoreCoordinates(List.of("ignoreCoordinates")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html) */ public interface BaseScreenshotProperty { /** * Coordinates that define the part of a screen to ignore during screenshot comparisons. * * To obtain the coordinates to use here, use the CloudWatch console to draw the boundaries on * the screen. For more information, see [Edit or delete a * canary](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/synthetics_canaries_deletion.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html#cfn-synthetics-canary-basescreenshot-ignorecoordinates) */ public fun ignoreCoordinates(): List<String> = unwrap(this).getIgnoreCoordinates() ?: emptyList() /** * The name of the screenshot. * * This is generated the first time the canary is run after the `UpdateCanary` operation that * specified for this canary to perform visual monitoring. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html#cfn-synthetics-canary-basescreenshot-screenshotname) */ public fun screenshotName(): String /** * A builder for [BaseScreenshotProperty] */ @CdkDslMarker public interface Builder { /** * @param ignoreCoordinates Coordinates that define the part of a screen to ignore during * screenshot comparisons. * To obtain the coordinates to use here, use the CloudWatch console to draw the boundaries on * the screen. For more information, see [Edit or delete a * canary](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/synthetics_canaries_deletion.html) * . */ public fun ignoreCoordinates(ignoreCoordinates: List<String>) /** * @param ignoreCoordinates Coordinates that define the part of a screen to ignore during * screenshot comparisons. * To obtain the coordinates to use here, use the CloudWatch console to draw the boundaries on * the screen. For more information, see [Edit or delete a * canary](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/synthetics_canaries_deletion.html) * . */ public fun ignoreCoordinates(vararg ignoreCoordinates: String) /** * @param screenshotName The name of the screenshot. * This is generated the first time the canary is run after the `UpdateCanary` operation that * specified for this canary to perform visual monitoring. */ public fun screenshotName(screenshotName: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty.builder() /** * @param ignoreCoordinates Coordinates that define the part of a screen to ignore during * screenshot comparisons. * To obtain the coordinates to use here, use the CloudWatch console to draw the boundaries on * the screen. For more information, see [Edit or delete a * canary](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/synthetics_canaries_deletion.html) * . */ override fun ignoreCoordinates(ignoreCoordinates: List<String>) { cdkBuilder.ignoreCoordinates(ignoreCoordinates) } /** * @param ignoreCoordinates Coordinates that define the part of a screen to ignore during * screenshot comparisons. * To obtain the coordinates to use here, use the CloudWatch console to draw the boundaries on * the screen. For more information, see [Edit or delete a * canary](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/synthetics_canaries_deletion.html) * . */ override fun ignoreCoordinates(vararg ignoreCoordinates: String): Unit = ignoreCoordinates(ignoreCoordinates.toList()) /** * @param screenshotName The name of the screenshot. * This is generated the first time the canary is run after the `UpdateCanary` operation that * specified for this canary to perform visual monitoring. */ override fun screenshotName(screenshotName: String) { cdkBuilder.screenshotName(screenshotName) } public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty, ) : CdkObject(cdkObject), BaseScreenshotProperty { /** * Coordinates that define the part of a screen to ignore during screenshot comparisons. * * To obtain the coordinates to use here, use the CloudWatch console to draw the boundaries on * the screen. For more information, see [Edit or delete a * canary](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/synthetics_canaries_deletion.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html#cfn-synthetics-canary-basescreenshot-ignorecoordinates) */ override fun ignoreCoordinates(): List<String> = unwrap(this).getIgnoreCoordinates() ?: emptyList() /** * The name of the screenshot. * * This is generated the first time the canary is run after the `UpdateCanary` operation that * specified for this canary to perform visual monitoring. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-basescreenshot.html#cfn-synthetics-canary-basescreenshot-screenshotname) */ override fun screenshotName(): String = unwrap(this).getScreenshotName() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): BaseScreenshotProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty): BaseScreenshotProperty = CdkObjectWrappers.wrap(cdkObject) as? BaseScreenshotProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: BaseScreenshotProperty): software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.BaseScreenshotProperty } } /** * Use this structure to input your script code for the canary. * * This structure contains the Lambda handler with the location where the canary should start * running the script. If the script is stored in an S3 bucket, the bucket name, key, and version are * also included. If the script is passed into the canary directly, the script code is contained in * the value of `Script` . * * 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.synthetics.*; * CodeProperty codeProperty = CodeProperty.builder() * .handler("handler") * // the properties below are optional * .s3Bucket("s3Bucket") * .s3Key("s3Key") * .s3ObjectVersion("s3ObjectVersion") * .script("script") * .sourceLocationArn("sourceLocationArn") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html) */ public interface CodeProperty { /** * The entry point to use for the source code when running the canary. * * For canaries that use the `syn-python-selenium-1.0` runtime or a `syn-nodejs.puppeteer` * runtime earlier than `syn-nodejs.puppeteer-3.4` , the handler must be specified as `*fileName* * .handler` . For `syn-python-selenium-1.1` , `syn-nodejs.puppeteer-3.4` , and later runtimes, the * handler can be specified as `*fileName* . *functionName*` , or you can specify a folder where * canary scripts reside as `*folder* / *fileName* . *functionName*` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-handler) */ public fun handler(): String /** * If your canary script is located in S3, specify the bucket name here. * * The bucket must already exist. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-s3bucket) */ public fun s3Bucket(): String? = unwrap(this).getS3Bucket() /** * The S3 key of your script. * * For more information, see [Working with Amazon S3 * Objects](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-s3key) */ public fun s3Key(): String? = unwrap(this).getS3Key() /** * The S3 version ID of your script. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-s3objectversion) */ public fun s3ObjectVersion(): String? = unwrap(this).getS3ObjectVersion() /** * If you input your canary script directly into the canary instead of referring to an S3 * location, the value of this parameter is the script in plain text. * * It can be up to 5 MB. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-script) */ public fun script(): String? = unwrap(this).getScript() /** * The ARN of the Lambda layer where Synthetics stores the canary script code. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-sourcelocationarn) */ public fun sourceLocationArn(): String? = unwrap(this).getSourceLocationArn() /** * A builder for [CodeProperty] */ @CdkDslMarker public interface Builder { /** * @param handler The entry point to use for the source code when running the canary. * For canaries that use the `syn-python-selenium-1.0` runtime or a `syn-nodejs.puppeteer` * runtime earlier than `syn-nodejs.puppeteer-3.4` , the handler must be specified as `*fileName* * .handler` . For `syn-python-selenium-1.1` , `syn-nodejs.puppeteer-3.4` , and later runtimes, * the handler can be specified as `*fileName* . *functionName*` , or you can specify a folder * where canary scripts reside as `*folder* / *fileName* . *functionName*` . */ public fun handler(handler: String) /** * @param s3Bucket If your canary script is located in S3, specify the bucket name here. * The bucket must already exist. */ public fun s3Bucket(s3Bucket: String) /** * @param s3Key The S3 key of your script. * For more information, see [Working with Amazon S3 * Objects](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html) . */ public fun s3Key(s3Key: String) /** * @param s3ObjectVersion The S3 version ID of your script. */ public fun s3ObjectVersion(s3ObjectVersion: String) /** * @param script If you input your canary script directly into the canary instead of referring * to an S3 location, the value of this parameter is the script in plain text. * It can be up to 5 MB. */ public fun script(script: String) /** * @param sourceLocationArn The ARN of the Lambda layer where Synthetics stores the canary * script code. */ public fun sourceLocationArn(sourceLocationArn: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty.builder() /** * @param handler The entry point to use for the source code when running the canary. * For canaries that use the `syn-python-selenium-1.0` runtime or a `syn-nodejs.puppeteer` * runtime earlier than `syn-nodejs.puppeteer-3.4` , the handler must be specified as `*fileName* * .handler` . For `syn-python-selenium-1.1` , `syn-nodejs.puppeteer-3.4` , and later runtimes, * the handler can be specified as `*fileName* . *functionName*` , or you can specify a folder * where canary scripts reside as `*folder* / *fileName* . *functionName*` . */ override fun handler(handler: String) { cdkBuilder.handler(handler) } /** * @param s3Bucket If your canary script is located in S3, specify the bucket name here. * The bucket must already exist. */ override fun s3Bucket(s3Bucket: String) { cdkBuilder.s3Bucket(s3Bucket) } /** * @param s3Key The S3 key of your script. * For more information, see [Working with Amazon S3 * Objects](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html) . */ override fun s3Key(s3Key: String) { cdkBuilder.s3Key(s3Key) } /** * @param s3ObjectVersion The S3 version ID of your script. */ override fun s3ObjectVersion(s3ObjectVersion: String) { cdkBuilder.s3ObjectVersion(s3ObjectVersion) } /** * @param script If you input your canary script directly into the canary instead of referring * to an S3 location, the value of this parameter is the script in plain text. * It can be up to 5 MB. */ override fun script(script: String) { cdkBuilder.script(script) } /** * @param sourceLocationArn The ARN of the Lambda layer where Synthetics stores the canary * script code. */ override fun sourceLocationArn(sourceLocationArn: String) { cdkBuilder.sourceLocationArn(sourceLocationArn) } public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty, ) : CdkObject(cdkObject), CodeProperty { /** * The entry point to use for the source code when running the canary. * * For canaries that use the `syn-python-selenium-1.0` runtime or a `syn-nodejs.puppeteer` * runtime earlier than `syn-nodejs.puppeteer-3.4` , the handler must be specified as `*fileName* * .handler` . For `syn-python-selenium-1.1` , `syn-nodejs.puppeteer-3.4` , and later runtimes, * the handler can be specified as `*fileName* . *functionName*` , or you can specify a folder * where canary scripts reside as `*folder* / *fileName* . *functionName*` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-handler) */ override fun handler(): String = unwrap(this).getHandler() /** * If your canary script is located in S3, specify the bucket name here. * * The bucket must already exist. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-s3bucket) */ override fun s3Bucket(): String? = unwrap(this).getS3Bucket() /** * The S3 key of your script. * * For more information, see [Working with Amazon S3 * Objects](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-s3key) */ override fun s3Key(): String? = unwrap(this).getS3Key() /** * The S3 version ID of your script. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-s3objectversion) */ override fun s3ObjectVersion(): String? = unwrap(this).getS3ObjectVersion() /** * If you input your canary script directly into the canary instead of referring to an S3 * location, the value of this parameter is the script in plain text. * * It can be up to 5 MB. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-script) */ override fun script(): String? = unwrap(this).getScript() /** * The ARN of the Lambda layer where Synthetics stores the canary script code. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-code.html#cfn-synthetics-canary-code-sourcelocationarn) */ override fun sourceLocationArn(): String? = unwrap(this).getSourceLocationArn() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CodeProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty): CodeProperty = CdkObjectWrappers.wrap(cdkObject) as? CodeProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CodeProperty): software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.CodeProperty } } /** * A structure that contains input information for a canary run. * * This structure is required. * * 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.synthetics.*; * RunConfigProperty runConfigProperty = RunConfigProperty.builder() * .activeTracing(false) * .environmentVariables(Map.of( * "environmentVariablesKey", "environmentVariables")) * .memoryInMb(123) * .timeoutInSeconds(123) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html) */ public interface RunConfigProperty { /** * Specifies whether this canary is to use active AWS X-Ray tracing when it runs. * * Active tracing enables this canary run to be displayed in the ServiceLens and X-Ray service * maps even if the canary does not hit an endpoint that has X-Ray tracing enabled. Using X-Ray * tracing incurs charges. For more information, see [Canaries and X-Ray * tracing](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html) * . * * You can enable active tracing only for canaries that use version `syn-nodejs-2.0` or later * for their canary runtime. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-activetracing) */ public fun activeTracing(): Any? = unwrap(this).getActiveTracing() /** * Specifies the keys and values to use for any environment variables used in the canary script. * * Use the following format: * * { "key1" : "value1", "key2" : "value2", ...} * * Keys must start with a letter and be at least two characters. The total size of your * environment variables cannot exceed 4 KB. You can't specify any Lambda reserved environment * variables as the keys for your environment variables. For more information about reserved keys, * see [Runtime environment * variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-environmentvariables) */ public fun environmentVariables(): Any? = unwrap(this).getEnvironmentVariables() /** * The maximum amount of memory that the canary can use while running. * * This value must be a multiple of 64. The range is 960 to 3008. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-memoryinmb) */ public fun memoryInMb(): Number? = unwrap(this).getMemoryInMb() /** * How long the canary is allowed to run before it must stop. * * You can't set this time to be longer than the frequency of the runs of this canary. * * If you omit this field, the frequency of the canary is used as this value, up to a maximum of * 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-timeoutinseconds) */ public fun timeoutInSeconds(): Number? = unwrap(this).getTimeoutInSeconds() /** * A builder for [RunConfigProperty] */ @CdkDslMarker public interface Builder { /** * @param activeTracing Specifies whether this canary is to use active AWS X-Ray tracing when * it runs. * Active tracing enables this canary run to be displayed in the ServiceLens and X-Ray service * maps even if the canary does not hit an endpoint that has X-Ray tracing enabled. Using X-Ray * tracing incurs charges. For more information, see [Canaries and X-Ray * tracing](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html) * . * * You can enable active tracing only for canaries that use version `syn-nodejs-2.0` or later * for their canary runtime. */ public fun activeTracing(activeTracing: Boolean) /** * @param activeTracing Specifies whether this canary is to use active AWS X-Ray tracing when * it runs. * Active tracing enables this canary run to be displayed in the ServiceLens and X-Ray service * maps even if the canary does not hit an endpoint that has X-Ray tracing enabled. Using X-Ray * tracing incurs charges. For more information, see [Canaries and X-Ray * tracing](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html) * . * * You can enable active tracing only for canaries that use version `syn-nodejs-2.0` or later * for their canary runtime. */ public fun activeTracing(activeTracing: IResolvable) /** * @param environmentVariables Specifies the keys and values to use for any environment * variables used in the canary script. * Use the following format: * * { "key1" : "value1", "key2" : "value2", ...} * * Keys must start with a letter and be at least two characters. The total size of your * environment variables cannot exceed 4 KB. You can't specify any Lambda reserved environment * variables as the keys for your environment variables. For more information about reserved * keys, see [Runtime environment * variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime) * . */ public fun environmentVariables(environmentVariables: IResolvable) /** * @param environmentVariables Specifies the keys and values to use for any environment * variables used in the canary script. * Use the following format: * * { "key1" : "value1", "key2" : "value2", ...} * * Keys must start with a letter and be at least two characters. The total size of your * environment variables cannot exceed 4 KB. You can't specify any Lambda reserved environment * variables as the keys for your environment variables. For more information about reserved * keys, see [Runtime environment * variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime) * . */ public fun environmentVariables(environmentVariables: Map<String, String>) /** * @param memoryInMb The maximum amount of memory that the canary can use while running. * This value must be a multiple of 64. The range is 960 to 3008. */ public fun memoryInMb(memoryInMb: Number) /** * @param timeoutInSeconds How long the canary is allowed to run before it must stop. * You can't set this time to be longer than the frequency of the runs of this canary. * * If you omit this field, the frequency of the canary is used as this value, up to a maximum * of 900 seconds. */ public fun timeoutInSeconds(timeoutInSeconds: Number) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty.builder() /** * @param activeTracing Specifies whether this canary is to use active AWS X-Ray tracing when * it runs. * Active tracing enables this canary run to be displayed in the ServiceLens and X-Ray service * maps even if the canary does not hit an endpoint that has X-Ray tracing enabled. Using X-Ray * tracing incurs charges. For more information, see [Canaries and X-Ray * tracing](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html) * . * * You can enable active tracing only for canaries that use version `syn-nodejs-2.0` or later * for their canary runtime. */ override fun activeTracing(activeTracing: Boolean) { cdkBuilder.activeTracing(activeTracing) } /** * @param activeTracing Specifies whether this canary is to use active AWS X-Ray tracing when * it runs. * Active tracing enables this canary run to be displayed in the ServiceLens and X-Ray service * maps even if the canary does not hit an endpoint that has X-Ray tracing enabled. Using X-Ray * tracing incurs charges. For more information, see [Canaries and X-Ray * tracing](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html) * . * * You can enable active tracing only for canaries that use version `syn-nodejs-2.0` or later * for their canary runtime. */ override fun activeTracing(activeTracing: IResolvable) { cdkBuilder.activeTracing(activeTracing.let(IResolvable.Companion::unwrap)) } /** * @param environmentVariables Specifies the keys and values to use for any environment * variables used in the canary script. * Use the following format: * * { "key1" : "value1", "key2" : "value2", ...} * * Keys must start with a letter and be at least two characters. The total size of your * environment variables cannot exceed 4 KB. You can't specify any Lambda reserved environment * variables as the keys for your environment variables. For more information about reserved * keys, see [Runtime environment * variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime) * . */ override fun environmentVariables(environmentVariables: IResolvable) { cdkBuilder.environmentVariables(environmentVariables.let(IResolvable.Companion::unwrap)) } /** * @param environmentVariables Specifies the keys and values to use for any environment * variables used in the canary script. * Use the following format: * * { "key1" : "value1", "key2" : "value2", ...} * * Keys must start with a letter and be at least two characters. The total size of your * environment variables cannot exceed 4 KB. You can't specify any Lambda reserved environment * variables as the keys for your environment variables. For more information about reserved * keys, see [Runtime environment * variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime) * . */ override fun environmentVariables(environmentVariables: Map<String, String>) { cdkBuilder.environmentVariables(environmentVariables) } /** * @param memoryInMb The maximum amount of memory that the canary can use while running. * This value must be a multiple of 64. The range is 960 to 3008. */ override fun memoryInMb(memoryInMb: Number) { cdkBuilder.memoryInMb(memoryInMb) } /** * @param timeoutInSeconds How long the canary is allowed to run before it must stop. * You can't set this time to be longer than the frequency of the runs of this canary. * * If you omit this field, the frequency of the canary is used as this value, up to a maximum * of 900 seconds. */ override fun timeoutInSeconds(timeoutInSeconds: Number) { cdkBuilder.timeoutInSeconds(timeoutInSeconds) } public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty, ) : CdkObject(cdkObject), RunConfigProperty { /** * Specifies whether this canary is to use active AWS X-Ray tracing when it runs. * * Active tracing enables this canary run to be displayed in the ServiceLens and X-Ray service * maps even if the canary does not hit an endpoint that has X-Ray tracing enabled. Using X-Ray * tracing incurs charges. For more information, see [Canaries and X-Ray * tracing](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html) * . * * You can enable active tracing only for canaries that use version `syn-nodejs-2.0` or later * for their canary runtime. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-activetracing) */ override fun activeTracing(): Any? = unwrap(this).getActiveTracing() /** * Specifies the keys and values to use for any environment variables used in the canary * script. * * Use the following format: * * { "key1" : "value1", "key2" : "value2", ...} * * Keys must start with a letter and be at least two characters. The total size of your * environment variables cannot exceed 4 KB. You can't specify any Lambda reserved environment * variables as the keys for your environment variables. For more information about reserved * keys, see [Runtime environment * variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-environmentvariables) */ override fun environmentVariables(): Any? = unwrap(this).getEnvironmentVariables() /** * The maximum amount of memory that the canary can use while running. * * This value must be a multiple of 64. The range is 960 to 3008. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-memoryinmb) */ override fun memoryInMb(): Number? = unwrap(this).getMemoryInMb() /** * How long the canary is allowed to run before it must stop. * * You can't set this time to be longer than the frequency of the runs of this canary. * * If you omit this field, the frequency of the canary is used as this value, up to a maximum * of 900 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-runconfig.html#cfn-synthetics-canary-runconfig-timeoutinseconds) */ override fun timeoutInSeconds(): Number? = unwrap(this).getTimeoutInSeconds() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): RunConfigProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty): RunConfigProperty = CdkObjectWrappers.wrap(cdkObject) as? RunConfigProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: RunConfigProperty): software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.RunConfigProperty } } /** * A structure that contains the configuration of the encryption-at-rest settings for artifacts * that the canary uploads to Amazon S3 . * * Artifact encryption functionality is available only for canaries that use Synthetics runtime * version syn-nodejs-puppeteer-3.3 or later. For more information, see [Encrypting canary * artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html) * . * * 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.synthetics.*; * S3EncryptionProperty s3EncryptionProperty = S3EncryptionProperty.builder() * .encryptionMode("encryptionMode") * .kmsKeyArn("kmsKeyArn") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-s3encryption.html) */ public interface S3EncryptionProperty { /** * The encryption method to use for artifacts created by this canary. * * Specify `SSE_S3` to use server-side encryption (SSE) with an Amazon S3-managed key. Specify * `SSE-KMS` to use server-side encryption with a customer-managed AWS KMS key. * * If you omit this parameter, an AWS -managed AWS KMS key is used. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-s3encryption.html#cfn-synthetics-canary-s3encryption-encryptionmode) */ public fun encryptionMode(): String? = unwrap(this).getEncryptionMode() /** * The ARN of the customer-managed AWS KMS key to use, if you specify `SSE-KMS` for * `EncryptionMode`. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-s3encryption.html#cfn-synthetics-canary-s3encryption-kmskeyarn) */ public fun kmsKeyArn(): String? = unwrap(this).getKmsKeyArn() /** * A builder for [S3EncryptionProperty] */ @CdkDslMarker public interface Builder { /** * @param encryptionMode The encryption method to use for artifacts created by this canary. * Specify `SSE_S3` to use server-side encryption (SSE) with an Amazon S3-managed key. Specify * `SSE-KMS` to use server-side encryption with a customer-managed AWS KMS key. * * If you omit this parameter, an AWS -managed AWS KMS key is used. */ public fun encryptionMode(encryptionMode: String) /** * @param kmsKeyArn The ARN of the customer-managed AWS KMS key to use, if you specify * `SSE-KMS` for `EncryptionMode`. */ public fun kmsKeyArn(kmsKeyArn: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty.builder() /** * @param encryptionMode The encryption method to use for artifacts created by this canary. * Specify `SSE_S3` to use server-side encryption (SSE) with an Amazon S3-managed key. Specify * `SSE-KMS` to use server-side encryption with a customer-managed AWS KMS key. * * If you omit this parameter, an AWS -managed AWS KMS key is used. */ override fun encryptionMode(encryptionMode: String) { cdkBuilder.encryptionMode(encryptionMode) } /** * @param kmsKeyArn The ARN of the customer-managed AWS KMS key to use, if you specify * `SSE-KMS` for `EncryptionMode`. */ override fun kmsKeyArn(kmsKeyArn: String) { cdkBuilder.kmsKeyArn(kmsKeyArn) } public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty, ) : CdkObject(cdkObject), S3EncryptionProperty { /** * The encryption method to use for artifacts created by this canary. * * Specify `SSE_S3` to use server-side encryption (SSE) with an Amazon S3-managed key. Specify * `SSE-KMS` to use server-side encryption with a customer-managed AWS KMS key. * * If you omit this parameter, an AWS -managed AWS KMS key is used. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-s3encryption.html#cfn-synthetics-canary-s3encryption-encryptionmode) */ override fun encryptionMode(): String? = unwrap(this).getEncryptionMode() /** * The ARN of the customer-managed AWS KMS key to use, if you specify `SSE-KMS` for * `EncryptionMode`. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-s3encryption.html#cfn-synthetics-canary-s3encryption-kmskeyarn) */ override fun kmsKeyArn(): String? = unwrap(this).getKmsKeyArn() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): S3EncryptionProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty): S3EncryptionProperty = CdkObjectWrappers.wrap(cdkObject) as? S3EncryptionProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: S3EncryptionProperty): software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.S3EncryptionProperty } } /** * This structure specifies how often a canary is to make runs and the date and time when it * should stop making runs. * * 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.synthetics.*; * ScheduleProperty scheduleProperty = ScheduleProperty.builder() * .expression("expression") * // the properties below are optional * .durationInSeconds("durationInSeconds") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-schedule.html) */ public interface ScheduleProperty { /** * How long, in seconds, for the canary to continue making regular runs according to the * schedule in the `Expression` value. * * If you specify 0, the canary continues making runs until you stop it. If you omit this field, * the default of 0 is used. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-schedule.html#cfn-synthetics-canary-schedule-durationinseconds) */ public fun durationInSeconds(): String? = unwrap(this).getDurationInSeconds() /** * A `rate` expression or a `cron` expression that defines how often the canary is to run. * * For a rate expression, The syntax is `rate( *number unit* )` . *unit* can be `minute` , * `minutes` , or `hour` . * * For example, `rate(1 minute)` runs the canary once a minute, `rate(10 minutes)` runs it once * every 10 minutes, and `rate(1 hour)` runs it once every hour. You can specify a frequency * between `rate(1 minute)` and `rate(1 hour)` . * * Specifying `rate(0 minute)` or `rate(0 hour)` is a special value that causes the canary to * run only once when it is started. * * Use `cron( *expression* )` to specify a cron expression. You can't schedule a canary to wait * for more than a year before running. For information about the syntax for cron expressions, see * [Scheduling canary runs using * cron](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-schedule.html#cfn-synthetics-canary-schedule-expression) */ public fun expression(): String /** * A builder for [ScheduleProperty] */ @CdkDslMarker public interface Builder { /** * @param durationInSeconds How long, in seconds, for the canary to continue making regular * runs according to the schedule in the `Expression` value. * If you specify 0, the canary continues making runs until you stop it. If you omit this * field, the default of 0 is used. */ public fun durationInSeconds(durationInSeconds: String) /** * @param expression A `rate` expression or a `cron` expression that defines how often the * canary is to run. * For a rate expression, The syntax is `rate( *number unit* )` . *unit* can be `minute` , * `minutes` , or `hour` . * * For example, `rate(1 minute)` runs the canary once a minute, `rate(10 minutes)` runs it * once every 10 minutes, and `rate(1 hour)` runs it once every hour. You can specify a frequency * between `rate(1 minute)` and `rate(1 hour)` . * * Specifying `rate(0 minute)` or `rate(0 hour)` is a special value that causes the canary to * run only once when it is started. * * Use `cron( *expression* )` to specify a cron expression. You can't schedule a canary to * wait for more than a year before running. For information about the syntax for cron * expressions, see [Scheduling canary runs using * cron](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html) * . */ public fun expression(expression: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty.builder() /** * @param durationInSeconds How long, in seconds, for the canary to continue making regular * runs according to the schedule in the `Expression` value. * If you specify 0, the canary continues making runs until you stop it. If you omit this * field, the default of 0 is used. */ override fun durationInSeconds(durationInSeconds: String) { cdkBuilder.durationInSeconds(durationInSeconds) } /** * @param expression A `rate` expression or a `cron` expression that defines how often the * canary is to run. * For a rate expression, The syntax is `rate( *number unit* )` . *unit* can be `minute` , * `minutes` , or `hour` . * * For example, `rate(1 minute)` runs the canary once a minute, `rate(10 minutes)` runs it * once every 10 minutes, and `rate(1 hour)` runs it once every hour. You can specify a frequency * between `rate(1 minute)` and `rate(1 hour)` . * * Specifying `rate(0 minute)` or `rate(0 hour)` is a special value that causes the canary to * run only once when it is started. * * Use `cron( *expression* )` to specify a cron expression. You can't schedule a canary to * wait for more than a year before running. For information about the syntax for cron * expressions, see [Scheduling canary runs using * cron](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html) * . */ override fun expression(expression: String) { cdkBuilder.expression(expression) } public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty, ) : CdkObject(cdkObject), ScheduleProperty { /** * How long, in seconds, for the canary to continue making regular runs according to the * schedule in the `Expression` value. * * If you specify 0, the canary continues making runs until you stop it. If you omit this * field, the default of 0 is used. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-schedule.html#cfn-synthetics-canary-schedule-durationinseconds) */ override fun durationInSeconds(): String? = unwrap(this).getDurationInSeconds() /** * A `rate` expression or a `cron` expression that defines how often the canary is to run. * * For a rate expression, The syntax is `rate( *number unit* )` . *unit* can be `minute` , * `minutes` , or `hour` . * * For example, `rate(1 minute)` runs the canary once a minute, `rate(10 minutes)` runs it * once every 10 minutes, and `rate(1 hour)` runs it once every hour. You can specify a frequency * between `rate(1 minute)` and `rate(1 hour)` . * * Specifying `rate(0 minute)` or `rate(0 hour)` is a special value that causes the canary to * run only once when it is started. * * Use `cron( *expression* )` to specify a cron expression. You can't schedule a canary to * wait for more than a year before running. For information about the syntax for cron * expressions, see [Scheduling canary runs using * cron](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-schedule.html#cfn-synthetics-canary-schedule-expression) */ override fun expression(): String = unwrap(this).getExpression() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): ScheduleProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty): ScheduleProperty = CdkObjectWrappers.wrap(cdkObject) as? ScheduleProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: ScheduleProperty): software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.ScheduleProperty } } /** * If this canary is to test an endpoint in a VPC, this structure contains information about the * subnet and security groups of the VPC endpoint. * * For more information, see [Running a Canary in a * VPC](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html) * . * * 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.synthetics.*; * VPCConfigProperty vPCConfigProperty = VPCConfigProperty.builder() * .securityGroupIds(List.of("securityGroupIds")) * .subnetIds(List.of("subnetIds")) * // the properties below are optional * .vpcId("vpcId") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html) */ public interface VPCConfigProperty { /** * The IDs of the security groups for this canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html#cfn-synthetics-canary-vpcconfig-securitygroupids) */ public fun securityGroupIds(): List<String> /** * The IDs of the subnets where this canary is to run. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html#cfn-synthetics-canary-vpcconfig-subnetids) */ public fun subnetIds(): List<String> /** * The ID of the VPC where this canary is to run. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html#cfn-synthetics-canary-vpcconfig-vpcid) */ public fun vpcId(): String? = unwrap(this).getVpcId() /** * A builder for [VPCConfigProperty] */ @CdkDslMarker public interface Builder { /** * @param securityGroupIds The IDs of the security groups for this canary. */ public fun securityGroupIds(securityGroupIds: List<String>) /** * @param securityGroupIds The IDs of the security groups for this canary. */ public fun securityGroupIds(vararg securityGroupIds: String) /** * @param subnetIds The IDs of the subnets where this canary is to run. */ public fun subnetIds(subnetIds: List<String>) /** * @param subnetIds The IDs of the subnets where this canary is to run. */ public fun subnetIds(vararg subnetIds: String) /** * @param vpcId The ID of the VPC where this canary is to run. */ public fun vpcId(vpcId: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty.builder() /** * @param securityGroupIds The IDs of the security groups for this canary. */ override fun securityGroupIds(securityGroupIds: List<String>) { cdkBuilder.securityGroupIds(securityGroupIds) } /** * @param securityGroupIds The IDs of the security groups for this canary. */ override fun securityGroupIds(vararg securityGroupIds: String): Unit = securityGroupIds(securityGroupIds.toList()) /** * @param subnetIds The IDs of the subnets where this canary is to run. */ override fun subnetIds(subnetIds: List<String>) { cdkBuilder.subnetIds(subnetIds) } /** * @param subnetIds The IDs of the subnets where this canary is to run. */ override fun subnetIds(vararg subnetIds: String): Unit = subnetIds(subnetIds.toList()) /** * @param vpcId The ID of the VPC where this canary is to run. */ override fun vpcId(vpcId: String) { cdkBuilder.vpcId(vpcId) } public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty, ) : CdkObject(cdkObject), VPCConfigProperty { /** * The IDs of the security groups for this canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html#cfn-synthetics-canary-vpcconfig-securitygroupids) */ override fun securityGroupIds(): List<String> = unwrap(this).getSecurityGroupIds() /** * The IDs of the subnets where this canary is to run. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html#cfn-synthetics-canary-vpcconfig-subnetids) */ override fun subnetIds(): List<String> = unwrap(this).getSubnetIds() /** * The ID of the VPC where this canary is to run. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-vpcconfig.html#cfn-synthetics-canary-vpcconfig-vpcid) */ override fun vpcId(): String? = unwrap(this).getVpcId() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): VPCConfigProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty): VPCConfigProperty = CdkObjectWrappers.wrap(cdkObject) as? VPCConfigProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: VPCConfigProperty): software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.VPCConfigProperty } } /** * Defines the screenshots to use as the baseline for comparisons during visual monitoring * comparisons during future runs of this canary. * * If you omit this parameter, no changes are made to any baseline screenshots that the canary * might be using already. * * Visual monitoring is supported only on canaries running the *syn-puppeteer-node-3.2* runtime or * later. For more information, see [Visual * monitoring](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Library_SyntheticsLogger_VisualTesting.html) * and [Visual monitoring * blueprint](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Blueprints_VisualTesting.html) * * 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.synthetics.*; * VisualReferenceProperty visualReferenceProperty = VisualReferenceProperty.builder() * .baseCanaryRunId("baseCanaryRunId") * // the properties below are optional * .baseScreenshots(List.of(BaseScreenshotProperty.builder() * .screenshotName("screenshotName") * // the properties below are optional * .ignoreCoordinates(List.of("ignoreCoordinates")) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-visualreference.html) */ public interface VisualReferenceProperty { /** * Specifies which canary run to use the screenshots from as the baseline for future visual * monitoring with this canary. * * Valid values are `nextrun` to use the screenshots from the next run after this update is * made, `lastrun` to use the screenshots from the most recent run before this update was made, or * the value of `Id` in the * [CanaryRun](https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html) * from any past run of this canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-visualreference.html#cfn-synthetics-canary-visualreference-basecanaryrunid) */ public fun baseCanaryRunId(): String /** * An array of screenshots that are used as the baseline for comparisons during visual * monitoring. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-visualreference.html#cfn-synthetics-canary-visualreference-basescreenshots) */ public fun baseScreenshots(): Any? = unwrap(this).getBaseScreenshots() /** * A builder for [VisualReferenceProperty] */ @CdkDslMarker public interface Builder { /** * @param baseCanaryRunId Specifies which canary run to use the screenshots from as the * baseline for future visual monitoring with this canary. * Valid values are `nextrun` to use the screenshots from the next run after this update is * made, `lastrun` to use the screenshots from the most recent run before this update was made, * or the value of `Id` in the * [CanaryRun](https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html) * from any past run of this canary. */ public fun baseCanaryRunId(baseCanaryRunId: String) /** * @param baseScreenshots An array of screenshots that are used as the baseline for * comparisons during visual monitoring. */ public fun baseScreenshots(baseScreenshots: IResolvable) /** * @param baseScreenshots An array of screenshots that are used as the baseline for * comparisons during visual monitoring. */ public fun baseScreenshots(baseScreenshots: List<Any>) /** * @param baseScreenshots An array of screenshots that are used as the baseline for * comparisons during visual monitoring. */ public fun baseScreenshots(vararg baseScreenshots: Any) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty.Builder = software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty.builder() /** * @param baseCanaryRunId Specifies which canary run to use the screenshots from as the * baseline for future visual monitoring with this canary. * Valid values are `nextrun` to use the screenshots from the next run after this update is * made, `lastrun` to use the screenshots from the most recent run before this update was made, * or the value of `Id` in the * [CanaryRun](https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html) * from any past run of this canary. */ override fun baseCanaryRunId(baseCanaryRunId: String) { cdkBuilder.baseCanaryRunId(baseCanaryRunId) } /** * @param baseScreenshots An array of screenshots that are used as the baseline for * comparisons during visual monitoring. */ override fun baseScreenshots(baseScreenshots: IResolvable) { cdkBuilder.baseScreenshots(baseScreenshots.let(IResolvable.Companion::unwrap)) } /** * @param baseScreenshots An array of screenshots that are used as the baseline for * comparisons during visual monitoring. */ override fun baseScreenshots(baseScreenshots: List<Any>) { cdkBuilder.baseScreenshots(baseScreenshots.map{CdkObjectWrappers.unwrap(it)}) } /** * @param baseScreenshots An array of screenshots that are used as the baseline for * comparisons during visual monitoring. */ override fun baseScreenshots(vararg baseScreenshots: Any): Unit = baseScreenshots(baseScreenshots.toList()) public fun build(): software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty, ) : CdkObject(cdkObject), VisualReferenceProperty { /** * Specifies which canary run to use the screenshots from as the baseline for future visual * monitoring with this canary. * * Valid values are `nextrun` to use the screenshots from the next run after this update is * made, `lastrun` to use the screenshots from the most recent run before this update was made, * or the value of `Id` in the * [CanaryRun](https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html) * from any past run of this canary. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-visualreference.html#cfn-synthetics-canary-visualreference-basecanaryrunid) */ override fun baseCanaryRunId(): String = unwrap(this).getBaseCanaryRunId() /** * An array of screenshots that are used as the baseline for comparisons during visual * monitoring. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-visualreference.html#cfn-synthetics-canary-visualreference-basescreenshots) */ override fun baseScreenshots(): Any? = unwrap(this).getBaseScreenshots() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): VisualReferenceProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty): VisualReferenceProperty = CdkObjectWrappers.wrap(cdkObject) as? VisualReferenceProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: VisualReferenceProperty): software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.synthetics.CfnCanary.VisualReferenceProperty } } }
4
null
0
4
9a242bcc59b2c1cf505be2f9d838f1cd8008fe12
134,393
kotlin-cdk-wrapper
Apache License 2.0
data/src/main/java/br/com/lucas/cordeiro/cryptowalletapp/data/di/module/RepositoryModule.kt
lucas-cordeiro
331,486,180
false
null
package br.com.lucas.cordeiro.cryptowalletapp.data.di.module import br.com.lucas.cordeiro.cryptowalletapp.data.repository.CoinRepositoryImpl import br.com.lucas.cordeiro.cryptowalletapp.domain.repository.CoinRepository import org.koin.dsl.module val repositoryModule = module { single { CoinRepositoryImpl() as CoinRepository } }
0
Kotlin
0
2
a15631fad4e972d061dcba5e512be29b64534e01
335
Crypto-Wallet-App
MIT License
WorkManager/app/src/main/java/com/example/personal/ThirdActivity.kt
leeGYPlus
222,656,177
true
{"Kotlin": 60932, "RenderScript": 2642}
package com.example.personal import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.work.* import kotlinx.coroutines.delay import java.time.Duration class ThirdActivity : AppCompatActivity() { private val duration: Duration = Duration.ofHours(1) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WorkManager.getInstance(this) .enqueueUniquePeriodicWork( "test_work", ExistingPeriodicWorkPolicy.KEEP, PeriodicWorkRequestBuilder<BackgroundWork>(duration).build()) } }
0
Kotlin
0
0
947ec5df159740851e7d536b40040053f02140d3
714
background-tasks-samples
Apache License 2.0
src/main/kotlin/xyz/acrylicstyle/gptxbot/function/ClearRemindFunction.kt
acrylic-style
723,533,167
false
{"Kotlin": 56506, "Dockerfile": 214}
package xyz.acrylicstyle.gptxbot.function import dev.kord.core.entity.Message import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @SerialName("clear_remind") data object ClearRemindFunction : Function { override suspend fun call(originalMessage: Message, addToolCallOutput: (String) -> Unit) { SetRemindFunction.reminds.removeIf { it.userId == originalMessage.author?.id } SetRemindFunction.saveReminds() addToolCallOutput("Successfully cleared reminds of ${originalMessage.author!!.id}") } }
2
Kotlin
1
1
83b3e82390453dd9f082c72e565cc5eb5007a780
571
gptx-bot
MIT License
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/awt/AwtEvents.desktop.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
package androidx.compose.ui.awt import androidx.compose.ui.input.key.InternalKeyEvent import androidx.compose.ui.input.key.internal import androidx.compose.ui.input.pointer.PointerEvent /** * The original raw native event from AWT. * * Null if: * - the native event is sent by another framework (when Compose UI is embed into it) * - there is no native event (in tests, for example) * - there was a synthetic move event sent by compose on re-layout * - there was a synthetic move event sent by compose when move is missing between two non-move events * * Always check for null when you want to handle the native event. */ val PointerEvent.awtEventOrNull: java.awt.event.MouseEvent? get() { return nativeEvent as? java.awt.event.MouseEvent? } /** * The original raw native event from AWT. * * Null if: * - the native event is sent by another framework (when Compose UI is embed into it) * - there is no native event (in tests, for example) * * Always check for null when you want to handle the native event. */ val InternalKeyEvent.awtEventOrNull: java.awt.event.KeyEvent? get() { return internal.nativeEvent as? java.awt.event.KeyEvent? }
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
1,168
compose
Apache License 2.0
services/cookbook/core/src/main/kotlin/recipe/InvalidNumber.kt
wolkenschloss
370,828,904
false
null
package family.haschka.wolkenschloss.cookbook.recipe class InvalidNumber(s: String) : RuntimeException(s)
56
null
1
1
218a04bde90f402d3d6c7981520bcd2e2ed15fc4
106
nubes
Apache License 2.0
2-Desafios/001-Principiante/09–Tabuada.kts
an-jorge
170,856,534
false
null
/* 09 – Tabuada Exercício Python 009: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada. */ fun main() { val tabuada = 10 println("== == Tabuada de $tabuada == ==") println() for (index in 0..12) { println("$tabuada * $index = ${tabuada * index}") } } main()
1
Kotlin
1
1
b3a217b44719c737b5925cecfbdfb6348532d741
324
Learning-Kotlin
MIT License
app/src/test/java/com/mrkaz/tokoin/di/MockWebServerDITest.kt
mrkazansky
348,208,334
false
null
package com.mrkaz.tokoin.di import okhttp3.mockwebserver.MockWebServer import org.koin.dsl.module val MockWebServerDIPTest = module { factory { MockWebServer() } }
1
null
1
1
4b4df194cbf375ec057d61f57516b5a45f27c1b1
183
mvvm-template
Apache License 2.0
app/common/src/desktopMain/kotlin/com/denchic45/studiversity/ui/profile/ProfileUI.kt
denchic45
435,895,363
false
{"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.ui.profile import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.* import androidx.compose.material.icons.rounded.Close import androidx.compose.material3.* import androidx.compose.material3.TopAppBarDefaults.topAppBarColors import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.denchic45.studiversity.domain.resource.onSuccess import com.denchic45.studiversity.systemRoleName import com.denchic45.studiversity.ui.BlockContent import com.denchic45.studiversity.ui.ScreenScaffold import com.denchic45.studiversity.ui.component.HeaderItemUI import com.denchic45.studiversity.ui.main.CustomAppBar import com.denchic45.studiversity.ui.main.NavigationIconBack import com.denchic45.studiversity.ui.theme.spacing import com.denchic45.studiversity.ui.theme.toDrawablePath import com.denchic45.stuiversity.api.course.model.CourseResponse import com.denchic45.stuiversity.api.role.model.Role import com.denchic45.stuiversity.api.studygroup.model.StudyGroupResponse import com.seiko.imageloader.rememberAsyncImagePainter import io.kamel.image.KamelImage import io.kamel.image.asyncPainterResource import java.util.* @Composable fun ProfileScreen(component: ProfileComponent) { val state by component.viewState.collectAsState() ScreenScaffold( topBar = { CustomAppBar( navigationContent = { NavigationIconBack(onClick = {}) }, title = { Text("Профиль") } ) } ) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { state.onSuccess { state -> ProfileHeaderBlock(state, onStudyGroupClick = component::onStudyGroupClick, onMoreStudyGroupsClick = component::onMoreStudyGroupsClick) Row { Column( Modifier.width(496.dp) .padding( end = MaterialTheme.spacing.normal, bottom = MaterialTheme.spacing.normal ) ) { state.roles.forEach { when (it) { Role.TeacherPerson -> {} Role.StudentPerson -> StudentInfoBlock() } } } Column { CoursesBlock( courses = state.courses, onCourseClick = component::onCourseClick, onMoreCoursesClick = component::onMoreCourseClick ) } } } } } } @Composable private fun StudentInfoBlock() { BlockContent { HeaderItemUI("Учебная деятельность") Row { StudentBlockElement(rememberVectorPainter(Icons.Outlined.CheckCircle), "Успеваемость") StudentBlockElement(rememberVectorPainter(Icons.Outlined.HotelClass), "Оценки") StudentBlockElement(rememberVectorPainter(Icons.Outlined.EmojiEvents), "Достижения") } } } @Composable private fun StudentBlockElement(painter: Painter, title: String) { Column { Box(modifier = Modifier.size(112.dp).clip(RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center) { Image(painter, contentDescription = null) } Text(title, modifier = Modifier.padding(vertical = MaterialTheme.spacing.normal)) } } @Composable fun ProfileHeaderBlock(state: ProfileViewState, onStudyGroupClick: (UUID) -> Unit, onMoreStudyGroupsClick: () -> Unit) { BlockContent { Row( Modifier.width(874.dp).height(232.dp).padding(horizontal = MaterialTheme.spacing.normal), verticalAlignment = Alignment.CenterVertically ) { val user = state.user KamelImage( resource = asyncPainterResource(user.avatarUrl), null, Modifier.size(168.dp).clip(CircleShape).background(Color.LightGray), contentScale = ContentScale.Crop, ) Spacer(Modifier.width(MaterialTheme.spacing.normal)) Column { Text( user.fullName, style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(vertical = MaterialTheme.spacing.small) ) Text( state.roles.joinToString(transform = Role::systemRoleName), Modifier.padding(bottom = MaterialTheme.spacing.small), style = MaterialTheme.typography.titleMedium ) Row { Icon( Icons.Outlined.Email, null, Modifier.padding(end = MaterialTheme.spacing.small) ) Text(state.user.account.email, style = MaterialTheme.typography.titleSmall) state.studyGroups.takeIf(List<StudyGroupResponse>::isNotEmpty)?.let { studyGroups -> Row(Modifier.clickable { if (studyGroups.size == 1) onStudyGroupClick(studyGroups.single().id) else onMoreStudyGroupsClick() }) { Icon( Icons.Outlined.Groups, null, Modifier.padding(end = MaterialTheme.spacing.small) ) val studyGroupsText = studyGroups.singleOrNull()?.name ?: "${studyGroups.size} групп" Text(studyGroupsText, style = MaterialTheme.typography.titleSmall) } } } Spacer(Modifier.height(MaterialTheme.spacing.normal)) FilledTonalButton(onClick = {}) { Text("Написать") } // if (profile.studyGroups.size == 1) { // Row { // Icon(Icons.Outlined.Groups, null) // Spacer(Modifier.width(MaterialTheme.spacing.small)) // val studyGroup = profile.studyGroups.single() // Text(studyGroup.name) // } // } else if (profile.studyGroups.size > 1) { // // TODO: сделать диалоговое окно с несклькими группами // Icon(Icons.Outlined.Groups, null) // Text("${profile.studyGroups.size} групп") // } } } } Spacer(Modifier.height(MaterialTheme.spacing.normal)) } @Composable fun CoursesBlock( courses: List<CourseResponse>, onCourseClick: (courseId: UUID) -> Unit, onMoreCoursesClick: () -> Unit ) { BlockContent(Modifier.clickable(onClick = onMoreCoursesClick)) { HeaderItemUI("Курсы") courses.forEach { course -> ListItem( headlineContent = { Text(course.name) }, modifier = Modifier.clickable { onCourseClick(course.id) }) } // if (studyGroups.size == 1) { // Row { // Icon(Icons.Outlined.Groups, null) // Spacer(Modifier.width(MaterialTheme.spacing.small)) // val studyGroup = studyGroups.single() // Text(studyGroup.name) // } // } else { // // TODO: сделать диалоговое окно с несклькими группами // Icon(Icons.Outlined.Groups, null) // Text("${studyGroups.size} групп") // } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ProfileSideBar( modifier: Modifier, profileComponent: ProfileComponent, onCloseClick: () -> Unit, ) { val profileViewState by profileComponent.viewState.collectAsState() Column(modifier) { TopAppBar( title = {}, actions = { IconButton(onCloseClick) { Icon(Icons.Rounded.Close, null) } }, colors = topAppBarColors( containerColor = Color.Transparent, // scrolledContainerColor = MaterialTheme.colorScheme.applyTonalElevation( // backgroundColor = containerColor, // elevation = TopAppBarSmallTokens.OnScrollContainerElevation //) ) ) profileViewState.onSuccess { profile -> val user = profile.user ProfileHeader(user.avatarUrl, user.fullName) // if (profile.groupInfo != null) { // ListItem(Modifier.clickable( // profile.groupClickable, // onClick = profileComponent::onGroupClick // ), // icon = { Icon(painterResource("ic_study_group".toDrawablePath()), null) }, // text = { // Text(text = profile.groupInfo, style = MaterialTheme.typography.bodyLarge) // }) // } Divider(Modifier.fillMaxWidth()) user.account.let { personalDate -> ListItem( leadingContent = { Icon(painterResource("ic_email".toDrawablePath()), null) }, headlineContent = { Text(personalDate.email, style = MaterialTheme.typography.bodyLarge) }, supportingContent = { Text("Почта", style = MaterialTheme.typography.bodyMedium) }) } } } } @Composable fun ProfileHeader(photoUrl: String, title: String) { Row( modifier = Modifier.height(100.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically ) { Image( painter = rememberAsyncImagePainter(photoUrl), null, Modifier.size(68.dp).clip(CircleShape), contentScale = ContentScale.Crop ) Column(Modifier.padding(start = 16.dp)) { Text(title, style = MaterialTheme.typography.titleLarge) } } }
0
Kotlin
0
7
9d1744ffd9e1652e93af711951e924b739e96dcc
11,207
Studiversity
Apache License 2.0
app/src/main/java/top/jiecs/screener/ui/resolution/ResolutionViewModel.kt
jiesou
727,220,282
false
{"Kotlin": 13071}
package top.jiecs.screener.ui.resolution import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import android.os.Build import android.view.Display import android.util.DisplayMetrics import android.view.WindowManager // import android.content.pm.UserInfo import android.util.Log import java.lang.reflect.Method import java.lang.reflect.Field import org.lsposed.hiddenapibypass.HiddenApiBypass import top.jiecs.screener.ui.resolution.ResolutionFragment class ResolutionViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "Physical Resolution Override" } val text: LiveData<String> = _text val resolutionMap: MutableLiveData<Map<String, Int>> by lazy { MutableLiveData<Map<String, Int>>() } fun fetchScreenResolution(windowManager: WindowManager) { val metrics = windowManager.currentWindowMetrics.bounds // TODO: get now Physical and Override size resolutionMap.value = mapOf( "height" to metrics.height(), "width" to metrics.width(), "dpi" to 520) } val usersList: MutableLiveData<List<Map<String, Any>>> by lazy { MutableLiveData<List<Map<String, Any>>>() } fun fetchUsers() { val userManager = ResolutionFragment.iUserManager val users = HiddenApiBypass.invoke(userManager::class.java, userManager, "getUsers", true, true, true) as List<*> Log.d("users", users.toString()) val userInfoFields = HiddenApiBypass.getInstanceFields(Class.forName("android.content.pm.UserInfo")) //val idField = userInfoFields.stream().filter { e: Field -> e.getName() == "id" }.findFirst().get() //val nameField = userInfoFields.stream().filter { e: Field -> e.getName() == "name" }.findFirst().get() // for (userInfo in users) { // _usersList.postValue(mapOf( // "id" to idField.get(userInfo), // "name" to nameField.get(userInfo) // // "id" to allInstanceFields.id.get(user), // // "name" to allInstanceFields.name.get(user) // )) // } // TODO usersList.setValue( listOf(mapOf( "id" to 0, "name" to "jiesou" ), mapOf( "id" to 10, "name" to "<NAME>") ) ) } }
0
Kotlin
0
5
933b2055203aaff53c0301d4ca801b356f2fca1e
2,463
Android-Screener
MIT License
app/src/main/kotlin/by/kirich1409/grsuschedule/schedule/viewholder/DayViewHolder.kt
mydos
48,542,594
false
null
package by.kirich1409.grsuschedule.schedule.viewholder import android.view.View import android.widget.TextView import by.kirich1409.grsuschedule.R import by.kirich1409.grsuschedule.app.BaseRecyclerItemViewHolder import by.kirich1409.grsuschedule.model.DaySchedule /** * Created by kirillrozov on 10/10/15. */ class DayViewHolder(rootView: View) : BaseRecyclerItemViewHolder(rootView.context, rootView) { private val mDayView: TextView init { mDayView = rootView.findViewById(R.id.day) as TextView } fun setDaySchedule(daySchedule: DaySchedule) { mDayView.text = daySchedule.date.format(true, false) } }
0
Kotlin
0
0
2fb2c70622f2a058fb6a983ad40e2d05201e4aab
647
GrSU-Schedule
Apache License 2.0
shared/src/commonMain/kotlin/me/inassar/data/remote/dto/BannersDTO.kt
Mustafa-Elazab
730,848,733
false
{"Kotlin": 81497, "Swift": 727, "Shell": 227, "Ruby": 101}
package me.inassar.data.remote.dto import kotlinx.serialization.Serializable @Serializable data class BannersDTO( val `data`: List<BannerDTO?>?, val message: String?, val status: Boolean? ) @Serializable data class CategoryDTO( val id: Int?, val image: String?, val name: String? ) @Serializable data class BannerDTO( val category: CategoryDTO?, val id: Int?, val image: String?, val product: ProductDTO? )
0
Kotlin
0
0
833de7404a4399bc29358f2711b0bc5cc0ab81d1
461
Multi-Platform-News
Apache License 2.0
EasyRoom/app/src/main/java/pt/ipca/easyroom/data/DataSourceActivity.kt
TheAdventurersOrg
695,132,245
false
{"Kotlin": 56137}
package pt.ipca.easyroom.data import android.content.ContentValues.TAG import android.content.Context import android.util.Log import android.widget.Toast import com.google.android.gms.tasks.Task import com.google.firebase.firestore.FirebaseFirestore import pt.ipca.easyroom.model.Property import pt.ipca.easyroom.model.Room import pt.ipca.easyroom.model.User interface PropertyCallback { fun onCallback(value: List<Property>) } interface RoomCallback { fun onCallback(value: List<Room>) } class DataSourceActivity(private val context: Context) { private var db: FirebaseFirestore = FirebaseFirestore.getInstance() fun addUser(user: User, uid: String) { val collectionName = when (user.userType) { "Owner" -> "owners" "Tenant" -> "tenants" else -> throw IllegalArgumentException("Invalid user type: ${user.userType}") } db.collection(collectionName) .document(uid) .set(user) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot added with ID: $uid") } .addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) } } fun addProperty(property: Property) { val newPropertyRef = db.collection("properties").document() property.id = newPropertyRef.id newPropertyRef.set(property) .addOnSuccessListener { Log.d(TAG, "Property added successfully with ID: ${property.id}") } .addOnFailureListener { _ -> Log.w(TAG, "Error adding property.") } } fun getPropertiesByOwner(ownerId: String, callback: PropertyCallback) { db.collection("properties") .whereEqualTo("ownerId", ownerId) .get() .addOnSuccessListener { documents -> val properties = ArrayList<Property>() for (document in documents) { val property = document.toObject(Property::class.java) properties.add(property) } callback.onCallback(properties) } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents: ", exception) } } fun updateProperty(propertyId: String, updatedProperty: Property): Task<Void> { return db.collection("properties") .document(propertyId) .set(updatedProperty) .addOnSuccessListener { Log.d(TAG, "Property updated successfully.") } .addOnFailureListener { e -> Log.w(TAG, "Error updating property.", e) } } fun getPropertyById(propertyId: String, callback: (Property?) -> Unit) { db.collection("properties") .document(propertyId) .get() .addOnSuccessListener { document -> if (document != null) { val property = document.toObject(Property::class.java) callback(property) } else { Log.d(TAG, "No such document") } } .addOnFailureListener { exception -> Log.d(TAG, "get failed with ", exception) } } fun deleteProperty(propertyId: String) { Toast.makeText(context, "Deleting property with ID: $propertyId", Toast.LENGTH_SHORT).show() db.collection("properties") .document(propertyId) .delete() .addOnSuccessListener { Log.d(TAG, "Property deleted successfully.") } .addOnFailureListener { e -> Log.w(TAG, "Error deleting property.", e) } .addOnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText(context, "Property deleted successfully.", Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, "Failed to delete property.", Toast.LENGTH_SHORT).show() } } } fun generateNewPropertyId(): String { return db.collection("properties").document().id } fun addRoom(room: Room) { val newRoomRef = db.collection("rooms").document() room.id = newRoomRef.id newRoomRef.set(room) .addOnSuccessListener { Log.d(TAG, "Room added successfully with ID: ${room.id}") } .addOnFailureListener { _ -> Log.w(TAG, "Error adding room.") } } fun getRoomsByProperty(propertyId: String, callback: RoomCallback) { db.collection("rooms") .whereEqualTo("propertyId", propertyId) .get() .addOnSuccessListener { documents -> val rooms = ArrayList<Room>() for (document in documents) { val room = document.toObject(Room::class.java) rooms.add(room) } callback.onCallback(rooms) } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents: ", exception) } } fun updateRoom(roomId: String, updatedRoom: Room): Task<Void> { return db.collection("rooms") .document(roomId) .set(updatedRoom) .addOnSuccessListener { Log.d(TAG, "Room updated successfully.") } .addOnFailureListener { e -> Log.w(TAG, "Error updating room.", e) } } fun getRoomById(roomId: String, callback: (Room?) -> Unit) { db.collection("rooms") .document(roomId) .get() .addOnSuccessListener { document -> if (document != null) { val room = document.toObject(Room::class.java) callback(room) } else { Log.d(TAG, "No such document") } } .addOnFailureListener { exception -> Log.d(TAG, "get failed with ", exception) } } fun deleteRoom(roomId: String) { Toast.makeText(context, "Deleting room with ID: $roomId", Toast.LENGTH_SHORT).show() db.collection("rooms") .document(roomId) .delete() .addOnSuccessListener { Log.d(TAG, "Room deleted successfully.") } .addOnFailureListener { e -> Log.w(TAG, "Error deleting room.", e) } .addOnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText(context, "Room deleted successfully.", Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, "Failed to delete room.", Toast.LENGTH_SHORT).show() } } } fun generateNewRoomId(): String { return db.collection("rooms").document().id } }
0
Kotlin
0
0
ce58e5332f31166859080a71c0ce8ffaeb129ec8
7,120
EasyRoom
MIT License
ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/config/AutoVersioningConfigurationServiceImpl.kt
nemerosa
19,351,480
false
{"Kotlin": 9228434, "JavaScript": 3016136, "Java": 1053512, "HTML": 506551, "Groovy": 377453, "CSS": 137546, "Less": 35335, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.extension.av.config import net.nemerosa.ontrack.common.syncForward import net.nemerosa.ontrack.extension.notifications.subscriptions.EventSubscription import net.nemerosa.ontrack.extension.notifications.subscriptions.EventSubscriptionFilter import net.nemerosa.ontrack.extension.notifications.subscriptions.EventSubscriptionService import net.nemerosa.ontrack.model.security.ProjectConfig import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.* import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class AutoVersioningConfigurationServiceImpl( private val securityService: SecurityService, private val entityDataService: EntityDataService, private val regexBranchSource: RegexBranchSource, private val structureService: StructureService, private val eventSubscriptionService: EventSubscriptionService, private val autoVersioningBranchExpressionService: AutoVersioningBranchExpressionService, ) : AutoVersioningConfigurationService { override fun setupAutoVersioning(branch: Branch, config: AutoVersioningConfig?) { securityService.checkProjectFunction(branch, ProjectConfig::class.java) if (config != null) { securityService.asAdmin { setupNotifications(branch, config) } entityDataService.store(branch, STORE, config) } else { securityService.asAdmin { setupNotifications(branch, null) } entityDataService.delete(branch, STORE) } } private data class AVConfigSubscription( val source: AutoVersioningSourceConfig, val notification: AutoVersioningNotification, ) { fun toEventSubscription(branch: Branch) = EventSubscription( projectEntity = branch, events = AutoVersioningNotificationScope.toEvents(notification.scope), keywords = "${source.sourceProject} ${branch.project.name} ${branch.name}", channel = notification.channel, channelConfig = notification.config, disabled = false, contentTemplate = notification.notificationTemplate, origin = AutoVersioningNotification.ORIGIN, ) } private fun setupNotifications(branch: Branch, config: AutoVersioningConfig?) { if (config == null) { eventSubscriptionService.deleteSubscriptionsByEntity(branch) } else { // Existing subscriptions val existingSubscriptions = eventSubscriptionService.filterSubscriptions( EventSubscriptionFilter( size = Int.MAX_VALUE, entity = branch.toProjectEntityID(), origin = AutoVersioningNotification.ORIGIN, ) ).pageItems // New subscriptions val newSubscriptions = config.configurations.flatMap { source -> source.notifications?.map { notification -> AVConfigSubscription(source, notification) } ?: emptyList() } // Subscription fun subscribe(item: AVConfigSubscription) { eventSubscriptionService.subscribe(item.toEventSubscription(branch)) } // Sync between current subscriptions & configured subscriptions syncForward( from = newSubscriptions, to = existingSubscriptions, ) { equality { item, existing -> item.toEventSubscription(branch) == existing.data } onCreation { item -> subscribe(item) } onModification { item, _ -> subscribe(item) } onDeletion { existing -> eventSubscriptionService.deleteSubscriptionById(branch, existing.id) } } } } override fun getAutoVersioning(branch: Branch): AutoVersioningConfig? = entityDataService.retrieve(branch, STORE, AutoVersioningConfig::class.java)?.postDeserialize() override fun getAutoVersioningBetween(parent: Branch, dependency: Branch): AutoVersioningSourceConfig? { // Gets the AV config of the parent branch // or returns null if not set at all val parentAVConfig = getAutoVersioning(parent) ?: return null // Gets the configurations matching the dependency project val dependencyConfigs = parentAVConfig.configurations.filter { it.sourceProject == dependency.project.name } // Among these project matching configurations, retains the one // where the dependency branch matches the last eligible branch val branchMatchingConfigs = dependencyConfigs.filter { val latestBranch = getLatestBranch(parent, dependency.project, it) latestBranch?.id == dependency.id } // Takes the first one return branchMatchingConfigs.firstOrNull() } override fun getBranchesConfiguredFor(project: String, promotion: String): List<Branch> = entityDataService.findEntities( type = ProjectEntityType.BRANCH, key = STORE, jsonQuery = """JSON_VALUE::jsonb->'configurations' @> '[{"sourceProject":"$project","sourcePromotion":"$promotion"}]'::jsonb""", jsonQueryParameters = emptyMap(), ).map { structureService.getBranch(ID.of(it.id)) } override fun getLatestBranch( eligibleTargetBranch: Branch, project: Project, config: AutoVersioningSourceConfig ): Branch? = if (config.sourceBranch.startsWith("&")) { val avBranchExpression = config.sourceBranch.drop(1) autoVersioningBranchExpressionService.getLatestBranch( eligibleTargetBranch = eligibleTargetBranch, promotion = config.sourcePromotion, project = project, avBranchExpression = avBranchExpression ) } else { regexBranchSource.getLatestBranch( config = config.sourceBranch, project = project, targetBranch = eligibleTargetBranch, promotion = config.sourcePromotion, ) } companion object { private val STORE: String = AutoVersioningConfig::class.java.name } }
44
Kotlin
26
96
fde26a48ea7b18689851fe579635f4ed72ad2c5a
6,598
ontrack
MIT License
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/CodeAnalysisBeforeCheckinHandler.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.CommonBundle.getCancelButtonText import com.intellij.codeInsight.CodeSmellInfo import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.ide.IdeBundle import com.intellij.ide.nls.NlsMessages.formatAndList import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.util.ProgressIndicatorBase import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.DumbService.isDumb import com.intellij.openapi.project.Project import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNo import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNoCancel import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Messages.YesNoCancelResult import com.intellij.openapi.util.Computable import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.util.io.FileUtil.getLocationRelativeToUserHome import com.intellij.openapi.util.io.FileUtil.toSystemDependentName import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil.removeEllipsisSuffix import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.CodeSmellDetector import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.filterOutGeneratedAndExcludedFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.vfs.VirtualFile import com.intellij.profile.codeInspection.InspectionProfileManager import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.PsiDocumentManager import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.util.ExceptionUtil.rethrowUnchecked import com.intellij.util.PairConsumer import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil.getWarningIcon import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.swing.JComponent private val LOG = logger<CodeAnalysisBeforeCheckinHandler>() class CodeAnalysisCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = CodeAnalysisBeforeCheckinHandler(panel) } class CodeAnalysisCommitProblem(val codeSmells: List<CodeSmellInfo>) : CommitProblem { override val text: String get() { val errors = codeSmells.count { it.severity == HighlightSeverity.ERROR } val warnings = codeSmells.size - errors val errorsText = if (errors > 0) HighlightSeverity.ERROR.getCountMessage(errors) else null val warningsText = if (warnings > 0) HighlightSeverity.WARNING.getCountMessage(warnings) else null return formatAndList(listOfNotNull(errorsText, warningsText)) } } /** * The check-in handler which performs code analysis before check-in. Source code for this class * is provided as a sample of using the [CheckinHandler] API. */ class CodeAnalysisBeforeCheckinHandler(private val commitPanel: CheckinProjectPanel) : CheckinHandler(), CommitCheck<CodeAnalysisCommitProblem> { private val project: Project get() = commitPanel.project private val settings: VcsConfiguration get() = VcsConfiguration.getInstance(project) override fun isEnabled(): Boolean = settings.CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT override suspend fun runCheck(indicator: ProgressIndicator): CodeAnalysisCommitProblem? { indicator.text = message("progress.text.analyzing.code") val files = filterOutGeneratedAndExcludedFiles(commitPanel.virtualFiles, project) PsiDocumentManager.getInstance(project).commitAllDocuments() val codeSmells = withContext(Dispatchers.Default) { ProgressManager.getInstance().runProcess( Computable { CodeSmellDetector.getInstance(project).findCodeSmells(files) }, ProgressIndicatorBase().apply { isIndeterminate = false } // [findCodeSmells] requires [ProgressIndicatorEx] set for thread ) } return if (codeSmells.isNotEmpty()) CodeAnalysisCommitProblem(codeSmells) else null } override fun showDetails(problem: CodeAnalysisCommitProblem) = CodeSmellDetector.getInstance(project).showCodeSmellErrors(problem.codeSmells) override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = object : BooleanCommitOption(commitPanel, message("before.checkin.standard.options.check.smells"), true, settings::CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT) { override fun getComponent(): JComponent { var profile: InspectionProfileImpl? = null if (settings.CODE_SMELLS_PROFILE != null) { val manager = if (settings.CODE_SMELLS_PROFILE_LOCAL) InspectionProfileManager.getInstance() else InspectionProjectProfileManager.getInstance(project) profile = manager.getProfile(settings.CODE_SMELLS_PROFILE) } setProfileText(profile) val showFiltersPopup = LinkListener<Any> { sourceLink, _ -> JBPopupMenu.showBelow(sourceLink, ActionPlaces.CODE_INSPECTION, createProfileChooser()) } val configureFilterLink = LinkLabel(message("before.checkin.options.check.smells.choose.profile"), null, showFiltersPopup) return JBUI.Panels.simplePanel(4, 0).addToLeft(checkBox).addToCenter(configureFilterLink) } private fun setProfileText(profile: InspectionProfileImpl?) { checkBox.text = if (profile == null || profile == InspectionProjectProfileManager.getInstance(project).currentProfile) message("before.checkin.standard.options.check.smells") else message("before.checkin.options.check.smells.profile", profile.displayName) } private fun createProfileChooser(): DefaultActionGroup { val group = DefaultActionGroup() group.add(Separator.create(IdeBundle.message("separator.scheme.stored.in", IdeBundle.message("scheme.project")))) fillActions(group, InspectionProjectProfileManager.getInstance(project)) group.add(Separator.create(IdeBundle.message("separator.scheme.stored.in", IdeBundle.message("scheme.ide")))) fillActions(group, InspectionProfileManager.getInstance()) return group } private fun fillActions(group: DefaultActionGroup, manager: InspectionProfileManager) { for (profile in manager.profiles) { group.add(object : AnAction(profile.displayName) { override fun actionPerformed(e: AnActionEvent) { settings.CODE_SMELLS_PROFILE = profile.name settings.CODE_SMELLS_PROFILE_LOCAL = manager !is InspectionProjectProfileManager setProfileText(profile) } }) } } } override fun beforeCheckin(executor: CommitExecutor?, additionalDataConsumer: PairConsumer<Any, Any>): ReturnResult { if (!isEnabled()) return ReturnResult.COMMIT if (isDumb(project)) return if (confirmCommitInDumbMode(project)) ReturnResult.COMMIT else ReturnResult.CANCEL return try { val codeSmells = findCodeSmells() if (codeSmells.isEmpty()) ReturnResult.COMMIT else processFoundCodeSmells(codeSmells, executor) } catch (e: ProcessCanceledException) { ReturnResult.CANCEL } catch (e: Exception) { LOG.error(e) if (confirmCommitWithCodeAnalysisFailure(project, e)) ReturnResult.COMMIT else ReturnResult.CANCEL } } private fun findCodeSmells(): List<CodeSmellInfo> { val files = filterOutGeneratedAndExcludedFiles(commitPanel.virtualFiles, project) val newAnalysisThreshold = Registry.intValue("vcs.code.analysis.before.checkin.show.only.new.threshold", 0) if (files.size > newAnalysisThreshold) return CodeSmellDetector.getInstance(project).findCodeSmells(files) PsiDocumentManager.getInstance(project).commitAllDocuments() return FindNewCodeSmellsTask(project, files).find() } private fun processFoundCodeSmells(codeSmells: List<CodeSmellInfo>, executor: CommitExecutor?): ReturnResult { val commitActionText = removeEllipsisSuffix(executor?.actionText ?: commitPanel.commitActionName) return when (askReviewCommitCancel(project, codeSmells, commitActionText)) { Messages.YES -> { CodeSmellDetector.getInstance(project).showCodeSmellErrors(codeSmells) ReturnResult.CLOSE_WINDOW } Messages.NO -> ReturnResult.COMMIT else -> ReturnResult.CANCEL } } } private class FindNewCodeSmellsTask(project: Project, private val files: List<VirtualFile>) : Task.WithResult<List<CodeSmellInfo>, Exception>(project, message("checking.code.smells.progress.title"), true) { fun find(): List<CodeSmellInfo> { queue() return try { result } catch (e: ProcessCanceledException) { LOG.info("Code analysis canceled", e) throw e } catch (e: Exception) { LOG.error(e) rethrowUnchecked(e) throw RuntimeException(e) } } override fun compute(indicator: ProgressIndicator): List<CodeSmellInfo> { indicator.isIndeterminate = true val codeSmells = CodeAnalysisBeforeCheckinShowOnlyNew.runAnalysis(myProject!!, files, indicator) indicator.text = message("before.checkin.waiting.for.smart.mode") DumbService.getInstance(myProject).waitForSmartMode() return codeSmells } } private fun confirmCommitInDumbMode(project: Project) = !yesNo(message("code.smells.error.indexing"), message("code.smells.error.indexing.message", ApplicationNamesInfo.getInstance().productName)) .icon(null) .yesText(message("checkin.wait")) .noText(message("checkin.commit")) .ask(project) private fun confirmCommitWithCodeAnalysisFailure(project: Project, e: Exception) = yesNo(message("checkin.code.analysis.failed"), message("checkin.code.analysis.failed.with.exception.name.message", e.javaClass.name, e.message)) .icon(null) .yesText(message("checkin.commit")) .noText(message("checkin.cancel")) .ask(project) @YesNoCancelResult private fun askReviewCommitCancel(project: Project, codeSmells: List<CodeSmellInfo>, @NlsContexts.Button commitActionText: String): Int = yesNoCancel(message("code.smells.error.messages.tab.name"), getDescription(codeSmells)) .icon(getWarningIcon()) .yesText(message("code.smells.review.button")) .noText(commitActionText) .cancelText(getCancelButtonText()) .show(project) @DialogMessage private fun getDescription(codeSmells: List<CodeSmellInfo>): String { val errorCount = codeSmells.count { it.severity == HighlightSeverity.ERROR } val warningCount = codeSmells.size - errorCount val virtualFiles = codeSmells.mapTo(mutableSetOf()) { FileDocumentManager.getInstance().getFile(it.document) } if (virtualFiles.size == 1) { val path = toSystemDependentName(getLocationRelativeToUserHome(virtualFiles.first()!!.path)) return message("before.commit.file.contains.code.smells.edit.them.confirm.text", path, errorCount, warningCount) } return message("before.commit.files.contain.code.smells.edit.them.confirm.text", virtualFiles.size, errorCount, warningCount) }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
12,092
intellij-community
Apache License 2.0
app/src/main/java/com/zrcoding/hackertab/features/setting/master/SettingMasterScreen.kt
zouhir96
486,281,742
false
null
package com.zrcoding.hackertab.features.setting.master import android.content.res.Configuration import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Card import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.zrcoding.hackertab.BuildConfig import com.zrcoding.hackertab.R import com.zrcoding.hackertab.theme.HackertabTheme import com.zrcoding.hackertab.theme.dimension @Composable fun SettingMasterScreen( onNavigateToTopics: () -> Unit, onNavigateToSources: () -> Unit ) { Box( modifier = Modifier .padding( top = MaterialTheme.dimension.extraBig, bottom = MaterialTheme.dimension.default ) .padding(horizontal = MaterialTheme.dimension.screenPaddingHorizontal) .fillMaxSize(), ) { Column( modifier = Modifier.align(Alignment.TopCenter), verticalArrangement = Arrangement.spacedBy(MaterialTheme.dimension.large) ) { SettingItemsContainer { SettingItem(R.string.setting_master_screen_topics, onClick = onNavigateToTopics) SettingItem(R.string.setting_master_screen_sources, onClick = onNavigateToSources) } } AppVersionName(modifier = Modifier.align(Alignment.BottomCenter)) } } @Preview(showBackground = true, showSystemUi = true) @Preview(showBackground = true, showSystemUi = true, uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL ) @Composable fun SettingMasterScreenPreview() { HackertabTheme { SettingMasterScreen(onNavigateToTopics = {}, onNavigateToSources = {}) } } @Composable fun SettingItemsContainer( content: @Composable ColumnScope.() -> Unit ) { Card(shape = MaterialTheme.shapes.large) { Column( modifier = Modifier .fillMaxWidth() .padding( horizontal = MaterialTheme.dimension.large, vertical = MaterialTheme.dimension.default ) ) { content() } } } @Preview(showBackground = true) @Composable fun SettingItemsContainerPreview() { HackertabTheme { SettingItemsContainer { SettingItem(R.string.setting_master_screen_topics) {} SettingItem(R.string.setting_master_screen_topics) {} } } } @Composable fun SettingItem( @StringRes text: Int, onClick: () -> Unit ) { Column( modifier = Modifier .fillMaxWidth() .clip(MaterialTheme.shapes.large) .clickable(onClick = onClick) .padding(MaterialTheme.dimension.large), verticalArrangement = Arrangement.spacedBy(MaterialTheme.dimension.large) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(id = text), color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.subtitle1 ) Icon( modifier = Modifier.size(MaterialTheme.dimension.big), painter = painterResource(id = R.drawable.ic_baseline_arrow_forward), contentDescription = null, tint = MaterialTheme.colors.onBackground ) } Divider( color = MaterialTheme.colors.onBackground, thickness = 1.dp ) } } @Preview(showBackground = true) @Composable fun SettingItemPreview() { HackertabTheme { SettingItem(R.string.setting_master_screen_topics) {} } } @Composable fun AppVersionName(modifier: Modifier = Modifier) { val versionName = BuildConfig.VERSION_NAME Text( modifier = modifier, text = stringResource(id = R.string.setting_master_screen_version_name, versionName), color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.subtitle1 ) }
0
null
1
20
99e8e5cd055215bb3af066c32c1b9fe70897140e
4,996
hackertab-android
Apache License 2.0
src/main/kotlin/summarisation/SummariseSentenceScore.kt
rock3125
138,799,834
false
{"Kotlin": 30711, "Java": 939, "Shell": 774}
package summarisation import summarisation.parser.Sentence import java.util.ArrayList /** * sentence sorting by both index and scoring after algorithm completes * */ class SummariseSentenceScore(var sentence: Sentence // the sentence held , var sentenceIndex: Int // original index of the sentence in the story , var score: Float // the summary score of this item ) : Comparable<SummariseSentenceScore> { private var sortKey: Int = 0 // sorting: 1 = by score (default), 2 = sentenceIndex init { this.sortKey = 1 } // sort highest scores first override fun compareTo(other: SummariseSentenceScore): Int { if (sortKey == 1) { if (score < other.score) return 1 if (score > other.score) return -1 } else { if (sentenceIndex < other.sentenceIndex) return -1 if (sentenceIndex > other.sentenceIndex) return 1 } return 0 } companion object { /** * generate the sorted summary * * @param sentenceList the sentences * @param scoreList the scores of these sentences * @param topN the top n items to return * @param sortBySentenceAfterTopN resort by story order after topN have been cut-off * @return the top n items */ fun getTopN(sentenceList: ArrayList<Sentence>, scoreList: ArrayList<Float>, topN: Int, sortBySentenceAfterTopN: Boolean): ArrayList<Sentence> { val results = ArrayList<SummariseSentenceScore>() for (i in sentenceList.indices) { results.add(SummariseSentenceScore(sentenceList[i], i, scoreList[i])) } results.sort() val summary = ArrayList<SummariseSentenceScore>() for (i in 0 until topN) { if (i < results.size) { val sss = results[i] sss.sortKey = 2 // change sort-key just in case we need resorting summary.add(sss) } } if (sortBySentenceAfterTopN) { summary.sort() } val sentenceSummary = ArrayList<Sentence>() for (sss in summary) { sentenceSummary.add(sss.sentence) } return sentenceSummary } } }
0
Kotlin
0
4
24d8916dbecde35eaeb760eb4307ca32a4ecb768
2,432
ExtractiveSummarisation
MIT License
rest-api-server/src/integrationTest/kotlin/org/orkg/contenttypes/adapter/input/rest/RosettaStoneStatementControllerIntegrationTest.kt
TIBHannover
197,416,205
false
{"Kotlin": 4856605, "Cypher": 219418, "Python": 4881, "Shell": 2767, "Groovy": 1936, "HTML": 240}
package org.orkg.contenttypes.adapter.input.rest import io.kotest.assertions.asClue import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.matchers.types.shouldBeInstanceOf import org.assertj.core.api.Assertions.assertThat import org.eclipse.rdf4j.common.net.ParsedIRI import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.orkg.common.ContributorId import org.orkg.common.ObservatoryId import org.orkg.common.OrganizationId import org.orkg.common.RealNumber import org.orkg.common.ThingId import org.orkg.community.input.ContributorUseCases import org.orkg.community.input.ObservatoryUseCases import org.orkg.community.input.OrganizationUseCases import org.orkg.contenttypes.adapter.input.rest.json.ContentTypeJacksonModule import org.orkg.contenttypes.domain.Certainty import org.orkg.contenttypes.domain.RosettaStoneStatementNotFound import org.orkg.contenttypes.input.CreateRosettaStoneTemplateUseCase import org.orkg.contenttypes.input.NumberLiteralPropertyDefinition import org.orkg.contenttypes.input.OtherLiteralPropertyDefinition import org.orkg.contenttypes.input.ResourcePropertyDefinition import org.orkg.contenttypes.input.RosettaStoneStatementUseCases import org.orkg.contenttypes.input.RosettaStoneTemplateUseCases import org.orkg.contenttypes.input.StringLiteralPropertyDefinition import org.orkg.contenttypes.input.UntypedPropertyDefinition import org.orkg.createClass import org.orkg.createClasses import org.orkg.createContributor import org.orkg.createLiteral import org.orkg.createObservatory import org.orkg.createOrganization import org.orkg.createPredicate import org.orkg.createResource import org.orkg.graph.domain.Class import org.orkg.graph.domain.Classes import org.orkg.graph.domain.ExtractionMethod import org.orkg.graph.domain.FormattedLabel import org.orkg.graph.domain.Literal import org.orkg.graph.domain.Literals import org.orkg.graph.domain.Predicate import org.orkg.graph.domain.Predicates import org.orkg.graph.domain.Resource import org.orkg.graph.domain.Visibility import org.orkg.graph.input.ClassUseCases import org.orkg.graph.input.LiteralUseCases import org.orkg.graph.input.PredicateUseCases import org.orkg.graph.input.ResourceUseCases import org.orkg.testing.MockUserDetailsService import org.orkg.testing.MockUserId import org.orkg.testing.andExpectRosettaStoneStatement import org.orkg.testing.annotations.TestWithMockUser import org.orkg.testing.spring.restdocs.RestDocumentationBaseTest import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Import import org.springframework.data.domain.PageRequest import org.springframework.test.web.servlet.RequestBuilder import org.springframework.test.web.servlet.ResultActions import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.transaction.annotation.Transactional @DisplayName("Rosetta Stone Statement Controller") @Transactional @Import(value = [MockUserDetailsService::class, ContentTypeJacksonModule::class]) class RosettaStoneStatementControllerIntegrationTest : RestDocumentationBaseTest() { @Autowired private lateinit var contributorService: ContributorUseCases @Autowired private lateinit var predicateService: PredicateUseCases @Autowired private lateinit var resourceService: ResourceUseCases @Autowired private lateinit var classService: ClassUseCases @Autowired private lateinit var literalService: LiteralUseCases @Autowired private lateinit var organizationService: OrganizationUseCases @Autowired private lateinit var observatoryService: ObservatoryUseCases @Autowired private lateinit var rosettaStoneTemplateService: RosettaStoneTemplateUseCases @Autowired private lateinit var rosettaStoneStatementService: RosettaStoneStatementUseCases @BeforeEach fun setup() { val tempPageable = PageRequest.of(0, 1) cleanup() assertThat(predicateService.findAll(tempPageable)).hasSize(0) assertThat(resourceService.findAll(tempPageable)).hasSize(0) assertThat(classService.findAll(tempPageable)).hasSize(0) assertThat(observatoryService.findAll(tempPageable)).hasSize(0) assertThat(organizationService.listOrganizations()).hasSize(0) assertThat(organizationService.listConferences()).hasSize(0) assertThat(rosettaStoneStatementService.findAll(tempPageable)).hasSize(0) listOf( Predicates.description, Predicates.exampleOfUsage, Predicates.placeholder, Predicates.shClass, Predicates.shClosed, Predicates.shDatatype, Predicates.shMaxCount, Predicates.shMaxInclusive, Predicates.shMinCount, Predicates.shMinInclusive, Predicates.shOrder, Predicates.shPath, Predicates.shPattern, Predicates.shProperty, Predicates.shTargetClass, Predicates.templateLabelFormat, Predicates.hasListElement, Predicates.hasSubjectPosition, Predicates.hasObjectPosition, ).forEach { predicateService.createPredicate(it) } setOf( Classes.rosettaNodeShape, Classes.propertyShape, Classes.researchField, ).forEach { classService.createClass(label = it.value, id = it.value) } Literals.XSD.entries.forEach { classService.createClass( label = it.`class`.value, id = it.`class`.value, uri = ParsedIRI(it.uri) ) } resourceService.createResource( id = "R12", label = "Computer Science", classes = setOf(Classes.researchField.value) ) // Example specific entities classService.createClasses("C123", "C28", "C25") resourceService.createResource(id = "R789") resourceService.createResource(id = "R174") resourceService.createResource(id = "R258", classes = setOf("C28")) resourceService.createResource(id = "R369", classes = setOf("C28")) literalService.createLiteral(id = ThingId("L123"), label = "123456") literalService.createLiteral(id = ThingId("L456"), label = "5", datatype = Literals.XSD.INT.prefixedUri) literalService.createLiteral(id = ThingId("L789"), label = "custom type", datatype = "http://orkg.org/orkg/class/C25") val contributorId = contributorService.createContributor() organizationService.createOrganization( createdBy = contributorId, id = OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e") ) observatoryService.createObservatory( organizations = setOf(OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e")), researchField = ThingId("R12"), id = ObservatoryId("1afefdd0-5c09-4c9c-b718-2b35316b56f3") ) } @AfterEach fun cleanup() { predicateService.removeAll() resourceService.removeAll() classService.removeAll() observatoryService.removeAll() organizationService.removeAll() contributorService.deleteAll() } @Test @TestWithMockUser fun createAndUpdate() { val rosettaStoneTemplateId = createRosettaStoneTemplate() val id = createRosettaStoneStatement(rosettaStoneTemplateId) val rosettaStoneStatement = get("/api/rosetta-stone/statements/{id}", id) .accept(ROSETTA_STONE_STATEMENT_JSON_V1) .contentType(ROSETTA_STONE_STATEMENT_JSON_V1) .characterEncoding("utf-8") .perform() .andExpect(status().isOk) .andExpectRosettaStoneStatement() .andReturn() .response .contentAsString .let { objectMapper.readValue(it, RosettaStoneStatementRepresentation::class.java) } rosettaStoneStatement.asClue { it.id shouldBe id it.context shouldBe ThingId("R789") it.templateId shouldBe rosettaStoneTemplateId it.classId shouldNotBe null it.versionId shouldNotBe id it.latestVersion shouldBe id it.formattedLabel shouldBe "{0} {1} {2} {3} {4} {5}" it.subjects.asClue { subjects -> subjects.size shouldBe 3 subjects[0] shouldBe ResourceReferenceRepresentation(ThingId("R258"), "label", setOf(ThingId("C28"))) subjects[1] shouldBe ResourceReferenceRepresentation(ThingId("R369"), "label", setOf(ThingId("C28"))) subjects[2].shouldBeInstanceOf<ResourceReferenceRepresentation>().asClue { subject -> subject.id shouldNotBe null subject.label shouldBe "Subject Resource" subject.classes shouldBe setOf(ThingId("C28")) } } it.objects.asClue { objects -> objects.size shouldBe 5 objects[0].asClue { position -> position.size shouldBe 3 position[0] shouldBe ResourceReferenceRepresentation(ThingId("R174"), "label", emptySet()) position[1].shouldBeInstanceOf<PredicateReferenceRepresentation>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "hasResult" } position[2].shouldBeInstanceOf<ClassReferenceRepresentation>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "new class" `object`.uri shouldBe null } } objects[1].asClue { position -> position.size shouldBe 2 position[0] shouldBe LiteralReferenceRepresentation("123456", Literals.XSD.STRING.prefixedUri) position[1] shouldBe LiteralReferenceRepresentation("0123456789", Literals.XSD.STRING.prefixedUri) } objects[2].asClue { position -> position.size shouldBe 2 position[0] shouldBe LiteralReferenceRepresentation("5", Literals.XSD.INT.prefixedUri) position[1] shouldBe LiteralReferenceRepresentation("1", Literals.XSD.INT.prefixedUri) } objects[3].asClue { position -> position.size shouldBe 2 position[0] shouldBe LiteralReferenceRepresentation("custom type", "http://orkg.org/orkg/class/C25") position[1] shouldBe LiteralReferenceRepresentation("some literal value", "http://orkg.org/orkg/class/C25") } objects[4].asClue { position -> position.size shouldBe 3 position[0] shouldBe ResourceReferenceRepresentation(ThingId("R258"), "label", setOf(ThingId("C28"))) position[1] shouldBe ResourceReferenceRepresentation(ThingId("R369"), "label", setOf(ThingId("C28"))) position[2].shouldBeInstanceOf<ResourceReferenceRepresentation>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "list" `object`.classes shouldBe setOf(Classes.list) } } } it.createdAt shouldNotBe null it.createdBy shouldBe ContributorId(MockUserId.USER) it.certainty shouldBe Certainty.HIGH it.negated shouldBe false it.observatories shouldBe listOf(ObservatoryId("1afefdd0-5c09-4c9c-b718-2b35316b56f3")) it.organizations shouldBe listOf(OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e")) it.extractionMethod shouldBe ExtractionMethod.MANUAL it.visibility shouldBe Visibility.DEFAULT it.unlistedBy shouldBe null it.modifiable shouldBe true it.deletedBy shouldBe null it.deletedAt shouldBe null } val updatedId = post("/api/rosetta-stone/statements/{id}", id) .content(updateRosettaStoneStatementJson) .accept(ROSETTA_STONE_STATEMENT_JSON_V1) .contentType(ROSETTA_STONE_STATEMENT_JSON_V1) .characterEncoding("utf-8") .perform() .andExpect(status().isCreated) .andReturn() .response .getHeaderValue("Location")!! .toString() .substringAfterLast("/") .let(::ThingId) val updatedRosettaStoneStatement = rosettaStoneStatementService.findByIdOrVersionId(id) .orElseThrow { RosettaStoneStatementNotFound(id) } updatedRosettaStoneStatement.asClue { it.id shouldBe rosettaStoneStatement.latestVersion it.contextId shouldBe rosettaStoneStatement.context it.templateId shouldBe rosettaStoneTemplateId it.templateTargetClassId.asClue { templateTargetClassId -> templateTargetClassId shouldNotBe null templateTargetClassId shouldBe rosettaStoneStatement.classId } it.label shouldBe "" it.versions.size shouldBe 2 it.versions[0].asClue { version -> version.id shouldBe rosettaStoneStatement.versionId version.formattedLabel shouldBe FormattedLabel.of("{0} {1} {2} {3} {4} {5}") version.subjects.asClue { subjects -> subjects.size shouldBe 3 subjects[0].shouldBeInstanceOf<Resource>().asClue { subject -> subject.id shouldBe ThingId("R258") subject.label shouldBe "label" subject.classes shouldBe setOf(ThingId("C28")) } subjects[1].shouldBeInstanceOf<Resource>().asClue { subject -> subject.id shouldBe ThingId("R369") subject.label shouldBe "label" subject.classes shouldBe setOf(ThingId("C28")) } subjects[2].shouldBeInstanceOf<Resource>().asClue { subject -> subject.id shouldNotBe null subject.label shouldBe "Subject Resource" subject.classes shouldBe setOf(ThingId("C28")) } } version.objects.asClue { objects -> objects.size shouldBe 5 objects[0].asClue { position -> position.size shouldBe 3 position[0].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldBe ThingId("R174") `object`.label shouldBe "label" `object`.classes shouldBe emptySet() } position[1].shouldBeInstanceOf<Predicate>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "hasResult" } position[2].shouldBeInstanceOf<Class>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "new class" `object`.uri shouldBe null } } objects[1].asClue { position -> position.size shouldBe 2 position[0].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "123456" `object`.datatype shouldBe Literals.XSD.STRING.prefixedUri } position[1].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "0123456789" `object`.datatype shouldBe Literals.XSD.STRING.prefixedUri } } objects[2].asClue { position -> position.size shouldBe 2 position[0].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "5" `object`.datatype shouldBe Literals.XSD.INT.prefixedUri } position[1].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "1" `object`.datatype shouldBe Literals.XSD.INT.prefixedUri } } objects[3].asClue { position -> position.size shouldBe 2 position[0].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "custom type" `object`.datatype shouldBe "http://orkg.org/orkg/class/C25" } position[1].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "some literal value" `object`.datatype shouldBe "http://orkg.org/orkg/class/C25" } } objects[4].asClue { position -> position.size shouldBe 3 position[0].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldBe ThingId("R258") `object`.label shouldBe "label" `object`.classes shouldBe setOf(ThingId("C28")) } position[1].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldBe ThingId("R369") `object`.label shouldBe "label" `object`.classes shouldBe setOf(ThingId("C28")) } position[2].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "list" `object`.classes shouldBe setOf(Classes.list) } } } version.createdAt shouldNotBe null version.createdBy shouldBe ContributorId(MockUserId.USER) version.certainty shouldBe Certainty.HIGH version.negated shouldBe false version.observatories shouldBe listOf(ObservatoryId("1afefdd0-5c09-4c9c-b718-2b35316b56f3")) version.organizations shouldBe listOf(OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e")) version.extractionMethod shouldBe ExtractionMethod.MANUAL version.visibility shouldBe Visibility.DEFAULT version.unlistedBy shouldBe null version.modifiable shouldBe true version.deletedBy shouldBe null version.deletedAt shouldBe null } it.versions[1].asClue { version -> version.id shouldNotBe updatedId version.formattedLabel shouldBe FormattedLabel.of("{0} {1} {2} {3} {4} {5}") version.subjects.asClue { subjects -> subjects.size shouldBe 3 subjects[0].shouldBeInstanceOf<Resource>().asClue { subject -> subject.id shouldBe ThingId("R369") subject.label shouldBe "label" subject.classes shouldBe setOf(ThingId("C28")) } subjects[1].shouldBeInstanceOf<Resource>().asClue { subject -> subject.id shouldBe ThingId("R258") subject.label shouldBe "label" subject.classes shouldBe setOf(ThingId("C28")) } subjects[2].shouldBeInstanceOf<Resource>().asClue { subject -> subject.id shouldNotBe null subject.label shouldBe "Updated Subject Resource" subject.classes shouldBe setOf(ThingId("C28")) } } version.objects.asClue { objects -> objects.size shouldBe 5 objects[0].asClue { position -> position.size shouldBe 3 position[0].shouldBeInstanceOf<Predicate>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "hasResult" } position[1].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldBe ThingId("R174") `object`.label shouldBe "label" `object`.classes shouldBe emptySet() } position[2].shouldBeInstanceOf<Class>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "updated new class" `object`.uri shouldBe null } } objects[1].asClue { position -> position.size shouldBe 2 position[0].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "9876543210" `object`.datatype shouldBe Literals.XSD.STRING.prefixedUri } position[1].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "123456" `object`.datatype shouldBe Literals.XSD.STRING.prefixedUri } } objects[2].asClue { position -> position.size shouldBe 2 position[0].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "4" `object`.datatype shouldBe Literals.XSD.INT.prefixedUri } position[1].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "5" `object`.datatype shouldBe Literals.XSD.INT.prefixedUri } } objects[3].asClue { position -> position.size shouldBe 2 position[0].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "some updated literal value" `object`.datatype shouldBe "http://orkg.org/orkg/class/C25" } position[1].shouldBeInstanceOf<Literal>().asClue { `object` -> `object`.label shouldBe "custom type" `object`.datatype shouldBe "http://orkg.org/orkg/class/C25" } } objects[4].asClue { position -> position.size shouldBe 3 position[0].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldBe ThingId("R369") `object`.label shouldBe "label" `object`.classes shouldBe setOf(ThingId("C28")) } position[1].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldBe ThingId("R258") `object`.label shouldBe "label" `object`.classes shouldBe setOf(ThingId("C28")) } position[2].shouldBeInstanceOf<Resource>().asClue { `object` -> `object`.id shouldNotBe null `object`.label shouldBe "list" `object`.classes shouldBe setOf(Classes.list) } } } version.createdAt shouldNotBe null version.createdBy shouldBe ContributorId(MockUserId.USER) version.certainty shouldBe Certainty.MODERATE version.negated shouldBe false version.observatories shouldBe listOf(ObservatoryId("1afefdd0-5c09-4c9c-b718-2b35316b56f3")) version.organizations shouldBe listOf(OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e")) version.extractionMethod shouldBe ExtractionMethod.AUTOMATIC version.visibility shouldBe Visibility.DEFAULT version.unlistedBy shouldBe null version.modifiable shouldBe true version.deletedBy shouldBe null version.deletedAt shouldBe null } it.observatories shouldBe listOf(ObservatoryId("1afefdd0-5c09-4c9c-b718-2b35316b56f3")) it.organizations shouldBe listOf(OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e")) it.extractionMethod shouldBe ExtractionMethod.AUTOMATIC it.visibility shouldBe Visibility.DEFAULT it.unlistedBy shouldBe null it.modifiable shouldBe true } } private fun createRosettaStoneTemplate() = rosettaStoneTemplateService.create( CreateRosettaStoneTemplateUseCase.CreateCommand( contributorId = ContributorId(MockUserId.USER), label = "rosetta stone template", description = "rosetta stone template description", formattedLabel = FormattedLabel.of("{0} {1} {2} {3} {4} {5}"), exampleUsage = "example statement usage", properties = listOf( ResourcePropertyDefinition( label = "subject position", placeholder = "subject", description = "subject", minCount = 1, maxCount = 4, path = Predicates.hasSubjectPosition, `class` = ThingId("C28") ), UntypedPropertyDefinition( label = "property label", placeholder = "property placeholder", description = "property description", minCount = 1, maxCount = 3, path = Predicates.hasObjectPosition ), StringLiteralPropertyDefinition( label = "string literal property label", placeholder = "string literal property placeholder", description = "string literal property description", minCount = 1, maxCount = 2, pattern = "\\d+", path = Predicates.hasObjectPosition, datatype = Classes.string ), NumberLiteralPropertyDefinition( label = "number literal property label", placeholder = "number literal property placeholder", description = "number literal property description", minCount = 1, maxCount = 2, minInclusive = RealNumber(-1), maxInclusive = RealNumber(10), path = Predicates.hasObjectPosition, datatype = Classes.integer ), OtherLiteralPropertyDefinition( label = "literal property label", placeholder = "literal property placeholder", description = "literal property description", minCount = 1, maxCount = 2, path = Predicates.hasObjectPosition, datatype = ThingId("C25") ), ResourcePropertyDefinition( label = "resource property label", placeholder = "resource property placeholder", description = "resource property description", minCount = 3, maxCount = 4, path = Predicates.hasObjectPosition, `class` = ThingId("C28") ), ), organizations = listOf(OrganizationId("edc18168-c4ee-4cb8-a98a-136f748e912e")), observatories = listOf(ObservatoryId("1afefdd0-5c09-4c9c-b718-2b35316b56f3")) ) ) private fun createRosettaStoneStatement(templateId: ThingId): ThingId = post("/api/rosetta-stone/statements") .content(createRosettaStoneStatementJson.replace("\$templateId", templateId.value)) .accept(ROSETTA_STONE_STATEMENT_JSON_V1) .contentType(ROSETTA_STONE_STATEMENT_JSON_V1) .characterEncoding("utf-8") .perform() .andExpect(status().isCreated) .andReturn() .response .getHeaderValue("Location")!! .toString() .substringAfterLast("/") .let(::ThingId) private fun RequestBuilder.perform(): ResultActions = mockMvc.perform(this) } private const val createRosettaStoneStatementJson = """{ "template_id": "${'$'}templateId", "context": "R789", "subjects": ["R258", "R369", "#temp1"], "objects": [ ["R174", "#temp2", "#temp3"], ["L123", "#temp4"], ["L456", "#temp5"], ["L789", "#temp6"], ["R258", "R369", "#temp7"] ], "certainty": "HIGH", "negated": false, "resources": { "#temp1": { "label": "Subject Resource", "classes": ["C28"] } }, "predicates": { "#temp2": { "label": "hasResult", "description": "has result" } }, "classes": { "#temp3": { "label": "new class", "uri": null } }, "literals": { "#temp4": { "label": "0123456789", "data_type": "xsd:string" }, "#temp5": { "label": "1", "data_type": "xsd:integer" }, "#temp6": { "label": "some literal value", "data_type": "http://orkg.org/orkg/class/C25" } }, "lists": { "#temp7": { "label": "list", "elements": ["#temp1", "C123"] } }, "observatories": [ "1afefdd0-5c09-4c9c-b718-2b35316b56f3" ], "organizations": [ "edc18168-c4ee-4cb8-a98a-136f748e912e" ], "extraction_method": "MANUAL" }""" private const val updateRosettaStoneStatementJson = """{ "subjects": ["R369", "R258", "#temp1"], "objects": [ ["#temp2", "R174", "#temp3"], ["#temp4", "L123"], ["#temp5", "L456"], ["#temp6", "L789"], ["R369", "R258", "#temp7"] ], "certainty": "MODERATE", "negated": false, "resources": { "#temp1": { "label": "Updated Subject Resource", "classes": ["C28"] } }, "predicates": { "#temp2": { "label": "hasResult", "description": "has result too" } }, "classes": { "#temp3": { "label": "updated new class", "uri": null } }, "literals": { "#temp4": { "label": "9876543210", "data_type": "xsd:string" }, "#temp5": { "label": "4", "data_type": "xsd:integer" }, "#temp6": { "label": "some updated literal value", "data_type": "http://orkg.org/orkg/class/C25" } }, "lists": { "#temp7": { "label": "list", "elements": ["C123", "#temp1"] } }, "observatories": [ "1afefdd0-5c09-4c9c-b718-2b35316b56f3" ], "organizations": [ "edc18168-c4ee-4cb8-a98a-136f748e912e" ], "extraction_method": "AUTOMATIC" }"""
0
Kotlin
0
4
ee884fb0b87c20e18b6e1ee81379f9d2ab17c8f3
32,650
orkg-backend
MIT License
common-legacy-api/src/main/kotlin/taboolib/common5/util/String2TimeCycle.kt
TabooLib
120,413,612
false
null
package taboolib.common5.util import taboolib.common5.Coerce import taboolib.common5.TimeCycle fun String.parseTimeCycle(): TimeCycle { val args = split(" ") return when (args[0]) { "day" -> TimeCycle( Coerce.toInteger(args[1]), Coerce.toInteger(args.getOrNull(2) ?: 0) ) "week" -> TimeCycle( TimeCycle.Type.WEEK, Coerce.toInteger(args[1]), Coerce.toInteger(args.getOrNull(2) ?: 0), Coerce.toInteger(args.getOrNull(3) ?: 0) ) "month" -> TimeCycle( TimeCycle.Type.MONTH, Coerce.toInteger(args[1]), Coerce.toInteger(args.getOrNull(2) ?: 0), Coerce.toInteger(args.getOrNull(3) ?: 0) ) else -> TimeCycle(args[0].parseMillis()) }.origin(this) }
4
null
101
307
f1178ac797c650042c977bfdf7a25e926522c032
829
taboolib
MIT License
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutBeyondBoundsModifierLocal.kt
androidx
256,589,781
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.layout import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.lazy.layout.LazyLayoutBeyondBoundsInfo.Interval import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.BeyondBoundsLayout import androidx.compose.ui.layout.BeyondBoundsLayout.BeyondBoundsScope import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Above import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.After import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Before import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Below import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Left import androidx.compose.ui.layout.BeyondBoundsLayout.LayoutDirection.Companion.Right import androidx.compose.ui.layout.ModifierLocalBeyondBoundsLayout import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ProvidableModifierLocal import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection.Ltr import androidx.compose.ui.unit.LayoutDirection.Rtl /** * This modifier is used to measure and place additional items when the lazy layout receives a * request to layout items beyond the visible bounds. */ @Suppress("ComposableModifierFactory") @Composable internal fun Modifier.lazyLayoutBeyondBoundsModifier( state: LazyLayoutBeyondBoundsState, beyondBoundsInfo: LazyLayoutBeyondBoundsInfo, reverseLayout: Boolean, layoutDirection: LayoutDirection, orientation: Orientation, enabled: Boolean ): Modifier = this then if (!enabled) { this } else { remember(state, beyondBoundsInfo, reverseLayout, layoutDirection, orientation, enabled) { LazyLayoutBeyondBoundsModifierLocal( state, beyondBoundsInfo, reverseLayout, layoutDirection, orientation ) } } internal class LazyLayoutBeyondBoundsModifierLocal( private val state: LazyLayoutBeyondBoundsState, private val beyondBoundsInfo: LazyLayoutBeyondBoundsInfo, private val reverseLayout: Boolean, private val layoutDirection: LayoutDirection, private val orientation: Orientation ) : ModifierLocalProvider<BeyondBoundsLayout?>, BeyondBoundsLayout { override val key: ProvidableModifierLocal<BeyondBoundsLayout?> get() = ModifierLocalBeyondBoundsLayout override val value: BeyondBoundsLayout get() = this companion object { private val emptyBeyondBoundsScope = object : BeyondBoundsScope { override val hasMoreContent = false } } override fun <T> layout( direction: BeyondBoundsLayout.LayoutDirection, block: BeyondBoundsScope.() -> T? ): T? { // If the lazy list is empty, or if it does not have any visible items (Which implies // that there isn't space to add a single item), we don't attempt to layout any more items. if (state.itemCount <= 0 || !state.hasVisibleItems) { return block.invoke(emptyBeyondBoundsScope) } // We use a new interval each time because this function is re-entrant. val startIndex = if (direction.isForward()) { state.lastPlacedIndex } else { state.firstPlacedIndex } var interval = beyondBoundsInfo.addInterval(startIndex, startIndex) var found: T? = null while (found == null && interval.hasMoreContent(direction)) { // Add one extra beyond bounds item. interval = addNextInterval(interval, direction).also { beyondBoundsInfo.removeInterval(interval) } state.remeasure() // When we invoke this block, the beyond bounds items are present. found = block.invoke( object : BeyondBoundsScope { override val hasMoreContent: Boolean get() = interval.hasMoreContent(direction) } ) } // Dispose the items that are beyond the visible bounds. beyondBoundsInfo.removeInterval(interval) state.remeasure() return found } private fun BeyondBoundsLayout.LayoutDirection.isForward(): Boolean = when (this) { Before -> false After -> true Above -> reverseLayout Below -> !reverseLayout Left -> when (layoutDirection) { Ltr -> reverseLayout Rtl -> !reverseLayout } Right -> when (layoutDirection) { Ltr -> !reverseLayout Rtl -> reverseLayout } else -> unsupportedDirection() } private fun addNextInterval( currentInterval: Interval, direction: BeyondBoundsLayout.LayoutDirection ): Interval { var start = currentInterval.start var end = currentInterval.end if (direction.isForward()) { end++ } else { start-- } return beyondBoundsInfo.addInterval(start, end) } private fun Interval.hasMoreContent(direction: BeyondBoundsLayout.LayoutDirection): Boolean { if (direction.isOppositeToOrientation()) return false return if (direction.isForward()) end < state.itemCount - 1 else start > 0 } private fun BeyondBoundsLayout.LayoutDirection.isOppositeToOrientation(): Boolean { return when (this) { Above, Below -> orientation == Orientation.Horizontal Left, Right -> orientation == Orientation.Vertical Before, After -> false else -> unsupportedDirection() } } } private fun unsupportedDirection(): Nothing = error( "Lazy list does not support beyond bounds layout for the specified direction" )
28
null
945
5,125
55c737bfb7a7320ac5b43787306f0c3af169f420
6,659
androidx
Apache License 2.0
vector/src/main/java/im/vector/app/ext/data/model/FiledtoItems.kt
huy22091999
542,926,323
false
{"Kotlin": 9903484, "Java": 166049, "HTML": 24691, "Shell": 23527, "Python": 17848, "FreeMarker": 7722, "JavaScript": 1782}
package im.vector.app.ext.data.model import com.google.gson.annotations.SerializedName data class FiledtoItems( @SerializedName("content") var content: ArrayList<FiledtoContent> = arrayListOf(), @SerializedName("empty") var empty : Boolean? = false )
0
Kotlin
0
0
9255297220ad63fef367b2c8b1a1065ad5241c92
265
edoctor_OCT
Apache License 2.0
source_codes/get_gif_api/android/app/src/main/kotlin/com/enesusta_/getgif/get_gif_api/MainActivity.kt
Turkmen48
461,888,649
false
{"Dart": 5033, "Swift": 404, "Kotlin": 137, "Objective-C": 38}
package com.enesusta_.getgif.get_gif_api import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
d8d3d7c2b002a14a6662aa6d01f4ba536118f9fb
137
Get_Gif_App_WithApi_Flutter
MIT License
jdk_17_maven/cs/rest/familie-tilbake/src/main/kotlin/no/nav/familie/tilbake/api/dto/VurdertForeldelseDto.kt
WebFuzzing
94,008,854
false
null
package no.nav.familie.tilbake.api.dto import no.nav.familie.kontrakter.felles.Datoperiode import no.nav.familie.tilbake.foreldelse.domain.Foreldelsesvurderingstype import java.math.BigDecimal import java.time.LocalDate data class VurdertForeldelseDto(val foreldetPerioder: List<VurdertForeldelsesperiodeDto>) data class VurdertForeldelsesperiodeDto( val periode: Datoperiode, val feilutbetaltBeløp: BigDecimal, val begrunnelse: String? = null, val foreldelsesvurderingstype: Foreldelsesvurderingstype? = null, val foreldelsesfrist: LocalDate? = null, val oppdagelsesdato: LocalDate? = null, )
3
null
16
26
1777aafb22c6fc7c1bc7db96c86b6ea70e38a36e
621
EMB
Apache License 2.0
app/src/main/java/com/example/AppTodoList/ui/tasks/TasksViewModel.kt
luga97
349,090,083
false
null
package com.example.AppTodoList.ui.tasks import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.ViewModel import com.example.AppTodoList.data.repository.TasksRepository /** * ViewModel Exclusivo del fragmento TaskFragment * nos permitira obtener todas las tareas desde las * fuentes de datos * @param repository repositorio que nos permita acceder a la capa de datos * @author <NAME> */ class TasksViewModel @ViewModelInject constructor( private val repository: TasksRepository ) : ViewModel() { val characters = repository.getTasks() }
0
Kotlin
0
0
b87aae8de7af134a637f63465513914dd2b44fba
570
AppTodoList
Apache License 2.0
src/test/java/com/ecwid/maleorang/method/v3_0/lists/members/MembersTest.kt
Ecwid
65,213,967
false
null
package com.ecwid.maleorang.method.v3_0.lists.members import com.ecwid.maleorang.MailchimpClient import com.ecwid.maleorang.MailchimpException import com.ecwid.maleorang.MailchimpObject import org.testng.Assert.assertEquals import org.testng.Assert.fail import org.testng.annotations.BeforeMethod import org.testng.annotations.Parameters import org.testng.annotations.Test import java.util.* class MembersTest @Parameters("mailchimp.test.apikey", "mailchimp.test.listid") constructor(private val apiKey: String, private val listId: String) { @BeforeMethod private fun cleanup() { MailchimpClient(apiKey).use { client -> var members: GetMembersMethod.Response = client.execute(GetMembersMethod(listId)) while (members.total_items!! > 0) { for (member in members.members!!) { client.execute(DeleteMemberMethod(listId, member.email_address!!)) } members = client.execute(GetMembersMethod(listId)) } } } @Test (enabled = false) fun test_POST_PATCH() { MailchimpClient(apiKey).use { client -> val email = "<EMAIL>" // Get nonexistent try { client.execute(GetMemberMethod(listId, email)) fail() } catch(e: MailchimpException) { assertEquals(e.code, 404) } // Creating the user client.execute(EditMemberMethod.Create(listId, email).apply { status = "subscribed" merge_fields = MailchimpObject().apply { mapping["FNAME"] = "Vasya" mapping["LNAME"] = "Pupkin" } timestamp_signup = Date(0) }).apply { assertEquals(email_address, email) assertEquals(status, "subscribed") assertEquals(merge_fields!!.mapping["FNAME"], "Vasya") assertEquals(merge_fields!!.mapping["LNAME"], "Pupkin") assertEquals(timestamp_signup, Date(0)) } // Updating the user using PATCH method client.execute(EditMemberMethod.Update(listId, email).apply { status = "unsubscribed" merge_fields = MailchimpObject().apply { mapping["FNAME"] = "Vasya1" mapping["LNAME"] = "Pupkin1" } timestamp_signup = Date(10000) }).apply { assertEquals(email_address, email) assertEquals(status, "unsubscribed") assertEquals(merge_fields!!.mapping["FNAME"], "Vasya1") assertEquals(merge_fields!!.mapping["LNAME"], "Pupkin1") assertEquals(timestamp_signup, Date(10000)) } // Get client.execute(GetMemberMethod(listId, email)).apply { assertEquals(email_address, email) assertEquals(status, "unsubscribed") assertEquals(merge_fields!!.mapping["FNAME"], "Vasya1") assertEquals(merge_fields!!.mapping["LNAME"], "Pupkin1") assertEquals(timestamp_signup, Date(10000)) } // Delete client.execute(DeleteMemberMethod(listId, email)) } } @Test (enabled = false) fun test_PUT() { MailchimpClient(apiKey).use { client -> val email = "<EMAIL>" // Get nonexistent try { client.execute(GetMemberMethod(listId, email)) fail() } catch(e: MailchimpException) { assertEquals(e.code, 404) } // Create client.execute(EditMemberMethod.CreateOrUpdate(listId, email).apply { status = "subscribed" merge_fields = MailchimpObject().apply { mapping["FNAME"] = "Vasya" mapping["LNAME"] = "Pupkin" } timestamp_signup = Date(1000000) }).apply { assertEquals(email_address, email) assertEquals(status, "subscribed") assertEquals(merge_fields!!.mapping["FNAME"], "Vasya") assertEquals(merge_fields!!.mapping["LNAME"], "Pupkin") assertEquals(timestamp_signup, Date(1000000)) } // Update client.execute(EditMemberMethod.CreateOrUpdate(listId, email).apply { status = "unsubscribed" merge_fields = MailchimpObject().apply { mapping["FNAME"] = "Vasya1" mapping["LNAME"] = "Pupkin1" } timestamp_signup = Date(1005000) }).apply { assertEquals(email_address, email) assertEquals(status, "unsubscribed") assertEquals(merge_fields!!.mapping["FNAME"], "Vasya1") assertEquals(merge_fields!!.mapping["LNAME"], "Pupkin1") assertEquals(timestamp_signup, Date(1005000)) } // Get client.execute(GetMemberMethod(listId, email)).apply { assertEquals(email_address, email) assertEquals(status, "unsubscribed") assertEquals(merge_fields!!.mapping["FNAME"], "Vasya1") assertEquals(merge_fields!!.mapping["LNAME"], "Pupkin1") assertEquals(timestamp_signup, Date(1005000)) } // Delete client.execute(DeleteMemberMethod(listId, email)) } } }
3
null
34
84
e7f4acc50a7b5c383d8f3c1441e6d4b77b37989f
5,656
maleorang
Apache License 2.0
newm-server/src/main/kotlin/io/newm/server/features/marketplace/database/MarketplaceBookmarkTable.kt
projectNEWM
447,979,150
false
{"Kotlin": 2128188, "HTML": 154009, "Shell": 2775, "Dockerfile": 2535, "Procfile": 60}
package io.newm.server.features.marketplace.database import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IdTable import org.jetbrains.exposed.sql.Column object MarketplaceBookmarkTable : IdTable<String>(name = "marketplace_bookmarks") { override val id: Column<EntityID<String>> = text("id").entityId() val txId: Column<String> = text("txid") val block: Column<Long> = long("block") val slot: Column<Long> = long("slot") }
1
Kotlin
4
9
3e0dc74a14a33b195b9311767c794b8d244db697
470
newm-server
Apache License 2.0
app/src/main/java/com/github/psm/jethouse/ui/widget/ProfileIcon.kt
Pidsamhai
400,962,881
false
null
package com.github.psm.jethouse.ui.widget import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import com.github.psm.jethouse.db.FakeDataSource import com.github.psm.jethouse.db.User import com.github.psm.jethouse.ui.theme.AvatarShape import com.github.psm.jethouse.ui.theme.JetHouseTheme import com.github.psm.jethouse.utils.toAvatarUrl @OptIn(ExperimentalCoilApi::class) @Composable fun ProfileIcon( modifier: Modifier = Modifier, user: User ) { Box( modifier = modifier .clip(AvatarShape) .background(Color(0xFFEEEEEE)) ) { Image( modifier = Modifier.fillMaxSize(), painter = rememberImagePainter(data = user.fullName.toAvatarUrl()), contentDescription = "Avatar Image" ) } } @Preview @Composable private fun ProfileIconPrev() { JetHouseTheme { ProfileIcon( modifier = Modifier.size(60.dp), user = FakeDataSource.user ) } }
0
Kotlin
0
0
d70f7a730f9e31c1ee83583e9f44b672b6f53448
1,490
jethouse
MIT License
ok-workout-be-common/src/main/kotlin/ru/otus/otuskotlin/workout/backend/common/models/MpUserGroups.kt
otuskotlin
377,713,426
false
null
package ru.otus.otuskotlin.workout.backend.common.models enum class MpUserGroups { USER, ADMIN, TEST, BAN }
0
Kotlin
1
0
7f9445aacad7e524a74b3a0cab0e853e845faba7
125
ok-202105-workout-kkh
MIT License
platform/platform-impl/src/com/intellij/ide/GeneralSettingsConfigurable.kt
ingokegel
72,937,917
true
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.ide import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.application.options.editor.checkBox import com.intellij.ide.ui.search.BooleanOptionDescription import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.PathChooserDialog import com.intellij.openapi.help.HelpManager import com.intellij.openapi.options.BoundCompositeSearchableConfigurable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.options.ex.ConfigurableWrapper import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.IdeUICustomization import com.intellij.ui.dsl.builder.* import com.intellij.util.PlatformUtils private val model: GeneralSettings get() = GeneralSettings.getInstance() private val myChkReopenLastProject: CheckboxDescriptor get() = CheckboxDescriptor(IdeUICustomization.getInstance().projectMessage("checkbox.reopen.last.project.on.startup"), model::isReopenLastProject) private val myConfirmExit: CheckboxDescriptor get() = CheckboxDescriptor(IdeBundle.message("checkbox.confirm.application.exit"), model::isConfirmExit) private val myChkSyncOnFrameActivation get() = CheckboxDescriptor(IdeBundle.message("checkbox.synchronize.files.on.frame.activation"), model::isSyncOnFrameActivation) private val myChkSyncInBackground get() = CheckboxDescriptor(IdeBundle.message("checkbox.synchronize.files.in.background"), model::isBackgroundSync) private val myChkSaveOnFrameDeactivation get() = CheckboxDescriptor(IdeBundle.message("checkbox.save.files.on.frame.deactivation"), model::isSaveOnFrameDeactivation) private val myChkAutoSaveIfInactive get() = CheckboxDescriptor(IdeBundle.message("checkbox.save.files.automatically"), model::isAutoSaveIfInactive) private val myChkUseSafeWrite get() = CheckboxDescriptor(IdeBundle.message("checkbox.safe.write"), model::isUseSafeWrite) internal val allOptionDescriptors: List<BooleanOptionDescription> get() = listOf( myChkReopenLastProject, myConfirmExit, myChkSyncOnFrameActivation, myChkSyncInBackground, myChkSaveOnFrameDeactivation, myChkAutoSaveIfInactive, myChkUseSafeWrite ) .map(CheckboxDescriptor::asUiOptionDescriptor) /** * To provide additional options in General section register implementation of [SearchableConfigurable] in the 'plugin.xml': * ``` * <extensions defaultExtensionNs="com.intellij"> * <generalOptionsProvider instance="class-name"/> * </extensions> * ``` * A new instance of the specified class will be created each time then the Settings dialog is opened. */ @Suppress("unused") private class GeneralSettingsConfigurable : BoundCompositeSearchableConfigurable<SearchableConfigurable>(IdeBundle.message("title.general"), "preferences.general"), SearchableConfigurable { private val model = GeneralSettings.getInstance().state override fun createPanel(): DialogPanel = panel { row { checkBox(myConfirmExit) } buttonsGroup { row(IdeBundle.message("group.settings.process.tab.close")) { radioButton(IdeBundle.message("radio.process.close.terminate"), ProcessCloseConfirmation.TERMINATE) radioButton(IdeBundle.message("radio.process.close.disconnect"), ProcessCloseConfirmation.DISCONNECT) radioButton(IdeBundle.message("radio.process.close.ask"), ProcessCloseConfirmation.ASK) } }.bind(model::processCloseConfirmation) { model.processCloseConfirmation = it } group(IdeUICustomization.getInstance().projectMessage("tab.title.project")) { row { checkBox(myChkReopenLastProject) } buttonsGroup { row(IdeUICustomization.getInstance().projectMessage("label.open.project.in")) { radioButton(IdeUICustomization.getInstance().projectMessage("radio.button.open.project.in.the.new.window"), GeneralSettings.OPEN_PROJECT_NEW_WINDOW) radioButton(IdeUICustomization.getInstance().projectMessage("radio.button.open.project.in.the.same.window"), GeneralSettings.OPEN_PROJECT_SAME_WINDOW) radioButton(IdeUICustomization.getInstance().projectMessage("radio.button.confirm.window.to.open.project.in"), GeneralSettings.OPEN_PROJECT_ASK) if (PlatformUtils.isDataSpell()) { radioButton(IdeUICustomization.getInstance().projectMessage("radio.button.attach"), GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) } }.layout(RowLayout.INDEPENDENT) }.bind(getter = { model.confirmOpenNewProject2 ?: GeneralSettings.defaultConfirmNewProject() }, setter = { model.confirmOpenNewProject2 = it }) row(IdeUICustomization.getInstance().projectMessage("settings.general.default.directory")) { textFieldWithBrowseButton(fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() .also { it.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, false) }) .bindText(GeneralLocalSettings.getInstance()::defaultProjectDirectory) .columns(COLUMNS_MEDIUM) .comment(IdeBundle.message("settings.general.directory.preselected"), 80) } } group(IdeBundle.message("settings.general.synchronization")) { row { val autoSaveCheckbox = checkBox(myChkAutoSaveIfInactive).gap(RightGap.SMALL) intTextField(GeneralSettings.SAVE_FILES_AFTER_IDLE_SEC.asRange()) .bindIntText(model::inactiveTimeout) { model.inactiveTimeout = it } .columns(4) .enabledIf(autoSaveCheckbox.selected) .gap(RightGap.SMALL) @Suppress("DialogTitleCapitalization") label(IdeBundle.message("label.inactive.timeout.sec")) } row { checkBox(myChkSaveOnFrameDeactivation) } row { checkBox(myChkUseSafeWrite) } row { checkBox(myChkSyncOnFrameActivation) } row { checkBox(myChkSyncInBackground) } row { comment(IdeBundle.message("label.autosave.comment")) { HelpManager.getInstance().invokeHelp("autosave") } }.topGap(TopGap.SMALL) } for (configurable in configurables) { appendDslConfigurable(configurable) } } override fun getId(): String = helpTopic!! override fun createConfigurables(): List<SearchableConfigurable> = ConfigurableWrapper.createConfigurables(EP_NAME) } private val EP_NAME = ExtensionPointName<GeneralSettingsConfigurableEP>("com.intellij.generalOptionsProvider")
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
6,929
intellij-community
Apache License 2.0
components/bridge/impl/src/main/java/com/flipperdevices/bridge/impl/manager/overflow/FlipperSerialOverflowThrottler.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.bridge.impl.manager.overflow import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import androidx.annotation.VisibleForTesting import com.flipperdevices.bridge.api.manager.service.FlipperSerialApi import com.flipperdevices.bridge.api.utils.Constants import com.flipperdevices.bridge.impl.manager.UnsafeBleManager import com.flipperdevices.bridge.impl.manager.service.BluetoothGattServiceWrapper import com.flipperdevices.bridge.impl.manager.service.getCharacteristicOrLog import com.flipperdevices.bridge.impl.manager.service.getServiceOrLog import com.flipperdevices.core.ktx.jre.withLock import com.flipperdevices.core.log.LogTagProvider import com.flipperdevices.core.log.info import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import no.nordicsemi.android.ble.data.Data import java.nio.ByteBuffer const val CLASS_TAG = "FlipperSerialOverflowThrottler" class FlipperSerialOverflowThrottler( private val serialApi: FlipperSerialApi, private val scope: CoroutineScope, private val requestStorage: FlipperRequestStorage ) : BluetoothGattServiceWrapper, LogTagProvider { override val TAG = CLASS_TAG private var overflowCharacteristics: BluetoothGattCharacteristic? = null private val mutex = Mutex() private var pendingBytes: ByteArray? = null private var overflowBufferJob: Job? = null /** * Bytes waiting to be sent to the device */ private var bufferSizeState = MutableSharedFlow<Int>(replay = 1) override fun onServiceReceived(gatt: BluetoothGatt): Boolean { val service = getServiceOrLog(gatt, Constants.BLESerialService.SERVICE_UUID) ?: return false overflowCharacteristics = getCharacteristicOrLog( service, Constants.BLESerialService.OVERFLOW ) ?: return false return true } override suspend fun initialize( bleManager: UnsafeBleManager ) = withLock(mutex, "initialize") { overflowBufferJob?.cancelAndJoin() overflowBufferJob = getOverflowBufferJob() pendingBytes = null bleManager.setNotificationCallbackUnsafe(overflowCharacteristics).with { _, data -> updateRemainingBuffer(data) } bleManager.enableNotificationsUnsafe(overflowCharacteristics).enqueue() bleManager.enableIndicationsUnsafe(overflowCharacteristics).enqueue() bleManager.readCharacteristicUnsafe(overflowCharacteristics).with { _, data -> updateRemainingBuffer(data) }.enqueue() } override suspend fun reset( bleManager: UnsafeBleManager ) = withLock(mutex, "reset") { overflowBufferJob?.cancelAndJoin() overflowBufferJob = null info { "Cancel overflow buffer job" } bufferSizeState.emit(0) pendingBytes = null } @VisibleForTesting fun updateRemainingBuffer(data: Data) { info { "Receive remaining buffer info" } val bytes = data.value ?: return val remainingInternal = ByteBuffer.wrap(bytes).int info { "Invalidate buffer size. New size: $remainingInternal" } scope.launch { bufferSizeState.emit(remainingInternal) } } private suspend fun CoroutineScope.sendCommandsWhileBufferNotEnd( bufferSize: Int ) { var remainingBufferSize = bufferSize while (isActive && remainingBufferSize > 0) { val pendingBytesToSend = getPendingBytesSafe(remainingBufferSize) remainingBufferSize -= pendingBytesToSend.size if (remainingBufferSize == 0) { info { "Sending only pending bytes" } serialApi.sendBytes(pendingBytesToSend) break } val (bytesToSend, pendingBytesInternal) = requestStorage.getPendingCommands( remainingBufferSize, Constants.BLE.RPC_SEND_WAIT_TIMEOUT_MS ) check(remainingBufferSize >= bytesToSend.size) { "getPendingCommands can't return bytes (${bytesToSend.size}) " + "more than buffer ($remainingBufferSize)" } remainingBufferSize -= bytesToSend.size pendingBytes = pendingBytesInternal serialApi.sendBytes(pendingBytesToSend + bytesToSend) } } private fun getPendingBytesSafe(maxLength: Int): ByteArray { val pendingBytesInternal = pendingBytes ?: return byteArrayOf() if (pendingBytesInternal.size <= maxLength) { pendingBytes = null return pendingBytesInternal } val toSend = pendingBytesInternal.copyOf(maxLength) pendingBytes = pendingBytesInternal.copyOfRange(maxLength, pendingBytesInternal.size) return toSend } private fun getOverflowBufferJob(): Job { return scope.launch(Dispatchers.Default) { bufferSizeState.collectLatest { bufferSize -> sendCommandsWhileBufferNotEnd(bufferSize) } } } }
9
null
78
850
4a30af6fffc8dc8dc51b24ef8d7526e9f580a38f
5,368
Flipper-Android-App
MIT License
ontrack-job/src/main/java/net/nemerosa/ontrack/job/orchestrator/NOPJobOrchestratorSupplier.kt
nemerosa
19,351,480
false
{"Kotlin": 9228434, "JavaScript": 3016136, "Java": 1053512, "HTML": 506551, "Groovy": 377453, "CSS": 137546, "Less": 35335, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.job.orchestrator import net.nemerosa.ontrack.job.JobRegistration import org.springframework.stereotype.Component @Component class NOPJobOrchestratorSupplier : JobOrchestratorSupplier { override val jobRegistrations: Collection<JobRegistration> = emptyList() }
44
Kotlin
25
96
fde26a48ea7b18689851fe579635f4ed72ad2c5a
294
ontrack
MIT License
app/src/main/java/com/example/jetpackcompose/material/FixedActionButtonActivity.kt
anitaa1990
264,724,714
true
null
package com.example.jetpackcompose.material import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.compose.Composable import androidx.compose.remember import androidx.ui.core.Modifier import androidx.ui.core.setContent import androidx.ui.foundation.Icon import androidx.ui.foundation.Text import androidx.ui.foundation.VerticalScroller import androidx.ui.foundation.shape.corner.RoundedCornerShape import androidx.ui.layout.Column import androidx.ui.layout.Spacer import androidx.ui.layout.fillMaxWidth import androidx.ui.layout.padding import androidx.ui.layout.preferredHeight import androidx.ui.material.BottomAppBar import androidx.ui.material.Card import androidx.ui.material.FloatingActionButton import androidx.ui.material.IconButton import androidx.ui.material.MaterialTheme import androidx.ui.material.Scaffold import androidx.ui.material.ScaffoldState import androidx.ui.material.TopAppBar import androidx.ui.material.icons.Icons import androidx.ui.material.icons.filled.Favorite import androidx.ui.tooling.preview.Preview import androidx.ui.unit.dp import com.example.jetpackcompose.core.colors class FixedActionButtonActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // This is an extension function of Activity that sets the @Composable function that's // passed to it as the root view of the activity. This is meant to replace the .xml file // that we would typically set using the setContent(R.id.xml_file) method. The setContent // block defines the activity's layout. setContent { ScaffoldWithBottomBarAndCutout() } } } // We represent a Composable function by annotating it with the @Composable annotation. Composable // functions can only be called from within the scope of other composable functions. We should // think of composable functions to be similar to lego blocks - each composable function is in turn // built up of smaller composable functions. @Composable fun ScaffoldWithBottomBarAndCutout() { // remember is a composable that allows you to store values that survive recomposition. That // means that the scaffoldState variable will continue to hold its value even if the // ScaffoldWithBottomBarAndCutout is recomposed. The value is calculated only during // the first composition and every subsequent recomposition returns the value produced by the // original composition. // ScaffoldState is a @Model class that holds basic screen state relevant to the Scaffold // composable eg. drawerState i.e whether the drawer is open or closed. val scaffoldState = remember { ScaffoldState() } // Consider negative values to mean 'cut corner' and positive values to mean 'round corner' val fabShape = RoundedCornerShape(50) // Scaffold is a pre-defined composable that implements the basic material design visual // layout structure. It takes in child composables for all the common elements that you see // in an app using material design - app bar, bottom app bar, floating action button, etc. It // also takes care of laying out these child composables in the correct positions - eg bottom // app bar is automatically placed at the bottom of the screen even though I didn't specify // that explicitly. Scaffold( scaffoldState = scaffoldState, topAppBar = { TopAppBar(title = { Text("Scaffold Examples") }) }, bottomAppBar = { fabConfiguration -> // We specify the shape of the FAB bu passing a shape composable (fabShape) as a // parameter to cutoutShape property of the BottomAppBar. It automatically creates a // cutout in the BottomAppBar based on the shape of the Floating Action Button. BottomAppBar(fabConfiguration = fabConfiguration, cutoutShape = fabShape) {} }, floatingActionButton = { FloatingActionButton( onClick = {}, // We specify the same shape that we passed as the cutoutShape above. shape = fabShape, // We use the secondary color from the current theme. It uses the defaults when // you don't specify a theme (this example doesn't specify a theme either hence // it will just use defaults. Look at DarkModeActivity if you want to see an // example of using themes. backgroundColor = MaterialTheme.colors.secondary ) { IconButton(onClick = {}) { Icon(asset = Icons.Filled.Favorite) } } }, floatingActionButtonPosition = Scaffold.FabPosition.CenterDocked, bodyContent = { modifier -> // Vertical scroller is a composable that adds the ability to scroll through the // child views VerticalScroller { // Column is a composable that places its children in a vertical sequence. You // can think of it similar to a LinearLayout with the vertical orientation. Column(modifier) { repeat(100) { // Card composable is a predefined composable that is meant to represent // the card surface as specified by the Material Design specification. We // also configure it to have rounded corners and apply a modifier. Card(color = colors[it % colors.size], shape = RoundedCornerShape(8.dp), modifier = Modifier.padding(8.dp) ) { Spacer(modifier = Modifier.fillMaxWidth() + Modifier.preferredHeight(200.dp)) } } } } } ) } /** * Android Studio lets you preview your composable functions within the IDE itself, instead of * needing to download the app to an Android device or emulator. This is a fantastic feature as you * can preview all your custom components(read composable functions) from the comforts of the IDE. * The main restriction is, the composable function must not take any parameters. If your composable * function requires a parameter, you can simply wrap your component inside another composable * function that doesn't take any parameters and call your composable function with the appropriate * params. Also, don't forget to annotate it with @Preview & @Composable annotations. */ @Preview("Fixed Aaction Button Example") @Composable fun ScaffoldWithBottomBarAndCutoutPreview() { ScaffoldWithBottomBarAndCutout() }
0
null
3
10
24da6d327fbc77a88c359c16d55eeb9f5fb1f1da
6,748
Learn-Jetpack-Compose-By-Example
Apache License 2.0
emoji-google-compat/src/commonMain/kotlin/com/vanniktech/emoji/googlecompat/category/FlagsCategoryChunk0.kt
vanniktech
53,511,222
false
{"Kotlin": 2552475, "JavaScript": 19229, "Ruby": 15950}
/* * Copyright (C) 2016 - <NAME>, <NAME>, <NAME> and contributors * * 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.vanniktech.emoji.androidxemoji2.category import com.vanniktech.emoji.androidxemoji2.AndroidxEmoji2 internal object FlagsCategoryChunk0 { internal val EMOJIS: List<AndroidxEmoji2> = listOf( AndroidxEmoji2("\ud83c\udfc1", listOf("checkered_flag")), AndroidxEmoji2("\ud83d\udea9", listOf("triangular_flag_on_post")), AndroidxEmoji2("\ud83c\udf8c", listOf("crossed_flags")), AndroidxEmoji2("\ud83c\udff4", listOf("waving_black_flag")), AndroidxEmoji2( unicode = "\ud83c\udff3", shortcodes = listOf("waving_white_flag"), variants = listOf( AndroidxEmoji2("\ud83c\udff3\ufe0f", emptyList()), ), ), AndroidxEmoji2( unicode = "\ud83c\udff3\u200d\ud83c\udf08", shortcodes = listOf("rainbow-flag"), variants = listOf( AndroidxEmoji2("\ud83c\udff3\ufe0f\u200d\ud83c\udf08", emptyList()), ), ), AndroidxEmoji2( unicode = "\ud83c\udff3\u200d\u26a7", shortcodes = listOf("transgender_flag"), variants = listOf( AndroidxEmoji2("\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f", emptyList()), ), ), AndroidxEmoji2( unicode = "\ud83c\udff4\u200d\u2620", shortcodes = listOf("pirate_flag"), variants = listOf( AndroidxEmoji2("\ud83c\udff4\u200d\u2620\ufe0f", emptyList()), ), ), AndroidxEmoji2("\ud83c\udde6\ud83c\udde8", listOf("flag-ac")), AndroidxEmoji2("\ud83c\udde6\ud83c\udde9", listOf("flag-ad")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddea", listOf("flag-ae")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddeb", listOf("flag-af")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddec", listOf("flag-ag")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddee", listOf("flag-ai")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf1", listOf("flag-al")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf2", listOf("flag-am")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf4", listOf("flag-ao")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf6", listOf("flag-aq")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf7", listOf("flag-ar")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf8", listOf("flag-as")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddf9", listOf("flag-at")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddfa", listOf("flag-au")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddfc", listOf("flag-aw")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddfd", listOf("flag-ax")), AndroidxEmoji2("\ud83c\udde6\ud83c\uddff", listOf("flag-az")), AndroidxEmoji2("\ud83c\udde7\ud83c\udde6", listOf("flag-ba")), AndroidxEmoji2("\ud83c\udde7\ud83c\udde7", listOf("flag-bb")), AndroidxEmoji2("\ud83c\udde7\ud83c\udde9", listOf("flag-bd")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddea", listOf("flag-be")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddeb", listOf("flag-bf")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddec", listOf("flag-bg")), AndroidxEmoji2("\ud83c\udde7\ud83c\udded", listOf("flag-bh")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddee", listOf("flag-bi")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddef", listOf("flag-bj")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf1", listOf("flag-bl")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf2", listOf("flag-bm")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf3", listOf("flag-bn")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf4", listOf("flag-bo")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf6", listOf("flag-bq")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf7", listOf("flag-br")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf8", listOf("flag-bs")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddf9", listOf("flag-bt")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddfb", listOf("flag-bv")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddfc", listOf("flag-bw")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddfe", listOf("flag-by")), AndroidxEmoji2("\ud83c\udde7\ud83c\uddff", listOf("flag-bz")), AndroidxEmoji2("\ud83c\udde8\ud83c\udde6", listOf("flag-ca")), AndroidxEmoji2("\ud83c\udde8\ud83c\udde8", listOf("flag-cc")), AndroidxEmoji2("\ud83c\udde8\ud83c\udde9", listOf("flag-cd")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddeb", listOf("flag-cf")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddec", listOf("flag-cg")), AndroidxEmoji2("\ud83c\udde8\ud83c\udded", listOf("flag-ch")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddee", listOf("flag-ci")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf0", listOf("flag-ck")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf1", listOf("flag-cl")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf2", listOf("flag-cm")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf3", listOf("cn", "flag-cn")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf4", listOf("flag-co")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf5", listOf("flag-cp")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddf7", listOf("flag-cr")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddfa", listOf("flag-cu")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddfb", listOf("flag-cv")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddfc", listOf("flag-cw")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddfd", listOf("flag-cx")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddfe", listOf("flag-cy")), AndroidxEmoji2("\ud83c\udde8\ud83c\uddff", listOf("flag-cz")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddea", listOf("de", "flag-de")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddec", listOf("flag-dg")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddef", listOf("flag-dj")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddf0", listOf("flag-dk")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddf2", listOf("flag-dm")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddf4", listOf("flag-do")), AndroidxEmoji2("\ud83c\udde9\ud83c\uddff", listOf("flag-dz")), AndroidxEmoji2("\ud83c\uddea\ud83c\udde6", listOf("flag-ea")), AndroidxEmoji2("\ud83c\uddea\ud83c\udde8", listOf("flag-ec")), AndroidxEmoji2("\ud83c\uddea\ud83c\uddea", listOf("flag-ee")), AndroidxEmoji2("\ud83c\uddea\ud83c\uddec", listOf("flag-eg")), AndroidxEmoji2("\ud83c\uddea\ud83c\udded", listOf("flag-eh")), AndroidxEmoji2("\ud83c\uddea\ud83c\uddf7", listOf("flag-er")), AndroidxEmoji2("\ud83c\uddea\ud83c\uddf8", listOf("es", "flag-es")), AndroidxEmoji2("\ud83c\uddea\ud83c\uddf9", listOf("flag-et")), AndroidxEmoji2("\ud83c\uddea\ud83c\uddfa", listOf("flag-eu")), AndroidxEmoji2("\ud83c\uddeb\ud83c\uddee", listOf("flag-fi")), AndroidxEmoji2("\ud83c\uddeb\ud83c\uddef", listOf("flag-fj")), AndroidxEmoji2("\ud83c\uddeb\ud83c\uddf0", listOf("flag-fk")), AndroidxEmoji2("\ud83c\uddeb\ud83c\uddf2", listOf("flag-fm")), AndroidxEmoji2("\ud83c\uddeb\ud83c\uddf4", listOf("flag-fo")), AndroidxEmoji2("\ud83c\uddeb\ud83c\uddf7", listOf("fr", "flag-fr")), AndroidxEmoji2("\ud83c\uddec\ud83c\udde6", listOf("flag-ga")), AndroidxEmoji2("\ud83c\uddec\ud83c\udde7", listOf("gb", "uk", "flag-gb")), AndroidxEmoji2("\ud83c\uddec\ud83c\udde9", listOf("flag-gd")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddea", listOf("flag-ge")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddeb", listOf("flag-gf")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddec", listOf("flag-gg")), AndroidxEmoji2("\ud83c\uddec\ud83c\udded", listOf("flag-gh")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddee", listOf("flag-gi")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddf1", listOf("flag-gl")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddf2", listOf("flag-gm")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddf3", listOf("flag-gn")), AndroidxEmoji2("\ud83c\uddec\ud83c\uddf5", listOf("flag-gp")), ) }
5
Kotlin
292
1,537
60efe8bbfe4f2900e424c4cdddf01dcc59e0b4bb
8,178
Emoji
Apache License 2.0
perf/app/src/main/java/com/google/firebase/quickstart/perfmon/EntryChoiceActivity.kt
firebase
57,147,349
false
null
package com.google.firebase.quickstart.perfmon import android.content.Intent import com.firebase.example.internal.BaseEntryChoiceActivity import com.firebase.example.internal.Choice class EntryChoiceActivity : BaseEntryChoiceActivity() { override fun getChoices(): List<Choice> { return listOf( Choice( "Java", "Run the Firebase Performance Monitoring quickstart written in Java.", Intent( this, com.google.firebase.quickstart.perfmon.java.MainActivity::class.java)), Choice( "Kotlin", "Run the Firebase Performance Monitoring quickstart written in Kotlin.", Intent( this, com.google.firebase.quickstart.perfmon.kotlin.MainActivity::class.java)) ) } }
68
null
7436
8,858
4d1e253dd1dd8052310e889fc1785084b1997aca
967
quickstart-android
Apache License 2.0
project/src/main/kotlin/cga/exercise/components/light/PointLight.kt
Merciii
284,711,888
false
null
package cga.exercise.components.light import cga.exercise.components.geometry.Transformable import cga.exercise.components.shader.ShaderProgram import org.joml.Vector3f open class PointLight(var pos :Vector3f,var color :Vector3f) :Transformable(),IPointLight{ var attenuation = Vector3f(1.0f,0.5f,0.1f) init { translateGlobal(pos) } override fun bind(shaderProgram: ShaderProgram, name: String) { shaderProgram.setUniform(name +"pointlight_col",color) shaderProgram.setUniform(name +"pointlight_pos",getWorldPosition()) shaderProgram.setUniform(name +"pointlight_attenuation",attenuation) } }
0
null
0
1
613b03d5e3adb042cb1262a169d8beccee0fd9d3
639
CGAProject2020BreidbachCinkaya
MIT License
base/lint/libs/lint-tests/src/test/java/com/android/tools/lint/detector/api/CategoryTest.kt
qiangxu1996
301,210,525
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint.detector.api import com.google.common.base.Joiner import com.google.common.collect.Lists import junit.framework.TestCase import java.lang.reflect.Modifier class CategoryTest : TestCase() { fun testCompare() { val categories = Lists.newArrayList<Category>() for (field in Category::class.java.declaredFields) { if (field.type == Category::class.java && field.modifiers and Modifier.STATIC != 0) { field.isAccessible = true val o = field.get(null) if (o is Category) { categories.add(o) } } } categories.sort() assertEquals( "" + "Lint\n" + "Correctness\n" + "Correctness:Messages\n" + "Correctness:Chrome OS\n" + "Security\n" + "Compliance\n" + "Performance\n" + "Performance:Application Size\n" + "Usability:Typography\n" + "Usability:Icons\n" + "Usability\n" + "Productivity\n" + "Accessibility\n" + "Internationalization\n" + "Internationalization:Bidirectional Text\n" + "Testing\n" + "Interoperability\n" + "Interoperability:Kotlin Interoperability\n" + "Interoperability:Java Interoperability\n" + "Lint Implementation Issues", Joiner.on("\n").join(categories) ) } fun testGetName() = assertEquals("Messages", Category.MESSAGES.name) fun testGetFullName() = assertEquals("Correctness:Messages", Category.MESSAGES.fullName) fun testEquals() { assertEquals(Category.MESSAGES, Category.MESSAGES) assertEquals(Category.create("Correctness", 100), Category.create("Correctness", 100)) assertFalse(Category.MESSAGES == Category.CORRECTNESS) assertFalse(Category.create("Correctness", 100) == Category.create("Correct", 100)) } }
1
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
2,743
vmtrace
Apache License 2.0
data/api/src/main/java/com/mataku/scrobscrob/data/api/endpoint/UserTopAlbumsEndpoint.kt
mataku
99,928,377
false
{"Kotlin": 406856, "Ruby": 2778, "Makefile": 558}
package com.mataku.scrobscrob.data.api.endpoint import com.mataku.scrobscrob.data.api.model.UserTopAlbumsApiResponse import io.ktor.http.HttpMethod data class UserTopAlbumsEndpoint( override val path: String = "/2.0/?method=user.getTopAlbums&format=json", override val requestType: HttpMethod = HttpMethod.Get, override val params: Map<String, Any> ) : Endpoint<UserTopAlbumsApiResponse>
2
Kotlin
2
9
5c93daff9786df8300f8f6209ab9c3bb79585352
396
SunsetScrob
Apache License 2.0
app/src/main/java/com/example/parentguide/navigation/KidUser/DataState.kt
COMBOxKILLER
802,642,141
false
{"Kotlin": 244975, "Java": 138062, "Assembly": 43}
package com.example.parentguide.navigation.KidUser sealed class DataState<out T> { data class Success<T>(val data: T) : DataState<T>() data class Failure(val message: String) : DataState<Nothing>() object Loading : DataState<Nothing>() object Empty : DataState<Nothing>() }
0
Kotlin
0
0
5c6ab91573d32bba1edbce0a27175d286feaa108
292
SecureKids-app-CU2000187
MIT License
unique-sdk/src/openApiGenerator/src/main/kotlin/network/unique/model/VideoDto.kt
UniqueNetwork
555,353,838
false
{"Kotlin": 1102840, "Rust": 7782, "Java": 2916}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package network.unique.model import com.squareup.moshi.Json /** * * * @param urlTemplate */ data class VideoDto ( @Json(name = "urlTemplate") val urlTemplate: kotlin.String? = null )
0
Kotlin
0
3
0f5afacd0cb7b7411bc78307f3a22c8d02a14e69
477
unique-sdk-kotlin
MIT License
android/src/main/kotlin/dev/msfjarvis/claw/android/MainActivity.kt
msfjarvis
289,347,156
false
null
/* * Copyright © 2021-2023 <NAME>. * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package dev.msfjarvis.claw.android import android.app.assist.AssistContent import android.net.Uri import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.WindowCompat import com.deliveryhero.whetstone.Whetstone import com.deliveryhero.whetstone.activity.ContributesActivityInjector import dev.msfjarvis.claw.android.ui.LobstersApp import dev.msfjarvis.claw.common.urllauncher.UrlLauncher import javax.inject.Inject @ContributesActivityInjector class MainActivity : ComponentActivity() { @Inject lateinit var urlLauncher: UrlLauncher private var webUri: String? = null @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() Whetstone.inject(this) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { val windowSizeClass = calculateWindowSizeClass(this) LobstersApp( urlLauncher = urlLauncher, windowSizeClass = windowSizeClass, setWebUri = { url -> webUri = url }, ) } } override fun onProvideAssistContent(outContent: AssistContent?) { super.onProvideAssistContent(outContent) if (outContent != null) { if (webUri != null) { outContent.webUri = Uri.parse(webUri) } else { outContent.webUri = null } } } }
6
null
7
53
44438da292394fd2d0d64ae9d4e000352f7a603b
1,875
compose-lobsters
MIT License
feature/changepassword/src/main/java/com/muammarahlnn/learnyscape/feature/changepassword/navigation/ChangePasswordNavigation.kt
muammarahlnn
663,132,195
false
{"Kotlin": 1077954}
package com.muammarahlnn.learnyscape.feature.changepassword.navigation import androidx.compose.runtime.rememberCoroutineScope import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import com.muammarahlnn.learnyscape.feature.changepassword.ChangePasswordController import com.muammarahlnn.learnyscape.feature.changepassword.ChangePasswordRoute /** * @author <NAME> (muammarahlnn) * @file ChangePasswordNavigation, 14/11/2023 11.57 by <NAME> */ const val CHANGE_PASSWORD_ROUTE = "change_password_route" fun NavController.navigateToChangePassword() { this.navigate(CHANGE_PASSWORD_ROUTE) { launchSingleTop = true } } fun NavGraphBuilder.changePasswordScreen( navigateBack: () -> Unit, ) { composable(CHANGE_PASSWORD_ROUTE) { ChangePasswordRoute( controller = ChangePasswordController( scope = rememberCoroutineScope(), navigateBack = navigateBack, ) ) } }
0
Kotlin
0
0
1a6aafc8a84cd2cbe54b7b64c6ec937c2c8c5580
1,036
Learnyscape
Apache License 2.0
workflows/src/test/kotlin/com/r3/corda/lib/tokens/workflows/TokenSelectionWithInFlowTest.kt
corda
160,397,060
false
null
package com.r3.corda.lib.tokens.workflows import com.r3.corda.lib.tokens.contracts.states.FungibleToken import com.r3.corda.lib.tokens.contracts.utilities.heldBy import com.r3.corda.lib.tokens.contracts.utilities.issuedBy import com.r3.corda.lib.tokens.contracts.utilities.of import com.r3.corda.lib.tokens.money.BTC import com.r3.corda.lib.tokens.workflows.flows.rpc.IssueTokens import net.corda.core.contracts.Amount import net.corda.core.utilities.getOrThrow import net.corda.testing.core.* import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNodeParameters import net.corda.testing.node.internal.startFlow import org.hamcrest.CoreMatchers.* import org.junit.* class TokenSelectionWithInFlowTest { @Test fun `should allow selection of tokens already issued from within a flow`() { val mockNet = InternalMockNetwork( cordappPackages = listOf( "com.r3.corda.lib.tokens.money", "com.r3.corda.lib.tokens.selection", "com.r3.corda.lib.tokens.contracts", "com.r3.corda.lib.tokens.workflows" ) ) try { val aliceNode = mockNet.createNode(InternalMockNodeParameters(legalName = ALICE_NAME)) val issuerNode = mockNet.createNode(InternalMockNodeParameters(legalName = CHARLIE_NAME)) val alice = aliceNode.info.singleIdentity() val issuer = issuerNode.info.singleIdentity() val btc = 100000 of BTC issuedBy issuer heldBy alice val resultFuture = issuerNode.services.startFlow(IssueTokens(listOf(btc))).resultFuture mockNet.runNetwork() val issueResultTx = resultFuture.get() val issuedStateRef = issueResultTx.coreTransaction.outRefsOfType<FungibleToken>().single() val tokensFuture = aliceNode.services.startFlow(SuspendingSelector(alice.owningKey, Amount(1, BTC))).resultFuture mockNet.runNetwork() val selectedToken = tokensFuture.getOrThrow().single() Assert.assertThat(issuedStateRef, `is`(equalTo(selectedToken))) } finally { mockNet.stopNodes() } } }
38
null
77
80
749483f691c2c6ca56d9caacdd73a9e6319a969e
2,223
token-sdk
Apache License 2.0
ide-common/src/main/kotlin/org/digma/intellij/plugin/auth/account/CentralizedLoginHandler.kt
digma-ai
472,408,329
false
{"Kotlin": 1686412, "Java": 579281, "C#": 117248, "Shell": 13664, "HTML": 11307, "FreeMarker": 10897}
package org.digma.intellij.plugin.auth.account import org.digma.intellij.plugin.analytics.RestAnalyticsProvider import org.digma.intellij.plugin.auth.reportAuthPosthogEvent import org.digma.intellij.plugin.auth.withAuthManagerDebug import org.digma.intellij.plugin.common.ExceptionUtils import org.digma.intellij.plugin.errorreporting.ErrorReporter import kotlin.time.Duration.Companion.seconds class CentralizedLoginHandler(analyticsProvider: RestAnalyticsProvider) : AbstractLoginHandler(analyticsProvider) { //make sure CredentialsHolder.digmaCredentials is always updated correctly override suspend fun loginOrRefresh(onAuthenticationError: Boolean, trigger: String): Boolean { return try { trace("loginOrRefresh called, url: {},trigger {}", analyticsProvider.apiUrl, trigger) withAuthManagerDebug { reportAuthPosthogEvent("loginOrRefresh", this.javaClass.simpleName, trigger) } val digmaAccount = getDefaultAccount() if (digmaAccount == null) { CredentialsHolder.digmaCredentials = null trace("no account found in loginOrRefresh, account is not logged in for centralized env url: {}", analyticsProvider.apiUrl) false } else if (digmaAccount.server.url != analyticsProvider.apiUrl) { trace( "digma account exists,but its url is different from analytics url, deleting account {}, url {}", digmaAccount, analyticsProvider.apiUrl ) logout("${this.javaClass.simpleName}: account url different from analytics url,$trigger") false } else { trace("found account in loginOrRefresh, account: {}", digmaAccount) val credentials = try { //exception here may happen if we change the credentials structure,which doesn't happen too much, // user will be redirected to log in again DigmaAccountManager.getInstance().findCredentials(digmaAccount) } catch (_: Throwable) { null } //if digma account is not null and credentials is null then probably something corrupted, // it may be that the credentials deleted from the password safe if (credentials == null) { trace( "no credentials found for account {}, maybe credentials deleted from password safe? deleting account, analytics url {}", digmaAccount, analyticsProvider.apiUrl ) logout("${this.javaClass.simpleName}: no credentials for account,$trigger") false } else { trace("found credentials for account {}", digmaAccount) if (!credentials.isAccessTokenValid()) { trace("access token for account expired, refreshing token. account {}", digmaAccount) val refreshResult = refresh(digmaAccount, credentials, "${this.javaClass.simpleName} token expired,$trigger") trace("refresh token completed for account {}, result {}", digmaAccount, refreshResult) refreshResult } else if (onAuthenticationError && credentials.isOlderThen(30.seconds)) { //why check isOlderThen(30.seconds)? //to prevent multiple unnecessary refresh token. //when credentials expired multiple threads will fail on authentication error. //maybe few threads will try to refresh the token. //but of course only one refresh is necessary. //if these threads try to refresh one after the other than when this code is // executed it will not refresh again if the credentials are valid and were refreshed // in the past 30 seconds trace("onAuthenticationError is true and credentials older then 30 seconds, refreshing token. account {}", digmaAccount) val refreshResult = refresh(digmaAccount, credentials, "${this.javaClass.simpleName} on onAuthenticationError and token is old,$trigger") trace("refresh token completed for account {}, result {}", digmaAccount, refreshResult) refreshResult } else { trace("no need to refresh token for account {}", digmaAccount) //found credentials and its valid, probably on startup, update CredentialsHolder CredentialsHolder.digmaCredentials = credentials true } } } } catch (e: Throwable) { warnWithException(e, "Exception in loginOrRefresh {}, url {}", e, analyticsProvider.apiUrl) ErrorReporter.getInstance().reportError("${javaClass.simpleName}.loginOrRefresh", e, mapOf("loginOrRefresh trigger" to trigger)) withAuthManagerDebug { val errorMessage = ExceptionUtils.getNonEmptyMessage(e) reportAuthPosthogEvent( "loginOrRefresh failed", this.javaClass.simpleName, trigger, mapOf("error" to errorMessage) ) } //if got exception here then we probably can't refresh,logout, user will be redirected to login, // throw the exception to report it logout("${this.javaClass.simpleName}: error in loginOrRefresh $e,$trigger") throw e } finally { withAuthManagerDebug { reportAuthPosthogEvent("loginOrRefresh completed", this.javaClass.simpleName, trigger) } } } }
477
Kotlin
7
32
ce460b0cdc604968d267b98e72bf9dd211cf39b3
6,094
digma-intellij-plugin
MIT License
app/src/main/java/com/mokelab/tools/shortcut/pages/create/setting/CreateSettingShortcutViewModel.kt
mokelab
280,076,271
false
null
package com.mokelab.tools.shortcut.pages.create.setting import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.VectorDrawable import android.provider.Settings import androidx.core.content.ContextCompat import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.graphics.drawable.IconCompat import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mokelab.tools.shortcut.R import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.launch class CreateSettingShortcutViewModel @ViewModelInject constructor( @ApplicationContext private val context: Context ) : ViewModel() { val idError = MutableLiveData<String>() val labelError = MutableLiveData<String>() val done = MutableLiveData<Boolean>() fun create( id: String, label: String ) { viewModelScope.launch { if (!isValidInput(id, label)) { return@launch } val info = ShortcutInfoCompat.Builder(context, id).apply { val intent = Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) setShortLabel(label) setIntent(intent) setIcon(IconCompat.createWithAdaptiveBitmap(createIcon())) }.build() ShortcutManagerCompat.addDynamicShortcuts(context, listOf(info)) done.value = true } } private fun isValidInput( id: String, label: String ): Boolean { var hasError = false if (id.trim().isEmpty()) { idError.value = "Input ID" hasError = true } else { idError.value = "" } if (label.trim().isEmpty()) { labelError.value = "Input label" hasError = true } else { labelError.value = "" } return !hasError } fun createIcon(): Bitmap { val drawable = ContextCompat.getDrawable(context, R.drawable.ic_baseline_settings_24) as VectorDrawable val bitmap = Bitmap.createBitmap( drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) drawable.setBounds(16, 16, canvas.width - 16, canvas.height - 16) drawable.draw(canvas) return bitmap } }
0
Kotlin
0
0
aadcc6a30c70c322294cc2c92f38f939d22d09c7
2,634
android-the-shortcut
Apache License 2.0
App/app/src/main/java/com/app/notes/database/repository/RepositoryImpl.kt
ericasaline
578,992,527
false
null
package com.app.notes.database.repository import com.app.notes.database.dao.NoteRoom import com.app.notes.database.entity.NoteModel class RepositoryImpl(private val room: NoteRoom): Repository { override suspend fun insert(note: NoteModel): Boolean { return try { room.insert(note) true } catch(e: Exception) { false } } override suspend fun update(note: NoteModel): Boolean { return try { room.update(note) true } catch(e: Exception) { false } } override suspend fun delete(id: String): Boolean { return try { room.delete(id) true } catch(e: Exception) { false } } override suspend fun showAll(): List<NoteModel> { return try { room.showAll() } catch(e: Exception) { emptyList() } } override suspend fun showNote(id: String): NoteModel? { return room.showNote(id) } }
0
Kotlin
0
0
b116c34c9da0ca0973adf0a477eaf92504f3545e
1,050
App-Notes
MIT License
app/src/main/java/com/example/leslie/carousellkotlin/ui/ProfileFragment.kt
leslieharland
135,650,274
false
{"Kotlin": 203127, "Java": 1767}
package com.example.leslie.carousellkotlin.ui import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.leslie.carousellkotlin.ui.layout.ProfileFragmentLayout class ProfileFragment : Fragment() { private val profileFragmentLayout = ProfileFragmentLayout() override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = profileFragmentLayout.bind(this) return rootView; } override fun onDestroyView() { super.onDestroyView() profileFragmentLayout.unbind(this) } }
0
Kotlin
0
0
8688f1031b5f66b88ce2974ca99e95ec8e25d9a4
698
Carousell-Kotlin
Apache License 2.0
12-animating-properties-using-compose/projects/starter/app/src/main/java/com/raywenderlich/android/jetreddit/screens/MyProfileScreen.kt
raywenderlich
276,131,170
false
null
package com.raywenderlich.android.jetreddit.screens import androidx.compose.animation.Crossfade import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Star import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.imageResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.ConstraintLayout import com.raywenderlich.android.jetreddit.R import com.raywenderlich.android.jetreddit.appdrawer.ProfileInfo import com.raywenderlich.android.jetreddit.components.PostAction import com.raywenderlich.android.jetreddit.domain.model.PostModel import com.raywenderlich.android.jetreddit.routing.JetRedditRouter import com.raywenderlich.android.jetreddit.routing.MyProfileRouter import com.raywenderlich.android.jetreddit.routing.MyProfileScreenType import com.raywenderlich.android.jetreddit.viewmodel.MainViewModel private val tabNames = listOf("Posts", "About") @Composable fun MyProfileScreen(viewModel: MainViewModel, modifier: Modifier = Modifier) { ConstraintLayout(modifier = modifier.fillMaxSize()) { val (topAppBar, tabs, bodyContent) = createRefs() val colors = MaterialTheme.colors TopAppBar( title = { Text( fontSize = 12.sp, text = stringResource(R.string.default_username), color = colors.primaryVariant ) }, navigationIcon = { IconButton( onClick = { JetRedditRouter.goBack() } ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = null, tint = colors.primaryVariant ) } }, backgroundColor = colors.primary, elevation = 0.dp, modifier = modifier .constrainAs(topAppBar) { top.linkTo(parent.top) start.linkTo(parent.start) end.linkTo(parent.end) } .height(48.dp) .background(Color.Blue) ) MyProfileTabs( modifier = modifier.constrainAs(tabs) { top.linkTo(topAppBar.bottom) start.linkTo(parent.start) end.linkTo(parent.end) } ) Surface( modifier = modifier .constrainAs(bodyContent) { top.linkTo(tabs.bottom) start.linkTo(parent.start) end.linkTo(parent.end) } .padding(bottom = 68.dp) ) { Crossfade(targetState = MyProfileRouter.currentScreen) { screen -> when (screen.value) { MyProfileScreenType.Posts -> MyProfilePosts(modifier, viewModel) MyProfileScreenType.About -> MyProfileAbout() } } } } } @Composable fun MyProfileTabs(modifier: Modifier = Modifier) { var selectedIndex by remember { mutableStateOf(0) } TabRow( selectedTabIndex = selectedIndex, backgroundColor = MaterialTheme.colors.primary, modifier = modifier ) { tabNames.forEachIndexed { index, name -> Tab( selected = index == selectedIndex, onClick = { selectedIndex = index changeScreen(index) } ) { Text( color = MaterialTheme.colors.primaryVariant, fontSize = 12.sp, text = name, modifier = Modifier.padding(top = 8.dp, bottom = 8.dp) ) } } } } private fun changeScreen(index: Int) { return when (index) { 0 -> MyProfileRouter.navigateTo(MyProfileScreenType.Posts) else -> MyProfileRouter.navigateTo(MyProfileScreenType.About) } } @Composable fun MyProfilePosts(modifier: Modifier, viewModel: MainViewModel) { val posts: List<PostModel> by viewModel.myPosts.observeAsState(listOf()) LazyColumn(modifier = modifier.background(color = MaterialTheme.colors.secondary)) { items(posts) { MyProfilePost(modifier, it) } } } @Composable fun MyProfilePost(modifier: Modifier, post: PostModel) { Card(shape = MaterialTheme.shapes.large) { ConstraintLayout( modifier = modifier.fillMaxSize() ) { val (redditIcon, subredditName, actionsBar, title, description, settingIcon) = createRefs() val postModifier = Modifier val colors = MaterialTheme.colors Image( imageVector = Icons.Default.Star, contentDescription = null, modifier = postModifier .size(20.dp) .constrainAs(redditIcon) { top.linkTo(parent.top) start.linkTo(parent.start) } .padding(start = 8.dp, top = 8.dp) ) Image( imageVector = ImageVector.vectorResource(id = R.drawable.ic_baseline_more_vert_24), contentDescription = null, modifier = postModifier .size(20.dp) .constrainAs(settingIcon) { top.linkTo(parent.top) end.linkTo(parent.end) } .padding(end = 8.dp, top = 8.dp) ) Text( text = "${post.username} • ${post.postedTime}", fontSize = 8.sp, modifier = postModifier .constrainAs(subredditName) { top.linkTo(redditIcon.top) bottom.linkTo(redditIcon.bottom) start.linkTo(redditIcon.end) } .padding(start = 2.dp, top = 8.dp) ) Text( text = post.title, color = colors.primaryVariant, fontSize = 12.sp, modifier = postModifier .constrainAs(title) { top.linkTo(redditIcon.bottom) start.linkTo(redditIcon.start) } .padding(start = 8.dp, top = 8.dp) ) Text( text = post.text, color = Color.DarkGray, fontSize = 10.sp, modifier = postModifier .constrainAs(description) { top.linkTo(title.bottom) start.linkTo(redditIcon.start) } .padding(start = 8.dp, top = 8.dp) ) Row( modifier = postModifier .fillMaxWidth() .constrainAs(actionsBar) { top.linkTo(description.bottom) start.linkTo(parent.start) end.linkTo(parent.end) } .padding(top = 8.dp, bottom = 8.dp, end = 16.dp, start = 16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { PostAction( vectorResourceId = R.drawable.ic_baseline_arrow_upward_24, text = post.likes, onClickAction = {} ) PostAction( vectorResourceId = R.drawable.ic_baseline_comment_24, text = post.comments, onClickAction = {} ) PostAction( vectorResourceId = R.drawable.ic_baseline_share_24, text = "Share", onClickAction = {} ) } } } Spacer(modifier = Modifier.height(6.dp)) } @Composable fun MyProfileAbout() { Column { ProfileInfo() Spacer(modifier = Modifier.height(8.dp)) BackgroundText(stringResource(R.string.trophies)) val trophies = listOf( "Verified Email", "Gold Medal", "Top Comment" ) LazyColumn { items(trophies) { Trophy(text = it) } } } } @Composable fun BackgroundText(text: String) { Text( text = text, fontWeight = FontWeight.Medium, fontSize = 10.sp, color = Color.DarkGray, modifier = Modifier .background(color = MaterialTheme.colors.secondary) .padding(start = 16.dp, top = 4.dp, bottom = 4.dp) .fillMaxWidth() ) } @Composable fun Trophy(text: String, modifier: Modifier = Modifier) { Spacer(modifier = modifier.height(16.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Spacer(modifier = modifier.width(16.dp)) Image( bitmap = ImageBitmap.imageResource(id = R.drawable.trophy), contentDescription = null, contentScale = ContentScale.Crop, modifier = modifier.size(24.dp) ) Spacer(modifier = modifier.width(16.dp)) Text( text = text, fontSize = 12.sp, color = MaterialTheme.colors.primaryVariant, textAlign = TextAlign.Center, fontWeight = FontWeight.Medium ) } }
5
null
41
98
35a9250d111fa9dac64e22dc99e5cabd81579702
10,373
jet-materials
Apache License 2.0
liberalize/src/main/java/liberalize/kotlin/sdk/models/CardDetailsResponse.kt
LiberationNetwork
420,028,908
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 44, "XML": 18, "Java": 2, "INI": 2}
package liberalize.kotlin.sdk.models import android.os.Parcelable import kotlinx.parcelize.Parcelize import org.json.JSONObject @Parcelize data class MountCardData( @JvmField val source: String?, @JvmField val securityCode: String? ) : Parcelable @Parcelize data class CardDetailsResponse( @JvmField val id: String?, @JvmField val posId: String?, @JvmField val organizationId: String?, @JvmField val card: Card?, @JvmField var securityCode: String? = null ) : Parcelable { companion object { fun fromJson(res: JSONObject?): CardDetailsResponse { val id = if (res?.has("id") == true) res.get("id") as String? else null val posId = if (res?.has("posId") == true) res.get("posId") as String? else null val organizationId = if (res?.has("organizationId") == true) { res.get("organizationId") as String? } else { null } val card = if (res?.has("card") == true) { Card.fromJson(res.get("card") as JSONObject?) } else { null } return CardDetailsResponse( id = id, posId = posId, organizationId = organizationId, card = card ) } } } @Parcelize data class Card( val name: String?, val data: CardData?, val expiry: Expiry? ) : Parcelable { companion object { fun fromJson(res: JSONObject?): Card { val name = if (res?.has("name") == true) res.get("name") as String? else null val cardData = if (res?.has("data") == true) { CardData.fromJson(res.get("data") as JSONObject?) } else { null } val expiry = if (res?.has("expiry") == true) { Expiry.fromJson(res.get("expiry") as JSONObject?) } else { null } return Card(name, cardData, expiry) } } } @Parcelize data class CardData( val iin: String?, val last4: String?, val scheme: String? ) : Parcelable { companion object { fun fromJson(res: JSONObject?): CardData { val iin = if (res?.has("iin") == true) res.get("iin") as String? else null val last4 = if (res?.has("last4") == true) res.get("last4") as String? else null val scheme = if (res?.has("scheme") == true) res.get("scheme") as String? else null return CardData(iin, last4, scheme) } } } @Parcelize class ErrorResponse( val code: Int?, var message: String? ) : Parcelable { companion object { fun fromJson(res: JSONObject?): ErrorResponse? { val code = if (res?.has("code") == true) res.get("code") as Int? else null val msg = if (res?.has("message") == true) res.get("message") as String? else null return if (code == null && msg == null) null else ErrorResponse(code, msg) } } }
1
null
1
1
f9e4ab00c2b09afc8937f60d3cae903238990fff
3,188
liberalize-frontend-android-sdk
MIT License
main/src/main/kotlin/us/wedemy/eggeum/android/main/viewmodel/HomeViewModel.kt
Wedemy
615,061,021
false
null
/* * Designed and developed by Wedemy 2023. * * Licensed under the MIT. * Please see full license: https://github.com/Wedemy/eggeum-android/blob/main/LICENSE */ package us.wedemy.eggeum.android.main.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.ItemSnapshotList import androidx.paging.cachedIn import androidx.paging.map import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import timber.log.Timber import us.wedemy.eggeum.android.domain.model.place.PlaceEntity import us.wedemy.eggeum.android.domain.usecase.GetNoticeListUseCase import us.wedemy.eggeum.android.domain.usecase.GetPlaceListUseCase import us.wedemy.eggeum.android.main.mapper.toUiModel @HiltViewModel class HomeViewModel @Inject constructor( getPlaceListUseCase: GetPlaceListUseCase, getNoticeListUseCase: GetNoticeListUseCase, ) : ViewModel() { private val _cafesList = MutableStateFlow<List<List<PlaceEntity>>>(listOf(listOf(), listOf(), listOf())) val cafesList: StateFlow<List<List<PlaceEntity>>> = _cafesList.asStateFlow() private val _newCafes = MutableStateFlow(listOf<PlaceEntity>()) val newCafes: StateFlow<List<PlaceEntity>> = _newCafes.asStateFlow() private val _newStudyCafes = MutableStateFlow(listOf<PlaceEntity>()) val newStudyCafes: StateFlow<List<PlaceEntity>> = _newStudyCafes.asStateFlow() private val _newStudyRooms = MutableStateFlow(listOf<PlaceEntity>()) val newStudyRooms: StateFlow<List<PlaceEntity>> = _newStudyRooms.asStateFlow() val cafeList = getPlaceListUseCase().cachedIn(viewModelScope) val noticeList = getNoticeListUseCase() .map { pagingData -> pagingData.map { notice -> notice.toUiModel() } } .cachedIn(viewModelScope) fun getNewCafeList(snapshot: ItemSnapshotList<PlaceEntity>) { val newCafeList = mutableListOf<PlaceEntity>() val newStudyCafeList = mutableListOf<PlaceEntity>() val newStudyRoomList = mutableListOf<PlaceEntity>() snapshot.toList().forEach { place -> place?.let { when (it.type) { CAFE_TYPE -> newCafeList.add(it) STUDY_CAFE_TYPE -> newStudyCafeList.add(it) STUDY_ROOM_TYPE -> newStudyRoomList.add(it) } } } _newCafes.value = newCafeList.take(3) _newStudyCafes.value = newStudyCafeList.take(3) _newStudyRooms.value = newStudyRoomList.take(3) _cafesList.value = listOf(newCafes.value, newStudyCafes.value, newStudyRooms.value) Timber.tag("cafesList").d("${cafesList.value}") } private companion object { private const val CAFE_TYPE = "CAFE" private const val STUDY_CAFE_TYPE = "STUDY_CAFE" private const val STUDY_ROOM_TYPE = "STUDY_ROOM" } }
12
null
0
7
25827748532b9d0013cf6215cb58c1ad52f6de4e
2,910
eggeum-android
MIT License
android/src/main/kotlin/app/begaz/obd/two/plugin/obd2_plugin/Obd2Plugin.kt
begaz
448,589,262
false
{"Dart": 30988, "Kotlin": 3854, "Ruby": 976, "Swift": 908, "Objective-C": 676}
package app.begaz.obd.two.plugin.obd2_plugin import android.bluetooth.BluetoothAdapter import android.content.Intent import androidx.annotation.NonNull import androidx.core.app.ActivityCompat.startActivityForResult import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import android.bluetooth.BluetoothManager import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import android.app.Activity import android.content.Context import io.flutter.embedding.engine.plugins.activity.ActivityAware /** Obd2Plugin */ class Obd2Plugin: FlutterPlugin, MethodCallHandler, ActivityAware { /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it /// when the Flutter Engine is detached from the Activity private lateinit var channel : MethodChannel private lateinit var activity: Activity private var bluetoothAdapter: BluetoothAdapter? = null private val REQUEST_ENABLE_BLUETOOTH: Int = 1337 private val REQUEST_DISCOVERABLE_BLUETOOTH: Int = 2137 private var pendingResultForActivityResult: Result? = null override fun onAttachedToActivity(binding: ActivityPluginBinding) { this.activity = binding.activity; val bluetoothManager: BluetoothManager = activity.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager this.bluetoothAdapter = bluetoothManager.adapter binding.addActivityResultListener { requestCode, resultCode, data -> when (requestCode) { REQUEST_ENABLE_BLUETOOTH -> { if (pendingResultForActivityResult != null) { pendingResultForActivityResult?.success(resultCode != 0) } return@addActivityResultListener true } REQUEST_DISCOVERABLE_BLUETOOTH -> { pendingResultForActivityResult?.success(if (resultCode == 0) -1 else resultCode) return@addActivityResultListener true } else -> return@addActivityResultListener false } } } override fun onDetachedFromActivityForConfigChanges() { } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { } override fun onDetachedFromActivity() { } override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { channel = MethodChannel(flutterPluginBinding.binaryMessenger, "obd2_plugin") channel.setMethodCallHandler(this) } override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { when (call.method) { "enableBluetooth" -> { if (bluetoothAdapter?.isEnabled != true) { pendingResultForActivityResult = result val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(activity, intent, REQUEST_ENABLE_BLUETOOTH, null) } else { result.success(true) } // result.success("Android ${android.os.Build.VERSION.RELEASE}") } "getPlatformVersion" -> { result.success("Android ${android.os.Build.VERSION.RELEASE}") } else -> { result.notImplemented() } } } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } }
0
Dart
10
24
734609d87ea727caf4a9f7cb8d1058b339fa48d0
3,705
OBDII
MIT License
serialization/src/commonMain/kotlin/pw/binom/openapi/serialization/ExampleGenerator.kt
caffeine-mgn
529,723,183
false
null
package pw.binom.openapi.serialization import kotlinx.serialization.* import kotlinx.serialization.modules.EmptySerializersModule import kotlinx.serialization.modules.SerializersModule object ExampleGenerator { fun <T : Any> generate( serializer: KSerializer<T>, serializersModule: SerializersModule = EmptySerializersModule ): T = serializer.deserialize(ExampleDecoder(serializersModule, serializer, null)) @OptIn(InternalSerializationApi::class) inline fun <reified T : Any> generate(serializersModule: SerializersModule = EmptySerializersModule) = generate( serializer = T::class.serializerOrNull() ?: throw SerializationException("${T::class} is not serializable"), serializersModule = serializersModule ) }
0
Kotlin
0
0
d3bd4d3f84bd93e68dd461e98a9677dc437eb2d6
787
openapi
Apache License 2.0
features/dd-sdk-android-trace/src/main/kotlin/com/datadog/android/trace/internal/domain/event/BigIntegerUtils.kt
DataDog
219,536,756
false
{"Kotlin": 9121111, "Java": 1179237, "C": 79303, "Shell": 63055, "C++": 32351, "Python": 5556, "CMake": 2000}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.trace.internal.domain.event import java.math.BigInteger internal object BigIntegerUtils { private const val LONG_BITS_SIZE = 64 private const val HEX_RADIX = 16 private const val REQUIRED_ID_HEX_LENGTH = 16 @Suppress("UnsafeThirdPartyFunctionCall") // this can't throw in this context private val LONG_MASK = BigInteger("ffffffffffffffff", HEX_RADIX) // we are not treating these exceptions because we are sure that the input is a valid BigInteger and the // BigInteger overflow cannot happen in this context @Suppress("SwallowedException") fun leastSignificant64BitsAsHex(traceId: BigInteger): String { return try { traceId.and(LONG_MASK).toString(HEX_RADIX).padStart(REQUIRED_ID_HEX_LENGTH, '0') } catch (e: NumberFormatException) { "" } catch (e: ArithmeticException) { "" } catch (e: IllegalArgumentException) { "" } } @Suppress("SwallowedException") fun leastSignificant64BitsAsDecimal(traceId: BigInteger): String { return try { traceId.and(LONG_MASK).toString() } catch (e: NumberFormatException) { "" } catch (e: ArithmeticException) { "" } } @Suppress("SwallowedException") fun mostSignificant64BitsAsHex(traceId: BigInteger): String { return try { traceId.shiftRight(LONG_BITS_SIZE).toString(HEX_RADIX).padStart(REQUIRED_ID_HEX_LENGTH, '0') } catch (e: NumberFormatException) { "" } catch (e: ArithmeticException) { "" } catch (e: IllegalArgumentException) { "" } } }
44
Kotlin
60
151
d7e640cf6440ab150c2bbfbac261e09b27e258f4
1,973
dd-sdk-android
Apache License 2.0
remote/src/main/kotlin/io/github/gmvalentino8/github/sample/remote/models/MergedMinusUpstreamApiModel.kt
wasabi-muffin
462,369,263
false
{"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812}
/** * GitHub v3 REST API * * GitHub's v3 REST API. * * The version of the OpenAPI document: 1.1.4 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package io.github.gmvalentino8.github.sample.remote.models import kotlinx.serialization.* import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder /** * Results of a successful merge upstream request * @param message * @param mergeType * @param baseBranch */ @Serializable data class MergedMinusUpstreamApiModel( @SerialName(value = "message") val message: kotlin.String? = null, @SerialName(value = "merge_type") val mergeType: MergedMinusUpstreamApiModel.MergeType? = null, @SerialName(value = "base_branch") val baseBranch: kotlin.String? = null ) { /** * * Values: merge,fastMinusForward,none */ @Serializable(with = MergeType.Serializer::class) enum class MergeType(val value: kotlin.String) { merge("merge"), fastMinusForward("fast-forward"), none("none"); @kotlinx.serialization.Serializer(forClass = MergeType::class) object Serializer { override fun deserialize(decoder: Decoder): MergeType { val decoded = decoder.decodeString() return values().first { it.value == decoded } } override val descriptor: SerialDescriptor get() = PrimitiveSerialDescriptor( "MergedMinusUpstreamApiModel.MergeType.Serializer", PrimitiveKind.STRING ) override fun serialize(encoder: Encoder, value: MergeType) { return encoder.encodeString(value.value) } } } }
0
Kotlin
0
1
2194a2504bde08427ad461d92586497c7187fb40
2,136
github-sample-project
Apache License 2.0
Frontend/app/src/main/java/com/example/spotivote/service/dto/TrackList.kt
UTN-FRBA-Mobile
637,448,794
false
null
package com.example.spotivote.service.dto data class TrackList(val items: List<TrackItem>)
0
Kotlin
0
1
1ab357641c8764c2ac418ddb83540845b4fa00e9
91
SpotiVote
MIT License
app/src/main/java/com/aitsuki/currency/CurrencyEditText.kt
aitsuki
762,651,045
false
{"Kotlin": 6658}
package com.aitsuki.currency import android.annotation.SuppressLint import android.content.Context import android.text.InputType import android.text.method.DigitsKeyListener import android.util.AttributeSet import android.widget.EditText import java.math.BigDecimal import java.text.DecimalFormatSymbols import java.util.Locale @SuppressLint("AppCompatCustomView") class CurrencyEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : EditText(context, attrs) { private lateinit var symbols: DecimalFormatSymbols private var currencyTextWatcher: CurrencyTextWatcher? = null init { inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL setLocale(Locale.getDefault()) } fun setLocale(locale: Locale) { val sourceValue = if (text.isNotEmpty()) getValue() else null symbols = DecimalFormatSymbols(locale) keyListener = DigitsKeyListener.getInstance("0123456789${symbols.groupingSeparator}${symbols.decimalSeparator}") removeTextChangedListener(currencyTextWatcher) currencyTextWatcher = CurrencyTextWatcher(this, symbols) addTextChangedListener(currencyTextWatcher) sourceValue?.let { setValue(it) } } fun setValue(value: BigDecimal) { val text = value.toPlainString().replace(".", symbols.decimalSeparator.toString()) setText(text) setSelection(getText().length) } fun getValue(): BigDecimal { val text = text.toString() if (text.isEmpty()) return BigDecimal.ZERO return text .replace(symbols.groupingSeparator.toString(), "") .replace(symbols.decimalSeparator.toString(), ".") .toBigDecimal() } fun setDoubleValue(value: Double) { setValue(BigDecimal.valueOf(value)) } fun getDoubleValue(): Double { return getValue().toDouble() } }
0
Kotlin
0
0
4f67e8d68391330c80513af8bdae9d568f63881d
1,925
CurrencyEditText
MIT License
src/main/kotlin/br/com/zup/gian/registrarchave/itau/TitularResponse.kt
gianmsouza
395,672,736
true
{"Kotlin": 64998}
package br.com.zup.gian.registrarchave.itau data class TitularResponse(val id: String, val nome: String, val cpf: String)
0
Kotlin
0
0
51dd2506d114c2d977e1b3b640b8c5b78639b5d9
123
orange-talents-06-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/com/github/mrbean355/admiralbulldog/arch/service/GitHubService.kt
MrBean355
181,222,587
false
null
/* * Copyright 2023 Michael Johnston * * 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.github.mrbean355.admiralbulldog.arch.service import com.github.mrbean355.admiralbulldog.arch.ReleaseInfo import okhttp3.ResponseBody import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create import retrofit2.http.GET import retrofit2.http.Streaming import retrofit2.http.Url interface GitHubService { @GET("https://api.github.com/repos/MrBean355/admiralbulldog-sounds/releases/latest") suspend fun getLatestReleaseInfo(): Response<ReleaseInfo> @GET @Streaming suspend fun downloadLatestRelease(@Url url: String): Response<ResponseBody> companion object { val INSTANCE: GitHubService = Retrofit.Builder() .baseUrl("http://unused") .addConverterFactory(GsonConverterFactory.create()) .build() .create() } }
7
null
5
31
24f2f5de5c8d8397c9aec94795f6da3bfaac3611
1,478
admiralbulldog-sounds
Apache License 2.0
cosec-core/src/main/kotlin/me/ahoo/cosec/principal/SimplePrincipal.kt
Ahoo-Wang
567,999,401
false
null
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.cosec.principal import me.ahoo.cosec.api.principal.CoSecPrincipal /** * Simple Principal. * * @author <NAME> */ data class SimplePrincipal( override val id: String, override val policies: Set<String> = emptySet(), override val roles: Set<String> = emptySet(), override val attributes: Map<String, String> = emptyMap() ) : CoSecPrincipal { companion object { @JvmField val ANONYMOUS: CoSecPrincipal = SimplePrincipal(CoSecPrincipal.ANONYMOUS_ID) } }
4
null
4
32
ea4af7a66c1ab4d6560d7f3ba5d7026cd6904c26
1,148
CoSec
Apache License 2.0
app/src/main/java/com/coinninja/coinkeeper/view/button/HelpLinkButton.kt
coinninjadev
175,276,289
false
null
package com.coinninja.coinkeeper.view.button import android.content.Context import android.content.Intent import android.net.Uri import android.util.AttributeSet import android.view.View import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.AppCompatButton import androidx.core.graphics.drawable.DrawableCompat import com.coinninja.coinkeeper.R class HelpLinkButton @JvmOverloads constructor(context: Context? = null, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatButton(context, attrs, defStyleAttr) { var uri: Uri = Uri.EMPTY var color: Int = -1 init { super.setOnClickListener { context?.let { if (uri.toString().isNotEmpty()) { Intent(Intent.ACTION_VIEW, uri).also { context.startActivity(it) } } } } context?.let { _context -> _context.obtainStyledAttributes(attrs, R.styleable.HelpLinkButton, defStyleAttr, 0)?.let { typedArray -> if (typedArray.hasValue(R.styleable.HelpLinkButton_url)) { typedArray.getResourceId(R.styleable.HelpLinkButton_url, -1).let { if (it != -1) { uri = Uri.parse(_context.getString(it)) } else { typedArray.getString(R.styleable.HelpLinkButton_url)?.let { uri = Uri.parse(it) } } } } typedArray.recycle() } textAlignment = View.TEXT_ALIGNMENT_CENTER background = AppCompatResources.getDrawable(context, R.drawable.question_mark_circle) text = _context.getString(R.string.default_help_link_label) } } override fun setOnClickListener(l: OnClickListener?) {} }
2
null
0
6
d67d7c0b9cad27db94470231073c5d6cdda83cd0
1,958
dropbit-android
MIT License
app/src/main/java/flaskoski/rs/smartmuseum/listAdapter/SubItemListAdapter.kt
flaskoski
173,016,051
false
null
package flaskoski.rs.smartmuseum.listAdapter import android.app.Activity import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import flaskoski.rs.smartmuseum.R import flaskoski.rs.smartmuseum.model.ItemRepository import flaskoski.rs.smartmuseum.model.Itemizable import flaskoski.rs.smartmuseum.model.SubItem import flaskoski.rs.smartmuseum.util.ApplicationProperties import kotlinx.android.synthetic.main.activity_item_detail.* import kotlinx.android.synthetic.main.sub_item.view.* /** * Copyright (c) 2019 <NAME> * código fonte licenciado pela MIT License - https://opensource.org/licenses/MIT */ class SubItemListAdapter(private val subItemList: List<SubItem>, private val activity : Activity) : RecyclerView.Adapter<SubItemListAdapter.ItemViewHolder>() { class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ItemViewHolder { val view = LayoutInflater.from(activity.applicationContext).inflate(R.layout.sub_item, p0, false) return ItemViewHolder(view) } override fun getItemCount(): Int { return subItemList.size } override fun onBindViewHolder(p0: ItemViewHolder, p1: Int) { // p0.itemView.txt_featureName.text = recommendedSubItemList[p1].description // p0.itemView.img_itemThumb.setImageResource(context.resources.getIdentifier(recommendedSubItemList?.get(p1)?.photoId, "drawable", context.packageName)) // p0.itemView.setBackgroundResource(context.resources.getIdentifier(recommendedSubItemList?.get(p1)?.photoId, "drawable", context.packageName)) p0.itemView.lb_subitem.text = subItemList[p1].title if(subItemList[p1].photoId.isNotBlank()) ItemRepository.loadBackgroundPhoto(activity.applicationContext, p0.itemView.layout_subitem, subItemList[p1].photoId) if(subItemList[p1].isVisited){ p0.itemView.subitem_icon_visited.visibility = View.VISIBLE p0.itemView.subitem_icon_visited.setBackgroundResource(android.R.drawable.checkbox_on_background) }else p0.itemView.subitem_icon_visited.visibility = View.GONE if(!ApplicationProperties.userNotDefinedYet()) p0.itemView.subitem_ratingBar.rating = subItemList[p1].recommedationRating else p0.itemView.subitem_ratingBar.rating = 0f p0.itemView.setOnClickListener{(activity as OnShareSubItemClickListener).shareOnItemClicked(subItemList[p1])} } interface OnShareSubItemClickListener{ fun shareOnItemClicked(subItem: SubItem) } }
0
Kotlin
0
1
2e180a388298e0b827cea35daef4593ec52f5811
2,670
SmartMuseum
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/FaceConfused.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.FaceConfused: ImageVector get() { if (_faceConfused != null) { return _faceConfused!! } _faceConfused = Builder(name = "FaceConfused", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 0.0f) curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f) reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f) reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f) reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f) close() moveTo(12.0f, 22.0f) curveToRelative(-5.514f, 0.0f, -10.0f, -4.486f, -10.0f, -10.0f) reflectiveCurveTo(6.486f, 2.0f, 12.0f, 2.0f) reflectiveCurveToRelative(10.0f, 4.486f, 10.0f, 10.0f) reflectiveCurveToRelative(-4.486f, 10.0f, -10.0f, 10.0f) close() moveTo(17.0f, 15.0f) curveToRelative(0.0f, 0.553f, -0.447f, 1.0f, -1.0f, 1.0f) horizontalLineToRelative(-4.0f) curveToRelative(-2.331f, 0.0f, -4.316f, 1.73f, -4.336f, 1.747f) curveToRelative(-0.19f, 0.169f, -0.427f, 0.252f, -0.663f, 0.252f) curveToRelative(-0.275f, 0.0f, -0.55f, -0.113f, -0.747f, -0.336f) curveToRelative(-0.366f, -0.412f, -0.331f, -1.041f, 0.08f, -1.409f) curveToRelative(0.103f, -0.092f, 2.559f, -2.254f, 5.666f, -2.254f) horizontalLineToRelative(4.0f) curveToRelative(0.553f, 0.0f, 1.0f, 0.447f, 1.0f, 1.0f) close() moveTo(17.0f, 9.5f) curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) close() moveTo(7.0f, 9.5f) curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f) close() } } .build() return _faceConfused!! } private var _faceConfused: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,316
icons
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageadjudicationsapi/controllers/draft/DraftAdjudicationController.kt
ministryofjustice
416,301,250
false
{"Kotlin": 1584553, "Dockerfile": 1411}
package uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.controllers.draft import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.Parameter import io.swagger.v3.oas.annotations.Parameters import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.tags.Tag import jakarta.validation.Valid import jakarta.validation.constraints.Size import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort import org.springframework.data.web.PageableDefault import org.springframework.format.annotation.DateTimeFormat import org.springframework.http.HttpStatus import org.springframework.security.access.prepost.PreAuthorize import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.config.ErrorResponse import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.DraftAdjudicationDto import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.Gender import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.services.draft.DraftAdjudicationService import java.time.LocalDate import java.time.LocalDateTime @Schema(description = "Request to create a new draft adjudication") data class NewAdjudicationRequest( @Schema(description = "Prison number assigned to a prisoner", example = "G2996UX") val prisonerNumber: String, @Schema(description = "Gender applied for adjuducation rules", example = "MALE") val gender: Gender = Gender.MALE, @Schema(description = "The agency id (or caseload) associated with this adjudication", example = "MDI") val agencyId: String, @Schema(description = "The optional agencyId where the prisoner now resides", example = "MDI") val overrideAgencyId: String? = null, @Schema(description = "The id of the location the incident took place") val locationId: Long, @Schema(description = "Date and time the incident occurred", example = "2010-10-12T10:00:00") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) val dateTimeOfIncident: LocalDateTime, @Schema(description = "Optional Date time if discovery date different to incident date", example = "2010-10-12T10:00:00") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) val dateTimeOfDiscovery: LocalDateTime? = null, @Schema(description = "offender book id used for api calls from dps") val offenderBookingId: Long? = null, ) @Schema(description = "Request to update the incident role") data class IncidentRoleRequest( @Schema(description = "The incident role code", title = "If not set then it is assumed they committed the offence on their own", example = "25a") val roleCode: String?, ) @Schema(description = "Request to set the associated prisoner") data class IncidentRoleAssociatedPrisonerRequest( @Schema(required = true, description = "The prison number of the other prisoner involved in the incident", example = "G2996UX") val associatedPrisonersNumber: String, @Schema(description = "The name of the other prisoner involved in the incident", title = "This only applies if the associated prisoner is from outside the establishment") val associatedPrisonersName: String?, ) @Schema(description = "Request to add or edit the incident statement for a draft adjudication") data class IncidentStatementRequest( @Schema(description = "The statement regarding the incident") @get:Size( max = 4000, message = "The incident statement exceeds the maximum character limit of {max}", ) val statement: String? = null, val completed: Boolean? = false, ) @Schema(description = "Request to edit the incident details") data class EditIncidentDetailsRequest( @Schema(description = "The id of the location the incident took place") val locationId: Long, @Schema(description = "Date and time the incident occurred", example = "2010-10-12T10:00:00") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) val dateTimeOfIncident: LocalDateTime, @Schema(description = "Optional Date time if discovery date different to incident date", example = "2010-10-12T10:00:00") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) val dateTimeOfDiscovery: LocalDateTime? = null, ) @Schema(description = "Request to edit incident role") data class EditIncidentRoleRequest( @Schema(description = "Information about the role of this prisoner in the incident") val incidentRole: IncidentRoleRequest, @Schema(description = "Whether to remove all existing offences") val removeExistingOffences: Boolean = false, ) @Schema(description = "Request to set applicable rules") data class ApplicableRulesRequest( @Schema(description = "Indicates whether the applicable rules are for a young offender") val isYouthOffenderRule: Boolean, @Schema(description = "Whether to remove all existing offences") val removeExistingOffences: Boolean = false, ) @Schema(description = "Request to update the gender") data class GenderRequest( @Schema(description = "The gender", title = "Gender of prisoner", example = "MALE") val gender: Gender, ) @Schema(description = "Request to update created on behalf of") data class CreatedOnBehalfOfRequest( @Schema(description = "Name the officer the report was created on behalf of") var createdOnBehalfOfOfficer: String, @Schema(description = "Reason why the report was created on behalf of another officer") var createdOnBehalfOfReason: String, ) @RestController @Validated @Tag(name = "10. Draft Adjudication Management") class DraftAdjudicationController( private val draftAdjudicationService: DraftAdjudicationService, ) : DraftAdjudicationBaseController() { @Parameters( Parameter( name = "page", description = "Results page you want to retrieve (0..N). Default 0, e.g. the first page", example = "0", ), Parameter( name = "size", description = "Number of records per page. Default 20", ), Parameter( name = "sort", description = "Sort as combined comma separated property and uppercase direction. Multiple sort params allowed to sort by multiple properties. Default to dateTimeOfDiscovery,DESC", ), Parameter( name = "startDate", required = false, description = "optional inclusive start date for results, default is today - 3 days", ), Parameter( name = "endDate", required = false, description = "optional inclusive end date for results, default is today", ), ) @GetMapping("/my-reports") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS')") @Operation(summary = "Returns all the in progress draft adjudications created by the current user") fun getCurrentUsersInProgressDraftAdjudications( @RequestParam(name = "startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) startDate: LocalDate?, @RequestParam(name = "endDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) endDate: LocalDate?, @PageableDefault(sort = ["IncidentDetailsDateTimeOfDiscovery"], direction = Sort.Direction.DESC, size = 20) pageable: Pageable, ): Page<DraftAdjudicationDto> = draftAdjudicationService.getCurrentUsersInProgressDraftAdjudications( startDate = startDate ?: LocalDate.now().minusWeeks(1), endDate = endDate ?: LocalDate.now(), pageable = pageable, ) @PostMapping @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") @Operation( summary = "Starts a new draft adjudication.", responses = [ io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "201", description = "New Adjudication Started", ), io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "415", description = "Not able to process the request because the payload is in a format not supported by this endpoint.", content = [ io.swagger.v3.oas.annotations.media.Content( mediaType = "application/json", schema = io.swagger.v3.oas.annotations.media.Schema(implementation = ErrorResponse::class), ), ], ), ], ) @ResponseStatus(HttpStatus.CREATED) fun startNewAdjudication(@RequestBody newAdjudicationRequest: NewAdjudicationRequest): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService .startNewAdjudication( newAdjudicationRequest.prisonerNumber, newAdjudicationRequest.gender, newAdjudicationRequest.agencyId, newAdjudicationRequest.overrideAgencyId, newAdjudicationRequest.locationId, newAdjudicationRequest.dateTimeOfIncident, newAdjudicationRequest.dateTimeOfDiscovery, newAdjudicationRequest.offenderBookingId, ) return DraftAdjudicationResponse( draftAdjudication, ) } @GetMapping(value = ["/{id}"]) @PreAuthorize("hasRole('VIEW_ADJUDICATIONS')") @Operation(summary = "Returns the draft adjudication details.") fun getDraftAdjudicationDetails(@PathVariable(name = "id") id: Long): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.getDraftAdjudicationDetails(id) return DraftAdjudicationResponse( draftAdjudication, ) } @PostMapping(value = ["/{id}/incident-statement"]) @Operation( summary = "Add the incident statement to the draft adjudication.", responses = [ io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "201", description = "Incident Statement Added", ), io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "415", description = "Not able to process the request because the payload is in a format not supported by this endpoint.", content = [ io.swagger.v3.oas.annotations.media.Content( mediaType = "application/json", schema = io.swagger.v3.oas.annotations.media.Schema(implementation = ErrorResponse::class), ), ], ), ], ) @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") @ResponseStatus(HttpStatus.CREATED) fun addIncidentStatement( @PathVariable(name = "id") id: Long, @RequestBody @Valid incidentStatementRequest: IncidentStatementRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.addIncidentStatement( id, incidentStatementRequest.statement, incidentStatementRequest.completed, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/incident-details"]) @Operation(summary = "Edit the incident details for a draft adjudication.") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun editIncidentDetails( @PathVariable(name = "id") id: Long, @RequestBody @Valid editIncidentDetailsRequest: EditIncidentDetailsRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.editIncidentDetails( id, editIncidentDetailsRequest.locationId, editIncidentDetailsRequest.dateTimeOfIncident, editIncidentDetailsRequest.dateTimeOfDiscovery, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/incident-role"]) @Operation(summary = "Edit the incident role for a draft adjudication.") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun editIncidentRole( @PathVariable(name = "id") id: Long, @RequestBody @Valid editIncidentRoleRequest: EditIncidentRoleRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.editIncidentRole( id, editIncidentRoleRequest.incidentRole, editIncidentRoleRequest.removeExistingOffences, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/associated-prisoner"]) @Operation(summary = "Set the associated prisoner for a draft adjudication.") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun setIncidentRoleAssociatedPrisoner( @PathVariable(name = "id") id: Long, @RequestBody @Valid associatedPrisonerRequest: IncidentRoleAssociatedPrisonerRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.setIncidentRoleAssociatedPrisoner( id, associatedPrisonerRequest, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/incident-statement"]) @Operation(summary = "Edit the incident statement for a draft adjudication.") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun editIncidentStatement( @PathVariable(name = "id") id: Long, @RequestBody @Valid editIncidentStatementRequest: IncidentStatementRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.editIncidentStatement( id, statement = editIncidentStatementRequest.statement, completed = editIncidentStatementRequest.completed, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/applicable-rules"]) @Operation(summary = "Set applicable rules for incident") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun setApplicableRules( @PathVariable(name = "id") id: Long, @RequestBody @Valid applicableRulesRequest: ApplicableRulesRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.setIncidentApplicableRule( id, applicableRulesRequest.isYouthOffenderRule, applicableRulesRequest.removeExistingOffences, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/gender"]) @Operation(summary = "Set gender") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun setGender( @PathVariable(name = "id") id: Long, @RequestBody @Valid genderRequest: GenderRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.setGender( id, genderRequest.gender, ) return DraftAdjudicationResponse( draftAdjudication, ) } @PutMapping(value = ["/{id}/created-on-behalf-of"]) @Operation(summary = "Set created on behalf of") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun setCreatedOnBehalfOf( @PathVariable(name = "id") id: Long, @RequestBody @Valid createdOnBehalfOfRequest: CreatedOnBehalfOfRequest, ): DraftAdjudicationResponse { val draftAdjudication = draftAdjudicationService.setCreatedOnBehalfOf( id, createdOnBehalfOfRequest.createdOnBehalfOfOfficer, createdOnBehalfOfRequest.createdOnBehalfOfReason, ) return DraftAdjudicationResponse( draftAdjudication, ) } @DeleteMapping(value = ["/{id}"]) @Operation(summary = "Delete by Id. Only owner can delete.") @PreAuthorize("hasRole('VIEW_ADJUDICATIONS') and hasAuthority('SCOPE_write')") fun deleteDraftAdjudication( @PathVariable(name = "id") id: Long, ) { draftAdjudicationService.deleteDraftAdjudications(id) } }
3
Kotlin
0
3
b09836ea73215eade93eb0a723ac4d8ddc365b1d
15,890
hmpps-manage-adjudications-api
MIT License
app/src/androidTest/java/com/meslmawy/ibtkarchallenge/logic/SaveImagesTest.kt
KhaledSherifSayed
278,113,314
false
null
/* * * Copyright (c) 2020 Khaled Sherif * 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 NON INFRINGEMENT. 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 com.meslmawy.ibtkarchallenge.logic import android.os.Bundle import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.Espresso.onView import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.InternalCoroutinesApi import org.junit.Test import org.junit.runner.RunWith import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers import com.meslmawy.ibtkarchallenge.R import com.meslmawy.ibtkarchallenge.domain.dto.PersonImage import com.meslmawy.ibtkarchallenge.presentation.photo.PhotoFragment import org.hamcrest.CoreMatchers @MediumTest @InternalCoroutinesApi @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) class SaveImagesTest { @Test fun personTitle_DisplayedInUi() { // GIVEN - Add active (incomplete) task to the DB val image = PersonImage(400, 600,0,0.0,"/jKiSaeRO4IPJoHsjGRqMpdrZu88.jpg", 0.66666666666667) val fragmentArgs = Bundle().apply { putParcelable("Image",image) putString("picture", "/jKiSaeRO4IPJoHsjGRqMpdrZu88.jpg") putString("name","Lisa Ann Walter") } launchFragmentInContainer<PhotoFragment>( fragmentArgs = fragmentArgs, // Bundle themeResId = R.style.AppTheme, factory = null ) // make sure that the title/description are both shown and correct onView(withId(R.id.fab)).check(matches(ViewMatchers.withTagValue(CoreMatchers.equalTo(R.drawable.ic_add)))) Thread.sleep(2000) } }
0
Kotlin
3
16
99dda9ded47348ea1a15bace1c24267411e2496b
2,859
PopularPeople
MIT License
app/src/main/kotlin/com/sukitsuki/tsukibb/activity/LoginWebViewActivity.kt
Tsuki
166,343,816
false
null
package com.sukitsuki.tsukibb.activity import android.annotation.SuppressLint import android.content.SharedPreferences import android.graphics.Bitmap import android.os.Bundle import android.webkit.CookieManager import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import android.widget.Toast import androidx.appcompat.app.ActionBar import butterknife.BindView import butterknife.ButterKnife import com.google.gson.GsonBuilder import com.sukitsuki.tsukibb.AppConst import com.sukitsuki.tsukibb.AppDatabase import com.sukitsuki.tsukibb.BuildConfig import com.sukitsuki.tsukibb.R import com.sukitsuki.tsukibb.entity.Cookie import com.sukitsuki.tsukibb.model.TelegramAuth import com.sukitsuki.tsukibb.repository.TbbRepository import dagger.android.AndroidInjector import dagger.android.support.DaggerAppCompatActivity import okhttp3.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.toast import org.jetbrains.anko.uiThread import timber.log.Timber import javax.inject.Inject class LoginWebViewActivity : DaggerAppCompatActivity() { @dagger.Subcomponent(modules = []) interface Component : AndroidInjector<LoginWebViewActivity> { @dagger.Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<LoginWebViewActivity>() } private val googleUrl = "https://ebb.io/auth/google" private val telegramUrl = "https://oauth.telegram.org/auth?bot_id=639045451&origin=https%3A%2F%2Febb.io" private val telegramAuthUrl = "https://oauth.telegram.org/auth/get?bot_id=639045451&lang=en" private val gson by lazy { GsonBuilder().serializeNulls().create() } private lateinit var cookieManager: CookieManager private var method: Int = -1 @Inject lateinit var mTbbRepository: TbbRepository @Inject lateinit var appDatabase: AppDatabase @Inject lateinit var sharedPreferences: SharedPreferences @Inject lateinit var okHttpClient: OkHttpClient @BindView(R.id.webview) lateinit var webView: WebView var toolbar: ActionBar? = null @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) method = intent.getIntExtra("login", -2) toolbar = supportActionBar Timber.d("login method $method") setContentView(R.layout.activity_web_view) ButterKnife.bind(this) cookieManager = CookieManager.getInstance() // cookieManager.removeAllCookies(null) // cookieManager.removeSessionCookies(null) // TODO Load cookie from SQLite cookieManager.flush() webView.settings.javaScriptEnabled = true webView.settings.userAgentString = AppConst.FakeUserAgent WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG) webView.webViewClient = LoginWebViewClient() // webView.webChromeClient = LoginWebViewClient() when (method) { 0 -> webView.loadUrl(googleUrl) 1 -> webView.loadUrl(telegramUrl) else -> finish() } } inner class LoginWebViewClient : WebViewClient() { override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { Timber.d("url:$url") toolbar?.title = url when (method) { 0 -> processGoogleLogin(url) 1 -> processTelegramLogin(url) else -> finish() } super.onPageStarted(view, url, favicon) } override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { Timber.d("shouldOverrideUrlLoading url: $url") return false } override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { Timber.d("shouldOverrideUrlLoading request: ${request?.url}") return false } private fun processGoogleLogin(url: String?) { if (url == "https://ebb.io/#") { val cookieString = CookieManager.getInstance().getCookie(url) Timber.d("cookieString $cookieString") val cookies = HttpUrl.parse(url)?.let { cookieString.split(";").mapNotNull { cs -> okhttp3.Cookie.parse(it, cs) } } ?: emptyList() doAsync { appDatabase.cookieDao().insert(*cookies.map(::Cookie).toTypedArray()) sharedPreferences.edit().putBoolean("is_login", true).apply() uiThread { Toast.makeText(this@LoginWebViewActivity, "Login success", Toast.LENGTH_LONG).show() setResult(RESULT_OK, null) finish() } } } } private fun processTelegramLogin(url: String?) { if (url == "https://oauth.telegram.org/close") { val cookieString = CookieManager.getInstance().getCookie(url) Timber.d("cookieString:$cookieString") val cookies = HttpUrl.parse(url)?.let { cookieString.split(";").mapNotNull { cs -> okhttp3.Cookie.parse(it, cs) } } ?: emptyList() val mediaType = MediaType.parse("application/x-www-form-urlencoded") val body = RequestBody.create(mediaType, "origin=https://ebb.io") val request = Request.Builder() .url(telegramAuthUrl).post(body) .addHeader("origin", "https://oauth.telegram.org") .addHeader("accept", "*/*") .addHeader("x-requested-with", "XMLHttpRequest") .build() doAsync { appDatabase.cookieDao().insert(*cookies.map(::Cookie).toTypedArray()) val response = okHttpClient.newCall(request).execute() val telegramAuth = response.body()!!.let { gson.fromJson(it.string(), TelegramAuth::class.java) } Timber.d("telegramAuth.user ${telegramAuth.user}") var success = false telegramAuth.user?.let { mTbbRepository.authTelegram(telegramAuth.user.toMap()).first("").blockingGet() success = true } uiThread { if (success) toast("Login success") else toast("Login fail please retry") setResult(RESULT_OK, null) sharedPreferences.edit().putBoolean("is_login", true).apply() finish() } } } } } override fun onDestroy() { super.onDestroy() webView.destroy() } }
0
Kotlin
0
0
17f676fc22bed38bd38622dd4c73215fe91e6860
6,131
TsukiBBkt
MIT License