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/src/main/java/pe/com/gianbravo/blockedcontacts/presentation/dialog/HowToUseDialogFragment.kt | giancarloBravo | 584,450,298 | false | null | package pe.com.gianbravo.blockedcontacts.presentation.dialog
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.*
import androidx.fragment.app.DialogFragment
import com.sonu.libraries.materialstepper.OnLastStepNextListener
import kotlinx.android.synthetic.main.dialog_how_to_use.*
import pe.com.gianbravo.blockedcontacts.R
/**
* @author <NAME>
*
*/
class HowToUseDialogFragment : DialogFragment() {
private var listener: DialogListener? = null
interface DialogListener {
fun onDismiss()
fun onCancel()
}
fun dialogListener(listener: DialogListener) {
this.listener = listener
}
override fun dismiss() {
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
listener?.onDismiss()
}
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
listener?.onCancel()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.dialog_how_to_use, null, false)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
setStyle(
STYLE_NO_TITLE,
R.style.Custom_Dialog
)
val dialog: Dialog = super.onCreateDialog(savedInstanceState)
dialog.window?.setLayout(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
override fun onStart() {
super.onStart()
setup()
}
private fun setup() {
//adding fragment manager for ViewPager Adapter
materialStepper?.let {
it.fragmentManager = childFragmentManager
//adding steps
it.addStep(InformationFragment0(getString(R.string.title_information_0)))
it.addStep(InformationFragment1(getString(R.string.title_information_1)))
it.addStep(InformationFragment2(getString(R.string.title_information_2)))
it.addStep(InformationFragment3(getString(R.string.title_information_3)))
it.addStep(InformationFragment4(getString(R.string.title_information_4)))
//adding functionality when NEXT button is clicked on last step
it.onLastStepNextListener = OnLastStepNextListener {
//some action
dialog?.dismiss()
}
}
}
} | 0 | Kotlin | 1 | 1 | b025bbe35e7fd41f7aa579968acbeac0446582f1 | 2,942 | BlacklistApp-PLAYSTORE | Apache License 2.0 |
tektoncd-pipeline/src/test/kotlin/GettingStarted.kt | kuberig-io | 304,522,204 | false | null | import kinds.tekton.dev.v1beta1.task
import kinds.tekton.dev.v1beta1.taskRun
/**
* Shows how the examples on the getting started page map when defined using the KubeRig DSL.
*
* https://tekton.dev/docs/getting-started/
*/
class GettingStarted {
fun aTask() {
task {
metadata {
name("hello")
}
spec {
steps {
step {
name("hello")
image("ubuntu")
command("echo")
args {
arg("'Hello World!'")
}
}
}
}
}
}
fun aTaskRun() {
taskRun {
metadata {
generateName("hello-run-")
}
spec {
taskRef {
name("hello")
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 32c5b9ea3681e8c2d10e747dcba5124292dd9aad | 969 | kuberig-crd-dsl | Apache License 2.0 |
node-kotlin/src/jsMain/kotlin/node/fs/readdirAsync.kt | karakum-team | 393,199,102 | false | {"Kotlin": 7083457} | // Automatically generated - do not modify!
@file:JsModule("node:fs/promises")
package node.fs
import js.core.ReadonlyArray
import js.promise.Promise
import node.buffer.Buffer
import node.buffer.BufferEncoding
/**
* Reads the contents of a directory.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
* will be passed as `Buffer` objects.
*
* If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects.
*
* ```js
* import { readdir } from 'fs/promises';
*
* try {
* const files = await readdir(path);
* for (const file of files)
* console.log(file);
* } catch (err) {
* console.error(err);
* }
* ```
* @since v10.0.0
* @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`.
*/
@JsName("readdir")
external fun readdirAsync(
path: PathLike,
options: BufferEncoding? /* | (ObjectEncodingOptions & {
withFileTypes?: false | undefined;
})
| BufferEncoding
*/ = definedExternally,
): Promise<ReadonlyArray<String>>
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
@JsName("readdir")
external fun readdirAsync(
path: PathLike,
options: BufferEncodingOption,
/* | {
encoding: 'buffer';
withFileTypes?: false | undefined;
}
| 'buffer' */
): Promise<ReadonlyArray<Buffer>>
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
*/
@JsName("readdir")
external fun readdirAsync(
path: PathLike,
options: ObjectEncodingOptions,
/* {
withFileTypes: true;
} */
): Promise<ReadonlyArray<Dirent>>
| 0 | Kotlin | 6 | 26 | 3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18 | 2,276 | types-kotlin | Apache License 2.0 |
src/test/kotlin/com/baidu/amis/util/JSONHelperTest.kt | aisuda | 403,282,808 | false | null | package com.baidu.amis.util
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
internal class JSONHelperTest {
// 测试 json 查找功能
@Test
fun testJSONFind() {
val mapper = ObjectMapper()
val amisSchema: JsonNode = mapper.readTree(
"""
{
"type": "page",
"body": [{
"type": "form",
"name": "myForm",
"api": "https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/mock2/form/saveForm",
"body": [
{
"type": "input-text",
"name": "name",
"label": "姓名:"
},
{
"name": "email",
"type": "input-email",
"label": "邮箱:"
}
]
}]
}
""".trimIndent()
)
val amisNode = JSONHelper.findObject(
amisSchema
) { key, node, parentNode ->
if (key != null && key.equals("name")) {
val type: String = parentNode.get("type").asText()
if (type == "form") {
if (node.asText().equals("myForm")) {
println("find")
return@findObject true
}
}
}
return@findObject false
}
assertEquals(amisNode.get("type").asText(), "form")
}
} | 0 | null | 2 | 11 | 67ce05ad559ddc203ae48ea02496d289060e12ef | 1,386 | amis-server | Apache License 2.0 |
server/src/main/kotlin/de/sambalmueslie/openevent/server/structure/StructureService.kt | sambalmueslie | 270,265,994 | false | {"Kotlin": 265865, "Dockerfile": 434, "Batchfile": 61} | package de.sambalmueslie.openevent.server.structure
import de.sambalmueslie.openevent.server.auth.AuthenticationHelper
import de.sambalmueslie.openevent.server.common.BaseAuthCrudService
import de.sambalmueslie.openevent.server.entitlement.ItemEntitlementCrudService
import de.sambalmueslie.openevent.server.entitlement.api.Entitlement
import de.sambalmueslie.openevent.server.item.api.ItemType
import de.sambalmueslie.openevent.server.member.MemberCrudService
import de.sambalmueslie.openevent.server.structure.actions.StructureMemberEntitlementAction
import de.sambalmueslie.openevent.server.structure.api.Structure
import de.sambalmueslie.openevent.server.structure.api.StructureChangeRequest
import de.sambalmueslie.openevent.server.structure.db.StructureData
import de.sambalmueslie.openevent.server.structure.db.StructureRepository
import de.sambalmueslie.openevent.server.user.api.User
import io.micronaut.data.model.Page
import io.micronaut.data.model.Pageable
import io.micronaut.security.authentication.Authentication
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import javax.inject.Singleton
@Singleton
class StructureService(
private val crudService: StructureCrudService,
private val authenticationHelper: AuthenticationHelper,
private val entitlementService: ItemEntitlementCrudService,
private val repository: StructureRepository
) : BaseAuthCrudService<Structure, StructureChangeRequest, StructureData>(crudService, authenticationHelper, logger) {
companion object {
val logger: Logger = LoggerFactory.getLogger(StructureService::class.java)
}
fun getRoots(authentication: Authentication, user: User, pageable: Pageable): Page<Structure> {
return if (authenticationHelper.isAdmin(authentication)) {
repository.findByParentStructureIdIsNull(pageable)
} else {
repository.getAllRootAccessible(user.id, pageable)
}.map { crudService.convert(it) }
}
fun getChildren(authentication: Authentication, user: User, objId: Long, pageable: Pageable): Page<Structure> {
return if (authenticationHelper.isAdmin(authentication)) {
repository.findByParentStructureId(objId, pageable)
} else {
repository.getAllChildAccessible(user.id, objId, pageable)
}.map { crudService.convert(it) }
}
override fun getAllAccessible(user: User, pageable: Pageable): Page<Structure> {
return repository.getAllAccessible(user.id, pageable).map { crudService.convert(it) }
}
override fun isAccessAllowed(user: User, obj: StructureData): Boolean {
return !obj.restricted || getEntitlement(user, obj.id).isGreaterThanEquals(Entitlement.VIEWER)
}
override fun isModificationAllowed(user: User, obj: StructureData): Boolean {
return getEntitlement(user, obj.id).isGreaterThanEquals(Entitlement.ADMINISTRATOR)
}
override fun isCreationAllowed(user: User, request: StructureChangeRequest): Boolean {
val parentId = request.parentStructureId ?: return false
return getEntitlement(user, parentId).isGreaterThanEquals(Entitlement.ADMINISTRATOR)
}
fun deleteAll(authentication: Authentication, user: User) {
if (authenticationHelper.isAdmin(authentication)) {
repository.deleteAll()
}
}
private fun getEntitlement(user: User, objId: Long) = entitlementService.findByUserIdAndItemIdAndType(user.id, objId, ItemType.STRUCTURE).entitlement
}
| 0 | Kotlin | 0 | 1 | 053fb05dbe4242941659518f93dcac4c34b29126 | 3,511 | open-event | Apache License 2.0 |
carparts-data-structures/src/main/kotlin/org/jesperancinha/talks/carparts/carpartsdatascructures/converter/CustomValidators.kt | jesperancinha | 784,170,182 | false | {"Kotlin": 33470, "Shell": 4641, "Java": 3468, "Makefile": 1871, "Dockerfile": 182} | package org.jesperancinha.talks.carparts.org.jesperancinha.talks.carparts.carpartsdatascructures.converter
import jakarta.validation.Constraint
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
import org.jesperancinha.talks.carparts.LocalDateTimeDelegate
import org.jesperancinha.talks.carparts.carpartsdatascructures.utils.getLogger
import org.slf4j.Logger
import java.util.*
import kotlin.reflect.KClass
object CustomValidators {
val logger: Logger = getLogger<LocalDateTimeValidator>()
}
@Target(AnnotationTarget.FIELD, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [LocalDateTimeValidator::class])
@MustBeDocumented
annotation class LocalDateTimeValidatorConstraint(
val message: String = "Invalid value",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<*>> = []
)
class LocalDateTimeValidator : ConstraintValidator<LocalDateTimeValidatorConstraint, LocalDateTimeDelegate> {
override fun initialize(constraintAnnotation: LocalDateTimeValidatorConstraint) {
}
override fun isValid(value: LocalDateTimeDelegate, context: ConstraintValidatorContext): Boolean {
val country = Locale.getDefault().country.trim()
logger.info("Current country is {}", country)
return when (country) {
"", "NL", "US", "PT", "ES", "UK", "FR"-> true
else -> false
}
}
companion object {
val logger: Logger = getLogger<LocalDateTimeValidator>()
}
}
| 0 | Kotlin | 0 | 1 | 81fc44de22ea6617fd441f0916eabf010cd5e1f7 | 1,546 | kotlin-mysteries | Apache License 2.0 |
compiler-plugin/src/main/kotlin/DynamicDelegationCommandLineProcessor.kt | Him188 | 433,969,532 | false | null | package me.him188.kotlin.dynamic.delegation.compiler
import com.google.auto.service.AutoService
import me.him188.kotlin.dynamic.delegation.compiler.PluginCompilerConfigurationKeys.EXAMPLE
import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
import org.jetbrains.kotlin.compiler.plugin.CliOption
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
import org.jetbrains.kotlin.config.CompilerConfiguration
@AutoService(CommandLineProcessor::class)
class DynamicDelegationCommandLineProcessor : CommandLineProcessor {
companion object {
const val COMPILER_PLUGIN_ID: String = "kotlin-dynamic-delegation"
val OPTION_EXAMPLE: CliOption = CliOption(
EXAMPLE.name,
"<example/example>",
"Example key",
required = false
)
}
override val pluginId: String = COMPILER_PLUGIN_ID
override val pluginOptions: Collection<CliOption> = listOf()
override fun processOption(option: AbstractCliOption, value: String, configuration: CompilerConfiguration) {
// when (option) {
// OPTION_EXAMPLE -> configuration.put(EXAMPLE, value)
// else -> throw CliOptionProcessingException("Unknown option: ${option.optionName}")
// }
}
} | 0 | null | 1 | 32 | 7822151af98d683af337cac15146e46a7cd007fb | 1,263 | kotlin-dynamic-delegation | Apache License 2.0 |
src/main/kotlin/org/opensearch/indexmanagement/indexstatemanagement/step/notification/AttemptNotificationStep.kt | opensearch-project | 354,094,562 | false | null | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.indexmanagement.indexstatemanagement.step.notification
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.logging.log4j.LogManager
import org.opensearch.client.Client
import org.opensearch.cluster.service.ClusterService
import org.opensearch.common.settings.Settings
import org.opensearch.indexmanagement.indexstatemanagement.model.ManagedIndexMetaData
import org.opensearch.indexmanagement.indexstatemanagement.model.action.NotificationActionConfig
import org.opensearch.indexmanagement.indexstatemanagement.model.managedindexmetadata.StepMetaData
import org.opensearch.indexmanagement.indexstatemanagement.settings.ManagedIndexSettings
import org.opensearch.indexmanagement.indexstatemanagement.step.Step
import org.opensearch.indexmanagement.opensearchapi.convertToMap
import org.opensearch.script.Script
import org.opensearch.script.ScriptService
import org.opensearch.script.TemplateScript
class AttemptNotificationStep(
val clusterService: ClusterService,
val scriptService: ScriptService,
val client: Client,
val settings: Settings,
val config: NotificationActionConfig,
managedIndexMetaData: ManagedIndexMetaData
) : Step("attempt_notification", managedIndexMetaData) {
private val logger = LogManager.getLogger(javaClass)
private var stepStatus = StepStatus.STARTING
private var info: Map<String, Any>? = null
private val hostDenyList = settings.getAsList(ManagedIndexSettings.HOST_DENY_LIST)
override fun isIdempotent() = false
@Suppress("TooGenericExceptionCaught")
override suspend fun execute(): AttemptNotificationStep {
try {
withContext(Dispatchers.IO) {
config.destination.publish(null, compileTemplate(config.messageTemplate, managedIndexMetaData), hostDenyList)
}
// publish internally throws an error for any invalid responses so its safe to assume if we reach this point it was successful
// publish and send throws an error for any invalid responses so its safe to assume if we reach this point it was successful
stepStatus = StepStatus.COMPLETED
info = mapOf("message" to getSuccessMessage(indexName))
} catch (e: Exception) {
handleException(e)
}
return this
}
private fun handleException(e: Exception) {
val message = getFailedMessage(indexName)
logger.error(message, e)
stepStatus = StepStatus.FAILED
val mutableInfo = mutableMapOf("message" to message)
val errorMessage = e.message
if (errorMessage != null) mutableInfo["cause"] = errorMessage
info = mutableInfo.toMap()
}
override fun getUpdatedManagedIndexMetaData(currentMetaData: ManagedIndexMetaData): ManagedIndexMetaData {
return currentMetaData.copy(
stepMetaData = StepMetaData(name, getStepStartTime().toEpochMilli(), stepStatus),
transitionTo = null,
info = info
)
}
private fun compileTemplate(template: Script, managedIndexMetaData: ManagedIndexMetaData): String {
return scriptService.compile(template, TemplateScript.CONTEXT)
.newInstance(template.params + mapOf("ctx" to managedIndexMetaData.convertToMap()))
.execute()
}
companion object {
fun getFailedMessage(index: String) = "Failed to send notification [index=$index]"
fun getSuccessMessage(index: String) = "Successfully sent notification [index=$index]"
}
}
| 74 | Kotlin | 31 | 17 | bab2b5a9cfa550f19b2eb87b7051423f74e12132 | 3,645 | index-management | Apache License 2.0 |
varp-mod/varp-mod-client-api/src/main/kotlin/net/voxelpi/varp/mod/client/api/warp/ClientRepository.kt | VoxelPi | 869,165,536 | false | {"Kotlin": 262928, "Java": 2907} | package net.voxelpi.varp.mod.client.api.warp
import net.voxelpi.varp.warp.repository.Repository
public interface ClientRepository : Repository {
/**
* If the client is currently is on a server with a supported varp implementation.
*/
public val active: Boolean
}
| 0 | Kotlin | 0 | 0 | eb0f4249df2eafba206b92638cc507234040fbb3 | 284 | Varp | MIT License |
app/src/main/java/com/example/githubusers/BaseApplication.kt | aditialukmana | 288,877,539 | true | {"Kotlin": 85870} | package com.example.githubusers
import com.example.githubusers.di.component.DaggerAppComponent
import dagger.android.AndroidInjector
import dagger.android.support.DaggerApplication
class BaseApplication : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent
.builder()
.application(this)
.build()
}
} | 0 | null | 0 | 0 | 9aaf996361149d0a1e05fff4a617dace21983fec | 428 | GithubUsers | Apache License 2.0 |
app/src/main/java/com/biolumeaccessfsm/features/viewAllOrder/interf/ColorListOnCLick.kt | DebashisINT | 740,453,031 | false | {"Kotlin": 13980759, "Java": 1001438} | package com.biolumeaccessfsm.features.viewAllOrder.interf
import com.biolumeaccessfsm.app.domain.NewOrderGenderEntity
import com.biolumeaccessfsm.features.viewAllOrder.model.ProductOrder
interface ColorListOnCLick {
fun colorListOnCLick(size_qty_list: ArrayList<ProductOrder>, adpPosition:Int)
} | 0 | Kotlin | 0 | 0 | 1a51f3bdcf8e79c9ef523846fb89fcfb6072bbb4 | 301 | BIOLUMESKINSCIENCE | Apache License 2.0 |
shared/src/commonTest/kotlin/com/kevinschildhorn/fotopresenter/data/datasources/PlaylistSQLDataSourceTest.kt | KevinSchildhorn | 522,216,678 | false | {"Kotlin": 340526, "Swift": 580} | package com.kevinschildhorn.fotopresenter.data.datasources
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
import com.kevinschildhorn.fotopresenter.PlaylistDatabase
import com.kevinschildhorn.fotopresenter.data.ImageDirectory
import com.kevinschildhorn.fotopresenter.data.network.DefaultNetworkDirectoryDetails
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.test.fail
/**
Testing [PlaylistDataSource]
**/
class PlaylistDataSourceTest {
private val imageDirectory = ImageDirectory(
DefaultNetworkDirectoryDetails(
fullPath = "Image1.png",
id = 1,
)
)
private val imageDirectoryList: List<ImageDirectory> = listOf(
imageDirectory,
ImageDirectory(
DefaultNetworkDirectoryDetails(
fullPath = "Photos/Image2.png",
id = 2,
)
),
ImageDirectory(
DefaultNetworkDirectoryDetails(
fullPath = "Image3.png",
id = 3,
)
),
)
@Test
fun `Create Playlist Success`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlist = dataSource.createPlaylist("Playlist1")
assertEquals("Playlist1", playlist?.name)
assertEquals(1, playlist?.id)
}
@Test
fun `Create Playlist Large`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlist = dataSource.createPlaylist("Playlist1", imageDirectoryList)
assertEquals("Playlist1", playlist?.name)
assertEquals(1, playlist?.id)
imageDirectoryList.forEach {
val image = dataSource.getPlaylistImage(playlist?.id!!, it.details.fullPath)
assertNotNull(image)
}
}
@Test
fun `Create Playlist Failure`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlist1 = dataSource.createPlaylist("Playlist1")
val playlist2 = dataSource.createPlaylist("Playlist1")
assertNotNull(playlist1)
assertNull(playlist2)
}
@Test
fun `Insert Playlist Image Success`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
dataSource.createPlaylist("Playlist1")?.let { playlist ->
val image = dataSource.insertPlaylistImage(playlist.id, imageDirectory)
assertEquals(playlist.id, image?.playlist_id)
assertEquals(imageDirectory.details.fullPath, image?.directory_path)
} ?: run {
fail("Didn't Create Playlist")
}
}
@Test
fun `Insert Playlist Image Failure`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
dataSource.createPlaylist("Playlist1")?.let { playlist ->
val image1 = dataSource.insertPlaylistImage(playlist.id, imageDirectory)
val image2 = dataSource.insertPlaylistImage(playlist.id, imageDirectory)
assertNotNull(image1)
assertNull(image2)
} ?: run {
fail("Didn't Create Playlist")
}
}
@Test
fun `Get Playlist by Name Success`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlistName = "Playlist1"
val playlist = dataSource.createPlaylist(playlistName)
val selectedPlaylist = dataSource.getPlaylistByName(playlistName)
assertEquals(playlist?.name, selectedPlaylist?.name)
assertEquals(playlist?.id, selectedPlaylist?.id)
}
@Test
fun `Select Playlist by Name Failure`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val selectedPlaylist = dataSource.getPlaylistByName("NonExistant")
assertNull(selectedPlaylist)
}
@Test
fun `Get Playlist Image Success`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
dataSource.createPlaylist("Playlist1")?.let { playlist ->
val image1 = dataSource.insertPlaylistImage(playlist.id, imageDirectory)
val image2 = dataSource.getPlaylistImage(playlist.id, imageDirectory.details.fullPath)
assertNotNull(image1)
assertNotNull(image2)
assertEquals(image1?.playlist_id, image2?.playlist_id)
assertEquals(image1?.id, image2?.id)
assertEquals(image1?.directory_path, image2?.directory_path)
} ?: run {
fail("Didn't Create Playlist")
}
}
@Test
fun `Get Playlist Image Failure`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val image = dataSource.getPlaylistImage(0, imageDirectory.details.fullPath)
assertNull(image)
}
@Test
fun `Delete Playlist Success`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val image = dataSource.getPlaylistImage(0, imageDirectory.details.fullPath)
assertNull(image)
}
@Test
fun `Delete Playlist Failure`() {
val playlistName = "Playlist1"
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlist = dataSource.createPlaylist(playlistName, imageDirectoryList)
assertNotNull(playlist)
val newPlaylist = dataSource.getPlaylistByName(playlistName)
assertNotNull(newPlaylist)
val image = dataSource.getPlaylistImage(playlist.id, imageDirectory.details.fullPath)
assertNotNull(image)
val result = dataSource.deletePlaylist(playlist.id)
assertTrue(result)
val deletedPlaylist = dataSource.getPlaylistByName(playlistName)
assertNull(deletedPlaylist)
val deletedImage = dataSource.getPlaylistImage(playlist.id, imageDirectory.details.fullPath)
assertNull(deletedImage)
}
@Test
fun `Select All Playlists Success`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlist = dataSource.createPlaylist("Playlist1", imageDirectoryList)
val playlists = dataSource.getAllPlaylists()
assertEquals(1, playlists.count())
}
@Test
fun `Select All Playlists Failure`() {
val dataSource = PlaylistDataSource(createInMemorySqlDriver())
val playlists = dataSource.getAllPlaylists()
assertEquals(0, playlists.count())
}
private fun createInMemorySqlDriver(): SqlDriver {
val driver: SqlDriver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
PlaylistDatabase.Schema.create(driver)
return driver
}
} | 0 | Kotlin | 0 | 0 | d7a98c80304b13c8189e82fe469b75bc2e8e4991 | 6,684 | FoToPresenter | Apache License 2.0 |
app/src/main/kotlin/com/mr3y/podcaster/ui/screens/FavoritesScreen.kt | mr3y-the-programmer | 720,570,256 | false | {"Kotlin": 944347, "HTML": 196} | package com.mr3y.podcaster.ui.screens
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.exclude
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.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScaffoldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.mr3y.podcaster.LocalStrings
import com.mr3y.podcaster.core.model.Episode
import com.mr3y.podcaster.core.sampledata.Episodes
import com.mr3y.podcaster.ui.components.CoilImage
import com.mr3y.podcaster.ui.components.LoadingIndicator
import com.mr3y.podcaster.ui.components.LocalAnimatedVisibilityScope
import com.mr3y.podcaster.ui.components.LocalSharedTransitionScope
import com.mr3y.podcaster.ui.components.TopBar
import com.mr3y.podcaster.ui.components.animateEnterExit
import com.mr3y.podcaster.ui.components.rememberHtmlToAnnotatedString
import com.mr3y.podcaster.ui.components.rememberSharedContentState
import com.mr3y.podcaster.ui.components.renderInSharedTransitionScopeOverlay
import com.mr3y.podcaster.ui.components.sharedElement
import com.mr3y.podcaster.ui.presenter.favorites.FavoritesUIState
import com.mr3y.podcaster.ui.presenter.favorites.FavoritesViewModel
import com.mr3y.podcaster.ui.preview.DynamicColorsParameterProvider
import com.mr3y.podcaster.ui.preview.PodcasterPreview
import com.mr3y.podcaster.ui.theme.PodcasterTheme
import com.mr3y.podcaster.ui.theme.isAppThemeDark
import com.mr3y.podcaster.ui.theme.setStatusBarAppearanceLight
@Composable
fun FavoritesScreen(
onEpisodeClick: (episodeId: Long, artworkUrl: String) -> Unit,
onNavigateUp: () -> Unit,
contentPadding: PaddingValues,
excludedWindowInsets: WindowInsets?,
modifier: Modifier = Modifier,
viewModel: FavoritesViewModel = hiltViewModel(),
) {
val state by viewModel.state.collectAsStateWithLifecycle()
FavoritesScreen(
state = state,
onEpisodeClick = onEpisodeClick,
onNavigateUp = onNavigateUp,
externalContentPadding = contentPadding,
excludedWindowInsets = excludedWindowInsets,
modifier = modifier,
)
}
@Composable
fun FavoritesScreen(
state: FavoritesUIState,
onEpisodeClick: (episodeId: Long, artworkUrl: String) -> Unit,
onNavigateUp: () -> Unit,
externalContentPadding: PaddingValues,
excludedWindowInsets: WindowInsets?,
modifier: Modifier = Modifier,
) {
val isDarkTheme = isAppThemeDark()
val context = LocalContext.current
LaunchedEffect(key1 = isDarkTheme) {
context.setStatusBarAppearanceLight(isAppearanceLight = !isDarkTheme)
}
Scaffold(
topBar = {
TopBar(
onUpButtonClick = onNavigateUp,
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent,
scrolledContainerColor = Color.Transparent,
),
modifier = Modifier
.renderInSharedTransitionScopeOverlay(
LocalSharedTransitionScope.current,
zIndexInOverlay = 1f,
)
.animateEnterExit(LocalAnimatedVisibilityScope.current)
.fillMaxWidth()
.padding(vertical = 8.dp)
.padding(end = 16.dp),
)
},
contentWindowInsets = if (excludedWindowInsets != null) ScaffoldDefaults.contentWindowInsets.exclude(excludedWindowInsets) else ScaffoldDefaults.contentWindowInsets,
containerColor = MaterialTheme.colorScheme.surface,
modifier = modifier,
) { contentPadding ->
val contentModifier = Modifier
.padding(contentPadding)
.padding(horizontal = 16.dp)
.fillMaxSize()
if (state.isLoading) {
LoadingIndicator(modifier = contentModifier)
} else {
FavoriteList(
favorites = state.favorites,
onEpisodeClick = onEpisodeClick,
externalContentPadding = externalContentPadding,
modifier = contentModifier,
)
}
}
}
@Composable
private fun FavoriteList(
favorites: List<Episode>,
onEpisodeClick: (episodeId: Long, artworkUrl: String) -> Unit,
externalContentPadding: PaddingValues,
modifier: Modifier = Modifier,
) {
if (favorites.isEmpty()) {
EmptyFavorites(modifier)
} else {
LazyColumn(
modifier = modifier,
contentPadding = externalContentPadding,
) {
itemsIndexed(
favorites,
key = { _, episode -> episode.id },
) { index, episode ->
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { onEpisodeClick(episode.id, episode.artworkUrl) })
.padding(vertical = 8.dp),
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.width(72.dp),
) {
CoilImage(
artworkUrl = episode.artworkUrl,
sharedTransitionKey = episode.id.toString(),
contentScale = ContentScale.FillBounds,
modifier = Modifier
.size(64.dp)
.aspectRatio(1f)
.sharedElement(
LocalSharedTransitionScope.current,
LocalAnimatedVisibilityScope.current,
rememberSharedContentState(key = episode.id.toString()),
)
.clip(RoundedCornerShape(8.dp)),
)
}
Column(
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.weight(1f),
) {
Text(
text = episode.title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
text = rememberHtmlToAnnotatedString(text = episode.description, indentUnit = TextUnit.Unspecified),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
}
if (index != favorites.lastIndex) {
HorizontalDivider()
}
}
}
}
}
@Composable
private fun EmptyFavorites(
modifier: Modifier = Modifier,
) {
val strings = LocalStrings.current
Box(
contentAlignment = Alignment.Center,
modifier = modifier,
) {
Text(
text = strings.favorites_empty_list,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
)
}
}
@PodcasterPreview
@Composable
fun FavoritesScreenPreview(
@PreviewParameter(DynamicColorsParameterProvider::class) isDynamicColorsOn: Boolean,
) {
PodcasterTheme(dynamicColor = isDynamicColorsOn) {
FavoritesScreen(
state = FavoritesUIState(isLoading = false, Episodes.slice(0..2)),
onEpisodeClick = { _, _ -> },
onNavigateUp = { },
externalContentPadding = PaddingValues(0.dp),
excludedWindowInsets = null,
modifier = Modifier.fillMaxSize(),
)
}
}
@PodcasterPreview
@Composable
fun FavoritesScreenEmptyFavoritesPreview() {
PodcasterTheme(dynamicColor = false) {
FavoritesScreen(
state = FavoritesUIState(isLoading = false, emptyList()),
onEpisodeClick = { _, _ -> },
onNavigateUp = { },
externalContentPadding = PaddingValues(0.dp),
excludedWindowInsets = null,
modifier = Modifier.fillMaxSize(),
)
}
}
| 9 | Kotlin | 3 | 68 | 74b816fea24c7f894ca866f9377e9851bd9d4c24 | 10,400 | Podcaster | Apache License 2.0 |
node/src/test/kotlin/net/corda/node/services/persistence/DBTransactionStorageLedgerRecoveryTests.kt | corda | 70,137,417 | false | null | package net.corda.node.services.persistence
import net.corda.core.contracts.StateRef
import net.corda.core.crypto.Crypto
import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.SignableData
import net.corda.core.crypto.SignatureMetadata
import net.corda.core.crypto.sign
import net.corda.core.flows.TransactionMetadata
import net.corda.core.flows.RecoveryTimeWindow
import net.corda.core.node.NodeInfo
import net.corda.core.node.StatesToRecord
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.WireTransaction
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.CordaClock
import net.corda.node.SimpleClock
import net.corda.node.services.identity.InMemoryIdentityService
import net.corda.node.services.network.PersistentNetworkMapCache
import net.corda.node.services.network.PersistentPartyInfoCache
import net.corda.node.services.persistence.DBTransactionStorage.TransactionStatus.IN_FLIGHT
import net.corda.node.services.persistence.DBTransactionStorage.TransactionStatus.VERIFIED
import net.corda.nodeapi.internal.DEV_ROOT_CA
import net.corda.nodeapi.internal.cryptoservice.CryptoService
import net.corda.nodeapi.internal.persistence.CordaPersistence
import net.corda.nodeapi.internal.persistence.DatabaseConfig
import net.corda.testing.core.ALICE_NAME
import net.corda.testing.core.BOB_NAME
import net.corda.testing.core.CHARLIE_NAME
import net.corda.testing.core.DUMMY_NOTARY_NAME
import net.corda.testing.core.SerializationEnvironmentRule
import net.corda.testing.core.TestIdentity
import net.corda.testing.core.dummyCommand
import net.corda.testing.internal.TestingNamedCacheFactory
import net.corda.testing.internal.configureDatabase
import net.corda.testing.internal.createWireTransaction
import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties
import net.corda.testing.node.internal.MockCryptoService
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.security.KeyPair
import java.time.Clock
import java.time.Instant.now
import java.time.temporal.ChronoUnit
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
class DBTransactionStorageLedgerRecoveryTests {
private companion object {
val ALICE = TestIdentity(ALICE_NAME, 70)
val BOB = TestIdentity(BOB_NAME, 80)
val CHARLIE = TestIdentity(CHARLIE_NAME, 90)
val DUMMY_NOTARY = TestIdentity(DUMMY_NOTARY_NAME, 20)
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule(inheritable = true)
private lateinit var database: CordaPersistence
private lateinit var transactionRecovery: DBTransactionStorageLedgerRecovery
private lateinit var partyInfoCache: PersistentPartyInfoCache
@Before
fun setUp() {
val dataSourceProps = makeTestDataSourceProperties()
database = configureDatabase(dataSourceProps, DatabaseConfig(), { null }, { null })
newTransactionRecovery()
}
@After
fun cleanUp() {
database.close()
}
@Test(timeout = 300_000)
fun `query local ledger for transactions with recovery peers within time window`() {
val beforeFirstTxn = now()
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME)), true)
val timeWindow = RecoveryTimeWindow(fromTime = beforeFirstTxn,
untilTime = beforeFirstTxn.plus(1, ChronoUnit.MINUTES))
val results = transactionRecovery.querySenderDistributionRecords(timeWindow)
assertEquals(1, results.size)
val afterFirstTxn = now()
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ONLY_RELEVANT, setOf(CHARLIE_NAME)), true)
assertEquals(2, transactionRecovery.querySenderDistributionRecords(timeWindow).size)
assertEquals(1, transactionRecovery.querySenderDistributionRecords(RecoveryTimeWindow(fromTime = afterFirstTxn)).size)
}
@Test(timeout = 300_000)
fun `query local ledger for transactions within timeWindow and excluding remoteTransactionIds`() {
val transaction1 = newTransaction()
transactionRecovery.addUnnotarisedTransaction(transaction1, TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME)), true)
val transaction2 = newTransaction()
transactionRecovery.addUnnotarisedTransaction(transaction2, TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME)), true)
val timeWindow = RecoveryTimeWindow(fromTime = now().minus(1, ChronoUnit.DAYS))
val results = transactionRecovery.querySenderDistributionRecords(timeWindow, excludingTxnIds = setOf(transaction1.id))
assertEquals(1, results.size)
}
@Test(timeout = 300_000)
fun `query local ledger by distribution record type`() {
val transaction1 = newTransaction()
// sender txn
transactionRecovery.addUnnotarisedTransaction(transaction1, TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME)), true)
val transaction2 = newTransaction()
// receiver txn
transactionRecovery.addUnnotarisedTransaction(transaction2, TransactionMetadata(BOB_NAME, StatesToRecord.ALL_VISIBLE, setOf(ALICE_NAME)), false)
val timeWindow = RecoveryTimeWindow(fromTime = now().minus(1, ChronoUnit.DAYS))
transactionRecovery.queryDistributionRecords(timeWindow, recordType = DistributionRecordType.SENDER).let {
assertEquals(1, it.size)
assertEquals((it[0] as SenderDistributionRecord).peerPartyId, BOB_NAME.hashCode().toLong())
}
transactionRecovery.queryDistributionRecords(timeWindow, recordType = DistributionRecordType.RECEIVER).let {
assertEquals(1, it.size)
assertEquals((it[0] as ReceiverDistributionRecord).initiatorPartyId, BOB_NAME.hashCode().toLong())
}
val resultsAll = transactionRecovery.queryDistributionRecords(timeWindow, recordType = DistributionRecordType.ALL)
assertEquals(2, resultsAll.size)
}
@Test(timeout = 300_000)
fun `query for sender distribution records by peers`() {
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME)), true)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ONLY_RELEVANT, setOf(CHARLIE_NAME)), true)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ONLY_RELEVANT, setOf(BOB_NAME, CHARLIE_NAME)), true)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(BOB_NAME, StatesToRecord.ONLY_RELEVANT, setOf(ALICE_NAME)), true)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(CHARLIE_NAME, StatesToRecord.ONLY_RELEVANT), true)
assertEquals(5, readSenderDistributionRecordFromDB().size)
val timeWindow = RecoveryTimeWindow(fromTime = now().minus(1, ChronoUnit.DAYS))
transactionRecovery.querySenderDistributionRecords(timeWindow, peers = setOf(BOB_NAME)).let {
assertEquals(2, it.size)
assertEquals(it[0].statesToRecord, StatesToRecord.ALL_VISIBLE)
assertEquals(it[1].statesToRecord, StatesToRecord.ONLY_RELEVANT)
}
assertEquals(1, transactionRecovery.querySenderDistributionRecords(timeWindow, peers = setOf(ALICE_NAME)).size)
assertEquals(2, transactionRecovery.querySenderDistributionRecords(timeWindow, peers = setOf(CHARLIE_NAME)).size)
}
@Test(timeout = 300_000)
fun `query for receiver distribution records by initiator`() {
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME, CHARLIE_NAME)), false)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.ONLY_RELEVANT, setOf(BOB_NAME)), false)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(ALICE_NAME, StatesToRecord.NONE, setOf(CHARLIE_NAME)), false)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(BOB_NAME, StatesToRecord.ALL_VISIBLE, setOf(ALICE_NAME)), false)
transactionRecovery.addUnnotarisedTransaction(newTransaction(), TransactionMetadata(CHARLIE_NAME, StatesToRecord.ONLY_RELEVANT), false)
val timeWindow = RecoveryTimeWindow(fromTime = now().minus(1, ChronoUnit.DAYS))
transactionRecovery.queryReceiverDistributionRecords(timeWindow, initiators = setOf(ALICE_NAME)).let {
assertEquals(3, it.size)
assertEquals(it[0].statesToRecord, StatesToRecord.ALL_VISIBLE)
assertEquals(it[1].statesToRecord, StatesToRecord.ONLY_RELEVANT)
assertEquals(it[2].statesToRecord, StatesToRecord.NONE)
}
assertEquals(1, transactionRecovery.queryReceiverDistributionRecords(timeWindow, initiators = setOf(BOB_NAME)).size)
assertEquals(1, transactionRecovery.queryReceiverDistributionRecords(timeWindow, initiators = setOf(CHARLIE_NAME)).size)
assertEquals(2, transactionRecovery.queryReceiverDistributionRecords(timeWindow, initiators = setOf(BOB_NAME, CHARLIE_NAME)).size)
}
@Test(timeout = 300_000)
fun `create un-notarised transaction with flow metadata and validate status in db`() {
val senderTransaction = newTransaction()
transactionRecovery.addUnnotarisedTransaction(senderTransaction, TransactionMetadata(ALICE_NAME, StatesToRecord.ALL_VISIBLE, setOf(BOB_NAME)), true)
assertEquals(IN_FLIGHT, readTransactionFromDB(senderTransaction.id).status)
readSenderDistributionRecordFromDB(senderTransaction.id).let {
assertEquals(1, it.size)
assertEquals(StatesToRecord.ALL_VISIBLE, it[0].statesToRecord)
assertEquals(BOB_NAME, partyInfoCache.getCordaX500NameByPartyId(it[0].peerPartyId))
}
val receiverTransaction = newTransaction()
transactionRecovery.addUnnotarisedTransaction(receiverTransaction, TransactionMetadata(ALICE_NAME, StatesToRecord.ONLY_RELEVANT, setOf(BOB_NAME)), false)
assertEquals(IN_FLIGHT, readTransactionFromDB(receiverTransaction.id).status)
readReceiverDistributionRecordFromDB(receiverTransaction.id).let {
assertEquals(StatesToRecord.ONLY_RELEVANT, it.statesToRecord)
assertEquals(ALICE_NAME, partyInfoCache.getCordaX500NameByPartyId(it.initiatorPartyId))
assertEquals(setOf(BOB_NAME), it.peerPartyIds.map { partyInfoCache.getCordaX500NameByPartyId(it) }.toSet() )
}
}
@Test(timeout = 300_000)
fun `finalize transaction with recovery metadata`() {
val transaction = newTransaction(notarySig = false)
transactionRecovery.finalizeTransaction(transaction,
TransactionMetadata(ALICE_NAME), false)
assertEquals(VERIFIED, readTransactionFromDB(transaction.id).status)
assertEquals(StatesToRecord.ONLY_RELEVANT, readReceiverDistributionRecordFromDB(transaction.id).statesToRecord)
}
@Test(timeout = 300_000)
fun `remove un-notarised transaction and associated recovery metadata`() {
val senderTransaction = newTransaction(notarySig = false)
transactionRecovery.addUnnotarisedTransaction(senderTransaction, TransactionMetadata(ALICE.name, peers = setOf(BOB.name, CHARLIE_NAME)), true)
assertNull(transactionRecovery.getTransaction(senderTransaction.id))
assertEquals(IN_FLIGHT, readTransactionFromDB(senderTransaction.id).status)
assertEquals(true, transactionRecovery.removeUnnotarisedTransaction(senderTransaction.id))
assertFailsWith<AssertionError> { readTransactionFromDB(senderTransaction.id).status }
assertEquals(0, readSenderDistributionRecordFromDB(senderTransaction.id).size)
assertNull(transactionRecovery.getTransactionInternal(senderTransaction.id))
val receiverTransaction = newTransaction(notarySig = false)
transactionRecovery.addUnnotarisedTransaction(receiverTransaction, TransactionMetadata(ALICE.name), false)
assertNull(transactionRecovery.getTransaction(receiverTransaction.id))
assertEquals(IN_FLIGHT, readTransactionFromDB(receiverTransaction.id).status)
assertEquals(true, transactionRecovery.removeUnnotarisedTransaction(receiverTransaction.id))
assertFailsWith<AssertionError> { readTransactionFromDB(receiverTransaction.id).status }
assertFailsWith<AssertionError> { readReceiverDistributionRecordFromDB(receiverTransaction.id) }
assertNull(transactionRecovery.getTransactionInternal(receiverTransaction.id))
}
private fun readTransactionFromDB(id: SecureHash): DBTransactionStorage.DBTransaction {
val fromDb = database.transaction {
session.createQuery(
"from ${DBTransactionStorage.DBTransaction::class.java.name} where tx_id = :transactionId",
DBTransactionStorage.DBTransaction::class.java
).setParameter("transactionId", id.toString()).resultList.map { it }
}
assertEquals(1, fromDb.size)
return fromDb[0]
}
private fun readSenderDistributionRecordFromDB(id: SecureHash? = null): List<SenderDistributionRecord> {
return database.transaction {
if (id != null)
session.createQuery(
"from ${DBTransactionStorageLedgerRecovery.DBSenderDistributionRecord::class.java.name} where tx_id = :transactionId",
DBTransactionStorageLedgerRecovery.DBSenderDistributionRecord::class.java
).setParameter("transactionId", id.toString()).resultList.map { it.toSenderDistributionRecord() }
else
session.createQuery(
"from ${DBTransactionStorageLedgerRecovery.DBSenderDistributionRecord::class.java.name}",
DBTransactionStorageLedgerRecovery.DBSenderDistributionRecord::class.java
).resultList.map { it.toSenderDistributionRecord() }
}
}
private fun readReceiverDistributionRecordFromDB(id: SecureHash): ReceiverDistributionRecord {
val fromDb = database.transaction {
session.createQuery(
"from ${DBTransactionStorageLedgerRecovery.DBReceiverDistributionRecord::class.java.name} where tx_id = :transactionId",
DBTransactionStorageLedgerRecovery.DBReceiverDistributionRecord::class.java
).setParameter("transactionId", id.toString()).resultList.map { it }
}
assertEquals(1, fromDb.size)
return fromDb[0].toReceiverDistributionRecord(MockCryptoService(emptyMap()))
}
private fun newTransactionRecovery(cacheSizeBytesOverride: Long? = null, clock: CordaClock = SimpleClock(Clock.systemUTC()),
cryptoService: CryptoService = MockCryptoService(emptyMap())) {
val networkMapCache = PersistentNetworkMapCache(TestingNamedCacheFactory(), database, InMemoryIdentityService(trustRoot = DEV_ROOT_CA.certificate))
val alice = createNodeInfo(listOf(ALICE))
val bob = createNodeInfo(listOf(BOB))
val charlie = createNodeInfo(listOf(CHARLIE))
networkMapCache.addOrUpdateNodes(listOf(alice, bob, charlie))
partyInfoCache = PersistentPartyInfoCache(networkMapCache, TestingNamedCacheFactory(), database)
partyInfoCache.start()
transactionRecovery = DBTransactionStorageLedgerRecovery(database, TestingNamedCacheFactory(cacheSizeBytesOverride
?: 1024), clock, cryptoService, partyInfoCache)
}
private var portCounter = 1000
private fun createNodeInfo(identities: List<TestIdentity>,
address: NetworkHostAndPort = NetworkHostAndPort("localhost", portCounter++)): NodeInfo {
return NodeInfo(
addresses = listOf(address),
legalIdentitiesAndCerts = identities.map { it.identity },
platformVersion = 3,
serial = 1
)
}
private fun newTransaction(notarySig: Boolean = true): SignedTransaction {
val wtx = createWireTransaction(
inputs = listOf(StateRef(SecureHash.randomSHA256(), 0)),
attachments = emptyList(),
outputs = emptyList(),
commands = listOf(dummyCommand(ALICE.publicKey)),
notary = DUMMY_NOTARY.party,
timeWindow = null
)
return makeSigned(wtx, ALICE.keyPair, notarySig = notarySig)
}
private fun makeSigned(wtx: WireTransaction, vararg keys: KeyPair, notarySig: Boolean = true): SignedTransaction {
val keySigs = keys.map { it.sign(SignableData(wtx.id, SignatureMetadata(1, Crypto.findSignatureScheme(it.public).schemeNumberID))) }
val sigs = if (notarySig) {
keySigs + notarySig(wtx.id)
} else {
keySigs
}
return SignedTransaction(wtx, sigs)
}
private fun notarySig(txId: SecureHash) =
DUMMY_NOTARY.keyPair.sign(SignableData(txId, SignatureMetadata(1, Crypto.findSignatureScheme(DUMMY_NOTARY.publicKey).schemeNumberID)))
}
| 55 | Kotlin | 1089 | 3,935 | 2e29e36e01ffa84272a81e69f133415012903e08 | 17,609 | corda | Apache License 2.0 |
app/src/main/java/com/jetpack/compose/learning/demosamples/instagramdemo/InstagramSplashActivity.kt | SimformSolutionsPvtLtd | 379,199,800 | false | null | package com.jetpack.compose.learning.demosamples.instagramdemo
import android.content.Intent
import android.os.Bundle
import android.view.animation.OvershootInterpolator
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import com.jetpack.compose.learning.R
import kotlinx.coroutines.delay
class InstagramSplashActivity: ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Surface(modifier = Modifier.fillMaxSize()) {
SplashScreen()
}
}
}
@Composable
fun SplashScreen() {
val context = LocalContext.current
val scale = remember {
Animatable(0f)
}
LaunchedEffect(key1 = true) {
scale.animateTo(
targetValue = 0.3f,
animationSpec = tween(
durationMillis = 500,
easing = {
OvershootInterpolator(2f).getInterpolation(it)
}
)
)
delay(3000L)
startActivity(Intent(context, InstagramLoginActivity::class.java))
finish()
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Image(
painter = painterResource(id = R.drawable.ic_logo_instagram),
contentDescription = "Logo",
modifier = Modifier.scale(scale.value)
)
}
}
} | 0 | Kotlin | 8 | 99 | 06fa9850a3cdfabfda2d09da1f4eda93898b8733 | 2,212 | SSComposeCookBook | Apache License 2.0 |
src/main/kotlin/name/stepin/es/handler/ProjectorRepository.kt | stepin | 641,644,694 | false | null | package name.stepin.es.handler
import jakarta.annotation.PostConstruct
import name.stepin.es.store.DomainEvent
import name.stepin.es.store.EventMetadata
import org.apache.logging.log4j.kotlin.Logging
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
@Service
class ProjectorRepository(
reflectionHelper: ReflectionHelper,
applicationContext: ApplicationContext,
) : HandlerRepository(
processorAnnotation = Projector::class,
reflectionHelper = reflectionHelper,
applicationContext = applicationContext,
) {
companion object : Logging
@PostConstruct
fun init() {
initProcessor()
}
override suspend fun process(
event: DomainEvent,
meta: EventMetadata,
) {
val eventClass = event.javaClass.canonicalName
val processors = map[eventClass]
if (processors.isNullOrEmpty()) {
logger.info { "No projectors for $eventClass" }
return
}
for ((processor, methodName, withMeta) in processors) {
logger.debug { "Projector ${processor::class.java} $methodName $withMeta" }
if (withMeta) {
processor.invokeSuspendFunction(methodName, event, meta)
} else {
processor.invokeSuspendFunction(methodName, event)
}
}
}
}
| 0 | Kotlin | 0 | 1 | bcd6c6d5e462490148da74b1477e6ab9bfe2b345 | 1,393 | kotlin-event-sourcing-app | MIT License |
cmdline-parser-gen/src/main/kotlin/CmdlineParserGenerator.kt | google | 297,744,725 | false | null | import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import java.io.OutputStream
private fun OutputStream.appendText(str: String) {
this.write(str.toByteArray())
}
private fun OutputStream.appendLine(str: String = "") {
appendText(str + System.lineSeparator())
}
// modueName => -module-name
private fun String.camelToOptionName(): String = fold(StringBuilder()) { acc, c ->
acc.let {
val lower = c.lowercase()
acc.append(if (acc.isEmpty() || c.isUpperCase()) "-$lower" else lower)
}
}.toString()
class CmdlineParserGenerator(
val codeGenerator: CodeGenerator,
val logger: KSPLogger,
val options: Map<String, String>
) : SymbolProcessor {
override fun process(resolver: Resolver): List<KSAnnotated> {
val annotationName = "com.google.devtools.ksp.processing.KSPArgParserGen"
val kspConfigBuilders =
resolver.getSymbolsWithAnnotation(annotationName)
kspConfigBuilders.filterIsInstance<KSClassDeclaration>().forEach { builderClass ->
val parserName = builderClass.annotations.single {
it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationName
}.arguments.single().value as String
val configClass = builderClass.parentDeclaration as KSClassDeclaration
val builderName = "${configClass.simpleName.asString()}.${builderClass.simpleName.asString()}"
codeGenerator.createNewFile(
Dependencies(false, builderClass.containingFile!!),
builderClass.packageName.asString(),
parserName
).use { os ->
os.appendLine("package ${builderClass.packageName.asString()}")
os.appendLine()
os.appendLine(
"fun $parserName(args: Array<String>): Pair<${configClass.simpleName.asString()}, List<String>> {"
)
os.appendLine(" val processorClasspath = mutableListOf<String>()")
os.appendLine(" return Pair($builderName().apply {")
os.appendLine(" var i = 0")
os.appendLine(" while (i < args.size) {")
os.appendLine(" val arg = args[i++]")
os.appendLine(" when {")
builderClass.getAllProperties().filter { it.setter != null }.forEach { prop ->
val type = prop.type.resolve()
val typeName = type.declaration.simpleName.asString()
val propName = prop.simpleName.asString()
val optionName = propName.camelToOptionName()
val optionNameLen = optionName.length
when (typeName) {
"String", "Boolean", "File" -> {
os.appendLine(
" arg == \"$optionName\" -> " +
"$propName = parse$typeName(getArg(args, i++))"
)
os.appendLine(
" arg.startsWith(\"$optionName=\") -> " +
"$propName = parse$typeName(arg.substring(${optionNameLen + 1}))"
)
}
"List", "Map" -> {
val elementTypeName =
type.arguments.last().type!!.resolve().declaration.simpleName.asString()
os.appendLine(
" arg == \"$optionName\" -> " +
"$propName = parse$typeName(getArg(args, i++), ::parse$elementTypeName)"
)
os.appendLine(
" arg.startsWith(\"$optionName=\") -> " +
"$propName = parse$typeName(arg.substring(${optionNameLen + 1}), " +
"::parse$elementTypeName)"
)
}
else -> {
throw IllegalArgumentException("Unknown type of option `$propName: ${prop.type}`")
}
}
}
// Free args are processor classpath
os.appendLine(" else -> {")
os.appendLine(" processorClasspath.addAll(parseList(arg, ::parseString))")
os.appendLine(" }")
os.appendLine(" }")
os.appendLine(" }")
os.appendLine(" }.build(), processorClasspath)")
os.appendLine("}")
}
codeGenerator.createNewFile(
Dependencies(false, builderClass.containingFile!!),
builderClass.packageName.asString(),
parserName + "Help"
).use { os ->
os.appendLine("package ${builderClass.packageName.asString()}")
os.appendLine()
os.appendLine(
"fun ${parserName}Help(): String = \"\"\""
)
builderClass.getAllProperties().filter { it.setter != null }.forEach { prop ->
val type = prop.type.resolve()
val typeName = type.toString()
val propName = prop.simpleName.asString()
val optionName = propName.camelToOptionName()
val prefix = if (Modifier.LATEINIT in prop.modifiers) "*" else " "
os.appendLine("$prefix $optionName=$typeName")
}
os.appendLine("* <processor classpath>")
os.appendLine("\"\"\"")
}
}
return emptyList()
}
}
class CmdlineParserGeneratorProvider : SymbolProcessorProvider {
override fun create(
environment: SymbolProcessorEnvironment
): SymbolProcessor {
return CmdlineParserGenerator(environment.codeGenerator, environment.logger, environment.options)
}
}
| 370 | null | 268 | 2,854 | a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3 | 6,165 | ksp | Apache License 2.0 |
android/DartsScorecard/libcore/src/main/java/nl/entreco/libcore/scopes/AppContext.kt | Entreco | 110,022,468 | false | null | package nl.entreco.libcore.scopes
import javax.inject.Qualifier
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class AppContext(val value: String = "AppContext") | 4 | null | 1 | 1 | a031a0eeadd0aa21cd587b5008364a16f890b264 | 197 | Darts-Scorecard | Apache License 2.0 |
kte/src/main/kotlin/de/tschuehly/spring/viewcomponent/kte/KteViewContextAspect.kt | tschuehly | 604,349,993 | false | null | package de.tschuehly.spring.viewcomponent.kte
import de.tschuehly.spring.viewcomponent.core.IViewContext
import gg.jte.TemplateEngine
import gg.jte.springframework.boot.autoconfigure.JteProperties
import org.aspectj.lang.annotation.AfterReturning
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
@Aspect
class KteViewContextAspect(
private val jteTemplateEngine: TemplateEngine,
private val jteProperties: JteProperties
) {
@Pointcut("@within(de.tschuehly.spring.viewcomponent.core.component.ViewComponent)")
fun isViewComponent() {
//
}
@Pointcut("execution(de.tschuehly.spring.viewcomponent.kte.ViewContext+ *(..))")
fun isRenderOrGetMethod() {
//
}
@AfterReturning(pointcut = "isViewComponent() && isRenderOrGetMethod()", returning = "viewContext")
fun renderInject(viewContext: ViewContext): ViewContext {
ViewContext.templateEngine = jteTemplateEngine
ViewContext.templateSuffix = jteProperties.templateSuffix
return viewContext
}
} | 4 | null | 8 | 185 | dfb9c2ffac60a7cd55a49f05a53ad2312c3a6098 | 1,062 | spring-view-component | MIT License |
app/src/main/java/com/example/android/wearable/composeforwearos/charts/MultipleLineChartUtils.kt | yingding | 587,725,377 | false | null | @file:JvmName("MultipleLineChartUtils")
package com.example.android.wearable.composeforwearos.charts
import com.github.mikephil.charting.data.Entry
import java.text.SimpleDateFormat
fun needSwitchToNewSeg2(current: TimeScoreData?, last: TimeScoreData?): Boolean {
return current == null && last != null || current != null && last == null
}
fun loadDiscontinuousLineSegments2(
dayBeginTS: Long,
cStressMap: Map<Long, TimeScoreData>,
localizedTimeFormat: SimpleDateFormat? = null
): DiscontinuousLinesContainer {
val HR_INTERVAL_LENGTH = 600
val dayEndTS: Long = dayBeginTS + 86400 // 24 hours later
// the list collection of all discontinuous lines
val lines = ArrayList<DiscontinuousLineSegment>()
// use a single global label array for all discontinuous lines
val labels = ArrayList<String>()
var firstIndexWithData = -1
var lastIndexWithData = -1
/*
* Preparing the data and detect how many discontinuous segments exist in the given line
* every discontinuous part is initialized as a custom DiscontinuousLineSegment obj.
*/
// need segId to assign the new seg
var segId = -1
var current: TimeScoreData?
var last: TimeScoreData? = null
var lineSegment: DiscontinuousLineSegment
// moving reference pointer of the discontinuous line entry list, a line consists of entries
var lineSegmentEntryList: ArrayList<Entry>? = null
/* use index and value in range
* https://stackoverflow.com/questions/48898102/how-to-get-the-current-index-in-for-each-kotlin/55297324#55297324
*
* Loop through the whole day every 10 min timestamp
*/
for ((index, curTS: Long) in (dayBeginTS..dayEndTS step HR_INTERVAL_LENGTH.toLong()).withIndex()) {
// add label to global label list, which must be large then the segment
labels.add(TimeConvertionUtil.utcTimestampToLongDaytimeStr(curTS, localizedTimeFormat)!!)
// get the current computed stress associated with the current timestamp
current = cStressMap[curTS]
// for the first timestamp of the day or (one of the current and last is null)
// a new discontinuous segment shall be initialized
if (curTS == dayBeginTS || needSwitchToNewSeg2(current, last)) {
segId++
lines.add(DiscontinuousLineSegment()) // add a Pair to the discontinuous line
lineSegment = lines[segId]
lineSegmentEntryList = lineSegment.valueSegment
if (current == null && !lineSegment.isAllZero) {
// set the indicator for all zero line segment
lineSegment.isAllZero = true
}
}
// do not use the else statement to null the entries since isNewSeg is false case still need to add to entries
if (current != null) {
// convert the double value (computedStress) to Float()
lineSegmentEntryList?.add(Entry(current.score.toFloat(), index))
if (firstIndexWithData == -1) {
firstIndexWithData = index
}
lastIndexWithData = index
} else {
// Adding zero value to the segment
lineSegmentEntryList?.add(Entry(-0.0f, index))
}
last = current
}
return DiscontinuousLinesContainer(labels, lines, firstIndexWithData, lastIndexWithData)
}
/**
* https://stackoverflow.com/questions/47307782/how-to-return-multiple-values-from-a-function-in-kotlin-like-we-do-in-swift/47308092#47308092
*/
data class DiscontinuousLinesContainer(
val labels: ArrayList<String>,
val lines: ArrayList<DiscontinuousLineSegment>,
val firstIdx: Int,
val lastIdx: Int)
class DiscontinuousLineSegment {
var isAllZero = false
val valueSegment = java.util.ArrayList<Entry>()
fun isEmpty(): Boolean {
return valueSegment.isEmpty()
}
} | 0 | Kotlin | 0 | 0 | ff0ca8c9d26dcfada8f0c6d6cd3766a90af48012 | 3,885 | swipeToDismiss | Apache License 2.0 |
buildSrc/src/main/kotlin/DownloadJavadocsPlugin.kt | paul-griffith | 444,600,204 | false | {"Kotlin": 240123, "Java": 37769} | import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getByName
import org.jsoup.Jsoup
import java.net.URI
import java.net.URL
data class JavadocUrl(
val base: String,
val noframe: Boolean = false,
) {
val url: URL
get() = URI("${base}allclasses${if (noframe) "-noframe" else ""}.html").toURL()
}
private fun javadoc(url: String) = JavadocUrl(url)
private fun legacyJavadoc(url: String) = JavadocUrl(url, noframe = true)
class DownloadJavadocsPlugin : Plugin<Project> {
private val toDownload = mapOf(
"8.1" to listOf(
javadoc("https://files.inductiveautomation.com/sdk/javadoc/ignition81/8.1.21/"),
javadoc("https://docs.oracle.com/en/java/javase/11/docs/api/"),
legacyJavadoc("https://www.javadoc.io/static/org.python/jython-standalone/2.7.1/")
),
"8.0" to listOf(
javadoc("https://files.inductiveautomation.com/sdk/javadoc/ignition80/8.0.14/"),
javadoc("https://docs.oracle.com/en/java/javase/11/docs/api/"),
legacyJavadoc("https://www.javadoc.io/static/org.python/jython-standalone/2.7.1/")
),
"7.9" to listOf(
legacyJavadoc("https://files.inductiveautomation.com/sdk/javadoc/ignition79/7921/"),
legacyJavadoc("https://docs.oracle.com/javase/8/docs/api/"),
legacyJavadoc("https://www.javadoc.io/static/org.python/jython-standalone/2.5.3/")
),
)
override fun apply(target: Project) {
val downloadJavadocs = target.tasks.register("downloadJavadocs", Task::class.java) {
val javadocsDir = temporaryDir.resolve("javadocs")
for ((version, urls) in toDownload) {
javadocsDir.resolve(version).apply {
mkdirs()
resolve("links.properties").printWriter().use { writer ->
for (javadocUrl in urls) {
javadocUrl.url.openStream().use { inputstream ->
Jsoup.parse(inputstream, Charsets.UTF_8.name(), "")
.select("a[href]")
.forEach { a ->
val className = a.text()
val packageName = a.attr("title").substringAfterLast(' ')
writer.append(packageName).append('.').append(className)
.append('=').append(javadocUrl.base).append(a.attr("href"))
.appendLine()
}
}
}
}
}
}
javadocsDir.resolve("versions.txt").printWriter().use { writer ->
for (version in toDownload.keys) {
writer.println(version)
}
}
outputs.dir(temporaryDir)
}
target.extensions.getByName<SourceSetContainer>("sourceSets")["main"].resources.srcDir(downloadJavadocs)
}
}
| 0 | Kotlin | 8 | 31 | bf963b2d7bab04414ed418059f94825e039d33ce | 3,254 | kindling | MIT License |
app/src/main/java/com/progix/fridgex/light/adapter/daily/DailyAdapter.kt | T8RIN | 417,568,516 | false | {"Kotlin": 454504, "Java": 146} | package com.progix.fridgex.light.adapter.daily
import android.content.Context
import android.content.res.Configuration
import android.database.Cursor
import android.os.Looper
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.PopupMenu
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.android.material.snackbar.Snackbar
import com.progix.fridgex.light.R
import com.progix.fridgex.light.activity.MainActivity
import com.progix.fridgex.light.activity.MainActivity.Companion.mDb
import com.progix.fridgex.light.application.FridgeXLightApplication
import com.progix.fridgex.light.custom.CustomSnackbar
import com.progix.fridgex.light.model.RecipeItem
class DailyAdapter(
var context: Context,
var recipeList: ArrayList<RecipeItem>,
var onClickListener: OnClickListener
) : RecyclerView.Adapter<DailyAdapter.ViewHolder>() {
override fun onFailedToRecycleView(holder: ViewHolder): Boolean {
return true
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
holder.clearAnimation()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
if (context is FridgeXLightApplication) context =
(context as FridgeXLightApplication).getCurrentContext()!!
val displayMetrics = context.resources.displayMetrics
val dpHeight = (displayMetrics.heightPixels / displayMetrics.density).toInt()
val k = (dpHeight + 50) / 3 - 271
val k2 = (dpHeight - 4) / 2 - 271
rand =
if (context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
ArrayList(listOf(254 + k, 280 + k, 266 + k, 273 + k, 295 + k, 262 + k))
} else {
ArrayList(listOf(240 + k2, 220 + k2, 240 + k2, 240 + k2, 220 + k2, 220 + k2))
}
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_daily, parent, false)
)
}
private var rand: ArrayList<Int> = ArrayList()
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
setAnimation(holder.itemView, position)
Glide.with(context).load(recipeList[position].image).into(holder.image)
Glide.with(context).load(recipeList[position].indicator).into(holder.indicator)
holder.recipeName.text = recipeList[position].recipeName
holder.time.text = recipeList[position].time
holder.xOfY.text = recipeList[position].xOfY
val params = holder.itemView.layoutParams
val random = rand[position]
val pixels = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
random.toFloat(),
context.resources.displayMetrics
)
params.height = pixels.toInt()
holder.itemView.layoutParams = params
val cursor: Cursor = mDb.rawQuery(
"SELECT * FROM recipes WHERE recipe_name = ?",
listOf(recipeList[position].recipeName).toTypedArray()
)
cursor.moveToFirst()
val starred = cursor.getInt(7) == 1
val banned = cursor.getInt(14) == 1
if (starred) holder.star.visibility = VISIBLE
else holder.star.visibility = GONE
holder.bind(onClickListener, cursor.getInt(0), position, starred, banned)
cursor.close()
}
private fun popupMenus(view: View, id: Int, position: Int, starred: Boolean, banned: Boolean) {
val popupMenus = PopupMenu(context, view)
inflatePopup(popupMenus, starred, banned)
popupMenus.setOnMenuItemClickListener {
when (it.itemId) {
R.id.star_recipe -> {
mDb.execSQL("UPDATE recipes SET is_starred = 1 WHERE id = $id")
showSnackBar(
context.getString(R.string.addedToStarred),
id,
position,
"is_starred",
0
)
notifyItemChanged(position)
true
}
R.id.ban_recipe -> {
mDb.execSQL("UPDATE recipes SET banned = 1 WHERE id = $id")
showSnackBar(
context.getString(R.string.addedToBanList),
id,
position,
"banned",
0
)
notifyItemChanged(position)
true
}
R.id.de_star_recipe -> {
mDb.execSQL("UPDATE recipes SET is_starred = 0 WHERE id = $id")
showSnackBar(context.getString(R.string.delStar), id, position, "is_starred", 1)
notifyItemChanged(position)
true
}
R.id.de_ban_recipe -> {
mDb.execSQL("UPDATE recipes SET banned = 0 WHERE id = $id")
showSnackBar(context.getString(R.string.delBan), id, position, "banned", 1)
notifyItemChanged(position)
true
}
else -> true
}
}
popupMenus.setForceShowIcon(true)
popupMenus.show()
}
private fun inflatePopup(popupMenus: PopupMenu, starred: Boolean, banned: Boolean) {
if (!starred && !banned) popupMenus.inflate(R.menu.popup_menu_empty)
else if (!starred && banned) popupMenus.inflate(R.menu.popup_menu_banned)
else if (starred && !banned) popupMenus.inflate(R.menu.popup_menu_starred)
else popupMenus.inflate(R.menu.popup_menu_both)
}
private fun showSnackBar(text: String, id: Int, position: Int, modifier: String, value: Int) {
CustomSnackbar(context)
.create(
(context as MainActivity).findViewById(R.id.main_root),
text,
Snackbar.LENGTH_LONG
)
.setAction(context.getString(R.string.undo)) {
mDb.execSQL("UPDATE recipes SET $modifier = $value WHERE id = $id")
notifyItemChanged(position)
}
.show()
}
override fun getItemCount(): Int {
return recipeList.size
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val image: ImageView = view.findViewById(R.id.image)
val recipeName: TextView = view.findViewById(R.id.recipeName)
val indicator: ImageView = view.findViewById(R.id.indicator)
val xOfY: TextView = view.findViewById(R.id.x_y)
val time: TextView = view.findViewById(R.id.time)
val star: ImageView = view.findViewById(R.id.star)
fun bind(
onClickListener: OnClickListener,
id: Int,
position: Int,
starred: Boolean,
banned: Boolean
) {
recursiveOnClick(onClickListener, itemView, image, id)
itemView.setOnLongClickListener {
popupMenus(it, id, position, starred, banned)
true
}
}
fun clearAnimation() {
itemView.clearAnimation()
}
}
private fun recursiveOnClick(
onClickListener: OnClickListener,
itemView: View,
image: ImageView,
id: Int
) {
itemView.setOnClickListener {
itemView.setOnClickListener {}
android.os.Handler(Looper.getMainLooper()).postDelayed({
recursiveOnClick(onClickListener, itemView, image, id)
}, 1000)
onClickListener.onClick(image, id)
}
}
class OnClickListener(val clickListener: (ImageView, Int) -> Unit) {
fun onClick(
image: ImageView,
id: Int
) = clickListener(image, id)
}
private var lastPosition = -1
private fun setAnimation(viewToAnimate: View, position: Int) {
val animation: Animation =
AnimationUtils.loadAnimation(context, R.anim.item_animation_fall_down)
viewToAnimate.startAnimation(animation)
lastPosition = position
}
} | 0 | Kotlin | 4 | 30 | dd77e17dc0737e1f0a1a2668a9381838ba627fdf | 8,512 | FridgeXLight | Apache License 2.0 |
app/src/main/java/com/baymax104/bookmanager20/architecture/view/BaseActivity.kt | Baymax104 | 616,083,064 | false | null | package com.baymax104.bookmanager20.architecture.view
import android.os.Bundle
import android.view.Menu
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.util.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.baymax104.bookmanager20.R
/**
*@Description
*@Author John
*@email
*@Date 2023/4/3 15:39
*@Version 1
*/
abstract class BaseActivity : AppCompatActivity() {
private var mBinding: ViewDataBinding? = null
protected abstract fun configureBinding(): DataBindingConfig
protected open fun createToolbarMenu(): Int? = null
protected open fun initUIComponent(binding: ViewDataBinding) {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// initBinding
val config = configureBinding()
val (layout, vmId, stateVM) = config
val binding: ViewDataBinding = DataBindingUtil.setContentView(this, layout)
binding.lifecycleOwner = this
binding.setVariable(vmId, stateVM)
config.params.forEach { key, value -> binding.setVariable(key, value) }
mBinding = binding
// initWindow
applyToolbar(binding.root)
initUIComponent(binding)
}
private fun applyToolbar(root: View) {
val toolbar: Toolbar = root.findViewById(R.id.toolbar) ?: return
setSupportActionBar(toolbar)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val menuId = createToolbarMenu()
return if (menuId != null) {
menuInflater.inflate(menuId, menu)
true
} else false
}
override fun onDestroy() {
super.onDestroy()
mBinding?.unbind()
mBinding = null
}
} | 0 | Kotlin | 0 | 0 | 28b23a44368c241d8519a946fdd5a349946ce194 | 1,849 | BookManager2.0 | MIT License |
defaults/src/commonMain/kotlin/jp/pois/oxacillin/defaults/models/entities/UrlEntity.kt | pois0 | 339,318,315 | true | {"Kotlin": 1970084} | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 StarryBlueSky
* Copyright (c) 2021 poispois
*
* 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 jp.pois.oxacillin.defaults.models.entities
import jp.pois.oxacillin.extensions.models.UrlEntityModel
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class UrlEntity(
public override val url: String,
@SerialName("expanded_url") public override val expandedUrl: String,
@SerialName("display_url") public val displayUrl: String,
public override val indices: IntArray
): UrlEntityModel {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as UrlEntity
if (url != other.url) return false
if (expandedUrl != other.expandedUrl) return false
if (displayUrl != other.displayUrl) return false
if (!indices.contentEquals(other.indices)) return false
return true
}
override fun hashCode(): Int {
var result = url.hashCode()
result = 31 * result + expandedUrl.hashCode()
result = 31 * result + displayUrl.hashCode()
result = 31 * result + indices.contentHashCode()
return result
}
}
| 0 | Kotlin | 0 | 0 | bc33905228c2a1ecf954fbeed53b08323cde6d41 | 2,365 | Oxacillin | MIT License |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/stepfunctions/tasks/EmrCreateClusterVolumeSpecificationPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.stepfunctions.tasks
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Number
import software.amazon.awscdk.Size
import software.amazon.awscdk.services.stepfunctions.tasks.EmrCreateCluster
/**
* EBS volume specifications such as volume type, IOPS, and size (GiB) that will be requested for
* the EBS volume attached to an EC2 instance in the cluster.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.*;
* import software.amazon.awscdk.services.stepfunctions.tasks.*;
* Size size;
* VolumeSpecificationProperty volumeSpecificationProperty = VolumeSpecificationProperty.builder()
* .volumeSize(size)
* .volumeType(EmrCreateCluster.getEbsBlockDeviceVolumeType().GP2)
* // the properties below are optional
* .iops(123)
* .build();
* ```
*
* [Documentation](https://docs.aws.amazon.com/emr/latest/APIReference/API_VolumeSpecification.html)
*/
@CdkDslMarker
public class EmrCreateClusterVolumeSpecificationPropertyDsl {
private val cdkBuilder: EmrCreateCluster.VolumeSpecificationProperty.Builder =
EmrCreateCluster.VolumeSpecificationProperty.builder()
/**
* @param iops The number of I/O operations per second (IOPS) that the volume supports.
*/
public fun iops(iops: Number) {
cdkBuilder.iops(iops)
}
/**
* @param volumeSize The volume size.
* If the volume type is EBS-optimized, the minimum value is 10GiB.
* Maximum size is 1TiB
*/
public fun volumeSize(volumeSize: Size) {
cdkBuilder.volumeSize(volumeSize)
}
/**
* @param volumeType The volume type.
* Volume types supported are gp2, io1, standard.
*/
public fun volumeType(volumeType: EmrCreateCluster.EbsBlockDeviceVolumeType) {
cdkBuilder.volumeType(volumeType)
}
public fun build(): EmrCreateCluster.VolumeSpecificationProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 2,153 | awscdk-dsl-kotlin | Apache License 2.0 |
domain/src/main/java/com/example/domain/usecase/planet/GetPlanetsUseCase.kt | Yang-Seungmin | 417,730,494 | false | {"Kotlin": 92702} | package com.example.domain.usecase.planet
import androidx.paging.PagingData
import com.example.domain.data.planet.Planet
import com.example.domain.repository.SwapiRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetPlanetsUseCase @Inject constructor(
private val swapiRepository: SwapiRepository
) {
operator fun invoke(): Flow<PagingData<Planet>> = swapiRepository.getPlanets()
} | 1 | Kotlin | 2 | 3 | c9325b4b1b81ca46c90f258f4b382ce49b50aec1 | 421 | clean-architecture-sample-android | Apache License 2.0 |
app/src/main/java/io/cricket/app/ui/modules/score_card/batting_score_card/BattingScoreCardModule.kt | amirishaque | 375,128,729 | false | null | package io.cricket.app.ui.modules.score_card.batting_score_card
import dagger.Module
import dagger.Provides
import io.cricket.app.data.database.AppDatabase
import io.cricket.app.data.remote.UserRestService
import io.cricket.app.di.InjectionViewModelProvider
import io.cricket.app.di.qualifiers.ViewModelInjection
import io.cricket.app.di.ui_modules.fragment.BaseFragmentModule
import io.cricket.app.preference.DataStoreManager
@Module
class BattingScoreCardModule : BaseFragmentModule<BattingScoreCardFragment>() {
@Provides
@ViewModelInjection
fun provideBattingScoreCardVM(
fragment: BattingScoreCardFragment,
viewModelProvider: InjectionViewModelProvider<BattingScoreCardVM>
): BattingScoreCardVM = viewModelProvider.get(fragment, BattingScoreCardVM::class)
@Provides
fun provideCricketAppDao(database: AppDatabase) = database.cricketAppDao()
@Provides
fun provideBattingScoreCardAdapter(
fragment: BattingScoreCardFragment,
dataStoreManager: DataStoreManager,
apiService: UserRestService
) =
BattingScoreCardFragment.Adapter(
fragment.mActivity,
fragment,
ArrayList(),
fragment.navigatorHelper,
dataStoreManager,
apiService
)
} | 0 | Kotlin | 0 | 0 | 42808ddd775b5ac6f7bff0d8cf518091588df844 | 1,300 | Cricklub_livecode | MIT License |
android-sdk/src/main/java/webtrekk/android/sdk/domain/worker/SendRequestsWorker.kt | acamarinkovic | 198,233,644 | true | {"Kotlin": 209891, "Java": 7560} | /*
* MIT License
*
* Copyright (c) 2019 Webtrekk GmbH
*
* 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 webtrekk.android.sdk.domain.worker
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import kotlinx.coroutines.withContext
import org.koin.standalone.KoinComponent
import org.koin.standalone.inject
import webtrekk.android.sdk.Logger
import webtrekk.android.sdk.util.CoroutineDispatchers
import webtrekk.android.sdk.data.entity.TrackRequest
import webtrekk.android.sdk.domain.internal.ExecuteRequest
import webtrekk.android.sdk.domain.internal.GetCachedDataTracks
import webtrekk.android.sdk.extension.buildUrlRequest
import webtrekk.android.sdk.util.currentEverId
import webtrekk.android.sdk.util.trackDomain
import webtrekk.android.sdk.util.trackIds
internal class SendRequestsWorker(
context: Context,
workerParameters: WorkerParameters
) :
CoroutineWorker(context, workerParameters), KoinComponent {
private val coroutineDispatchers: CoroutineDispatchers by inject()
private val getCachedDataTracks: GetCachedDataTracks by inject()
private val executeRequest: ExecuteRequest by inject()
private val logger: Logger by inject()
override suspend fun doWork(): Result {
// todo handle Result.failure()
withContext(coroutineDispatchers.ioDispatcher) {
getCachedDataTracks(
GetCachedDataTracks.Params(
requestStates = listOf(
TrackRequest.RequestState.NEW,
TrackRequest.RequestState.FAILED
)
)
)
.onSuccess { dataTracks ->
if (dataTracks.isNotEmpty()) {
logger.info("Executing the requests")
// Must execute requests sync and in order
dataTracks.forEach { dataTrack ->
val urlRequest = dataTrack.buildUrlRequest(trackDomain, trackIds, currentEverId)
logger.info("Sending request = $urlRequest")
executeRequest(
ExecuteRequest.Params(
request = urlRequest,
dataTrack = dataTrack
)
)
.onSuccess { logger.debug("Sent the request successfully $it") }
.onFailure { logger.error("Failed to send the request $it") }
}
}
}
.onFailure { logger.error("Error getting cached data tracks: $it") }
}
return Result.success()
}
companion object {
const val TAG = "send_track_requests"
const val TAG_ONE_TIME_WORKER = "send_track_requests_now"
}
}
| 0 | Kotlin | 0 | 0 | ec8c385b329921d9f027545f405da86ef3346e84 | 3,990 | webtrekk-android-sdk-BETA | MIT License |
android-sdk/src/main/java/webtrekk/android/sdk/domain/worker/SendRequestsWorker.kt | acamarinkovic | 198,233,644 | true | {"Kotlin": 209891, "Java": 7560} | /*
* MIT License
*
* Copyright (c) 2019 Webtrekk GmbH
*
* 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 webtrekk.android.sdk.domain.worker
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import kotlinx.coroutines.withContext
import org.koin.standalone.KoinComponent
import org.koin.standalone.inject
import webtrekk.android.sdk.Logger
import webtrekk.android.sdk.util.CoroutineDispatchers
import webtrekk.android.sdk.data.entity.TrackRequest
import webtrekk.android.sdk.domain.internal.ExecuteRequest
import webtrekk.android.sdk.domain.internal.GetCachedDataTracks
import webtrekk.android.sdk.extension.buildUrlRequest
import webtrekk.android.sdk.util.currentEverId
import webtrekk.android.sdk.util.trackDomain
import webtrekk.android.sdk.util.trackIds
internal class SendRequestsWorker(
context: Context,
workerParameters: WorkerParameters
) :
CoroutineWorker(context, workerParameters), KoinComponent {
private val coroutineDispatchers: CoroutineDispatchers by inject()
private val getCachedDataTracks: GetCachedDataTracks by inject()
private val executeRequest: ExecuteRequest by inject()
private val logger: Logger by inject()
override suspend fun doWork(): Result {
// todo handle Result.failure()
withContext(coroutineDispatchers.ioDispatcher) {
getCachedDataTracks(
GetCachedDataTracks.Params(
requestStates = listOf(
TrackRequest.RequestState.NEW,
TrackRequest.RequestState.FAILED
)
)
)
.onSuccess { dataTracks ->
if (dataTracks.isNotEmpty()) {
logger.info("Executing the requests")
// Must execute requests sync and in order
dataTracks.forEach { dataTrack ->
val urlRequest = dataTrack.buildUrlRequest(trackDomain, trackIds, currentEverId)
logger.info("Sending request = $urlRequest")
executeRequest(
ExecuteRequest.Params(
request = urlRequest,
dataTrack = dataTrack
)
)
.onSuccess { logger.debug("Sent the request successfully $it") }
.onFailure { logger.error("Failed to send the request $it") }
}
}
}
.onFailure { logger.error("Error getting cached data tracks: $it") }
}
return Result.success()
}
companion object {
const val TAG = "send_track_requests"
const val TAG_ONE_TIME_WORKER = "send_track_requests_now"
}
}
| 0 | Kotlin | 0 | 0 | ec8c385b329921d9f027545f405da86ef3346e84 | 3,990 | webtrekk-android-sdk-BETA | MIT License |
app/src/main/java/com/vilp/forcetrace/viewmodel/StylusViewModel.kt | filipe-varela | 751,057,127 | false | {"Kotlin": 47668} | // Copyright 2024 Filipe André Varela
//
// 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.vilp.forcetrace.viewmodel
import android.os.Build
import android.view.MotionEvent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.vilp.forcetrace.model.DataPoint
import com.vilp.forcetrace.model.ForcePoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlin.jvm.internal.Ref.FloatRef
import kotlin.math.pow
class StylusViewModel : ViewModel() {
private var totalSize: Float = 1f
private var dataPoints = HistoryState(mutableListOf<ForcePoint>())
private var tmpPoints = mutableListOf<ForcePoint>()
private var _stylusState = MutableStateFlow(StylusState())
val stylusState: StateFlow<StylusState> = _stylusState
private val removeBrush = DataPoint(-100f, -100f)
private var t0 = 0L
// private val damping = 1000
private val _isLoading = MutableStateFlow(true)
val isLoading = _isLoading.asStateFlow()
init {
viewModelScope.launch {
delay(2500)
_isLoading.value = false
}
}
private fun requestRendering(stylusState: StylusState) {
_stylusState.update {
return@update stylusState
}
}
fun processMotionEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
t0 = System.currentTimeMillis()
tmpPoints.add(
ForcePoint(
event.x,
event.y,
event.pressure,
0L
)
)
}
MotionEvent.ACTION_MOVE -> {
val dt = System.currentTimeMillis() - t0
// val previousForce = tmpPoints.last().f
val currentForce = event.pressure
tmpPoints.add(
ForcePoint(
event.x,
event.y,
currentForce,
dt
)
)
}
MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_UP -> performActionUp(event)
MotionEvent.ACTION_CANCEL -> cancelLastStroke()
else -> return false
}
requestRendering(
StylusState(
points = buildPoints(),
isPressing = event.actionMasked == MotionEvent.ACTION_MOVE
)
)
return true
}
fun processErasingEvent(event: MotionEvent, radius: Float): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
if (dataPoints.current.isNotEmpty()) {
val cleanedPoints = dataPoints.current.filter {
computeDistance(it, event) > radius
}.toMutableList()
if (cleanedPoints.size != dataPoints.current.size) dataPoints.add(cleanedPoints)
requestRendering(
stylusState.value.copy(
lastPosition = DataPoint(event.x, event.y),
points = buildPoints()
)
)
} else {
requestRendering(
stylusState.value.copy(
lastPosition = DataPoint(event.x, event.y)
)
)
}
}
MotionEvent.ACTION_CANCEL -> {
requestRendering(stylusState.value.copy(lastPosition = removeBrush))
}
MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_UP -> {
requestRendering(stylusState.value.copy(lastPosition = removeBrush))
}
else -> return false
}
return true
}
private fun computeDistance(
it: ForcePoint,
event: MotionEvent
) = ((it.x - event.x).pow(2f) + (it.y - event.y).pow(2f)).pow(.5f)
private fun performActionUp(event: MotionEvent) {
val canceled =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && (event.flags and MotionEvent.FLAG_CANCELED) == MotionEvent.FLAG_CANCELED
if (canceled) {
cancelLastStroke()
} else {
tmpPoints.add(
ForcePoint(
event.x,
event.y,
event.pressure,
System.currentTimeMillis() - t0
)
)
val totalPoints = dataPoints.current.toMutableList()
totalPoints.addAll(tmpPoints)
dataPoints.add(totalPoints)
tmpPoints.clear()
}
}
private fun buildPoints(): List<ForcePoint> {
val points = mutableListOf<ForcePoint>()
points.addAll(dataPoints.current.toList())
if (tmpPoints.isNotEmpty()) tmpPoints.forEach { points.add(it) }
return points
}
fun undoPoints() {
if (dataPoints.canUndo()) {
dataPoints.undo()
updatePoints()
}
}
fun redoPoints() {
if (dataPoints.canRedo()) {
dataPoints.redo()
updatePoints()
}
}
fun clearPoints() {
if (dataPoints.current.isNotEmpty()) {
dataPoints.add(mutableListOf())
updatePoints()
}
}
private fun updatePoints() {
requestRendering(
stylusState.value.copy(
points = buildPoints()
)
)
}
private fun cancelLastStroke() {
tmpPoints.clear()
}
fun switchErasingModes() {
requestRendering(stylusState.value.copy(erasingMode = !stylusState.value.erasingMode))
}
fun exportingPointsAsCSV(): String {
return "t,pos_x,pos_y,force\n" + dataPoints.current.map {
ForcePoint(
it.x / totalSize,
it.y / totalSize,
it.f,
it.t
)
}.joinToString("\n") {
"${it.t},${it.x},${it.y},${it.f}"
}
}
fun importingPointsFromCSV(points: List<List<Float>>) {
clearPoints()
dataPoints.add(points.map { point -> ForcePoint(
t = point[0].toLong(),
x = (point[1] + 1) / 2f * totalSize,
y = totalSize - (point[2] + 1) / 2f * totalSize,
f = point[3]
)}.toMutableList())
updatePoints()
}
fun updateTotalSize(ts: Float) { totalSize = ts }
} | 0 | Kotlin | 0 | 0 | 5510740849333862f2bd02fa56cec73de180baf9 | 7,374 | ForceTrace | Apache License 2.0 |
app/src/main/java/com/costular/marvelheroes/presentation/heroeslist/HeroesListActivity.kt | lgomezal | 139,233,017 | false | {"Kotlin": 47165} | package com.costular.marvelheroes.presentation.heroeslist
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.costular.marvelheroes.R
import com.costular.marvelheroes.data.repository.MarvelHeroesRepositoryImpl
import com.costular.marvelheroes.di.components.ApplicationComponent
import com.costular.marvelheroes.di.components.DaggerGetMarvelHeroesListComponent
import com.costular.marvelheroes.di.modules.GetMarvelHeroesListModule
import com.costular.marvelheroes.domain.model.MarvelHeroEntity
import com.costular.marvelheroes.presentation.MainApp
import com.costular.marvelheroes.presentation.heroedetail.MarvelHeroeDetailViewModel
import com.costular.marvelheroes.presentation.util.Navigator
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
class HeroesListActivity : AppCompatActivity() {
private var heroImage : View? = null
@Inject
lateinit var navigator: Navigator
@Inject
lateinit var heroesListViewModel: HeroesListViewModel
lateinit var adapter: HeroesListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
inject()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setUpRecycler()
setUpViewModel()
}
fun inject() {
DaggerGetMarvelHeroesListComponent
.builder()
.applicationComponent((application as MainApp).component)
.getMarvelHeroesListModule(GetMarvelHeroesListModule(this))
.build()
.inject(this)
}
private fun setUpViewModel() {
bindEvents()
}
private fun setUpRecycler() {
adapter = HeroesListAdapter ({ hero, image -> goToHeroDetail(hero, image) },
{ hero -> updateHero(hero) })
heroesListRecycler.layoutManager = GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false)
heroesListRecycler.itemAnimator = DefaultItemAnimator()
heroesListRecycler.adapter = adapter
}
private fun goToHeroDetail(hero: MarvelHeroEntity, image: View) {
navigator.goToHeroDetail(this, hero, image)
}
fun updateHero(hero: MarvelHeroEntity) {
heroesListViewModel.updateHero(hero)
}
private fun bindEvents() {
heroesListViewModel.isLoagingState.observe(this, Observer { isLoading ->
isLoading?.let {
showLoading(it)
}
})
heroesListViewModel.heroesListState.observe(this, Observer {heroesList ->
heroesList?.let {
showHeroesList(it)
}
})
}
private fun showLoading(isLoading: Boolean) {
heroesListLoading.visibility = if(isLoading) View.VISIBLE else View.GONE
}
private fun showHeroesList(heroes: List<MarvelHeroEntity>) {
adapter.swapData(heroes)
}
override fun onResume() {
super.onResume()
heroesListViewModel.loadMarvelHeroes()
}
}
| 0 | Kotlin | 0 | 0 | bff190b9e376e4f2ff20a21be0461ff54bfe1356 | 3,282 | marvelmvvm | MIT License |
core/src/commonMain/kotlin/com/paligot/kighlighter/Kighlighter.kt | GerardPaligot | 402,898,581 | false | null | package com.paligot.kighlighter
import com.paligot.kighlighter.core.*
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
class Kighlighter<T: ColorScheme>(private val language: Language<T>) {
suspend fun apply(snippet: String) = coroutineScope {
return@coroutineScope language.patterns()
.map { pattern -> async { pattern.matches(snippet, language.colorScheme) } }
.awaitAll()
.flatten()
.sortedBy { it.range.first }
.fillEmptyRanges(snippet.length, language.colorScheme.contentColor)
}
}
| 0 | Kotlin | 1 | 23 | 4001f7f7bbb9996ecfc3d9d34dde6d2523c143df | 624 | kighlighter | Apache License 2.0 |
src/main/kotlin/blog/peaksong/auth/filter/AuthFilter.kt | PeakSongBlog | 364,918,697 | false | null | package blog.peaksong.auth.filter
import blog.peaksong.auth.util.JwtUtil
import blog.peaksong.base.ResponseWrap
import blog.peaksong.base.WebConstant
import blog.peaksong.util.LoggerDelegate
import org.springframework.http.MediaType
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import java.nio.charset.StandardCharsets
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import kotlin.streams.toList
class AuthFilter(authenticationManager: AuthenticationManager) :
UsernamePasswordAuthenticationFilter(authenticationManager) {
private val log by LoggerDelegate()
init {
super.setAuthenticationManager(authenticationManager)
setRequiresAuthenticationRequestMatcher(AntPathRequestMatcher(WebConstant.API_AUTH_URL))
}
override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
if (request.method != "POST")
throw AuthenticationServiceException("不被支持的认证方法: ${request.method}")
// 可以在此验证header
// if (request.getHeader(""))
// throw AuthenticationServiceException("")
var username = obtainUsername(request) ?: throw AuthenticationServiceException("用户名不允许为空")
val password = obtainPassword(request) ?: throw AuthenticationServiceException("密码不允许为空")
username = username.trim()
val authRequest = UsernamePasswordAuthenticationToken(username, password)
setDetails(request, authRequest)
return this.authenticationManager.authenticate(authRequest)
}
override fun successfulAuthentication(
request: HttpServletRequest,
response: HttpServletResponse,
chain: FilterChain,
authResult: Authentication
) {
SecurityContextHolder.getContext().authentication = authResult
val username = authResult.name
val token = JwtUtil.createToken(username, authResult.authorities.stream().map { it.authority }.toList())
log.info("用户${JwtUtil.getUserName(token)}认证成功, 角色: ${JwtUtil.getRole(token)}")
response.setHeader(JwtUtil.tokenHeader, "${JwtUtil.tokenPrefix} $token")
response.contentType = MediaType.APPLICATION_JSON_VALUE
response.characterEncoding = StandardCharsets.UTF_8.name()
response.status = WebConstant.AUTH_SUCCESS
response.writer.println(
ResponseWrap.success("认证成功", "Authentication Success").toJson()
)
response.writer.flush()
}
override fun unsuccessfulAuthentication(
request: HttpServletRequest,
response: HttpServletResponse,
failed: AuthenticationException
) {
response.contentType = MediaType.APPLICATION_JSON_VALUE
response.characterEncoding = StandardCharsets.UTF_8.name()
response.status = WebConstant.AUTH_SUCCESS
response.writer.println(
ResponseWrap.fail(failed.message.toString(), "Authentication Fail").toJson()
)
response.writer.flush()
}
} | 1 | null | 1 | 1 | 85afd1f836a9e663e9ae3afb593c1e857cdcaa23 | 3,620 | SpringSecurityDemo | MIT License |
app/src/main/java/com/example/spiritualguide01/home/cards/cardsUI/cardReadings/loveOracle/LoveOracleFragment.kt | drAgon-235 | 711,589,915 | false | {"Kotlin": 167564} | package com.example.spiritualguide01.home.cards.cardsUI.cardReadings.loveOracle
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.example.spiritualguide01.databinding.FragmentLoveOracleBinding
import com.example.spiritualguide01.home.cards.cardsViewModel.CardsViewModel
import com.example.spiritualguide01.home.cards.cardsModel.Card
class LoveOracleFragment : Fragment() {
private lateinit var binding: FragmentLoveOracleBinding
private val viewmodel: CardsViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentLoveOracleBinding.inflate(inflater, container, false)
return binding.root }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val rotatingCard = binding.rotatingCardIV
viewmodel.loadCardListFromDBinViewModel()
// Loading the simple, UNSHUFFLED List<Cards> into viewmodel's 'cardListSimple' (NO LiveData):
var shuffledCardList: List<Card> =
viewmodel.cardListSimple // is not shuffled yet for educational purposes & control/testing
// Shuffeling Cards Button:
binding.shuffleCross.setOnClickListener {
// First: Shaking Animation
YoYo.with(Techniques.Shake).playOn(rotatingCard)
// Second Animation: Rotating up & down
rotatingCard.animate().apply {
duration = 400
rotationYBy(360f)
}.withEndAction {
rotatingCard.animate().apply {
duration = 400
rotationXBy(360f)
}
}
// NOW we are really shuffeling and using shuffled Card List:
shuffledCardList = shuffledCardList.shuffled()
// NOW we make "LAY"-Button visible:
binding.layCrossBTN.visibility = View.VISIBLE
}
// Laying Cards Button:
binding.layCrossBTN.setOnClickListener {
binding.interpeteBTN.visibility = View.VISIBLE
// Connecting the pictures to the View (not visible yet), taking the shuffled cards from top (left) to bottom (right):
var pic1 = shuffledCardList[0].picture
val id1 = shuffledCardList[0].id
// Here we comply with the proper laying order ( pic2 <-> pic3 ) that's the ONLY (minimal) difference to the LittleCrossFragment:
var pic3 = shuffledCardList[1].picture
val id3 = shuffledCardList[1].id
var pic2 = shuffledCardList[2].picture
val id2 = shuffledCardList[2].id
var pic4 = shuffledCardList[3].picture
val id4 = shuffledCardList[3].id
binding.card1IV.setImageResource(pic1)
binding.card2IV.setImageResource(pic2)
binding.card03IV.setImageResource(pic3)
binding.card04IV.setImageResource(pic4)
// Appearing-Animation Card 01 - A:
// CardBack comes faning in dowm...
binding.back01IV.visibility = View.VISIBLE
YoYo.with(Techniques.FadeInDown).playOn(binding.back01IV)
// Appearing-Animation Card 01 - B:
// CardBack turns by 90 degrees and later disappears...
binding.back01IV.animate().apply {
duration = 1500
this.rotationYBy(90f)
binding.card1IV.animate().rotationYBy(90f)
}.withEndAction {
// (CardBack disappears:)
binding.back01IV.isVisible = false
// ... now the 1st Card from deck appears visible and turns by 90 degrees
binding.card1IV.isVisible = true
binding.card1IV.animate().apply {
duration = 1000
this.rotationYBy(270f)
}
}
// Appearing-Animation Card 02 - A:
binding.back02IV.visibility = View.VISIBLE
YoYo.with(Techniques.FadeInDown).playOn(binding.back02IV)
// Appearing-Animation Card 02 - B:
binding.back02IV.animate().apply {
duration = 1500
this.rotationYBy(90f)
binding.card2IV.animate().rotationYBy(90f)
}.withEndAction {
binding.back02IV.isVisible = false
binding.card2IV.isVisible = true
binding.card2IV.animate().apply {
duration = 1000
this.rotationYBy(270f)
}
}
// Appearing-Animation Card 03 - A:
binding.back03IV.visibility = View.VISIBLE
YoYo.with(Techniques.FadeInDown).playOn(binding.back03IV)
// Appearing-Animation Card 03 - B:
binding.back03IV.animate().apply {
duration = 1500
this.rotationYBy(90f)
binding.card03IV.animate().rotationYBy(90f)
}.withEndAction {
binding.back03IV.isVisible = false
binding.card03IV.isVisible = true
binding.card03IV.animate().apply {
duration = 1000
this.rotationYBy(270f)
}
}
// Appearing-Animation Card 04 - A:
binding.back04IV.visibility = View.VISIBLE
YoYo.with(Techniques.FadeInDown).playOn(binding.back04IV)
// Appearing-Animation Card 04 - B:
binding.back04IV.animate().apply {
duration = 1500
this.rotationYBy(90f)
binding.card04IV.animate().rotationYBy(90f)
}.withEndAction {
binding.back04IV.isVisible = false
binding.card04IV.isVisible = true
binding.card04IV.animate().apply {
duration = 1000
this.rotationYBy(270f)
}
}
}
// Interpretation Button:
// Navigating to MeaningFragment and transmitting our 4 cards by id:
binding.interpeteBTN.setOnClickListener {
val id1 = shuffledCardList[0].id
val id2 = shuffledCardList[1].id
val id3 = shuffledCardList[2].id
val id4 = shuffledCardList[3].id
findNavController().navigate(
LoveOracleFragmentDirections.actionLoveOracleFragmentToLoveOracleMeaningFragment(
id1,
id2,
id3,
id4
)
)
}
}
} | 0 | Kotlin | 0 | 0 | ed039bedbc58d313476213528ec5e30b226f18d2 | 7,240 | SpiritualGuide01 | The Unlicense |
sdks/kotlin/common/FilterKt.kt | knox-networks | 595,429,463 | false | {"Rust": 17246636, "C++": 6138133, "C#": 3083132, "JavaScript": 2183132, "TypeScript": 1665259, "Kotlin": 1249671} | // Generated by the protocol buffer compiler. DO NOT EDIT!
// NO CHECKED-IN PROTOBUF GENCODE
// source: common/v1/common.proto
// Generated files should ignore deprecation warnings
@file:Suppress("DEPRECATION")
package common;
@kotlin.jvm.JvmName("-initializefilter")
public inline fun filter(block: common.FilterKt.Dsl.() -> kotlin.Unit): common.Common.Filter =
common.FilterKt.Dsl._create(common.Common.Filter.newBuilder()).apply { block() }._build()
/**
* ```
* [Example]
* {
* "filters": [
* {
* "field": "FIELD1",
* "operator": 0,
* "value": {
* "str_value": "STRINGVAL"
* }
* },
* {
* "field": "FIELD2",
* "operator": 0,
* "value": {
* "int_value": 10
* }
* },
* {
* "field": "FIELD3",
* "operator": 0,
* "value": {
* "bool_value": false
* }
* }
* ],
* "operator": 0
* }
* ```
*
* Protobuf type `common.Filter`
*/
public object FilterKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
public class Dsl private constructor(
private val _builder: common.Common.Filter.Builder
) {
public companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: common.Common.Filter.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): common.Common.Filter = _builder.build()
/**
* An uninstantiable, behaviorless type to represent the field in
* generics.
*/
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
public class FiltersProxy private constructor() : com.google.protobuf.kotlin.DslProxy()
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
*/
public val filters: com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>
@kotlin.jvm.JvmSynthetic
get() = com.google.protobuf.kotlin.DslList(
_builder.getFiltersList()
)
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
* @param value The filters to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addFilters")
public fun com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>.add(value: common.Common.FilterItem) {
_builder.addFilters(value)
}
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
* @param value The filters to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignFilters")
@Suppress("NOTHING_TO_INLINE")
public inline operator fun com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>.plusAssign(value: common.Common.FilterItem) {
add(value)
}
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
* @param values The filters to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addAllFilters")
public fun com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>.addAll(values: kotlin.collections.Iterable<common.Common.FilterItem>) {
_builder.addAllFilters(values)
}
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
* @param values The filters to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignAllFilters")
@Suppress("NOTHING_TO_INLINE")
public inline operator fun com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>.plusAssign(values: kotlin.collections.Iterable<common.Common.FilterItem>) {
addAll(values)
}
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
* @param index The index to set the value at.
* @param value The filters to set.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("setFilters")
public operator fun com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>.set(index: kotlin.Int, value: common.Common.FilterItem) {
_builder.setFilters(index, value)
}
/**
* ```
* List of Filters.
* ```
*
* `repeated .common.FilterItem filters = 1;`
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("clearFilters")
public fun com.google.protobuf.kotlin.DslList<common.Common.FilterItem, FiltersProxy>.clear() {
_builder.clearFilters()
}
/**
* ```
* Operator for Filter.
* ```
*
* `.common.LogicalOperator operator = 2;`
*/
public var operator: common.Common.LogicalOperator
@JvmName("getOperator")
get() = _builder.getOperator()
@JvmName("setOperator")
set(value) {
_builder.setOperator(value)
}
public var operatorValue: kotlin.Int
@JvmName("getOperatorValue")
get() = _builder.getOperatorValue()
@JvmName("setOperatorValue")
set(value) {
_builder.setOperatorValue(value)
}
/**
* ```
* Operator for Filter.
* ```
*
* `.common.LogicalOperator operator = 2;`
*/
public fun clearOperator() {
_builder.clearOperator()
}
}
}
@kotlin.jvm.JvmSynthetic
public inline fun common.Common.Filter.copy(block: `common`.FilterKt.Dsl.() -> kotlin.Unit): common.Common.Filter =
`common`.FilterKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 0 | Rust | 1 | 0 | 16af58a5dc1e9e51859be4a6e0f6791b7adcb2f2 | 5,563 | grpc-sdks | Apache License 2.0 |
library/src/main/java/com/hdlang/android/v2/library/model/DownloadTaskResult.kt | linwenhui0 | 502,305,698 | false | {"Kotlin": 64466, "Java": 27913} | package com.hdlang.android.v2.library.model
import android.app.DownloadManager
import com.hdlang.android.v2.library.utils.constants.DownloadConstants
/**
* 下载进度实体类
*/
data class DownloadTaskResult(val id: Long, val url: String, val status: Int) {
var fileLocalUri: String = ""
var md5: String = ""
var current: Long = 0
var total: Long = 0
@Synchronized
fun getProgress(): Double {
if (status == DownloadManager.STATUS_SUCCESSFUL) {
return 1.0
}
if (total > current) {
return current.toDouble() / total
}
return 0.0
}
fun toMap(): Map<String, Any> {
val dataMap = HashMap<String, Any>()
dataMap[DownloadConstants.KEY_DOWNLOAD_ID] = id
dataMap[DownloadConstants.KEY_DOWNLOAD_URL] = url
dataMap[DownloadConstants.KEY_DOWNLOAD_STATUS] = status
dataMap[DownloadConstants.KEY_DOWNLOAD_FILE_LOCAL_URL] = fileLocalUri
dataMap[DownloadConstants.KEY_DOWNLOAD_CURRENT] = current
dataMap[DownloadConstants.KEY_DOWNLOAD_TOTAL] = total
dataMap[DownloadConstants.KEY_DOWNLOAD_FILE_MD5] = md5
return dataMap
}
}
| 0 | Kotlin | 0 | 0 | f464fa8afafd651e95b074f65716d6dfac861e67 | 1,175 | CommonLibraryV2 | Apache License 2.0 |
src/commonMain/kotlin/com/inari/firefly/graphics/shape/EShape.kt | AndreasHefti | 387,557,032 | false | null | package com.inari.firefly.graphics.shape
import com.inari.firefly.core.ComponentSystem
import com.inari.firefly.core.Entity
import com.inari.firefly.core.EntityComponent
import com.inari.firefly.core.EntityComponentBuilder
import com.inari.firefly.core.api.BlendMode
import com.inari.firefly.core.api.EntityIndex
import com.inari.firefly.core.api.ShapeData
import com.inari.firefly.core.api.ShapeType
import com.inari.util.FloatPropertyAccessor
import com.inari.util.collection.DynArray
import com.inari.util.geom.Vector4f
import kotlin.jvm.JvmField
class EShape private constructor() : EntityComponent(EShape) {
@JvmField val renderData = ShapeData()
var type: ShapeType
get() = renderData.type
set(value) { renderData.type = value }
var vertices: FloatArray
get() = renderData.vertices
set(value) { renderData.vertices = value }
var segments: Int
get() = renderData.segments
set(value) { renderData.segments = value }
val color1: Vector4f
get() = renderData.color1
var color2: Vector4f?
get() = renderData.color2
set(value) { renderData.color2 = value }
var color3: Vector4f?
get() = renderData.color3
set(value) { renderData.color3 = value }
var color4: Vector4f?
get() = renderData.color4
set(value) { renderData.color4 = value }
var blend: BlendMode
get() = renderData.blend
set(value) { renderData.blend = value }
var fill: Boolean
get() = renderData.fill
set(value) { renderData.fill = value }
override fun reset() {
type = ShapeType.POINT
vertices = floatArrayOf()
segments = -1
color1(1f, 1f, 1f, 1f)
color2 = null
color3 = null
color4 = null
blend = BlendMode.NONE
fill = false
}
object PropertyAccessor {
private inline fun getColorRed(index: EntityIndex) = EShape[index].color1.v0PropertyAccessor
private inline fun getColorGreen(index: EntityIndex) = EShape[index].color1.v1PropertyAccessor
private inline fun getColorBlue(index: EntityIndex) = EShape[index].color1.v2PropertyAccessor
private inline fun getColorAlpha(index: EntityIndex) = EShape[index].color1.v3PropertyAccessor
@JvmField val COLOR_RED: (EntityIndex) -> FloatPropertyAccessor = this::getColorRed
@JvmField val COLOR_GREEN: (EntityIndex) -> FloatPropertyAccessor = this::getColorGreen
@JvmField val COLOR_BLUE: (EntityIndex) -> FloatPropertyAccessor = this::getColorBlue
@JvmField val COLOR_ALPHA: (EntityIndex) -> FloatPropertyAccessor = this::getColorAlpha
}
override val componentType = Companion
companion object : EntityComponentBuilder<EShape>("EShape") {
override fun allocateArray() = DynArray.of<EShape>()
override fun create() = EShape()
}
} | 6 | Kotlin | 0 | 11 | e0376a8445dc8f1becc4fa74a177b34f7a817f46 | 2,894 | flyko-lib | Apache License 2.0 |
app/src/main/java/com/cvshealth/accessibility/apps/composeaccessibilitytechniques/ui/text_alternatives/TextAlternatives.kt | cvs-health | 798,314,046 | false | {"Kotlin": 1173207} | /*
Copyright 2023-2024 CVS Health and/or one of its affiliates
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.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.text_alternatives
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.invisibleToUser
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.R
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.BadExampleHeading
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.BodyText
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.GenericScaffold
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.GoodExampleHeading
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.OkExampleHeading
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.SimpleHeading
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.SnackbarLauncher
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.components.VisibleFocusBorderIconButton
import com.cvshealth.accessibility.apps.composeaccessibilitytechniques.ui.theme.ComposeAccessibilityTechniquesTheme
const val textAlternativesHeadingTestTag = "textAlternativesHeading"
const val textAlternativesExample1HeadingTestTag = "textAlternativesExample1Heading"
const val textAlternativesExample1UngroupedTextAndIcon1TestTag = "textAlternativesExample1UngroupedTextAndIcon1"
const val textAlternativesExample1UngroupedTextAndIcon2TestTag = "textAlternativesExample1UngroupedTextAndIcon2"
const val textAlternativesExample2HeadingTestTag = "textAlternativesExample2Heading"
const val textAlternativesExample2UngroupedTextAndIcon1TestTag = "textAlternativesExample2UngroupedTextAndIcon1"
const val textAlternativesExample2UngroupedTextAndIcon2TestTag = "textAlternativesExample2UngroupedTextAndIcon2"
const val textAlternativesExample3HeadingTestTag = "textAlternativesExample3Heading"
const val textAlternativesExample3GroupedTextAndIcon1TestTag = "textAlternativesExample3GroupedTextAndIcon1"
const val textAlternativesExample3GroupedTextAndIcon2TestTag = "textAlternativesExample3GroupedTextAndIcon2"
const val textAlternativesExample4HeadingTestTag = "textAlternativesExample4Heading"
const val textAlternativesExample4GroupedTextAndIcon1TestTag = "textAlternativesExample4GroupedTextAndIcon1"
const val textAlternativesExample4GroupedTextAndIcon2TestTag = "textAlternativesExample4GroupedTextAndIcon2"
const val textAlternativesExample5HeadingTestTag = "textAlternativesExample5Heading"
const val textAlternativesExample5GroupedTextAndIcon1TestTag = "textAlternativesExample5GroupedTextAndIcon1"
const val textAlternativesExample5GroupedTextAndIcon2TestTag = "textAlternativesExample5GroupedTextAndIcon2"
const val textAlternativesExample6HeadingTestTag = "textAlternativesExample6Heading"
const val textAlternativesExample6IconButtonTestTag = "textAlternativesExample6IconButton"
const val textAlternativesExample7HeadingTestTag = "textAlternativesExample7Heading"
const val textAlternativesExample7IconButtonTestTag = "textAlternativesExample7IconButton"
const val textAlternativesExample8HeadingTestTag = "textAlternativesExample8Heading"
const val textAlternativesExample8IconButtonTestTag = "textAlternativesExample8IconButton"
const val textAlternativesExample9HeadingTestTag = "textAlternativesExample9Heading"
const val textAlternativesExample9Icon1TestTag = "textAlternativesExample9Icon1"
const val textAlternativesExample9Icon2TestTag = "textAlternativesExample9Icon2"
const val textAlternativesExample9TextTestTag = "textAlternativesExample9Text"
const val textAlternativesExample10HeadingTestTag = "textAlternativesExample10Heading"
const val textAlternativesExample10Icon1TestTag = "textAlternativesExample10Icon1"
const val textAlternativesExample10Icon2TestTag = "textAlternativesExample10Icon2"
const val textAlternativesExample10TextTestTag = "textAlternativesExample10Text"
const val textAlternativesExample11HeadingTestTag = "textAlternativesExample11Heading"
const val textAlternativesExample11Icon1TestTag = "textAlternativesExample11Icon1"
const val textAlternativesExample11Icon2TestTag = "textAlternativesExample11Icon2"
const val textAlternativesExample11TextTestTag = "textAlternativesExample11Text"
const val textAlternativesExample12HeadingTestTag = "textAlternativesExample12Heading"
const val textAlternativesExample12GroupTestTag = "textAlternativesExample12Group"
const val textAlternativesExample13HeadingTestTag = "textAlternativesExample13Heading"
const val textAlternativesExample13GroupTestTag = "textAlternativesExample13Group"
const val textAlternativesExample14HeadingTestTag = "textAlternativesExample14Heading"
const val textAlternativesExample14GroupTestTag = "textAlternativesExample14Group"
/**
* Demonstrate accessibility techniques for text alternatives to non-text content (in these cases,
* icons) in accordance with WCAG [Success Criterion 1.1.1 Non-text Content](https://www.w3.org/TR/WCAG22/#non-text-content).
*
* Applies [GenericScaffold] to wrap the screen content. Hosts Snackbars.
*
* @param onBackPressed handler function for "Navigate Up" button
*/
@Composable
fun TextAlternativesScreen(
onBackPressed: () -> Unit
) {
val snackbarHostState = remember { SnackbarHostState() }
val snackbarLauncher = SnackbarLauncher(rememberCoroutineScope(), snackbarHostState)
GenericScaffold(
title = stringResource(id = R.string.text_alternatives_title),
onBackPressed = onBackPressed,
snackbarHost = { SnackbarHost(snackbarHostState) }
) { modifier: Modifier ->
val scrollState = rememberScrollState()
Column(
modifier = modifier
.verticalScroll(scrollState)
.padding(horizontal = 16.dp)
.fillMaxWidth()
) {
TextAlternativesHeadingSection()
BadExample1()
OkExample2()
GoodExample3()
GoodExample4()
GoodExample5()
BadExample6(snackbarLauncher)
BadExample7(snackbarLauncher)
GoodExample8(snackbarLauncher)
BadExample9()
BadExample10()
GoodExample11()
BadExample12()
OkExample13()
GoodExample14()
Spacer(modifier = Modifier.height(8.dp))
}
}
}
@Preview(showBackground = true)
@Composable
private fun PreviewWithScaffold() {
ComposeAccessibilityTechniquesTheme {
TextAlternativesScreen {}
}
}
@Composable
private fun TextAlternativesHeadingSection() {
SimpleHeading(
text = stringResource(id = R.string.text_alternatives_heading),
modifier = Modifier.testTag(textAlternativesHeadingTestTag)
)
BodyText(textId = R.string.text_alternatives_description_1)
BodyText(textId = R.string.text_alternatives_description_2)
BodyText(textId = R.string.text_alternatives_description_3)
}
@Composable
private fun PreviewWrapper(
content: @Composable () -> Unit
) {
ComposeAccessibilityTechniquesTheme {
Column(
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxWidth()
) {
content()
}
}
}
@Preview(showBackground = true)
@Composable
private fun TextAlternativesHeadingSectionPreview() {
PreviewWrapper {
TextAlternativesHeadingSection()
}
}
@Composable
private fun BadExample1() {
// Bad example 1: Sunrise and sunset times and icons with empty text alternatives
BadExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_1_heading),
modifier = Modifier.testTag(textAlternativesExample1HeadingTestTag)
)
UngroupedTextAndImage(
textId = R.string.text_alternatives_example_sunrise_time,
iconId = R.drawable.ic_sunrise_fill,
modifier = Modifier.testTag(textAlternativesExample1UngroupedTextAndIcon1TestTag),
contentDescription = "" // Never use the empty string as a contentDescription
)
UngroupedTextAndImage(
textId = R.string.text_alternatives_example_sunset_time,
iconId = R.drawable.ic_sunset_fill,
modifier = Modifier.testTag(textAlternativesExample1UngroupedTextAndIcon2TestTag),
contentDescription = "" // Never use the empty string as a contentDescription
)
}
@Preview(showBackground = true)
@Composable
private fun BadExample1Preview() {
PreviewWrapper {
BadExample1()
}
}
@Composable
private fun OkExample2() {
// OK example 2: Sunrise and sunset times and icons with text alternatives
OkExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_2_heading),
modifier = Modifier.testTag(textAlternativesExample2HeadingTestTag)
)
// Key technique: Provide a concise contentDescription for all informative images.
UngroupedTextAndImage(
textId = R.string.text_alternatives_example_sunrise_time,
iconId = R.drawable.ic_sunrise_fill,
modifier = Modifier.testTag(textAlternativesExample2UngroupedTextAndIcon1TestTag),
contentDescription = stringResource(id = R.string.text_alternatives_example_sunrise_description)
)
UngroupedTextAndImage(
textId = R.string.text_alternatives_example_sunset_time,
iconId = R.drawable.ic_sunset_fill,
modifier = Modifier.testTag(textAlternativesExample2UngroupedTextAndIcon2TestTag),
contentDescription = stringResource(id = R.string.text_alternatives_example_sunset_description)
)
}
@Preview(showBackground = true)
@Composable
private fun OkExample2Preview() {
PreviewWrapper {
OkExample2()
}
}
@Composable
private fun GoodExample3() {
// Good example 3: Sunrise and sunset times grouped with their icons
GoodExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_3_heading),
modifier = Modifier.testTag(textAlternativesExample3HeadingTestTag)
)
// Key techniques:
// 1. Group Column content with Modifier.semantics( mergeDescendants = true ).
// 2. Provide a concise contentDescription for all informative images.
TextAndImageGroup(
textId = R.string.text_alternatives_example_sunrise_time,
iconId = R.drawable.ic_sunrise_fill,
modifier = Modifier.testTag(textAlternativesExample3GroupedTextAndIcon1TestTag),
contentDescription = stringResource(id = R.string.text_alternatives_example_sunrise_description)
)
TextAndImageGroup(
textId = R.string.text_alternatives_example_sunset_time,
iconId = R.drawable.ic_sunset_fill,
modifier = Modifier.testTag(textAlternativesExample3GroupedTextAndIcon2TestTag),
contentDescription = stringResource(id = R.string.text_alternatives_example_sunset_description)
)
}
@Preview(showBackground = true)
@Composable
private fun GoodExample3Preview() {
PreviewWrapper {
GoodExample3()
}
}
@Composable
private fun GoodExample4() {
// Good example 4: Sunrise and sunset times grouped with their icons and redundant text
GoodExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_4_heading),
modifier = Modifier.testTag(textAlternativesExample4HeadingTestTag)
)
// Key techniques:
// 1. Group Column content with Modifier.semantics( mergeDescendants = true ).
// 2. Set contentDescription = null for all decorative or redundant images.
TextImageAndTextGroup(
textId = R.string.text_alternatives_example_sunrise_time,
iconId = R.drawable.ic_sunrise_fill,
textId2 = R.string.text_alternatives_example_sunrise_description,
modifier = Modifier.testTag(textAlternativesExample4GroupedTextAndIcon1TestTag),
contentDescription = null // text is redundant with image, so image is decorative
)
TextImageAndTextGroup(
textId = R.string.text_alternatives_example_sunset_time,
iconId = R.drawable.ic_sunset_fill,
textId2 = R.string.text_alternatives_example_sunset_description,
modifier = Modifier.testTag(textAlternativesExample4GroupedTextAndIcon2TestTag),
contentDescription = null // text is redundant with image, so image is decorative
)
BodyText(textId = R.string.text_alternatives_example_4_note)
}
@Preview(showBackground = true)
@Composable
private fun GoodExample4Preview() {
PreviewWrapper {
GoodExample4()
}
}
@Composable
private fun GoodExample5() {
// Good example 5: Sunrise and sunset times and icons with group text alternatives
GoodExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_5_heading),
modifier = Modifier.testTag(textAlternativesExample5HeadingTestTag)
)
// Key techniques:
// 1. Set a group-level contentDescription with
// Modifier.semantics(mergeDescendants = true) { contentDescription = ... }
// 2. Suppress unnecessary child composable accessibility text/contentDescription with
// Modifier.semantics { invisibleToUser() } or Modifier.clearAndSetSemantics {...}.
// 3. Set contentDescription = null for all decorative or redundant images.
TextAndImageGroupSemanticsReplaced(
textId = R.string.text_alternatives_example_sunrise_time,
iconId = R.drawable.ic_sunrise_fill,
modifier = Modifier.testTag(textAlternativesExample5GroupedTextAndIcon1TestTag),
groupContentDescriptionId = R.string.text_alternatives_example_5_grouped_sunrise_text
)
TextAndImageGroupSemanticsReplaced(
textId = R.string.text_alternatives_example_sunset_time,
iconId = R.drawable.ic_sunset_fill,
modifier = Modifier.testTag(textAlternativesExample5GroupedTextAndIcon2TestTag),
groupContentDescriptionId = R.string.text_alternatives_example_5_grouped_sunset_text
)
}
@Preview(showBackground = true)
@Composable
private fun GoodExample5Preview() {
PreviewWrapper {
GoodExample5()
}
}
@Composable
private fun BadExample6(
snackbarLauncher: SnackbarLauncher?
) {
// Bad example 6: A 'Share' icon button with an empty text alternative
BadExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_6_heading),
modifier = Modifier.testTag(textAlternativesExample6HeadingTestTag)
)
val popupMessage = stringResource(id = R.string.text_alternatives_example_6_message)
VisibleFocusBorderIconButton(
onClick = {
snackbarLauncher?.show(popupMessage)
},
modifier = Modifier
.testTag(textAlternativesExample6IconButtonTestTag)
.minimumInteractiveComponentSize()
) {
Icon(
painter = painterResource(id = R.drawable.ic_share_fill),
contentDescription = "" // Never use the empty string as a contentDescription
)
}
BodyText(textId = R.string.text_alternatives_example_6_note)
}
@Preview(showBackground = true)
@Composable
private fun BadExample6Preview() {
PreviewWrapper {
BadExample6(snackbarLauncher = null)
}
}
@Composable
private fun BadExample7(
snackbarLauncher: SnackbarLauncher?
) {
// Bad example 7: A 'Share' icon button with a null text alternative
BadExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_7_heading),
modifier = Modifier.testTag(textAlternativesExample7HeadingTestTag)
)
// Note: Do not use Icon(..., contentDescription = null) to mark active (e.g., button)
// images unless the active composable has text or a contentDescription.
val popupMessage = stringResource(id = R.string.text_alternatives_example_7_message)
VisibleFocusBorderIconButton(
onClick = {
snackbarLauncher?.show(popupMessage)
},
modifier = Modifier
.testTag(textAlternativesExample7IconButtonTestTag)
.minimumInteractiveComponentSize()
) {
Icon(
painter = painterResource(id = R.drawable.ic_share_fill),
contentDescription = null // Use null for active images only if there is text too.
)
}
}
@Preview(showBackground = true)
@Composable
private fun BadExample7Preview() {
PreviewWrapper {
BadExample7(snackbarLauncher = null)
}
}
@Composable
private fun GoodExample8(
snackbarLauncher: SnackbarLauncher?
) {
// Good example 8: A 'Share' icon button with a text alternative
GoodExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_8_heading),
modifier = Modifier.testTag(textAlternativesExample8HeadingTestTag)
)
// Key technique: Provide a concise contentDescription for all active images.
val popupMessage = stringResource(id = R.string.text_alternatives_example_8_message)
VisibleFocusBorderIconButton(
onClick = {
snackbarLauncher?.show(popupMessage)
},
modifier = Modifier
.testTag(textAlternativesExample8IconButtonTestTag)
.minimumInteractiveComponentSize()
) {
Icon(
painter = painterResource(id = R.drawable.ic_share_fill),
contentDescription = stringResource(id = R.string.text_alternatives_example_8_content_description)
)
}
}
@Preview(showBackground = true)
@Composable
private fun GoodExample8Preview() {
PreviewWrapper {
GoodExample8(snackbarLauncher = null)
}
}
@Composable
private fun BadExample9() {
// Bad example 9: Decorative images with empty contentDescription
BadExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_9_heading),
modifier = Modifier.testTag(textAlternativesExample9HeadingTestTag)
)
Row(
modifier = Modifier.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = "", // Never use the empty string as a contentDescription
modifier = Modifier.testTag(textAlternativesExample9Icon1TestTag)
)
SampleText(
textId = R.string.text_alternatives_example_9_decorated_text,
modifier = Modifier
.testTag(textAlternativesExample9TextTestTag)
.padding(start = 4.dp, end = 4.dp)
)
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = "", // Never use the empty string as a contentDescription
modifier = Modifier.testTag(textAlternativesExample9Icon2TestTag)
)
}
}
@Preview(showBackground = true)
@Composable
private fun BadExample9Preview() {
PreviewWrapper {
BadExample9()
}
}
@Composable
private fun BadExample10() {
// Bad example 10: Decorative images with text alternatives
BadExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_10_heading),
modifier = Modifier.testTag(textAlternativesExample10HeadingTestTag)
)
Row(
modifier = Modifier.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = stringResource(
id = R.string.text_alternatives_example_10_content_description
), // Do not use a non-null contentDescription for a purely decorative image.
modifier = Modifier.testTag(textAlternativesExample10Icon1TestTag)
)
SampleText(
textId = R.string.text_alternatives_example_10_decorated_text,
modifier = Modifier
.testTag(textAlternativesExample10TextTestTag)
.padding(start = 4.dp, end = 4.dp)
)
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = stringResource(
id = R.string.text_alternatives_example_10_content_description
), // Do not use a non-null contentDescription for a purely decorative image.
modifier = Modifier.testTag(textAlternativesExample10Icon2TestTag)
)
}
}
@Preview(showBackground = true)
@Composable
private fun BadExample10Preview() {
PreviewWrapper {
BadExample10()
}
}
@Composable
private fun GoodExample11() {
// Good example 11: Decorative images with null contentDescription
// Key technique: Use Icon(..., contentDescription = null) to mark the images as decorative.
GoodExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_11_heading),
modifier = Modifier.testTag(textAlternativesExample11HeadingTestTag)
)
Row(
modifier = Modifier.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = null,
modifier = Modifier.testTag(textAlternativesExample11Icon1TestTag)
)
SampleText(
textId = R.string.text_alternatives_example_11_decorated_text,
modifier = Modifier
.testTag(textAlternativesExample11TextTestTag)
.padding(start = 4.dp, end = 4.dp)
)
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = null,
modifier = Modifier.testTag(textAlternativesExample11Icon2TestTag)
)
}
}
@Preview(showBackground = true)
@Composable
private fun GoodExample11Preview() {
PreviewWrapper {
GoodExample11()
}
}
@Composable
private fun BadExample12() {
// Bad example 12: Grouped decorative images with empty contentDescription
BadExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_12_heading),
modifier = Modifier.testTag(textAlternativesExample12HeadingTestTag)
)
BodyText(textId = R.string.text_alternatives_example_12_description)
// Key technique: Use Modifier.semantics(mergeDescendants = true) to merge the Row contents.
Row(
modifier = Modifier
.testTag(textAlternativesExample12GroupTestTag)
.padding(top = 8.dp)
.semantics(mergeDescendants = true) { },
verticalAlignment = Alignment.CenterVertically
) {
// Key failures: Uses Icon(..., contentDescription = "").
// Note: Empty string contentDescriptions are a bad code smell. They change the semantics
// tree's contents and can affect jUnit UI tests.
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = "" // Do not do this. See note above.
)
SampleText(
textId = R.string.text_alternatives_example_12_decorated_text,
modifier = Modifier.padding(start = 4.dp, end = 4.dp)
)
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = "" // Do not do this. See note above.
)
}
}
@Preview(showBackground = true)
@Composable
private fun BadExample12Preview() {
PreviewWrapper {
BadExample12()
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun OkExample13() {
// OK example 13: Grouped decorative images with invisibleToUser()
// Key techniques:
// 1. Use Modifier.semantics(mergeDescendants = true) {} to group content semantic text.
// 2. Use Modifier.semantics { invisibleToUser() } to mark the Icons as not
// applicable to the accessibility API.
// Use the invisibleToUser() technique for more complex composables, because for Icons,
// contentDescription=null is a simpler approach. See Good Example 14 below.
OkExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_13_heading),
modifier = Modifier.testTag(textAlternativesExample13HeadingTestTag)
)
Row(
modifier = Modifier
.testTag(textAlternativesExample13GroupTestTag)
.padding(top = 8.dp)
.semantics(mergeDescendants = true) { },
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = stringResource(
id = R.string.text_alternatives_example_13_content_description
),
modifier = Modifier.semantics { invisibleToUser() }
)
SampleText(
textId = R.string.text_alternatives_example_13_decorated_text,
modifier = Modifier.padding(start = 4.dp, end = 4.dp)
)
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = stringResource(
id = R.string.text_alternatives_example_13_content_description
),
modifier = Modifier.semantics { invisibleToUser() }
)
}
}
@Preview(showBackground = true)
@Composable
private fun OkExample13Preview() {
PreviewWrapper {
OkExample13()
}
}
@Composable
private fun GoodExample14() {
// Good example 14: Grouped decorative images with null contentDescription
// Key techniques:
// 1. Use Modifier.semantics(mergeDescendants = true) to merge the Row contents.
// 2. Use Icon(..., contentDescription = null) to mark the images as decorative.
GoodExampleHeading(
text = stringResource(id = R.string.text_alternatives_example_14_heading),
modifier = Modifier.testTag(textAlternativesExample14HeadingTestTag)
)
Row(
modifier = Modifier
.testTag(textAlternativesExample14GroupTestTag)
.padding(top = 8.dp)
.semantics(mergeDescendants = true) { },
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = null
)
SampleText(
textId = R.string.text_alternatives_example_14_decorated_text,
modifier = Modifier.padding(start = 4.dp, end = 4.dp)
)
Icon(
painter = painterResource(id = R.drawable.ic_sprout_fill),
contentDescription = null
)
}
}
@Preview(showBackground = true)
@Composable
private fun GoodExample14Preview() {
PreviewWrapper {
GoodExample14()
}
}
// Helper composables:
/**
* Helper composable to simplify creation of sample text in examples.
*
* @param textId string resource identifier for sample text to display
* @param modifier optional [Modifier] for [Text]
*/
@Composable
private fun SampleText(@StringRes textId: Int, modifier: Modifier = Modifier) {
Text(
stringResource(id = textId),
modifier = modifier,
style = MaterialTheme.typography.bodyMedium
)
}
@Preview(showBackground = true)
@Composable
private fun SampleTextPreview() {
ComposeAccessibilityTechniquesTheme {
SampleText(textId = R.string.text_alternatives_title)
}
}
/**
* Helper to create examples of an ungrouped [Row] containing a [Text], followed by an [Icon].
*
* @param textId string resource identifier for sample text to display
* @param iconId drawable resource identifier for sample [Icon] to display
* @param modifier optional [Modifier] for layout [Row]
* @param contentDescription optional content description string for [Icon]
*/
@Composable
private fun UngroupedTextAndImage(
@StringRes textId: Int,
@DrawableRes iconId: Int,
modifier: Modifier = Modifier,
contentDescription: String? = null
) {
Row(
modifier = modifier.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
SampleText(
textId = textId,
modifier = Modifier.padding(end = 8.dp)
)
Icon(
painter = painterResource(id = iconId),
contentDescription = contentDescription
)
}
}
@Preview(showBackground = true)
@Composable
private fun UngroupedTextAndImagePreview() {
ComposeAccessibilityTechniquesTheme {
UngroupedTextAndImage(
textId = R.string.text_alternatives_title,
iconId = R.drawable.ic_angle_right_outline
)
}
}
/**
* Helper to create examples of a grouped [Row] using merge semantics to combine the screen reader
* announcements of a [Text] followed by an [Icon].
*
* @param textId string resource identifier for sample text to display
* @param iconId drawable resource identifier for sample [Icon] to display
* @param modifier optional [Modifier] for layout [Row]
* @param contentDescription optional content description string for [Icon]
*/
@Composable
private fun TextAndImageGroup(
@StringRes textId: Int,
@DrawableRes iconId: Int,
modifier: Modifier = Modifier,
contentDescription: String? = null
) {
Row(
modifier = modifier
.padding(top = 8.dp)
.semantics(mergeDescendants = true) { },
verticalAlignment = Alignment.CenterVertically
) {
SampleText(
textId = textId,
modifier = Modifier.padding(end = 8.dp)
)
Icon(
painter = painterResource(id = iconId),
contentDescription = contentDescription
)
}
}
@Preview(showBackground = true)
@Composable
private fun TextAndImageGroupPreview() {
ComposeAccessibilityTechniquesTheme {
TextAndImageGroup(
textId = R.string.text_alternatives_title,
iconId = R.drawable.ic_angle_right_outline
)
}
}
/**
* Helper to create examples of a grouped [Row] using merge semantics and contentDescription to
* replace the screen reader announcements of a [Text] followed by an [Icon].
*
* @param textId string resource identifier for sample text to display
* @param iconId drawable resource identifier for sample [Icon] to display
* @param groupContentDescriptionId content description string resource identifier for layout [Row]
* @param modifier optional [Modifier] for layout [Row]
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun TextAndImageGroupSemanticsReplaced(
@StringRes textId: Int,
@DrawableRes iconId: Int,
@StringRes groupContentDescriptionId: Int,
modifier: Modifier = Modifier
) {
val groupContentDescription = stringResource(id = groupContentDescriptionId)
Row(
modifier = modifier
.padding(top = 8.dp)
// Key technique 1: Supply a layout-level contentDescription and set
// semantics(mergeDescendants = true) to combine layout and child semantic texts.
.semantics(mergeDescendants = true) {
contentDescription = groupContentDescription
},
// Alternative key technique: clearAndSetSemantics { contentDescription = ... } replaces
// the current composable's semantics, and that of all of its children, with this single
// contentDescription. With that approach, child element semantics do not need to be
// altered, because they are ignored. This is a very heavy-weight approach and can lead
// to problems if applied when there are many nested children that may need to express
// their own semantics. But it is sometimes appropriate.
// .clearAndSetSemantics {
// contentDescription = groupContentDescription
// },
verticalAlignment = Alignment.CenterVertically
) {
SampleText(
textId = textId,
modifier = Modifier
.padding(end = 8.dp)
// Key technique 2: Make all redundant child composable semantics invisibleToUser()
.semantics {
invisibleToUser()
}
)
Icon(
painter = painterResource(id = iconId),
// Key technique 3: Suppress semantic text from any Icon child elements with a null
// contentDescription.
contentDescription = null
)
}
}
@Preview(showBackground = true)
@Composable
private fun TextAndImageGroupReplacedPreview() {
ComposeAccessibilityTechniquesTheme {
TextAndImageGroupSemanticsReplaced(
textId = R.string.text_alternatives_title,
iconId = R.drawable.ic_angle_right_outline,
groupContentDescriptionId = R.string.text_alternatives_heading
)
}
}
/**
* Helper to create examples of a grouped [Row] using merge semantics to combine the screen reader
* announcements of a [Text] followed by an [Icon] followed by a [Text].
*
* @param textId string resource identifier for the first sample text to display
* @param iconId drawable resource identifier for sample [Icon] to display
* @param textId2 string resource identifier for the second sample text to display
* @param modifier optional [Modifier] for layout [Row]
* @param contentDescription optional content description string for [Icon]
*/
@Composable
private fun TextImageAndTextGroup(
@StringRes textId: Int,
@DrawableRes iconId: Int,
@StringRes textId2: Int,
modifier: Modifier = Modifier,
contentDescription: String? = null
) {
Row(
modifier = modifier
.padding(top = 8.dp)
.semantics(mergeDescendants = true) { },
verticalAlignment = Alignment.CenterVertically
) {
SampleText(
textId = textId,
modifier = Modifier.padding(end = 8.dp)
)
Icon(
painter = painterResource(id = iconId),
contentDescription = contentDescription
)
SampleText(
textId = textId2,
modifier = Modifier.padding(start = 8.dp)
)
}
}
@Preview(showBackground = true)
@Composable
private fun TextImageAndTextGroupPreview() {
ComposeAccessibilityTechniquesTheme {
TextImageAndTextGroup(
textId = R.string.home_title,
iconId = R.drawable.ic_angle_right_outline,
textId2 = R.string.text_alternatives_title
)
}
} | 3 | Kotlin | 3 | 57 | 7eb27a9c8cf78a72def44214188d99c534a9f8b6 | 36,324 | android-compose-accessibility-techniques | Apache License 2.0 |
NLiteAVDemo-Android-Java/call-ui/src/main/java/com/netease/yunxin/nertc/ui/base/Others.kt | netease-kit | 292,760,923 | false | {"Objective-C": 561786, "JavaScript": 505188, "Kotlin": 345942, "Java": 90377, "TypeScript": 4400, "Ruby": 4111, "Python": 2061, "C": 596} | /*
* Copyright (c) 2022 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
package com.netease.yunxin.nertc.ui.base
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.netease.yunxin.kit.call.group.NEGroupCallInfo
import com.netease.yunxin.kit.call.p2p.NECallEngine
import com.netease.yunxin.kit.call.p2p.model.NECallType
import com.netease.yunxin.kit.call.p2p.model.NEInviteInfo
import com.netease.yunxin.nertc.nertcvideocall.utils.CallParams
import com.netease.yunxin.nertc.ui.CallKitUI
import com.netease.yunxin.nertc.ui.service.UIServiceManager
fun CallParam.currentUserIsCaller(): Boolean {
return !TextUtils.isEmpty(callerAccId) && TextUtils.equals(callerAccId, currentAccId)
}
fun CallParam.getChannelId(): String? {
return extras?.run {
this[CallParams.INVENT_CHANNEL_ID] as? String
}
}
fun CallParam.channelId(channelId: String?) {
if (extras == null) {
extras = HashMap()
}
extras?.run {
this[CallParams.INVENT_CHANNEL_ID] = channelId
}
}
fun NEInviteInfo.toCallParam(): CallParam {
return CallParam(
true,
callType,
callerAccId,
CallKitUI.currentUserAccId,
callExtraInfo = extraInfo,
globalExtraCopy = NECallEngine.sharedInstance().callInfo.signalInfo.globalExtraCopy,
rtcChannelName = NECallEngine.sharedInstance().callInfo.rtcInfo.channelName,
extras = mutableMapOf(
CallParams.INVENT_CHANNEL_ID to channelId
)
)
}
fun NEInviteInfo.toCallIntent(context: Context): Intent {
return Intent().apply {
when (callType) {
NECallType.AUDIO -> setClass(
context,
UIServiceManager.getInstance().uiService!!.getOneToOneAudioChat()!!
)
else -> setClass(
context,
UIServiceManager.getInstance().uiService!!.getOneToOneVideoChat()!!
)
}
}.apply {
putExtra(Constants.PARAM_KEY_CALL, toCallParam())
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
}
fun NEGroupCallInfo.toCallIntent(context: Context): Intent {
return Intent().apply {
setClass(context, UIServiceManager.getInstance().uiService!!.getGroupChat()!!)
}.apply {
putExtra(Constants.PARAM_KEY_GROUP_CALL_INFO, this@toCallIntent)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
}
| 2 | Objective-C | 27 | 38 | 9b2593a34179155cf2009124bec0e01944359d2d | 2,571 | NEVideoCall-1to1 | MIT License |
app/src/main/java/com/easy/view/EasyApplication.kt | shishoufengwise1234 | 289,488,783 | false | null | package com.easy.view
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.multidex.MultiDex
import com.easy.view.utils.EASY_VIEW_TAG
import com.orhanobut.logger.*
import dagger.hilt.android.HiltAndroidApp
import java.lang.NullPointerException
/**
* Created by shishoufeng on 2020/9/6.
* email:[email protected]
*
*
* desc: application 初始化
*/
@HiltAndroidApp
class EasyApplication : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}
override fun onCreate() {
super.onCreate()
val formatStrategy: FormatStrategy = PrettyFormatStrategy.newBuilder()
.showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true
.methodCount(2) // (Optional) How many method line to show. Default 2
.methodOffset(7) // (Optional) Hides internal method calls up to offset. Default 5
.logStrategy(LogcatLogStrategy()) // (Optional) Changes the log strategy to print out. Default LogCat
.tag(EASY_VIEW_TAG) // (Optional) Global tag for every log. Default PRETTY_LOGGER
.build()
Logger.addLogAdapter(AndroidLogAdapter(formatStrategy))
registerActivityLifecycleCallbacks(EasyLifecycleCallBack())
}
}
class EasyLifecycleCallBack : Application.ActivityLifecycleCallbacks{
override fun onActivityCreated(activity: Activity, p1: Bundle?) {
Logger.i("onActivityCreated() activity = $activity")
}
override fun onActivityStarted(activity: Activity) {
Logger.i("onActivityStarted() activity = $activity")
}
override fun onActivityResumed(activity: Activity) {
Logger.i("onActivityResumed() activity = $activity")
// throw NullPointerException("resume is null")
}
override fun onActivityPaused(activity: Activity) {
Logger.i("onActivityPaused() activity = $activity")
}
override fun onActivityStopped(activity: Activity) {
Logger.i("onActivityStopped() activity = $activity")
}
override fun onActivitySaveInstanceState(activity: Activity, p1: Bundle) {
Logger.i("onActivitySaveInstanceState() activity = $activity")
}
override fun onActivityDestroyed(activity: Activity) {
Logger.i("onActivityDestroyed() activity = $activity")
}
} | 1 | null | 1 | 1 | 4764e3ca16ca1bc54e206f1eaa7049087db98a7f | 2,476 | AndroidEasyView | Apache License 2.0 |
ui/ui-util/src/commonMain/kotlin/androidx/compose/ui/util/annotation/Annotation.kt | Sathawale27 | 284,157,908 | true | {"Java Properties": 20, "Shell": 44, "Markdown": 43, "Java": 4516, "HTML": 17, "Kotlin": 3557, "Python": 28, "Proguard": 37, "Batchfile": 6, "JavaScript": 1, "CSS": 1, "TypeScript": 6, "Gradle Kotlin DSL": 2, "INI": 1, "CMake": 1, "C++": 2} | /*
* Copyright 2020 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.ui.util.annotation
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class ColorInt()
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class FloatRange(
val from: Double,
val to: Double,
val fromInclusive: Boolean = true,
val toInclusive: Boolean = true
)
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class IntRange(val from: Long = Long.MIN_VALUE, val to: Long = Long.MAX_VALUE)
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class Size(
val value: Long = -1,
val min: Long = Long.MIN_VALUE,
val max: Long = Long.MAX_VALUE,
val multiple: Long = 1
)
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class GuardedBy(
val value: String
)
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class VisibleForTesting(
val otherwise: Int = 2
)
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class CallSuper()
@OptionalExpectation
@ExperimentalMultiplatform
expect annotation class MainThread() | 0 | null | 0 | 1 | 549e3e3003cd308939ff31799cf1250e86d3e63e | 1,700 | androidx | Apache License 2.0 |
grpc-spring-boot-client/src/main/kotlin/xyz/srclab/grpc/spring/boot/client/GrpcStub.kt | srclab-projects | 232,052,266 | false | {"Java": 155574, "Kotlin": 116394} | package xyz.srclab.grpc.spring.boot.client
import io.grpc.stub.AbstractStub
interface GrpcStub<S : AbstractStub<S>> {
fun get(): S
} | 1 | null | 1 | 1 | 608ecf76915a57b08150b62cbf4ee379f494517e | 139 | grpc-spring-boot | Apache License 2.0 |
library/src/main/java/com/github/genaku/compactcalendarview/WeekUtils.kt | genaku | 134,539,242 | true | {"Kotlin": 73115, "Java": 50234} | package com.github.genaku.compactcalendarview
import java.text.DateFormatSymbols
import java.util.*
class WeekUtils {
companion object {
fun getWeekdayNames(locale: Locale, day: Int, useThreeLetterAbbreviation: Boolean): ArrayList<String> {
val dateFormatSymbols = DateFormatSymbols(locale)
val dayNames = dateFormatSymbols.shortWeekdays
?: throw IllegalStateException("Unable to determine weekday names from default locale")
if (dayNames.size != 8) {
throw IllegalStateException("Expected weekday names from default locale to be of size 7 but: "
+ Arrays.toString(dayNames) + " with size " + dayNames.size + " was returned.")
}
val weekDayNames = ArrayList<String>()
val weekDaysFromSunday = arrayOf(dayNames[1], dayNames[2], dayNames[3], dayNames[4], dayNames[5], dayNames[6], dayNames[7])
var currentDay = day - 1
for (i in 0..6) {
currentDay = if (currentDay >= 7) 0 else currentDay
weekDayNames.add(weekDaysFromSunday[currentDay])
currentDay++
}
if (!useThreeLetterAbbreviation) {
for (idx in weekDayNames.indices) {
weekDayNames[idx] = weekDayNames[idx].substring(0, 1)
}
}
return weekDayNames
}
}
}
| 0 | Kotlin | 0 | 0 | c88f34c120931b8727b8753ebdd5099842b5da3a | 1,443 | CompactCalendarView | MIT License |
kotlin/send-whatsapp-message/app/src/main/kotlin/send/whatsapp/message/App.kt | appwrite | 295,727,993 | false | null | /*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package send.whatsapp.message
import com.google.gson.Gson
import okhttp3.*
import org.json.JSONObject
/**
* Class *Whatsapp*.
*
* This class initializing Twilio to send whatsapp message using Twilio Whatsapp API
*
* @property accountSsid Twilio Account SID.
* @property authToken Twilio Account Auth Token.
* @property fromNumber Twilio Sender Number.
* @constructor Init Twilio.
*/
class Whatsapp(private val accountSsid: String, private val authToken: String, private val fromNumber: String) {
/**
* send whatsapp message.
* @param phoneNumber target phone number.
* @param text message body.
*/
fun sendWhatsAppMessage(phoneNumber: String, text: String): ApiResponse {
val client = OkHttpClient().newBuilder().build()
val formBody: RequestBody = FormBody.Builder()
.add("From", "whatsapp:${fromNumber}")
.add("Body", text)
.add("To", "whatsapp:${phoneNumber}")
.build()
val request: Request = Request.Builder()
.url("https://api.twilio.com/2010-04-01/Accounts/${accountSsid}/Messages.json")
.addHeader("Authorization", Credentials.basic(accountSsid, authToken))
.addHeader("Accept", "application/json")
.post(formBody)
.build()
val response: Response = client.newCall(request).execute()
val jsonres: String = response.body()?.string() ?: "NULL"
val objRes: ApiResponse = Gson().fromJson(jsonres, ApiResponse::class.java)
return objRes
}
}
/**
* main function get ENV Variabel then call sendWhatsAppMessage inside Whatsapp Class.
*/
fun main() {
val payload = System.getenv("APPWRITE_FUNCTION_DATA")
val accountSsid = System.getenv("ACCOUNT_SID")
val authToken = System.getenv("AUTH_TOKEN")
val fromNumber = System.getenv("FROM_NUMBER")
if (!payload.isNullOrEmpty()) {
try {
val json = JSONObject(payload)
val phoneNumber = json.getString("phoneNumber")
val text = json.getString("text")
val whatsapp = Whatsapp(accountSsid, authToken, fromNumber)
val msg = whatsapp.sendWhatsAppMessage(phoneNumber, text)
println("Message ${msg.status} TO : ${msg.to} at ${msg.date_created}")
} catch (e: Exception) {
println("Error Sending Message")
println(e.message)
}
}else{
println("You Must Provide Phone Number and text message")
}
} | 31 | null | 159 | 81 | 2b6161c21c6bc8a7f38df4c518cedbbf8824ff03 | 2,571 | demos-for-functions | MIT License |
Kotlin/swap_two_numbers.kt | dark-coder-cat | 413,174,508 | false | null |
fun main(){
println("Enter two numbers")
var a= readLine()!!
var b = readLine()!!
var ai:Int=a.toInt()
var bi:Int=b.toInt()
println("Before swapping")
println("Value of ai: $ai")
println("Value of b1: $bi")
val temp=ai
ai=bi
bi=temp
println("After swapping")
println("Value of ai: $ai")
println("Value of b1: $bi")
}
| 19 | Java | 258 | 48 | 0b3c3a535cab43c7334d7465a76d35d584aaa349 | 444 | Hacktoberfest2021 | MIT License |
crowdin/src/main/java/com/crowdin/platform/data/remote/DistributionInfoManager.kt | crowdin | 193,449,073 | false | null | package com.crowdin.platform.data.remote
import android.util.Log
import com.crowdin.platform.data.DataManager
import com.crowdin.platform.data.DataManager.Companion.DISTRIBUTION_DATA
import com.crowdin.platform.data.DistributionInfoCallback
import com.crowdin.platform.data.remote.api.CrowdinApi
import com.crowdin.platform.data.remote.api.DistributionInfoResponse
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
internal class DistributionInfoManager(
private val crowdinApi: CrowdinApi,
private val dataManager: DataManager,
private val distributionHash: String
) {
fun getDistributionInfo(callback: DistributionInfoCallback) {
crowdinApi.getInfo(distributionHash)
.enqueue(object : Callback<DistributionInfoResponse> {
override fun onResponse(
call: Call<DistributionInfoResponse>,
response: Response<DistributionInfoResponse>
) {
val distributionInfo = response.body()
if (distributionInfo == null) {
Log.w(
DistributionInfoManager::class.java.simpleName,
"Distribution info not loaded. Response code: ${response.code()}"
)
} else {
dataManager.saveData(DISTRIBUTION_DATA, distributionInfo.data)
}
callback.onResponse()
}
override fun onFailure(call: Call<DistributionInfoResponse>, throwable: Throwable) {
callback.onError(throwable)
}
})
}
}
| 6 | null | 38 | 98 | 468e9d2c50cf37ed1aa2a540a2f66e410f4b7ab5 | 1,699 | mobile-sdk-android | MIT License |
java/ql/test-kotlin2/library-tests/collection-literals/test.kt | github | 143,040,428 | false | {"CodeQL": 25842115, "Kotlin": 23987519, "C#": 22195988, "Java": 6236003, "Python": 3772581, "C": 2567089, "JavaScript": 2549912, "C++": 1735352, "Go": 941374, "Swift": 659593, "Ruby": 426711, "TypeScript": 237078, "Rust": 237068, "HTML": 143548, "Starlark": 121774, "Shell": 47929, "Mustache": 22984, "Lua": 17766, "Makefile": 6555, "Batchfile": 6330, "Thrift": 5983, "ASP.NET": 3739, "Emacs Lisp": 3445, "CMake": 3193, "Vue": 2881, "RAML": 2825, "GAP": 2665, "Scheme": 2092, "Vim Script": 1949, "Perl": 1941, "EJS": 1478, "PowerShell": 1214, "Handlebars": 1000, "Nunjucks": 923, "Objective-C": 524, "Dockerfile": 496} | annotation class Ann(val arr1: Array<String> = ["hello", "world"], val arr2: IntArray = [1, 2, 3]) { }
| 1,149 | CodeQL | 1492 | 7,510 | 5108799224a667d9acb2a1a28ff45e680e76e13c | 103 | codeql | MIT License |
agendaview/src/main/java/com/github/jdmbotero/agendaview/adapter/viewholder/WeekPagerViewHolder.kt | jdmbotero | 119,607,306 | false | null | package com.github.jdmbotero.agendaview.adapter.viewholder
import android.support.v7.widget.RecyclerView
import android.util.TypedValue
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.github.jdmbotero.agendaview.AgendaView
import com.github.jdmbotero.agendaview.R
import com.github.jdmbotero.agendaview.model.Day
import com.github.jdmbotero.agendaview.util.DateManager
import com.github.jdmbotero.agendaview.util.Utils
import io.reactivex.subjects.PublishSubject
class WeekPagerViewHolder(var view: View) : RecyclerView.ViewHolder(view) {
fun bind(day: Day, observable: PublishSubject<Day>) {
val textDay = (view as LinearLayout).getChildAt(0) as TextView
val textName = (view as LinearLayout).getChildAt(1) as TextView
val screenSize = Utils.getScreenSize(view.context)
val params = LinearLayout.LayoutParams((screenSize[0] / 7) - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, view.resources.displayMetrics).toInt(),
(screenSize[0] / 7) - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, view.resources.displayMetrics).toInt())
textDay.layoutParams = params
textDay.text = DateManager.getFormatDate(day.date, "dd")
textName.text = DateManager.getFormatDate(day.date, "EEE")
if (day.isToday) {
textDay.setTextColor(AgendaView.dayCurrentColor)
textName.setTextColor(AgendaView.dayCurrentColor)
} else {
textDay.setTextColor(AgendaView.dayTextColor)
textName.setTextColor(AgendaView.dayTextColor)
}
if (day.isSelected) textDay.background = AgendaView.daySelectedBackground
else textDay.background = AgendaView.dayBackground
view.setOnClickListener {
observable.onNext(day)
}
}
} | 0 | Kotlin | 0 | 0 | f6e089a4602fc874e88b93fa44222230b172e5c1 | 1,860 | AgendaView | Apache License 2.0 |
library/src/main/java/com/mooveit/library/providers/EducatorProviderImpl.kt | moove-it | 79,579,060 | false | null | package com.mooveit.library.providers
import com.mooveit.library.Fakeit
import com.mooveit.library.providers.base.BaseProvider
import com.mooveit.library.providers.definition.EducatorProvider
class EducatorProviderImpl : BaseProvider(), EducatorProvider {
override fun name(): String {
return getValue("name") { Fakeit.fetch("educator.name") }
}
override fun secondary(): String {
return getValue("secondary") { Fakeit.fetch("educator.secondary") }
}
override fun tertiaryType(): String {
return getValue("tertiaryType") { Fakeit.fetch("educator.tertiary.type") }
}
override fun tertiaryCourseSubject(): String {
return getValue("tertiaryCourseSubject") { Fakeit.fetch("educator.tertiary.course.subject") }
}
override fun tertiaryCourseType(): String {
return getValue("tertiaryCourseType") { Fakeit.fetch("educator.tertiary.course.type") }
}
} | 18 | null | 48 | 525 | 12b87899d62c5fa701141f8f98cb7265ab58bc15 | 931 | fakeit | MIT License |
maskwalletcore/src/main/java/com/dimension/maskwalletcore/MaskWalletCore.kt | DimensionDev | 366,981,416 | false | null | package com.dimension.maskwalletcore
internal object MaskWalletCore {
init {
System.loadLibrary("maskwalletdroid")
}
external fun request(value: ByteArray): ByteArray
fun call(request: Api.MWRequest): Api.MWResponse {
return request(request.toByteArray()).let { bytes ->
Api.MWResponse.parseFrom(bytes).let { response ->
if (response.hasError()) {
throw MaskWalletCoreException(response.error.errorCode, response.error.errorMsg)
} else {
response
}
}
}
}
fun call(builder: MWRequestKt.Dsl.() -> Unit): Api.MWResponse {
return call(mWRequest(builder))
}
}
| 0 | Kotlin | 1 | 2 | 2fbf966710f59dcd8d8ad8d7406e8653386a7493 | 732 | MaskWalletCore-Android | MIT License |
sqlite-embedder-graalvm/src/jvmMain/kotlin/ru/pixnews/sqlite/open/helper/graalvm/host/preview1/func/EnvironSizesGet.kt | illarionov | 769,429,996 | false | {"Kotlin": 749374, "C": 64230} | /*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package ru.pixnews.sqlite.open.helper.graalvm.host.preview1.func
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary
import com.oracle.truffle.api.frame.VirtualFrame
import org.graalvm.wasm.WasmContext
import org.graalvm.wasm.WasmInstance
import org.graalvm.wasm.WasmLanguage
import ru.pixnews.sqlite.open.helper.common.api.WasmPtr
import ru.pixnews.sqlite.open.helper.graalvm.ext.asWasmPtr
import ru.pixnews.sqlite.open.helper.graalvm.host.BaseWasmNode
import ru.pixnews.sqlite.open.helper.graalvm.host.Host
import ru.pixnews.sqlite.open.helper.host.wasi.preview1.ext.WasiEnvironmentFunc
internal class EnvironSizesGet(
language: WasmLanguage,
instance: WasmInstance,
private val host: Host,
functionName: String = "environ_sizes_get",
) : BaseWasmNode(language, instance, functionName) {
override fun executeWithContext(frame: VirtualFrame, context: WasmContext): Int {
val args = frame.arguments
return environSizesGet(
args.asWasmPtr(0),
args.asWasmPtr(1),
)
}
@TruffleBoundary
@Suppress("MemberNameEqualsClassName")
private fun environSizesGet(
environCountAddr: WasmPtr<Int>,
environSizeAddr: WasmPtr<Int>,
): Int {
return WasiEnvironmentFunc.environSizesGet(
envProvider = host.systemEnvProvider,
memory = memory,
environCountAddr = environCountAddr,
environSizeAddr = environSizeAddr,
).code
}
}
| 0 | Kotlin | 0 | 0 | 192349956f722665f53c526b72c7ca47f7e85891 | 1,765 | wasm-sqlite-open-helper | Apache License 2.0 |
src/main/java/freemusic/music/pojo/wy/Ar.kt | springmarker | 69,713,282 | false | {"Kotlin": 45500, "HTML": 18243, "Java": 8401, "JavaScript": 1482} | package freemusic.music.pojo.wy
data class Ar(var id: Int = 0, var name: String = "") | 0 | Kotlin | 6 | 20 | e6a8d0e32423778e7d3274ab27df9f1dfc0cffc2 | 86 | free-music | Apache License 2.0 |
app/src/main/java/app/chintan/naturist/util/Constants.kt | chintanrparmar | 413,295,236 | false | {"Kotlin": 42704} | package app.chintan.naturist.util
import androidx.datastore.preferences.core.stringPreferencesKey
object Constants {
const val USER_COLLECTION = "users"
const val POST_COLLECTION = "posts"
val ROLE_KEY = stringPreferencesKey("ROLE")
} | 0 | Kotlin | 0 | 0 | 86519839299b012a51cca61069ecb4fee542e414 | 248 | Naturist | Apache License 2.0 |
app/src/main/java/com/madreain/aachulk/module/multi/MultiAdapter.kt | binbin0915 | 342,184,458 | true | {"Kotlin": 265090} | package com.madreain.aachulk.module.multi;
import androidx.databinding.DataBindingUtil
import com.madreain.aachulk.R
import com.madreain.aachulk.databinding.ItemActivityMulti2Binding
import com.madreain.aachulk.databinding.ItemActivityMultiBinding
import com.madreain.aachulk.databinding.ItemListBinding
import com.madreain.libhulk.base.BaseMultiAdapter
import com.madreain.libhulk.view.baseviewholder.HulkViewHolder
import java.util.*
/**
* @author madreain
* @date
* module:
* description:
*/
public class MultiAdapter : BaseMultiAdapter<MultiListData>(ArrayList()) {
override fun onItemViewHolderCreated(viewHolder: HulkViewHolder, viewType: Int) {
when (viewType) {
MultiListData.type_1 -> {
DataBindingUtil.bind<ItemActivityMultiBinding>(viewHolder.itemView)
}
MultiListData.type_2 -> {
DataBindingUtil.bind<ItemActivityMulti2Binding>(viewHolder.itemView)
}
}
}
/**
* 布局
*/
override fun convert(helper: HulkViewHolder, item: MultiListData) {
when (item.itemType) {
MultiListData.type_1 -> {
val itemListBinding = helper.getBinding<ItemActivityMultiBinding>()
if (itemListBinding != null) {
itemListBinding.multiListData = item
}
}
MultiListData.type_2 -> {
val itemListBinding = helper.getBinding<ItemActivityMulti2Binding>()
if (itemListBinding != null) {
itemListBinding.multiListData = item
}
}
}
}
override fun addItemType() {
addItemType(MultiListData.type_1, R.layout.item_activity_multi)
addItemType(MultiListData.type_2, R.layout.item_activity_multi2)
}
} | 0 | null | 0 | 0 | 80f7976d327ec77acfdfce6d43848d7817ae87dd | 1,831 | AACHulk | Apache License 2.0 |
analysis/low-level-api-fir/testData/lazyAnnotations/contains/classWithRegularAnnotationsTrue.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} | // QUERY: contains: MyAnno
@MyAnno
class F<caret>oo
annotation class MyAnno | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 76 | kotlin | Apache License 2.0 |
api/src/main/kotlin/edu/wgu/osmt/config/AppConfig.kt | wgu-opensource | 371,168,832 | false | {"TypeScript": 870780, "Kotlin": 663910, "HTML": 153260, "JavaScript": 87226, "Shell": 42875, "HCL": 13700, "SCSS": 9144, "Java": 8284, "Smarty": 5908, "Dockerfile": 477} | package edu.wgu.osmt.config
import edu.wgu.osmt.db.DbConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.core.env.Environment
import org.springframework.stereotype.Component
@Component
@ConfigurationProperties(prefix = "app", ignoreInvalidFields = true)
class AppConfig(
@Value("\${app.baseDomain}")
val baseDomain: String,
@Value("\${app.baseUrl}")
val baseUrl: String,
@Value("\${app.defaultAuthorName}")
val defaultAuthorName: String,
@Value("\${app.defaultAuthorUri}")
val defaultAuthorUri: String,
@Value("\${app.defaultCreatorUri}")
val defaultCreatorUri: String,
@Value("\${app.frontendUrl}")
val frontendUrl: String,
@Value("\${app.loginSuccessRedirectUrl}")
val loginSuccessRedirectUrl: String,
@Value("\${app.userName:name}")
val userName: String,
@Value("\${app.userIdentifier:email}")
val userIdentifier: String,
@Value("\${app.allowPublicSearching}")
val allowPublicSearching: Boolean = true,
@Value("\${app.allowPublicLists}")
val allowPublicLists: Boolean = true,
@Value("\${app.enableRoles}")
val enableRoles: Boolean = false,
@Value("\${app.baseLineAuditLogIfEmpty}")
val baseLineAuditLogIfEmpty: Boolean,
@Value("\${app.rsd-context-url}")
val rsdContextUrl: String,
@Value("\${app.security.cors.allowedOrigins}")
val corsAllowedOrigins: String,
//This next values are WGU specific.
@Value("\${osmt.security.role.admin:Osmt_Admin}")
val roleAdmin: String,
@Value("\${osmt.security.role.curator:Osmt_Curator}")
val roleCurator: String,
@Value("\${osmt.security.role.view:Osmt_View}")
val roleView: String,
@Value("\${osmt.security.scope.read:SCOPE_osmt.read}")
val scopeRead: String
) {
@Autowired
lateinit var environment: Environment
@Autowired
lateinit var dbConfig: DbConfig
}
| 59 | TypeScript | 9 | 38 | c0453c9f678615a8da004b7cd4010c79585a028c | 2,068 | osmt | Apache License 2.0 |
codenamesServer/task/src/main/kotlin/jetbrains/kotlin/course/codenames/card/CardModel.kt | Alain-David-001 | 765,951,825 | false | {"Kotlin": 41204, "HTML": 22512, "JavaScript": 10504, "CSS": 7560, "Assembly": 24} | package jetbrains.kotlin.course.codenames.card
interface CardData
data class WordCardData(val word: String) : CardData
enum class CardState{
Front,
Back
}
data class Card(val data:CardData, val state: CardState)
| 0 | Kotlin | 0 | 0 | cbb0239f4c843f99f4c87c721ccb966bedddc2e0 | 224 | Kotlin-Onboarding-OOP | MIT License |
android-uitests/testSrc/com/android/tools/idea/tests/gui/projectstructure/ModuleVariantConflictTest.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 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 com.android.tools.idea.tests.gui.projectstructure
import com.android.tools.idea.gradle.variant.view.BuildVariantView
import com.android.tools.idea.tests.gui.framework.GuiTestRule
import com.android.tools.idea.tests.gui.framework.RunIn
import com.android.tools.idea.tests.gui.framework.TestGroup
import com.google.common.truth.Truth.assertThat
import com.intellij.testGuiFramework.framework.GuiTestRemoteRunner
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(GuiTestRemoteRunner::class)
class ModuleVariantConflictTest {
@Rule
@JvmField
val guiTest = GuiTestRule()
@RunIn(TestGroup.FAST_BAZEL)
@Test
@Throws(Exception::class)
fun displayConflict() {
val ide = guiTest.importModuleVariantConflictsApplication()
// app and app2 depends on different variants of mylibrary
assertThat(ide.buildVariantsWindow.jTableFixture.contents()).isEqualTo(arrayOf(
arrayOf("Module: 'SimpleVariantConflictApp.app'", "flv1Debug (default)"),
arrayOf("Module: 'SimpleVariantConflictApp.app2'", "flv2Debug (default)"),
arrayOf("Module: 'SimpleVariantConflictApp.mylibrary'", "flv1Debug (default)")))
ide.buildVariantsWindow.getModuleCell("SimpleVariantConflictApp.app").background().requireNotEqualTo(BuildVariantView.CONFLICT_CELL_BACKGROUND)
ide.buildVariantsWindow.getModuleCell("SimpleVariantConflictApp.app2").background().requireEqualTo(BuildVariantView.CONFLICT_CELL_BACKGROUND)
// Resolve app2 conflict by changing the variant of mylibrary to match app2
ide.buildVariantsWindow.selectVariantForModule("SimpleVariantConflictApp.mylibrary", "flv2Debug")
guiTest.waitForBackgroundTasks()
ide.buildVariantsWindow.getModuleCell("SimpleVariantConflictApp.app").background().requireEqualTo(BuildVariantView.CONFLICT_CELL_BACKGROUND)
ide.buildVariantsWindow.getModuleCell("SimpleVariantConflictApp.app2").background().requireNotEqualTo(BuildVariantView.CONFLICT_CELL_BACKGROUND)
}
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 2,601 | android | Apache License 2.0 |
app/src/main/java/com/cocktailbar/presentation/cocktails/CocktailEditRootScreen.kt | olegaches | 680,145,725 | false | {"Kotlin": 98906} | package com.cocktailbar.presentation.cocktails
import androidx.compose.runtime.Composable
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@Composable
fun CocktailEditRootScreen(cocktailEditRootComponent: ICocktailEditRootComponent) {
val childSlot = cocktailEditRootComponent.childSlot.collectAsStateWithLifecycle().value
CocktailEditScreen(cocktailEditComponent = cocktailEditRootComponent.cocktailEditComponent)
childSlot.child?.instance?.let { instance ->
when (instance) {
is ICocktailEditRootComponent.SlotChild.CocktailIngredient -> {
IngredientDialog(ingredientDialogComponent = instance.component)
}
}
}
} | 0 | Kotlin | 0 | 0 | b6eab221523ed3330099f5445f140848cfe2cf06 | 701 | cocktail-recipes | Apache License 2.0 |
Chapter-1/SampleProject/app/src/main/java/com/nanamare/mac/sample/ui/MainActivity.kt | Nanamare | 230,109,850 | false | null | package com.nanamare.mac.sample.ui
import android.app.ProgressDialog
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.nanamare.mac.sample.R
import com.nanamare.mac.sample.api.DisposableManager
import com.nanamare.mac.sample.api.upbit.UpBitServiceManager
import io.reactivex.android.schedulers.AndroidSchedulers
class MainActivity : AppCompatActivity() {
companion object {
const val KET_MARKET_LIST = "key_market_list"
const val PROGRESS_DIALOG_FRAGMENT = "progress_dialog_fragment"
}
private lateinit var disposableManager: DisposableManager
private lateinit var dialog: ProgressDialogFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dialog = ProgressDialogFragment()
dialog.show(supportFragmentManager, PROGRESS_DIALOG_FRAGMENT)
disposableManager = DisposableManager()
disposableManager.add(
UpBitServiceManager.getAllMarketList()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
dialog.dismiss()
val marketMap: LinkedHashMap<String, List<String>> = LinkedHashMap()
val marketList = listOf<String>().toMutableList()
it.body()?.map { marketModel ->
marketModel.market!!.split("-")[0].let { market ->
marketList.add(marketModel.market)
marketMap.put(market, marketList)
}
}
val bundle = Bundle().apply {
putString(KET_MARKET_LIST, Gson().toJson(marketMap))
}
goToFragment(MarketListFragment::class.java, bundle)
}, {
dialog.dismiss()
})
)
}
private fun goToFragment(cls: Class<*>, args: Bundle?) {
try {
val fragment = cls.newInstance() as Fragment
fragment.arguments = args
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction().replace(R.id.fl_content, fragment).commit()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onDestroy() {
disposableManager.dispose()
super.onDestroy()
}
} | 0 | Kotlin | 1 | 18 | 065feb0c017ce4ebacfc4b23bca101532b700bac | 2,527 | android_architecture | MIT License |
app/src/main/java/com/bett/nqnotes/activities/MainActivity.kt | betranthanh | 104,788,203 | false | null | package com.bett.nqnotes.activities
import android.content.Intent
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import butterknife.BindView
import butterknife.OnClick
import com.bett.nqnotes.R
import com.bett.nqnotes.adapters.NotesAdapter
import com.bett.nqnotes.bus.NoteEvent
import com.bett.nqnotes.models.NoteDto
import com.bett.nqnotes.realm.NotesRealmManager
import com.bett.nqnotes.utils.Constants
import com.squareup.otto.Bus
import com.squareup.otto.Subscribe
import io.reactivex.disposables.Disposable
import javax.inject.Inject
class MainActivity : BaseActivity() {
@LayoutRes
override fun getLayoutResId(): Int {
return R.layout.activity_main
}
@BindView(R.id.recyclerView) lateinit var recyclerView: RecyclerView
private val adapter = NotesAdapter()
@Inject lateinit var notesRealmManager: NotesRealmManager
@Inject lateinit var bus: Bus
private var subscrible: Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appComponent().inject(this);
bus.register(this)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView.layoutManager = layoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.adapter = adapter
adapter.items = notesRealmManager.findAll()
adapter.notifyDataSetChanged()
subscrible = adapter.clickEvent.subscribe {
var intent = Intent(this, CreateNoteActivity::class.java)
intent.putExtra(Constants.INTENT_KEY_NOTE_ID, it.id)
startActivity(intent)
}
}
override fun onDestroy() {
super.onDestroy()
subscrible?.dispose()
}
@OnClick(R.id.btnAddNew)
fun onClickBtnAddNew() {
val intent = Intent(this, CreateNoteActivity::class.java)
intent.putExtra(Constants.INTENT_KEY_NOTE_ID, -1L)
startActivity(intent)
}
@OnClick(R.id.btnInfo)
fun onClickBtnInfo() {
val intent = Intent(this, AboutActivity::class.java)
startActivity(intent)
}
@Subscribe
fun onTodoEvent(event: NoteEvent) {
adapter.items = notesRealmManager.findAll()
adapter.notifyDataSetChanged()
}
}
| 0 | Kotlin | 10 | 29 | fd867d353448b363c22df8a5130b632ea34ce6ad | 2,451 | android-kotlin-sample-note | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/PlateUtensils.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.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.straight.Icons
public val Icons.Outline.PlateUtensils: ImageVector
get() {
if (_plateUtensils != null) {
return _plateUtensils!!
}
_plateUtensils = Builder(name = "PlateUtensils", defaultWidth = 24.0.dp, defaultHeight =
24.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) {
moveToRelative(24.0f, 0.0f)
verticalLineToRelative(9.0f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(12.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-12.0f)
horizontalLineToRelative(-1.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
lineTo(14.0f, 0.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(9.0f)
curveToRelative(0.0f, 0.551f, 0.449f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(1.0f)
lineTo(18.0f, 0.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(10.0f)
horizontalLineToRelative(1.0f)
curveToRelative(0.551f, 0.0f, 1.0f, -0.449f, 1.0f, -1.0f)
lineTo(22.0f, 0.0f)
horizontalLineToRelative(2.0f)
close()
moveTo(2.0f, 12.0f)
curveTo(2.0f, 6.486f, 6.486f, 2.0f, 12.0f, 2.0f)
lineTo(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)
curveToRelative(1.404f, 0.0f, 2.747f, -0.255f, 4.0f, -0.7f)
verticalLineToRelative(-2.141f)
curveToRelative(-1.226f, 0.538f, -2.578f, 0.841f, -4.0f, 0.841f)
curveToRelative(-5.514f, 0.0f, -10.0f, -4.486f, -10.0f, -10.0f)
close()
moveTo(6.0f, 12.0f)
curveToRelative(0.0f, -3.309f, 2.691f, -6.0f, 6.0f, -6.0f)
verticalLineToRelative(-2.0f)
curveToRelative(-4.411f, 0.0f, -8.0f, 3.589f, -8.0f, 8.0f)
reflectiveCurveToRelative(3.589f, 8.0f, 8.0f, 8.0f)
curveToRelative(1.458f, 0.0f, 2.822f, -0.398f, 4.0f, -1.082f)
verticalLineToRelative(-2.458f)
curveToRelative(-1.063f, 0.954f, -2.462f, 1.54f, -4.0f, 1.54f)
curveToRelative(-3.309f, 0.0f, -6.0f, -2.691f, -6.0f, -6.0f)
close()
}
}
.build()
return _plateUtensils!!
}
private var _plateUtensils: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,514 | icons | MIT License |
edge_to_edge_preview_lib/src/main/java/de/drick/compose/edgetoedgepreviewlib/navigation_bar.kt | timo-drick | 828,494,878 | false | null | package de.drick.compose.edgetoedgepreviewlib
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.filled.Rectangle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Preview(name = "Navigation bar",
device = "id:pixel_8"
)
@Composable
private fun PreviewNavigationBar() {
NavigationBar(
size = 50.dp,
navMode = NavigationMode.ThreeButton
)
}
@Composable
fun NavigationBar(
size: Dp,
modifier: Modifier = Modifier,
isVertical: Boolean = false,
isDarkMode: Boolean = true,
navMode: NavigationMode = NavigationMode.ThreeButton,
alpha: Float = 0.5f,
) {
val contentColor = if (isDarkMode) Color.LightGray else Color.DarkGray
val backgroundColor = if (isDarkMode)
Color.Black.copy(alpha = alpha)
else
Color.White.copy(alpha = alpha)
val iconSize = 32.dp
when {
navMode == NavigationMode.Gesture -> {
Row(
modifier = modifier.height(size).fillMaxWidth().padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(Modifier.weight(1f))
Spacer(
Modifier
.background(color = contentColor, shape = RoundedCornerShape(4.dp))
.width(100.dp)
.height(6.dp)
)
Spacer(Modifier.weight(1f))
}
}
isVertical -> {
Column(
modifier = modifier
.width(size)
.fillMaxHeight()
.background(backgroundColor)
.padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(Modifier.weight(1f))
Image(
modifier = Modifier.size(size),
imageVector = Icons.AutoMirrored.Default.ArrowBack,
contentDescription = "Back",
colorFilter = ColorFilter.tint(contentColor)
)
Spacer(Modifier.weight(1f))
Image(
modifier = Modifier.size(iconSize),
imageVector = Icons.Default.Circle,
contentDescription = "Home",
colorFilter = ColorFilter.tint(contentColor)
)
Spacer(Modifier.weight(1f))
Image(
modifier = Modifier.size(iconSize),
imageVector = Icons.Default.Rectangle,
contentDescription = "History",
colorFilter = ColorFilter.tint(contentColor)
)
Spacer(Modifier.weight(1f))
}
}
else -> {
Row(
modifier = modifier
.height(size)
.fillMaxWidth()
.background(backgroundColor)
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(Modifier.weight(1f))
Image(
modifier = Modifier.size(iconSize),
imageVector = Icons.Default.Rectangle,
contentDescription = "History",
colorFilter = ColorFilter.tint(contentColor)
)
Spacer(Modifier.weight(1f))
Image(
modifier = Modifier.size(iconSize),
imageVector = Icons.Default.Circle,
contentDescription = "Home",
colorFilter = ColorFilter.tint(contentColor)
)
Spacer(Modifier.weight(1f))
Image(
modifier = Modifier.size(iconSize),
imageVector = Icons.AutoMirrored.Default.ArrowBack,
contentDescription = "Back",
colorFilter = ColorFilter.tint(contentColor)
)
Spacer(Modifier.weight(1f))
}
}
}
}
| 2 | null | 0 | 7 | f0f8953dba0653afd093602fbc79cb41eea9ea6c | 5,121 | compose_edge_to_edge_preview | The Unlicense |
app/src/main/java/com/ieeevit/gakko/ui/home/homehost/HomeHostViewModelFactory.kt | VibhorChinda | 279,553,228 | true | {"Kotlin": 218578} | package com.ieeevit.gakko.ui.home.homehost
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.ieeevit.gakko.data.repository.ListenerRepo
@Suppress("UNCHECKED_CAST")
class HomeHostViewModelFactory(
private val listenerRepo: ListenerRepo
): ViewModelProvider.NewInstanceFactory(){
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return HomeHostViewModel(listenerRepo) as T
}
} | 0 | null | 0 | 3 | bd2fa42693e81ff464d268cc88b629dd7a66cd8f | 453 | Gakko | MIT License |
src/day06/Day06.kt | JakubMosakowski | 572,993,890 | false | {"Kotlin": 66633} | package day06
import readInput
/**
* The preparations are finally complete;
* you and the Elves leave camp on foot and begin to make your way toward the star fruit grove.
*
* As you move through the dense undergrowth, one of the Elves gives you a handheld device.
* He says that it has many fancy features, but the most important one to set up right now is the communication system.
*
* However, because he's heard you have significant experience dealing with signal-based systems,
* he convinced the other Elves that it would be okay to give you their one malfunctioning device
* - surely you'll have no problem fixing it.
*
* As if inspired by comedic timing, the device emits a few colorful sparks.
*
* To be able to communicate with the Elves, the device needs to lock on to their signal.
* The signal is a series of seemingly-random characters that the device receives one at a time.
*
* To fix the communication system,
* you need to add a subroutine to the device that detects a start-of-packet marker in the datastream.
* In the protocol being used by the Elves, the start of a packet is indicated by a sequence of four characters that are all different.
*
* The device will send your subroutine a datastream buffer (your puzzle input);
* your subroutine needs to identify the first position where the four most recently received characters were all different.
* Specifically,
* it needs to report the number of characters from the beginning of the buffer to the end of the first such four-character marker.
*
* For example, suppose you receive the following datastream buffer:
*
* mjqjpqmgbljsphdztnvjfqwrcgsmlb
* After the first three characters (mjq) have been received,
* there haven't been enough characters received yet to find the marker.
* The first time a marker could occur is after the fourth character is received, making the most recent four characters mjqj. Because j is repeated, this isn't a marker.
*
* The first time a marker appears is after the seventh character arrives. Once it does, the last four characters received are jpqm, which are all different. In this case, your subroutine should report the value 7, because the first start-of-packet marker is complete after 7 characters have been processed.
*
* Here are a few more examples:
*
* bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 5
* nppdvjthqldpwncqszvftbrmjlhg: first marker after character 6
* nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 10
* zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 11
* How many characters need to be processed before the first start-of-packet marker is detected?
*
* PART 2:
* Your device's communication system is correctly detecting packets, but still isn't working.
* It looks like it also needs to look for messages.
*
* A start-of-message marker is just like a start-of-packet marker, except it consists of 14 distinct characters rather than 4.
*
* Here are the first positions of start-of-message markers for all of the above examples:
*
* mjqjpqmgbljsphdztnvjfqwrcgsmlb: first marker after character 19
* bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 23
* nppdvjthqldpwncqszvftbrmjlhg: first marker after character 23
* nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 29
* zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 26
* How many characters need to be processed before the first start-of-message marker is detected?
*/
private fun main() {
fun part1(input: List<String>): Int =
input.first().findIndex(FIRST_REQUESTED_MARKER_SIZE)
fun part2(input: List<String>): Int =
input.first().findIndex(SECOND_REQUESTED_MARKER_SIZE)
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
private fun String.findIndex(requestedMarkerSize: Int): Int {
val currentMarker = mutableListOf<Char>()
forEachIndexed { index, char ->
if (currentMarker.toCharArray().distinct().size == requestedMarkerSize) {
return index
}
currentMarker += char
if (currentMarker.size > requestedMarkerSize)
currentMarker.removeAt(0)
}
return NOT_FOUND
}
private const val FIRST_REQUESTED_MARKER_SIZE = 4
private const val SECOND_REQUESTED_MARKER_SIZE = 14
private const val NOT_FOUND = -1
| 0 | Kotlin | 0 | 0 | f6e9a0b6c2b66c28f052d461c79ad4f427dbdfc8 | 4,480 | advent-of-code-2022 | Apache License 2.0 |
js/js.translator/testData/api/stdlib/jquery.kt | jordanrjames | 271,690,591 | true | {"Markdown": 67, "Gradle": 699, "Gradle Kotlin DSL": 481, "Java Properties": 14, "Shell": 10, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 12, "Java": 6516, "Kotlin": 57855, "Proguard": 12, "XML": 1590, "Text": 11485, "INI": 174, "JavaScript": 265, "JAR Manifest": 2, "Roff": 212, "Roff Manpage": 38, "AsciiDoc": 1, "HTML": 484, "SVG": 33, "Groovy": 33, "JSON": 156, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 8, "Ant Build System": 50, "Graphviz (DOT)": 65, "C": 1, "Ruby": 3, "Objective-C": 4, "OpenStep Property List": 5, "Swift": 7, "Scala": 1, "YAML": 14} | package jquery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") @kotlin.js.JsName(name = "$") public external fun jq(): jquery.JQuery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") @kotlin.js.JsName(name = "$") public external fun jq(/*0*/ callback: () -> kotlin.Unit): jquery.JQuery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") @kotlin.js.JsName(name = "$") public external fun jq(/*0*/ obj: jquery.JQuery): jquery.JQuery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") @kotlin.js.JsName(name = "$") public external fun jq(/*0*/ selector: kotlin.String): jquery.JQuery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") @kotlin.js.JsName(name = "$") public external fun jq(/*0*/ selector: kotlin.String, /*1*/ context: org.w3c.dom.Element): jquery.JQuery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") @kotlin.js.JsName(name = "$") public external fun jq(/*0*/ el: org.w3c.dom.Element): jquery.JQuery
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") public final external class JQuery {
/*primary*/ public constructor JQuery()
public final fun addClass(/*0*/ f: (kotlin.Int, kotlin.String) -> kotlin.String): jquery.JQuery
public final fun addClass(/*0*/ className: kotlin.String): jquery.JQuery
public final fun append(/*0*/ str: kotlin.String): jquery.JQuery
public final fun attr(/*0*/ attrName: kotlin.String): kotlin.String
public final fun attr(/*0*/ attrName: kotlin.String, /*1*/ value: kotlin.String): jquery.JQuery
public final fun change(/*0*/ handler: () -> kotlin.Unit): jquery.JQuery
public final fun click(): jquery.JQuery
public final fun click(/*0*/ handler: (jquery.MouseClickEvent) -> kotlin.Unit): jquery.JQuery
public final fun dblclick(/*0*/ handler: (jquery.MouseClickEvent) -> kotlin.Unit): jquery.JQuery
public final fun hasClass(/*0*/ className: kotlin.String): kotlin.Boolean
public final fun height(): kotlin.Number
public final fun hover(/*0*/ handlerInOut: () -> kotlin.Unit): jquery.JQuery
public final fun hover(/*0*/ handlerIn: () -> kotlin.Unit, /*1*/ handlerOut: () -> kotlin.Unit): jquery.JQuery
public final fun html(): kotlin.String
public final fun html(/*0*/ f: (kotlin.Int, kotlin.String) -> kotlin.String): jquery.JQuery
public final fun html(/*0*/ s: kotlin.String): jquery.JQuery
public final fun load(/*0*/ handler: () -> kotlin.Unit): jquery.JQuery
public final fun mousedown(/*0*/ handler: (jquery.MouseEvent) -> kotlin.Unit): jquery.JQuery
public final fun mousemove(/*0*/ handler: (jquery.MouseEvent) -> kotlin.Unit): jquery.JQuery
public final fun mouseup(/*0*/ handler: (jquery.MouseEvent) -> kotlin.Unit): jquery.JQuery
public final fun next(): jquery.JQuery
public final fun parent(): jquery.JQuery
public final fun ready(/*0*/ handler: () -> kotlin.Unit): jquery.JQuery
public final fun removeClass(/*0*/ className: kotlin.String): jquery.JQuery
public final fun slideUp(): jquery.JQuery
public final fun text(/*0*/ text: kotlin.String): jquery.JQuery
public final fun `val`(): kotlin.String?
public final fun width(): kotlin.Number
}
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") public final external class MouseClickEvent : jquery.MouseEvent {
/*primary*/ public constructor MouseClickEvent()
public final val which: kotlin.Int
public final fun <get-which>(): kotlin.Int
}
@kotlin.Deprecated(message = "Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.") public open external class MouseEvent {
/*primary*/ public constructor MouseEvent()
public final val pageX: kotlin.Double
public final fun <get-pageX>(): kotlin.Double
public final val pageY: kotlin.Double
public final fun <get-pageY>(): kotlin.Double
public final fun isDefaultPrevented(): kotlin.Boolean
public final fun preventDefault(): kotlin.Unit
} | 0 | null | 0 | 1 | 2bf31ae3c302278dc9e8c5fad75f2fc7700552d3 | 4,545 | kotlin | Apache License 2.0 |
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/fundamentals/2_coroutines.kt | Naszi | 788,361,252 | false | {"Kotlin": 207516} | package com.lukaslechner.coroutineusecasesonandroid.playground.fundamentals
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.runBlocking
/**
* Coroutine: A coroutine is a generalization of a subroutine (routine)
* that can pause its execution at certain points and allow other code
* to run before it resumes. This allows for cooperative multitasking,
* where different parts of a program can run concurrently without requiring
* separate threads or processes. Coroutines can yield control back to the caller,
* and the caller can later resume the coroutine from where it left off.
* */
fun main() = runBlocking {
println("main starts")
joinAll(
async { coroutine(1, 500) },
async { coroutine(2, 300) }
)
println("main ends")
}
suspend fun coroutine(number: Int, delay: Long) {
println("Coroutine $number starts work")
delay(delay)
println("Coroutine $number has finished")
} | 0 | Kotlin | 0 | 0 | 56b4be5a81cf86df262cc775bf46868cd40ad0fe | 1,005 | coroutine-and-flow-tutorial- | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/BinaryGapStrategy.kt | ashtanko | 203,993,092 | false | {"Kotlin": 7199469, "Shell": 1168, "Makefile": 1135} | /*
* Copyright 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 dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.annotations.Iterative
import dev.shtanko.algorithms.annotations.OnePass
import dev.shtanko.algorithms.annotations.level.Easy
private const val MAX_SIZE = 32
/**
* 868. Binary Gap
* @see <a href="https://leetcode.com/problems/binary-gap/">Source</a>
*/
@Easy("https://leetcode.com/problems/binary-gap")
fun interface BinaryGap {
operator fun invoke(num: Int): Int
}
/**
* Approach 1: Store Indexes
* Time Complexity: O(log N).
* Space Complexity: O(log N).
*/
@Iterative
class BGStoreIndexes : BinaryGap {
override fun invoke(num: Int): Int {
val indexes = IntArray(MAX_SIZE)
var indexCount = 0
for (i in 0 until MAX_SIZE) {
if (num shr i and 1 != 0) {
indexes[indexCount++] = i
}
}
var maxGap = 0
for (i in 0 until indexCount - 1) maxGap = maxGap.coerceAtLeast(indexes[i + 1] - indexes[i])
return maxGap
}
}
/**
* Approach 2: One Pass
* Time Complexity: O(log N).
* Space Complexity: O(1).
*/
@OnePass
class BGOnePass : BinaryGap {
override fun invoke(num: Int): Int {
var last = -1
var ans = 0
for (i in 0 until MAX_SIZE) if (num shr i and 1 > 0) {
if (last >= 0) ans = ans.coerceAtLeast(i - last)
last = i
}
return ans
}
}
class BGOther : BinaryGap {
override fun invoke(num: Int): Int {
var max = 0
var pos = 0
var lastPos = -1
var changed = num
while (changed != 0) {
pos++
if (changed and 1 == 1) {
if (lastPos != -1) {
max = max.coerceAtLeast(pos - lastPos)
}
lastPos = pos
}
changed = changed shr 1
}
return max
}
}
| 6 | Kotlin | 0 | 19 | dd8ee7dc420c608d4a46d5dc5a19b11e6d3c7b9d | 2,464 | kotlab | Apache License 2.0 |
common/src/main/kotlin/no/nav/tiltakspenger/objectmothers/BehandlingMother.kt | navikt | 487,246,438 | false | {"Kotlin": 908223, "Dockerfile": 495, "Shell": 216, "HTML": 45} | package no.nav.tiltakspenger.objectmothers
import no.nav.tiltakspenger.domene.behandling.BehandlingTilBeslutter
import no.nav.tiltakspenger.domene.behandling.BehandlingVilkårsvurdert
import no.nav.tiltakspenger.domene.behandling.Søknad
import no.nav.tiltakspenger.domene.behandling.Søknadsbehandling
import no.nav.tiltakspenger.domene.saksopplysning.Kilde
import no.nav.tiltakspenger.domene.saksopplysning.Saksopplysning
import no.nav.tiltakspenger.domene.saksopplysning.TypeSaksopplysning
import no.nav.tiltakspenger.domene.vilkår.Vilkår
import no.nav.tiltakspenger.felles.Periode
import no.nav.tiltakspenger.felles.SakId
import no.nav.tiltakspenger.felles.januar
import no.nav.tiltakspenger.felles.mars
import java.time.LocalDate
interface BehandlingMother {
fun behandling(
periode: Periode = Periode(1.januar(2023), 31.mars(2023)),
sakId: SakId = SakId.random(),
søknad: Søknad = ObjectMother.nySøknad(periode = periode),
): Søknadsbehandling.Opprettet {
return Søknadsbehandling.Opprettet.opprettBehandling(
sakId = sakId,
søknad = søknad,
)
}
fun saksopplysning(
fom: LocalDate = 1.januar(2023),
tom: LocalDate = 31.mars(2023),
kilde: Kilde = Kilde.SAKSB,
vilkår: Vilkår = Vilkår.AAP,
type: TypeSaksopplysning = TypeSaksopplysning.HAR_YTELSE,
saksbehandler: String? = null,
) =
Saksopplysning(
fom = fom,
tom = tom,
kilde = kilde,
vilkår = vilkår,
detaljer = "",
typeSaksopplysning = type,
saksbehandler = saksbehandler,
)
fun behandlingVilkårsvurdertInnvilget(
periode: Periode = Periode(1.januar(2023), 31.mars(2023)),
sakId: SakId = SakId.random(),
søknad: Søknad = ObjectMother.nySøknad(periode = periode),
): BehandlingVilkårsvurdert.Innvilget {
val behandling = vilkårViHenter().fold(behandling(periode, sakId, søknad)) { b: Søknadsbehandling, vilkår ->
b.leggTilSaksopplysning(
saksopplysning(
vilkår = vilkår,
type = TypeSaksopplysning.HAR_IKKE_YTELSE,
),
).behandling
} as BehandlingVilkårsvurdert
return behandling.vurderPåNytt() as BehandlingVilkårsvurdert.Innvilget
}
fun behandlingVilkårsvurdertAvslag(
periode: Periode = Periode(1.januar(2023), 31.mars(2023)),
sakId: SakId = SakId.random(),
søknad: Søknad = ObjectMother.nySøknad(periode = periode),
): BehandlingVilkårsvurdert.Avslag {
val behandling = behandlingVilkårsvurdertInnvilget().leggTilSaksopplysning(
saksopplysning(vilkår = Vilkår.KVP, type = TypeSaksopplysning.HAR_YTELSE),
).behandling as BehandlingVilkårsvurdert
return behandling.vurderPåNytt() as BehandlingVilkårsvurdert.Avslag
}
fun behandlingTilBeslutterInnvilget(): BehandlingTilBeslutter.Innvilget {
return behandlingVilkårsvurdertInnvilget().copy(
saksbehandler = "123",
).tilBeslutting()
}
fun behandlingTilBeslutterAvslag(): BehandlingTilBeslutter.Avslag {
return behandlingVilkårsvurdertAvslag().copy(
saksbehandler = "123",
).tilBeslutting()
}
fun vilkårViHenter() = listOf(
Vilkår.AAP,
Vilkår.DAGPENGER,
Vilkår.PLEIEPENGER_NÆRSTÅENDE,
Vilkår.PLEIEPENGER_SYKT_BARN,
Vilkår.FORELDREPENGER,
Vilkår.OPPLÆRINGSPENGER,
Vilkår.OMSORGSPENGER,
Vilkår.ALDER,
Vilkår.TILTAKSPENGER,
Vilkår.UFØRETRYGD,
Vilkår.SVANGERSKAPSPENGER,
)
}
| 2 | Kotlin | 0 | 2 | 36d727295e2168f80c6d7fe671b0a63865b1f34b | 3,709 | tiltakspenger-vedtak | MIT License |
harness/tests/src/main/kotlin/godot/tests/static/CallStaticTest.kt | utopia-rise | 289,462,532 | false | null | package godot.tests.static
import godot.DirAccess
import godot.Node
import godot.ProjectSettings
import godot.annotation.RegisterClass
import godot.annotation.RegisterFunction
import godot.core.Color
@RegisterClass
class CallStaticTest: Node() {
@RegisterFunction
fun testStaticCall(): Boolean {
return DirAccess.dirExistsAbsolute(ProjectSettings.globalizePath("res://scripts"))
}
}
| 63 | null | 44 | 634 | ac2a1bd5ea931725e2ed19eb5093dea171962e3f | 406 | godot-kotlin-jvm | MIT License |
androidApp/src/main/java/com/ramo/getride/android/ui/user/home/HomeScreen.kt | OmAr-Kader | 863,044,993 | false | {"Kotlin": 218461, "Swift": 189097} | package com.ramo.getride.android.ui.user.home
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ModalBottomSheetProperties
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SheetState
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberDrawerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberStandardBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLngBounds
import com.google.maps.android.compose.rememberCameraPositionState
import com.ramo.getride.android.global.base.Theme
import com.ramo.getride.android.global.base.outlinedTextFieldStyle
import com.ramo.getride.android.global.navigation.Screen
import com.ramo.getride.android.global.ui.LoadingScreen
import com.ramo.getride.android.global.ui.OnLaunchScreen
import com.ramo.getride.android.global.ui.RatingBar
import com.ramo.getride.android.global.ui.rememberTaxi
import com.ramo.getride.android.ui.common.BarMainScreen
import com.ramo.getride.android.ui.common.HomeUserDrawer
import com.ramo.getride.android.ui.common.MapData
import com.ramo.getride.android.ui.common.MapScreen
import com.ramo.getride.android.ui.common.defaultLocation
import com.ramo.getride.data.model.Ride
import com.ramo.getride.data.model.RideProposal
import com.ramo.getride.data.model.RideRequest
import com.ramo.getride.data.model.UserPref
import com.ramo.getride.global.base.AUTH_SCREEN_ROUTE
import com.ramo.getride.global.base.PREF_LAST_LATITUDE
import com.ramo.getride.global.base.PREF_LAST_LONGITUDE
import com.ramo.getride.global.util.loggerError
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.compose.koinInject
@Composable
fun HomeScreen(
userPref: UserPref,
findPreference: (String, (it: String?) -> Unit) -> Unit,
@Suppress("UNUSED_PARAMETER") navigateToScreen: suspend (Screen, String) -> Unit,
navigateHome: suspend (String) -> Unit,
viewModel: HomeViewModel = koinViewModel(),
theme: Theme = koinInject()
) {
val scope = rememberCoroutineScope()
val state by viewModel.uiState.collectAsState()
val sheetState = rememberBottomSheetScaffoldState(rememberStandardBottomSheetState(initialValue = SheetValue.Expanded), SnackbarHostState())
val sheetModalState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val drawerState = rememberDrawerState(androidx.compose.material3.DrawerValue.Closed)
val cameraPositionState = rememberCameraPositionState {
position = CameraPosition.fromLatLngZoom(state.mapData.currentLocation ?: defaultLocation, 15F) // Default position
}
val popUpSheet: () -> Unit = remember {
{
scope.launch { sheetState.bottomSheetState.show() }
}
}
val refreshScope: (MapData) -> Unit = remember {
{ mapData ->
scope.launch {
val bounds = LatLngBounds.Builder().also { boundsBuilder ->
listOf(mapData.startPoint, mapData.endPoint, mapData.currentLocation).forEach {
it?.let { it1 -> boundsBuilder.include(it1) }
}
}.build()
cameraPositionState.animate(CameraUpdateFactory.newLatLngBounds(bounds, 100))
}
}
}
OnLaunchScreen {
findPreference(PREF_LAST_LATITUDE) { latitude ->
findPreference(PREF_LAST_LONGITUDE) { longitude ->
latitude?.toDoubleOrNull()?.let { lat ->
longitude?.toDoubleOrNull()?.also { lng ->
scope.launch {
kotlinx.coroutines.coroutineScope {
cameraPositionState.position = CameraPosition.fromLatLngZoom(com.google.android.gms.maps.model.LatLng(lat, lng), 15F)
}
}
}
}
}
}
}
ModalNavigationDrawer(
drawerContent = {
HomeUserDrawer(theme) {
scope.launch {
drawerState.close()
}
viewModel.signOut({
scope.launch { navigateHome(AUTH_SCREEN_ROUTE) }
}) {
scope.launch {
sheetState.snackbarHostState.showSnackbar(message = "Failed")
}
}
}
LoadingScreen(isLoading = state.isProcess, theme = theme)
},
drawerState = drawerState,
gesturesEnabled = drawerState.isOpen
) {
BottomSheetScaffold(
scaffoldState = sheetState,
snackbarHost = {
SnackbarHost(sheetState.snackbarHostState) {
Snackbar(it, containerColor = theme.backDarkSec, contentColor = theme.textColor)
}
},
containerColor = theme.backDark,
contentColor = theme.textColor,
sheetDragHandle = {
RideSheetDragHandler(state.ride != null, theme)
},
sheetContent = {
state.ride?.also { ride ->
RideSheet(ride = ride, theme = theme, cancelRide = {
viewModel.cancelRideFromUser(ride = ride)
}, submitFeedback = {
viewModel.submitFeedback(ride.driverId, it)
}) {
viewModel.clearRide()
}
} ?: MapSheetUser(userId = userPref.id, viewModel = viewModel, state = state, refreshScope = refreshScope, theme = theme) { txt ->
scope.launch {
sheetState.snackbarHostState.showSnackbar(txt)
}
}
}
) { padding ->
BarMainScreen(userPref = userPref) {
scope.launch {
drawerState.open()
}
}
Column(modifier = Modifier.padding(padding)) {
Spacer(Modifier.height(60.dp))
MapScreen(
mapData = state.mapData,
cameraPositionState = cameraPositionState,
updateCurrentLocation = { location, update ->
viewModel.updateCurrentLocation(location) {
update()
viewModel.checkForActiveRide(userPref.id, popUpSheet, refreshScope)
}
},
theme = theme
) { start, end ->
viewModel.setMapMarks(startPoint = start, endPoint = end, invoke = refreshScope)
}
}
state.rideRequest?.also { rideRequest ->
RideRequestSheet(
sheetModalState,
rideRequest,
theme,
onDismissRequest = {
scope.launch { sheetModalState.expand() }
},
cancelRideRequest = {
state.rideRequest?.let { viewModel.cancelRideRequest(it) }
}
) { proposal ->
viewModel.acceptProposal(userId = userPref.id, rideRequest = rideRequest, proposal = proposal, invoke = popUpSheet) {
scope.launch {
sheetState.snackbarHostState.showSnackbar("Failed")
}
}
}
}
LoadingScreen(isLoading = state.isProcess, theme = theme)
}
}
}
@Composable
fun MapSheetUser(userId: Long, viewModel: HomeViewModel, state: HomeViewModel.State, refreshScope: (MapData) -> Unit, theme: Theme, snakeBar: (String) -> Unit) {
val focusManager = LocalFocusManager.current
val focusToRequester = remember { FocusRequester() }
Column(Modifier.padding(start = 20.dp, end = 20.dp)) {
Spacer(Modifier.height(5.dp))
Row(horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth()) {
Text(
text = state.mapData.durationDistance,
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 20.sp
)
if (state.fare != 0.0) {
Text(
text = "$${state.fare}",//Price:
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 20.sp
)
}
}
Spacer(Modifier.height(5.dp))
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = state.fromText,
onValueChange = viewModel::setFromText,
shape = RoundedCornerShape(12.dp),
placeholder = { Text(text = "From", fontSize = 14.sp) },
label = { Text(text = "Ride From", fontSize = 14.sp) },
singleLine = true,
colors = theme.outlinedTextFieldStyle(),
trailingIcon = {
if (state.fromText.isNotEmpty()) {
if (state.fromText == state.mapData.fromText) {
IconButton(onClick = viewModel::clearFromText) {
Icon(
imageVector = Icons.Default.Clear,
contentDescription = "Clear From text"
)
}
} else {
IconButton(onClick = {
viewModel.searchForLocationOfPlaceFrom(state.fromText)
focusManager.clearFocus()
}) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = "Search for From place"
)
}
}
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(
onSearch = {
viewModel.searchForLocationOfPlaceFrom(state.fromText)
focusManager.clearFocus()
}
)
)
if (state.locationsFrom.isNotEmpty()) {
DropdownMenu(
expanded = true,
onDismissRequest = viewModel::clearFromList,
modifier = Modifier.fillMaxWidth()
) {
state.locationsFrom.forEach { locationFrom ->
DropdownMenuItem(
text = { Text(locationFrom.title) },
onClick = {
viewModel.setFrom(locationFrom) { mapData ->
refreshScope(mapData)
}
focusManager.clearFocus() // Close keyboard and set text
}
)
}
}
}
Spacer(Modifier.height(5.dp))
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusToRequester),
value = state.toText,
onValueChange = viewModel::setToText,
shape = RoundedCornerShape(12.dp),
placeholder = { Text(text = "To", fontSize = 14.sp) },
label = { Text(text = "To", fontSize = 14.sp) },
singleLine = true,
colors = theme.outlinedTextFieldStyle(),
trailingIcon = {
if (state.toText.isNotEmpty()) {
if (state.toText == state.mapData.toText) {
IconButton(onClick = viewModel::clearToText) {
Icon(
imageVector = Icons.Default.Clear,
contentDescription = "Clear To text"
)
}
} else {
IconButton(onClick = {
viewModel.searchForLocationOfPlaceTo(state.toText)
focusManager.clearFocus()
}) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = "Search for To place"
)
}
}
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(
onSearch = {
viewModel.searchForLocationOfPlaceTo(state.toText)
focusManager.clearFocus()
}
)
)
if (state.locationsTo.isNotEmpty()) {
DropdownMenu(
expanded = true,
onDismissRequest = viewModel::clearToList,
modifier = Modifier.fillMaxWidth()
) {
state.locationsTo.forEach { locationTo ->
DropdownMenuItem(
text = { Text(locationTo.title) },
onClick = {
viewModel.setTo(locationTo) { mapData ->
refreshScope(mapData)
}
focusManager.clearFocus() // Close keyboard and set text
}
)
}
}
}
Spacer(Modifier.height(10.dp))
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier
.fillMaxWidth()
.padding()) {
Spacer(Modifier)
ExtendedFloatingActionButton(
text = { Text(text = "Get Ride", color = theme.textForPrimaryColor) },
onClick = {
if (state.mapData.startPoint != null && state.mapData.endPoint != null) {
if (userId != 0L) {
viewModel.pushRideRequest(userId = userId)
} else {
snakeBar("Something Wrong")
}
} else {
snakeBar("Pick destination, Please")
}
},
containerColor = theme.primary,
shape = RoundedCornerShape(15.dp),
expanded = state.mapData.startPoint != null && state.mapData.endPoint != null,
icon = {
Icon(
modifier = Modifier.size(30.dp),
imageVector = rememberTaxi(theme.textForPrimaryColor),
contentDescription = "Ride",
tint = theme.textForPrimaryColor
)
}
)
}
Spacer(Modifier.height(15.dp))
}
}
@Composable
fun RideSheet(ride: Ride, theme: Theme, cancelRide: () -> Unit, submitFeedback: (Float) -> Unit, clearRide: () -> Unit) {
val statusTitle: String = when (ride.status) {
0 -> { // To Update Status To 1
"${ride.driverName} is getting ready to go."
}
1 -> { // To Update Status To 2
"${ride.driverName} on way"
}
2 -> { // To Update Status To 3
"${ride.driverName} waiting for you"
}
3 -> { // To Update Status To 4
"Ride Started"
}
4 -> { // To Update Status To 4
"Give ${ride.driverName} feedback"
}
else -> "Canceled"
}
Column(
Modifier
.padding(start = 20.dp, end = 20.dp)
.fillMaxWidth()
.defaultMinSize(minHeight = 100.dp)
) {
Spacer(Modifier.height(5.dp))
Text(
text = statusTitle,
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 18.sp
)
Spacer(Modifier.height(10.dp))
Row(
Modifier
.fillMaxWidth()
.padding()
) {
Text(
text = ride.durationDistance,
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 16.sp
)
Spacer(Modifier)
Text(
text = "Fare: $${ride.fare}",
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 16.sp
)
Spacer(Modifier)
}
Spacer(Modifier.height(10.dp))
if (ride.status == 4) {
RatingBar(rating = 0F, modifier = Modifier.padding(), onRate = submitFeedback)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(),
horizontalArrangement = Arrangement.SpaceBetween
) {
if (ride.status != -2 && ride.status != -1 && ride.status != 3 && ride.status != 4) {
Button(
onClick = {
cancelRide()
},
colors = ButtonDefaults.buttonColors().copy(containerColor = Color.Red, contentColor = Color.Black)
) {
Text(
text = "Cancel Ride",
color = Color.Black
)
}
Spacer(Modifier.width(5.dp))
}
if (ride.status == 4) {
Spacer(Modifier)
Button(
onClick = clearRide,
colors = ButtonDefaults.buttonColors().copy(containerColor = Color.Green, contentColor = Color.Black),
contentPadding = PaddingValues(start = 30.dp, top = 7.dp, end = 30.dp, bottom = 7.dp)
) {
Text(
text = "Close",
color = Color.Black
)
}
}
}
Spacer(Modifier.height(5.dp))
}
}
@Composable
fun RideRequestSheet(
sheetModalState: SheetState,
rideRequest: RideRequest,
theme: Theme,
onDismissRequest: () -> Unit,
cancelRideRequest: () -> Unit,
acceptProposal: (RideProposal) -> Unit
) {
ModalBottomSheet(
onDismissRequest = onDismissRequest,
sheetState = sheetModalState,
properties = ModalBottomSheetProperties(shouldDismissOnBackPress = false),
containerColor = theme.backDark,
contentColor = theme.textColor,
dragHandle = {
Column(
Modifier
.fillMaxWidth()
.background(theme.backDark),
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(
modifier = Modifier
.padding(top = 22.dp),
color = theme.textGrayColor,
shape = MaterialTheme.shapes.extraLarge
) {
Box(
Modifier
.size(
width = 32.dp,
height = 4.0.dp
)
)
}
Text(
modifier = Modifier
.fillMaxWidth()
.padding(7.dp), text = "Waiting for Drivers", color = theme.textColor,
fontSize = 16.sp
)
Column(
modifier = Modifier
.fillMaxWidth()
.height(3.dp)
) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(3.dp),
trackColor = Color.Transparent,
color = theme.primary
)
}
Spacer(Modifier.height(5.dp))
}
}
) {
LazyColumn(
Modifier
.padding(start = 20.dp, end = 20.dp)
.fillMaxWidth()
.height(350.dp)) {
item {
Spacer(Modifier.height(5.dp))
Row(horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth()) {
Text(
text = rideRequest.durationDistance,
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 20.sp
)
if (rideRequest.fare != 0.0) {
Text(
text = "$${rideRequest.fare}",//Price:
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 20.sp
)
}
}
Spacer(Modifier.height(10.dp))
}
items(rideRequest.driverProposals) { proposal ->
loggerError("proposal", proposal.toString())
Column(Modifier.padding()) {
Row(
Modifier
.fillMaxWidth()
.padding()) {
Text(
text = proposal.driverName,
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 18.sp
)
Spacer(Modifier)
Text(
text = "Price: $${proposal.fare}",
color = theme.textColor, modifier = Modifier.padding(),
fontSize = 18.sp
)
Spacer(Modifier)
}
if (proposal.rate != 0F) {
Spacer(Modifier.height(5.dp))
RatingBar(rating = proposal.rate, starSize = 20.dp, modifier = Modifier.padding())
}
Spacer(Modifier.height(5.dp))
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier
.fillMaxWidth()
.padding()) {
Spacer(Modifier)
/*Button({
}, colors = ButtonDefaults.buttonColors().copy(containerColor = Color.Red, contentColor = Color.Black)) {
Text(
text = "Reject",
color = Color.Black
)
}*/
Button(
onClick = {
acceptProposal(proposal)
},
colors = ButtonDefaults.buttonColors().copy(containerColor = Color.Green, contentColor = Color.Black),
contentPadding = PaddingValues(start = 30.dp, top = 7.dp, end = 30.dp, bottom = 7.dp)
) {
Text(
text = "Accept",
color = Color.Black
)
}
}
}
Spacer(Modifier.height(10.dp))
}
}
Spacer(Modifier.height(10.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Spacer(Modifier)
ExtendedFloatingActionButton(
text = { Text(text = "Cancel Ride", color = theme.textForPrimaryColor) },
onClick = cancelRideRequest,
containerColor = theme.primary,
shape = RoundedCornerShape(35.dp),
expanded = true,
icon = {
}
)
}
}
}
@Composable
fun RideSheetDragHandler(isUserHaveRide: Boolean, theme: Theme) {
Column(
Modifier
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(
modifier = Modifier
.padding(top = 22.dp),
color = theme.textGrayColor,
shape = MaterialTheme.shapes.extraLarge
) {
Box(
Modifier
.size(
width = 32.dp,
height = 4.0.dp
)
)
}
if (isUserHaveRide) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(7.dp), text = "Ride Status", color = theme.textColor,
fontSize = 16.sp
)
}
Spacer(Modifier.height(10.dp))
}
}
| 0 | Kotlin | 0 | 0 | 710e3130a0718eb2c71558b3d6b8743a19869edc | 28,081 | GetRide | Apache License 2.0 |
eudi-wallet-oidc-android/src/main/java/com/ewc/eudi_wallet_oidc_android/services/issue/IssueService.kt | EWC-consortium | 749,764,479 | false | {"Kotlin": 225322} | package com.ewc.eudi_wallet_oidc_android.services.issue
import android.net.Uri
import android.util.Log
import com.ewc.eudi_wallet_oidc_android.models.AuthorisationServerWellKnownConfiguration
import com.ewc.eudi_wallet_oidc_android.models.AuthorizationDetails
import com.ewc.eudi_wallet_oidc_android.models.ClientMetaDataas
import com.ewc.eudi_wallet_oidc_android.models.CredentialDefinition
import com.ewc.eudi_wallet_oidc_android.models.CredentialOffer
import com.ewc.eudi_wallet_oidc_android.models.CredentialRequest
import com.ewc.eudi_wallet_oidc_android.models.CredentialTypeDefinition
import com.ewc.eudi_wallet_oidc_android.models.ErrorResponse
import com.ewc.eudi_wallet_oidc_android.models.IssuerWellKnownConfiguration
import com.ewc.eudi_wallet_oidc_android.models.Jwt
import com.ewc.eudi_wallet_oidc_android.models.ProofV3
import com.ewc.eudi_wallet_oidc_android.models.VpFormatsSupported
import com.ewc.eudi_wallet_oidc_android.models.WrappedCredentialResponse
import com.ewc.eudi_wallet_oidc_android.models.WrappedTokenResponse
import com.ewc.eudi_wallet_oidc_android.models.v1.CredentialOfferEbsiV1
import com.ewc.eudi_wallet_oidc_android.models.v1.CredentialOfferEwcV1
import com.ewc.eudi_wallet_oidc_android.models.v2.CredentialOfferEwcV2
import com.ewc.eudi_wallet_oidc_android.models.v2.DeferredCredentialRequestV2
import com.ewc.eudi_wallet_oidc_android.services.UriValidationFailed
import com.ewc.eudi_wallet_oidc_android.services.UrlUtils
import com.ewc.eudi_wallet_oidc_android.services.codeVerifier.CodeVerifierService
import com.ewc.eudi_wallet_oidc_android.services.network.ApiManager
import com.google.gson.Gson
import com.nimbusds.jose.JOSEObjectType
import com.nimbusds.jose.JWSAlgorithm
import com.nimbusds.jose.JWSHeader
import com.nimbusds.jose.crypto.ECDSASigner
import com.nimbusds.jose.crypto.Ed25519Signer
import com.nimbusds.jose.jwk.ECKey
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jose.jwk.OctetKeyPair
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Response
import java.util.Date
import java.util.UUID
class IssueService : IssueServiceInterface {
/**
* To process the credential offer request
*
* @param data - will accept the full data which is scanned from the QR
* code or deep link The data can contain credential offer or
* credential offer uri
* @return Credential Offer
*/
override suspend fun resolveCredentialOffer(data: String?): CredentialOffer? {
if (data.isNullOrBlank()) return null
try {
val uri = Uri.parse(data)
val credentialOfferUri = uri.getQueryParameter("credential_offer_uri")
UrlUtils.validateUri(credentialOfferUri)
if (!credentialOfferUri.isNullOrBlank()) {
val response =
ApiManager.api.getService()?.resolveCredentialOffer(credentialOfferUri)
return if (response?.isSuccessful == true) {
parseCredentialOffer(credentialOfferJson = response.body()?.string())
} else {
null
}
}
val credentialOfferString = uri.getQueryParameter("credential_offer")
if (!credentialOfferString.isNullOrBlank()) {
return Gson().fromJson(credentialOfferString, CredentialOffer::class.java)
}
return null
} catch (exc: UriValidationFailed) {
return null
}
}
private fun parseCredentialOffer(credentialOfferJson: String?): CredentialOffer? {
val gson = Gson()
val credentialOfferV2Response = try {
gson.fromJson(credentialOfferJson, CredentialOfferEwcV2::class.java)
} catch (e: Exception) {
null
}
if (credentialOfferV2Response?.credentialConfigurationIds == null) {
val credentialOfferEbsiV1Response = try {
gson.fromJson(credentialOfferJson, CredentialOfferEbsiV1::class.java)
} catch (e: Exception) {
null
}
return if (credentialOfferEbsiV1Response?.credentials == null) {
val credentialOfferEwcV1Response = try {
gson.fromJson(credentialOfferJson, CredentialOfferEwcV1::class.java)
} catch (e: Exception) {
null
}
if (credentialOfferEwcV1Response == null) {
null
} else {
CredentialOffer(ewcV1 = credentialOfferEwcV1Response)
}
} else {
credentialOfferEbsiV1Response?.let { CredentialOffer(ebsiV1 = it) }
}
} else {
return CredentialOffer(ewcV2 = credentialOfferV2Response)
}
}
/**
* To process the authorisation request The authorisation request is to
* grant access to the credential endpoint
*
* @param did - DID created for the issuance
* @param subJwk - for singing the requests
* @param credentialOffer - To build the authorisation request
* @param codeVerifier - to build the authorisation request
* @param authorisationEndPoint - to build the authorisation request
* @return String - short-lived authorisation code
*/
override suspend fun processAuthorisationRequest(
did: String?,
subJwk: JWK?,
credentialOffer: CredentialOffer?,
codeVerifier: String,
authConfig: AuthorisationServerWellKnownConfiguration?,
format: String?,
docType: String?,
issuerConfig: IssuerWellKnownConfiguration?
): String? {
val authorisationEndPoint =authConfig?.authorizationEndpoint
val responseType = "code"
val types = getTypesFromCredentialOffer(credentialOffer)
val scope = if (format == "mso_mdoc") {
"${types.firstOrNull() ?: ""} openid"
} else {
"openid"
}
val state = UUID.randomUUID().toString()
val clientId = did
val authorisationDetails = buildAuthorizationRequest(
credentialOffer = credentialOffer,
format = format,
doctype = docType,
issuerConfig = issuerConfig,
version = credentialOffer?.version
)
val redirectUri = "http://localhost:8080"
val nonce = UUID.randomUUID().toString()
val codeChallenge = CodeVerifierService().generateCodeChallenge(codeVerifier)
val codeChallengeMethod = "S256"
val clientMetadata = if (format == "mso_mdoc") "" else Gson().toJson(
ClientMetaDataas(
vpFormatsSupported = VpFormatsSupported(
jwtVp = Jwt(arrayListOf("ES256")), jwtVc = Jwt(arrayListOf("ES256"))
), responseTypesSupported = arrayListOf(
"vp_token", "id_token"
), authorizationEndpoint = redirectUri
)
)
var response: Response<HashMap<String, Any>>?=null
if (authConfig?.requirePushedAuthorizationRequests == true){
val parResponse = ApiManager.api.getService()?.processParAuthorisationRequest(
authConfig.pushedAuthorizationRequestEndpoint ?: "",
mapOf(
"response_type" to responseType,
"scope" to scope.trim(),
"state" to state,
"client_id" to (clientId ?: ""),
"authorization_details" to authorisationDetails,
"redirect_uri" to redirectUri,
"nonce" to nonce,
"code_challenge" to (codeChallenge ?: ""),
"code_challenge_method" to codeChallengeMethod,
"client_metadata" to clientMetadata,
"issuer_state" to (credentialOffer?.grants?.authorizationCode?.issuerState ?: "")
),
)
// Check if the PAR request was successful
parResponse?.code()
if (parResponse?.isSuccessful == true) {
// Extract requestUri from the PAR response
val requestUri = parResponse.body()?.requestUri ?: ""
// Second API call: processAuthorisationRequest
response = ApiManager.api.getService()?.processAuthorisationRequest(
authorisationEndPoint ?: "",
mapOf(
"client_id" to (clientId ?: ""),
"request_uri" to requestUri
)
)
}
}
else{
response = ApiManager.api.getService()?.processAuthorisationRequest(
authorisationEndPoint ?: "",
mapOf(
"response_type" to responseType,
"scope" to scope.trim(),
"state" to state,
"client_id" to (clientId ?: ""),
"authorization_details" to authorisationDetails,
"redirect_uri" to redirectUri,
"nonce" to nonce,
"code_challenge" to (codeChallenge ?: ""),
"code_challenge_method" to codeChallengeMethod,
"client_metadata" to clientMetadata,
"issuer_state" to (credentialOffer?.grants?.authorizationCode?.issuerState ?: "")
),
)
}
if (response?.code() == 502) {
throw Exception("Unexpected error. Please try again.")
}
val location: String? = if (response?.code() == 302) {
if (response.headers()["Location"]?.contains("error") == true || response.headers()["Location"]?.contains(
"error_description"
) == true
) {
response.headers()["Location"]
} else {
response.headers()["Location"]
}
} else {
null
}
return if (location != null && Uri.parse(location).getQueryParameter("error") != null) {
location
} else if (location != null && (Uri.parse(location).getQueryParameter("code") != null
|| Uri.parse(location).getQueryParameter("presentation_definition") != null
|| (Uri.parse(location).getQueryParameter("request_uri") != null &&
Uri.parse(location).getQueryParameter("response_type") == null &&
Uri.parse(location).getQueryParameter("state") == null))
) {
location
} else {
processAuthorisationRequestUsingIdToken(
did = did,
authorisationEndPoint = authorisationEndPoint,
location = location,
subJwk = subJwk
)
}
}
private suspend fun processAuthorisationRequestUsingIdToken(
did: String?,
authorisationEndPoint: String?,
location: String?,
subJwk: JWK?
): String? {
val claimsSet =
JWTClaimsSet.Builder()
.issueTime(Date())
.expirationTime(Date(Date().time + 60000))
.issuer(did)
.subject(did)
.audience(authorisationEndPoint)
.claim("nonce", Uri.parse(location).getQueryParameter("nonce"))
.build()
// Create JWT for ES256K alg
val jwsHeader =
JWSHeader.Builder(if (subJwk is OctetKeyPair) JWSAlgorithm.EdDSA else JWSAlgorithm.ES256)
.type(JOSEObjectType.JWT)
.keyID("$did#${did?.replace("did:key:", "")}")
.build()
val jwt = SignedJWT(
jwsHeader, claimsSet
)
// Sign with private EC key
jwt.sign(
if (subJwk is OctetKeyPair) Ed25519Signer(subJwk as OctetKeyPair) else ECDSASigner(
subJwk as ECKey
)
)
val response = ApiManager.api.getService()?.sendIdTokenForCode(
url = Uri.parse(location).getQueryParameter("redirect_uri") ?: "",
idToken = jwt.serialize(),
state = Uri.parse(location).getQueryParameter("state") ?: "",
contentType = "application/x-www-form-urlencoded"
)
return if (response?.code() == 302) {
response.headers()["Location"]
} else {
null
}
}
private fun buildAuthorizationRequest(
credentialOffer: CredentialOffer?,
format: String?,
doctype: String?
): String {
val gson = Gson()
var credentialDefinitionNeeded = false
try {
if (credentialOffer?.credentials?.get(0)?.trustFramework == null)
credentialDefinitionNeeded = true
} catch (e: Exception) {
credentialDefinitionNeeded = true
}
if (format == "mso_mdoc" && doctype != null) {
return gson.toJson(
arrayListOf(
AuthorizationDetails(
format = format,
doctype = doctype,
locations = arrayListOf(credentialOffer?.credentialIssuer ?: "")
)
)
)
} else {
if (credentialDefinitionNeeded) {
return gson.toJson(
arrayListOf(
AuthorizationDetails(
format = "jwt_vc_json",
locations = arrayListOf(credentialOffer?.credentialIssuer ?: ""),
credentialDefinition = CredentialTypeDefinition(
type = getTypesFromCredentialOffer(credentialOffer)
)
)
)
)
} else {
return gson.toJson(
arrayListOf(
AuthorizationDetails(
format = "jwt_vc",
types = getTypesFromCredentialOffer(credentialOffer),
locations = arrayListOf(credentialOffer?.credentialIssuer ?: "")
)
)
)
}
}
}
private fun buildAuthorizationRequest(
credentialOffer: CredentialOffer?,
format: String?,
doctype: String?,
version: Int? = 2,
issuerConfig: IssuerWellKnownConfiguration?
): String {
val credentialConfigurationId = credentialOffer?.credentials?.get(0)?.types?.firstOrNull()
val gson = Gson()
if (format == "mso_mdoc" && doctype != null) {
return gson.toJson(
arrayListOf(
AuthorizationDetails(
format = format,
doctype = doctype,
credentialConfigurationId = credentialConfigurationId,
locations = arrayListOf(credentialOffer?.credentialIssuer ?: "")
)
)
)
} else {
when (version) {
1 -> {
return buildAuthorizationRequest(
credentialOffer = credentialOffer,
format = format,
doctype = doctype
)
}
else -> {
return gson.toJson(
arrayListOf(
AuthorizationDetails(
format = format,
credentialConfigurationId = credentialConfigurationId,
credentialDefinition = if (format?.contains("sd-jwt") == true) null else CredentialTypeDefinition(
type = getTypesFromIssuerConfig(
issuerConfig = issuerConfig,
type = credentialConfigurationId,
version = version
) as ArrayList<String>
),
vct = if (format?.contains("sd-jwt") == true) getTypesFromIssuerConfig(
issuerConfig = issuerConfig,
type = credentialConfigurationId,
version = version
) as String else null
)
)
)
}
}
}
}
/**
* To process the token,
*
* @param did
* @param tokenEndPoint
* @param code - If the credential offer is pre authorised, then use the
* pre authorised code from the credential offer else use the code from
* the previous function - processAuthorisationRequest
* @param codeVerifier - use the same code verifier used for
* processAuthorisationRequest
* @param isPreAuthorisedCodeFlow - boolean value to notify its a pre
* authorised request if pre-authorized_code is present
* @param userPin - optional value, if the user_pin_required is true PIN
* will be provided by the user
* @return Token response
*/
override suspend fun processTokenRequest(
did: String?,
tokenEndPoint: String?,
code: String?,
codeVerifier: String?,
isPreAuthorisedCodeFlow: Boolean?,
userPin: String?,
version: Int?
): WrappedTokenResponse? {
val response = ApiManager.api.getService()?.getAccessTokenFromCode(
tokenEndPoint ?: "",
if (isPreAuthorisedCodeFlow == true) mapOf(
"grant_type" to "urn:ietf:params:oauth:grant-type:pre-authorized_code",
"pre-authorized_code" to (code ?: ""),
if(version == 1){
"user_pin" to (userPin ?: "")
}else{
"tx_code" to (userPin ?: "")
}
)
else mapOf(
"grant_type" to "authorization_code",
"code" to (code ?: ""),
"client_id" to (did ?: ""),
"code_verifier" to (codeVerifier ?: "")
),
)
val tokenResponse = when {
response?.isSuccessful == true -> {
WrappedTokenResponse(
tokenResponse = response.body()
)
}
(response?.code() ?: 0) >= 400 -> {
try {
WrappedTokenResponse(
errorResponse = processError(response?.errorBody()?.string())
)
} catch (e: Exception) {
null
}
}
else -> {
null
}
}
return tokenResponse
}
/**
* To process the credential, credentials can be issued in two ways,
* intime and deferred
*
* If its intime, then we will receive the credential as the response
* If its deferred, then we will get he acceptance token and use this acceptance token to call deferred
*
* @param did
* @param subJwk
* @param nonce
* @param credentialOffer
* @param issuerConfig
* @param accessToken
* @param format
*
* @return credential response
*/
override suspend fun processCredentialRequest(
did: String?,
subJwk: JWK?,
nonce: String?,
credentialOffer: CredentialOffer?,
issuerConfig: IssuerWellKnownConfiguration?,
accessToken: String?,
format: String
): WrappedCredentialResponse? {
val doctype = if (format == "mso_mdoc") "org.iso.18013.5.1.mDL" else null
// Add claims
val claimsSet = JWTClaimsSet
.Builder()
.issueTime(Date())
.expirationTime(Date(Date().time + 86400))
.issuer(did)
.audience(issuerConfig?.credentialIssuer ?: "")
.claim("nonce", nonce).build()
// Add header
val jwsHeader = JWSHeader
.Builder(if (subJwk is OctetKeyPair) JWSAlgorithm.EdDSA else JWSAlgorithm.ES256)
.type(JOSEObjectType("openid4vci-proof+jwt"))
.keyID("$did#${did?.replace("did:key:", "")}")
// .jwk(subJwk?.toPublicJWK())
.build()
// Sign with private EC key
val jwt = SignedJWT(
jwsHeader, claimsSet
)
jwt.sign(
if (subJwk is OctetKeyPair) Ed25519Signer(subJwk as OctetKeyPair) else ECDSASigner(
subJwk as ECKey
)
)
// Construct credential request
val body = buildCredentialRequest(
credentialOffer = credentialOffer,
issuerConfig = issuerConfig,
format = format,
doctype = doctype,
jwt = jwt.serialize()
)
// API call
val response = ApiManager.api.getService()?.getCredential(
issuerConfig?.credentialEndpoint ?: "",
"application/json",
"Bearer $accessToken",
body
)
val credentialResponse = when {
(response?.code() ?: 0) >= 400 -> {
try {
WrappedCredentialResponse(
errorResponse = processError(response?.errorBody()?.string())
)
} catch (e: Exception) {
null
}
}
response?.isSuccessful == true -> {
WrappedCredentialResponse(
credentialResponse = response.body()
)
}
else -> {
null
}
}
return credentialResponse
}
private fun buildCredentialRequest(
credentialOffer: CredentialOffer?,
issuerConfig: IssuerWellKnownConfiguration?,
format: String?,
jwt: String,
doctype: String?
): CredentialRequest {
val gson = Gson()
var credentialDefinitionNeeded = false
try {
if (credentialOffer?.credentials?.get(0)?.trustFramework == null)
credentialDefinitionNeeded = true
} catch (e: Exception) {
credentialDefinitionNeeded = true
}
if (format == "mso_mdoc") {
return CredentialRequest(
format = format,
doctype = doctype,
proof = ProofV3(
proofType = "jwt",
jwt = jwt
)
)
} else {
if (credentialDefinitionNeeded) {
var types: ArrayList<String>? = getTypesFromCredentialOffer(credentialOffer)
when (val data = getTypesFromIssuerConfig(
issuerConfig,
type = if (types?.isNotEmpty() == true) types.last() else "",
version = credentialOffer?.version,
)) {
is ArrayList<*> -> {
return CredentialRequest(
credentialDefinition = CredentialDefinition(type = data as ArrayList<String>),
format = format,
proof = ProofV3(
proofType = "jwt",
jwt = jwt
)
)
}
is String -> {
return CredentialRequest(
vct = data as String,
format = format,
proof = ProofV3(
proofType = "jwt",
jwt = jwt
)
)
}
}
return CredentialRequest(
credentialDefinition = CredentialDefinition(type = types),
format = format,
proof = ProofV3(
proofType = "jwt",
jwt = jwt
)
)
} else {
return CredentialRequest(
types = getTypesFromCredentialOffer(credentialOffer),
format = format,
proof = ProofV3(
proofType = "jwt",
jwt = jwt
)
)
}
}
}
fun processError(err: String?): ErrorResponse? {
// Known possibilities for error:
// 1. "Validation is failed"
// 2. {"error_description": "Validation is failed", }
// 3. {"errors": [{ "message": "Validation is failed" }]}
// 4. {"error": "Validation is failed"}
// 5. {"detail": "VC token expired"}
val jsonObject = try {
err?.let { JSONObject(it) }
} catch (e: Exception) {
null
}
val errorResponse = when {
err?.contains(
"Invalid Proof JWT: iss doesn't match the expected client_id",
true
) == true -> {
ErrorResponse(error = 1, errorDescription = "DID is invalid")
}
jsonObject?.has("error_description") == true -> {
ErrorResponse(
error = -1,
errorDescription = jsonObject.getString("error_description")
)
}
jsonObject?.has("errors") == true -> {
val errorList = JSONArray(jsonObject.getString("errors"))
ErrorResponse(
error = -1,
errorDescription = errorList.getJSONObject(0).getString("message")
)
}
jsonObject?.has("error") == true -> {
ErrorResponse(
error = -1,
errorDescription = jsonObject.getString("error")
)
}
jsonObject?.has("detail") == true -> {
ErrorResponse(
error = -1,
errorDescription = jsonObject.getString("detail")
)
}
else -> {
null
}
}
return errorResponse
}
/**
* For issuance of the deferred credential.
*
* @param acceptanceToken - token which we got from credential request
* @param deferredCredentialEndPoint - end point to call the deferred
* credential
* @return Credential response
*/
override suspend fun processDeferredCredentialRequest(
acceptanceToken: String?,
deferredCredentialEndPoint: String?
): WrappedCredentialResponse? {
val response = ApiManager.api.getService()?.getDifferedCredential(
deferredCredentialEndPoint ?: "",
"Bearer $acceptanceToken",
CredentialRequest() // empty object
)
return if (response?.isSuccessful == true
&& response.body()?.credential != null
) {
WrappedCredentialResponse(credentialResponse = response.body())
} else {
null
}
}
override suspend fun processDeferredCredentialRequestV2(
transactionId: String?,
accessToken: String?,
deferredCredentialEndPoint: String?
): WrappedCredentialResponse? {
val response = ApiManager.api.getService()?.getDifferedCredentialV2(
deferredCredentialEndPoint ?: "",
"Bearer $accessToken",
DeferredCredentialRequestV2(transactionId)
)
return if (response?.isSuccessful == true
&& response.body()?.credential != null
) {
WrappedCredentialResponse(credentialResponse = response.body())
} else {
null
}
}
/**
* Get format from IssuerWellKnownConfiguration
*
* @param issuerConfig
* @param type
*/
override fun getFormatFromIssuerConfig(
issuerConfig: IssuerWellKnownConfiguration?,
type: String?
): String? {
var format: String = "jwt_vc"
val credentialOfferJsonString = Gson().toJson(issuerConfig)
val jsonObject = JSONObject(credentialOfferJsonString)
val credentialsSupported: Any = jsonObject.opt("credentials_supported") ?: return null
when (credentialsSupported) {
is JSONObject -> {
try {
val credentialSupported = credentialsSupported.getJSONObject(type ?: "")
format = credentialSupported.getString("format")
} catch (e: Exception) {
}
}
is JSONArray -> {
try {
for (i in 0 until credentialsSupported.length()) {
val jsonObject: JSONObject = credentialsSupported.getJSONObject(i)
// Get the "types" JSONArray
val typesArray = jsonObject.getJSONArray("types")
// Check if the string is present in the "types" array
for (j in 0 until typesArray.length()) {
if (typesArray.getString(j) == type) {
format = jsonObject.getString("format")
break
}
}
}
} catch (e: Exception) {
}
}
else -> {
// Neither JSONObject nor JSONArray
println("Child is neither JSONObject nor JSONArray")
}
}
return format
}
/**
* Get types from IssuerWellKnownConfiguration
*
* @param issuerConfig
* @param type
*/
override fun getTypesFromIssuerConfig(
issuerConfig: IssuerWellKnownConfiguration?,
type: String?
): Any? {
var types: ArrayList<String> = ArrayList()
// Check if issuerConfig is null
if (issuerConfig == null) {
return null
}
try {
val credentialOfferJsonString = Gson().toJson(issuerConfig)
// Check if credentialOfferJsonString is null or empty
if (credentialOfferJsonString.isNullOrEmpty()) {
return null
}
val jsonObject = JSONObject(credentialOfferJsonString)
val credentialsSupported: Any = jsonObject.opt("credentials_supported") ?: return null
when (credentialsSupported) {
is JSONObject -> {
try {
val credentialSupported = credentialsSupported.getJSONObject(type ?: "")
val format =
if (credentialSupported.has("format")) credentialSupported.getString("format") else ""
if (format == "vc+sd-jwt") {
return credentialSupported.getJSONObject("credential_definition")
.getString("vct")
} else {
val typeFromCredentialIssuer: JSONArray =
credentialSupported.getJSONObject("credential_definition")
.getJSONArray("type")
for (i in 0 until typeFromCredentialIssuer.length()) {
// Get each JSONObject from the JSONArray
val type: String = typeFromCredentialIssuer.getString(i)
types.add(type)
}
return types
}
} catch (e: Exception) {
}
}
is JSONArray -> {
try {
for (i in 0 until credentialsSupported.length()) {
val jsonObject: JSONObject = credentialsSupported.getJSONObject(i)
// Get the "types" JSONArray
val typesArray = jsonObject.getJSONArray("types")
// Check if the string is present in the "types" array
for (j in 0 until typesArray.length()) {
if (typesArray.getString(j) == type) {
val format =
if (jsonObject.has("format")) jsonObject.getString("format") else ""
if (format == "vc+sd-jwt") {
return jsonObject.getJSONObject("credential_definition")
.getString("vct")
} else {
val typeFromCredentialIssuer: JSONArray =
jsonObject.getJSONObject("credential_definition")
.getJSONArray("type")
for (i in 0 until typeFromCredentialIssuer.length()) {
// Get each JSONObject from the JSONArray
val type: String = typeFromCredentialIssuer.getString(i)
types.add(type)
}
return types
}
break
}
}
}
} catch (e: Exception) {
}
}
else -> {
// Neither JSONObject nor JSONArray
println("Child is neither JSONObject nor JSONArray")
}
}
} catch (e: JSONException) {
Log.e("getTypesFromIssuerConfig", "Error parsing JSON", e)
}
return types
}
override fun getTypesFromIssuerConfig(
issuerConfig: IssuerWellKnownConfiguration?,
type: String?,
version: Int?
): Any? {
var types: ArrayList<String> = ArrayList()
// Check if issuerConfig is null
if (issuerConfig == null) {
return null
}
when (version) {
1 -> {
return getTypesFromIssuerConfig(issuerConfig, type)
}
else -> {
try {
val credentialOfferJsonString = Gson().toJson(issuerConfig)
// Check if credentialOfferJsonString is null or empty
if (credentialOfferJsonString.isNullOrEmpty()) {
return null
}
val jsonObject = JSONObject(credentialOfferJsonString)
val credentialsSupported: Any =
jsonObject.opt("credentials_supported") ?: return null
when (credentialsSupported) {
is JSONObject -> {
try {
val credentialSupported =
credentialsSupported.getJSONObject(type ?: "")
val format =
if (credentialSupported.has("format")) credentialSupported.getString(
"format"
) else ""
if (format == "vc+sd-jwt") {
return credentialSupported.getString("vct")
} else {
val typeFromCredentialIssuer: JSONArray =
credentialSupported.getJSONObject("credential_definition")
.getJSONArray("type")
for (i in 0 until typeFromCredentialIssuer.length()) {
// Get each JSONObject from the JSONArray
val type: String = typeFromCredentialIssuer.getString(i)
types.add(type)
}
return types
}
} catch (e: Exception) {
}
}
}
} catch (e: Exception) {
}
}
}
return types
}
/**
* Get types from credential offer
*
* @param credentialOffer
* @return
*/
override fun getTypesFromCredentialOffer(credentialOffer: CredentialOffer?): ArrayList<String> {
var types: ArrayList<String> = ArrayList()
val credentialOfferJsonString = Gson().toJson(credentialOffer)
try {
try {
val credentialOffer =
Gson().fromJson(credentialOfferJsonString, CredentialOffer::class.java)
types = credentialOffer.credentials?.get(0)?.types ?: ArrayList()
} catch (e: Exception) {
}
} catch (e: Exception) {
}
return types
}
/**
* Get cryptographicSuits from issuer config
*
* @param issuerConfig
* @param type
* @return
*/
override fun getCryptoFromIssuerConfig(
issuerConfig: IssuerWellKnownConfiguration?,
type: String?
): ArrayList<String>? {
var types: ArrayList<String> = ArrayList()
val credentialOfferJsonString = Gson().toJson(issuerConfig)
val jsonObject = JSONObject(credentialOfferJsonString)
val credentialsSupported: Any = jsonObject.opt("credentials_supported") ?: return null
when (credentialsSupported) {
is JSONObject -> {
try {
val credentialSupported = credentialsSupported.getJSONObject(type ?: "")
val cryptographicSuitsSupported =
credentialSupported.getJSONArray("cryptographic_suites_supported")
for (i in 0 until cryptographicSuitsSupported.length()) {
// Get each JSONObject from the JSONArray
val type: String = cryptographicSuitsSupported.getString(i)
types.add(type)
}
} catch (e: Exception) {
}
}
is JSONArray -> {
try {
for (i in 0 until credentialsSupported.length()) {
val jsonObject: JSONObject = credentialsSupported.getJSONObject(i)
// Get the "types" JSONArray
val typesArray = jsonObject.getJSONArray("types")
// Check if the string is present in the "types" array
for (j in 0 until typesArray.length()) {
if (typesArray.getString(j) == type) {
val cryptographicSuitsSupported =
jsonObject.getJSONArray("cryptographic_suites_supported")
for (i in 0 until cryptographicSuitsSupported.length()) {
// Get each JSONObject from the JSONArray
val type: String = cryptographicSuitsSupported.getString(i)
types.add(type)
}
break
}
}
}
} catch (e: Exception) {
}
}
else -> {
// Neither JSONObject nor JSONArray
println("Child is neither JSONObject nor JSONArray")
}
}
return types
}
} | 0 | Kotlin | 1 | 0 | c5150e09427148af9761a307fe8954d868f5cd1e | 40,679 | eudi-wallet-oid4vc-android | Apache License 2.0 |
src/test/kotlin/no/nav/helse/spenn/simulering/SimuleringServiceTest.kt | navikt | 176,742,371 | false | null | package no.nav.helse.spenn.simulering
import io.mockk.every
import io.mockk.mockk
import no.nav.system.os.eksponering.simulerfpservicewsbinding.SimulerBeregningFeilUnderBehandling
import no.nav.system.os.eksponering.simulerfpservicewsbinding.SimulerFpService
import no.nav.system.os.tjenester.simulerfpservice.feil.FeilUnderBehandling
import no.nav.system.os.tjenester.simulerfpservice.simulerfpservicegrensesnitt.SimulerBeregningRequest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
internal class SimuleringServiceTest {
private val simulerFpService = mockk<SimulerFpService>()
private val simuleringService = SimuleringService(simulerFpService)
@Test
fun `tom simuleringsrespons`() {
every { simulerFpService.simulerBeregning(any()) } returns null
val result = simuleringService.simulerOppdrag(SimulerBeregningRequest())
assertEquals(SimuleringStatus.OK, result.status)
assertNull(result.feilmelding)
assertNull(result.simulering)
}
@Test
fun `simulering med feil under behandling`() {
every {
simulerFpService.simulerBeregning(any())
} throws SimulerBeregningFeilUnderBehandling("Helt feil", FeilUnderBehandling())
val result = simuleringService.simulerOppdrag(SimulerBeregningRequest())
assertEquals(SimuleringStatus.FUNKSJONELL_FEIL, result.status)
}
} | 0 | Kotlin | 1 | 1 | 82d5ae15c2ca3b71eb5579c007327ce36a1d1a51 | 1,510 | helse-spenn | MIT License |
app/src/main/java/epsz/mapalarm/GeofenceTransitionsIntentService.kt | Fargren | 47,000,072 | false | null | package epsz.mapalarm
import android.app.IntentService
import android.content.Intent
import android.util.Log
import com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER
import com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_EXIT
import com.google.android.gms.location.GeofencingEvent
class GeofenceTransitionsIntentService() : IntentService("GeofenceTransitionsIntentService") {
private val TAG: String = "GeofenceTransitionsIntentService"
override fun onHandleIntent(intent: Intent) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
val errorMessage = "ERROR"
Log.e(TAG, errorMessage)
return;
}
// Get the transition type.
val geofenceTransition = geofencingEvent.getGeofenceTransition()
// Test that the reported transition was of interest.
if (geofenceTransition == GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
val triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
/*
val geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
*/
}
}
} | 0 | Kotlin | 0 | 0 | 1e4b09826053b0c44b7719a2a879b31bba87e228 | 1,694 | kotlin-map-alarm | MIT License |
JSEnv/src/main/java/com/aolig/jsenv/IJSInterface.kt | NiuGuohui | 340,277,620 | false | null | package com.aolig.jsenv
import com.eclipsesource.v8.V8
interface IJSInterface {
val runtime: V8
val actuator: JSActuator
fun install()
fun release()
} | 0 | Kotlin | 0 | 1 | 6e74d1f87e101ed0aa86375b445214b9c08c760f | 169 | JSEnv | MIT License |
src/main/kotlin/com/ecwid/apiclient/v3/dto/profile/result/ExtrafieldConfigDeleteResult.kt | Ecwid | 160,232,759 | false | {"Kotlin": 1019261} | package com.ecwid.apiclient.v3.dto.profile.result
import com.ecwid.apiclient.v3.dto.common.ApiResultDTO
data class ExtrafieldConfigDeleteResult(
val deleteCount: Int = 0
) : ApiResultDTO
| 11 | Kotlin | 13 | 17 | 2f94bfea3ad2073b89b8ea2b38dacdaa5f443a47 | 190 | ecwid-java-api-client | Apache License 2.0 |
sdk/src/main/java/com/qonversion/android/sdk/internal/provider/EnvironmentProvider.kt | qonversion | 224,974,105 | false | {"Kotlin": 604976, "Java": 9442, "Ruby": 2698} | package com.qonversion.android.sdk.internal.provider
import com.qonversion.android.sdk.dto.QEnvironment
internal interface EnvironmentProvider {
val apiUrl: String
val environment: QEnvironment
val isSandbox: Boolean
}
| 2 | Kotlin | 21 | 122 | 619465b65dbf2612486ec3adad9b0a8750d76c7b | 236 | android-sdk | MIT License |
utilify/src/main/java/com/boryans/utilify/exception/NothingToValidateException.kt | borYans | 542,781,458 | false | {"Kotlin": 25440} | package com.boryans.utilify.exception
class NothingToValidateException(message: String) : Exception(message) | 3 | Kotlin | 0 | 0 | adf98ca6442bf9f3271a6ea4c31715db2322e5cb | 109 | Utilify | The Unlicense |
crabzilla-pg-writer/src/main/kotlin/io/github/crabzilla/writer/WriterApi.kt | crabzilla | 91,769,036 | false | {"Kotlin": 206836} | package io.github.crabzilla.writer
import io.github.crabzilla.context.CrabzillaRuntimeException
import io.github.crabzilla.context.EventMetadata
import io.github.crabzilla.context.JsonObjectSerDer
import io.github.crabzilla.context.TargetStream
import io.github.crabzilla.context.ViewEffect
import io.github.crabzilla.context.ViewTrigger
import io.vertx.core.Future
import io.vertx.core.json.JsonObject
import io.vertx.sqlclient.SqlConnection
import java.util.*
data class CommandMetadata(
val commandId: UUID = UUID.randomUUID(),
val metadata: JsonObject? = null,
)
interface WriterApi<C : Any> {
fun handle(
targetStream: TargetStream,
command: C,
commandMetadata: CommandMetadata = CommandMetadata(),
): Future<EventMetadata>
fun handleWithinTransaction(
sqlConnection: SqlConnection,
targetStream: TargetStream,
command: C,
commandMetadata: CommandMetadata = CommandMetadata(),
): Future<EventMetadata>
}
data class WriterConfig<S : Any, C : Any, E : Any>(
val initialState: S,
val eventHandler: (S, E) -> S,
val commandHandler: (S, C) -> List<E>,
val eventSerDer: JsonObjectSerDer<E>,
val commandSerDer: JsonObjectSerDer<C>? = null,
// TODO consider an optional state serder (on stream module (to migrate the stream))
val viewEffect: ViewEffect? = null,
val viewTrigger: ViewTrigger? = null,
)
class BusinessException(message: String, cause: Throwable) : CrabzillaRuntimeException(message, cause)
| 0 | Kotlin | 8 | 67 | 4b87a2ee219f669eb5a4d98425af2833f6c089d2 | 1,464 | crabzilla | Apache License 2.0 |
app/src/main/java/online/erthru/animespot/ui/activity/top/TopActivity.kt | erthru | 144,743,552 | false | null | package online.erthru.animespot.ui.activity.top
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.WindowManager
import kotlinx.android.synthetic.main.activity_top.*
import online.erthru.animespot.R
import online.erthru.animespot.base.BaseActivity
import online.erthru.animespot.network.model.Top
class TopActivity : BaseActivity(),TopContract.View {
lateinit var presenter:TopContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_top)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
val window = window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = resources.getColor(R.color.colorPurpleDark)
}
initProgressBar(pbTop)
presenter = TopPresenter(this)
imgBackTop.setOnClickListener { this.finish() }
rvTop.layoutManager = LinearLayoutManager(this)
rvTop.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
}
override fun onResume() {
super.onResume()
rvTop.adapter = null
presenter.loadTop()
}
override fun topLoaded(data: ArrayList<Top>?) {
val adapter = TopRecyclerView(this,data)
adapter.notifyDataSetChanged()
rvTop.adapter = adapter
}
}
| 0 | Kotlin | 10 | 23 | b81ce0a4ea8c9ebe20c9bb84ec2081797bf1ec30 | 1,590 | AnimeSpot | MIT License |
compiler/testData/asJava/lightClasses/nullabilityAnnotations/OverrideAnyWithUnit.kt | chashnikov | 14,658,474 | false | null | // C
trait Base {
fun foo(): Any
}
class C : Base {
override fun foo(): Unit {}
} | 0 | null | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 91 | kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/com/laioffer/Kotlin基础/pkg18_解构/HiKotlin9.kt | yuanuscfighton | 632,030,844 | false | {"Kotlin": 1005102, "Java": 675082} | package Kotlin基础.pkg18_解构
// Kotlin严格区分可变集合与不可变集合
// 要清楚的一点是:区分开可变集合的只读视图与实际上真正的不可变集合
fun main() {
val stringList: MutableList<String> = mutableListOf("hello", "world", "hello world")
val readOnlyView: List<String> = stringList
println(stringList)
stringList.add("welcome")
println(readOnlyView)
// readOnlyView.clear()
// stringList.clear()
}
| 0 | Kotlin | 0 | 0 | b03a297acdf094f56c5d43f99eb29afa35146109 | 362 | SiberianHusky | Apache License 2.0 |
kotlin/src/main/kotlin/com/laioffer/Kotlin基础/pkg18_解构/HiKotlin9.kt | yuanuscfighton | 632,030,844 | false | {"Kotlin": 1005102, "Java": 675082} | package Kotlin基础.pkg18_解构
// Kotlin严格区分可变集合与不可变集合
// 要清楚的一点是:区分开可变集合的只读视图与实际上真正的不可变集合
fun main() {
val stringList: MutableList<String> = mutableListOf("hello", "world", "hello world")
val readOnlyView: List<String> = stringList
println(stringList)
stringList.add("welcome")
println(readOnlyView)
// readOnlyView.clear()
// stringList.clear()
}
| 0 | Kotlin | 0 | 0 | b03a297acdf094f56c5d43f99eb29afa35146109 | 362 | SiberianHusky | Apache License 2.0 |
blog/src/main/kotlin/com/liux/blog/dao/FileMapper.kt | lx0758 | 334,699,858 | false | {"Kotlin": 200977, "Vue": 104221, "CSS": 94393, "JavaScript": 82498, "HTML": 63110, "TypeScript": 23981} | package com.liux.blog.dao
import com.liux.blog.bean.po.File
import org.springframework.stereotype.Repository
@Repository
interface FileMapper {
fun deleteByPrimaryKey(id: Int?): Int
fun insert(record: File?): Int
fun insertSelective(record: File?): Int
fun getByPrimaryKey(id: Int?): File?
fun getCount(): Int
fun selectByAdmin(file: File): List<File>
fun updateByPrimaryKeySelective(file: File?): Int
fun updateByPrimaryKey(file: File?): Int
} | 0 | Kotlin | 0 | 0 | 4a7240c8a806ad625d046fc30f0619b22a57cd85 | 478 | Blog | MIT License |
lambda/src/main/typings/configservice.module_aws-sdk.kt | kartoffelsup | 252,152,703 | false | null | @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION")
import kotlin.js.*
import kotlin.js.Json
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
import ConfigService.AccountAggregationSource
import ConfigService.AggregateComplianceByConfigRule
import ConfigService.AggregateComplianceCount
import ConfigService.AggregateEvaluationResult
import ConfigService.AggregatedSourceStatus
import ConfigService.AggregationAuthorization
import ConfigService.BaseConfigurationItem
import ConfigService.ComplianceByConfigRule
import ConfigService.ComplianceByResource
import ConfigService.ComplianceSummaryByResourceType
import ConfigService.ConfigRuleEvaluationStatus
import ConfigService.ConfigRule
import ConfigService.ConfigurationAggregator
import ConfigService.ConfigurationItem
import ConfigService.ConfigurationRecorder
import ConfigService.ConfigurationRecorderStatus
import ConfigService.ConformancePackComplianceSummary
import ConfigService.ConformancePackDetail
import ConfigService.ConformancePackInputParameter
import ConfigService.ConformancePackRuleCompliance
import ConfigService.ConformancePackEvaluationResult
import ConfigService.ConformancePackStatusDetail
import ConfigService.DeliveryChannel
import ConfigService.DeliveryChannelStatus
import ConfigService.AggregateResourceIdentifier
import ConfigService.EvaluationResult
import ConfigService.Evaluation
import ConfigService.FailedDeleteRemediationExceptionsBatch
import ConfigService.FailedRemediationBatch
import ConfigService.FailedRemediationExceptionBatch
import ConfigService.FieldInfo
import ConfigService.GroupedResourceCount
import ConfigService.MemberAccountStatus
import ConfigService.OrganizationConfigRuleStatus
import ConfigService.OrganizationConfigRule
import ConfigService.OrganizationConformancePackDetailedStatus
import ConfigService.OrganizationConformancePackStatus
import ConfigService.OrganizationConformancePack
import ConfigService.PendingAggregationRequest
import ConfigService.Relationship
import ConfigService.RemediationConfiguration
import ConfigService.RemediationExceptionResourceKey
import ConfigService.RemediationException
import ConfigService.RemediationExecutionStatus
import ConfigService.RemediationExecutionStep
import ConfigService.ResourceCount
import ConfigService.ResourceIdentifier
import ConfigService.ResourceKey
import ConfigService.RetentionConfiguration
import ConfigService.SourceDetail
import ConfigService.Tag
import ConfigService.BatchGetAggregateResourceConfigRequest
import ConfigService.BatchGetAggregateResourceConfigResponse
import ConfigService.BatchGetResourceConfigRequest
import ConfigService.BatchGetResourceConfigResponse
import ConfigService.DeleteAggregationAuthorizationRequest
import ConfigService.DeleteConfigRuleRequest
import ConfigService.DeleteConfigurationAggregatorRequest
import ConfigService.DeleteConfigurationRecorderRequest
import ConfigService.DeleteConformancePackRequest
import ConfigService.DeleteDeliveryChannelRequest
import ConfigService.DeleteEvaluationResultsRequest
import ConfigService.DeleteEvaluationResultsResponse
import ConfigService.DeleteOrganizationConfigRuleRequest
import ConfigService.DeleteOrganizationConformancePackRequest
import ConfigService.DeletePendingAggregationRequestRequest
import ConfigService.DeleteRemediationConfigurationRequest
import ConfigService.DeleteRemediationConfigurationResponse
import ConfigService.DeleteRemediationExceptionsRequest
import ConfigService.DeleteRemediationExceptionsResponse
import ConfigService.DeleteResourceConfigRequest
import ConfigService.DeleteRetentionConfigurationRequest
import ConfigService.DeliverConfigSnapshotRequest
import ConfigService.DeliverConfigSnapshotResponse
import ConfigService.DescribeAggregateComplianceByConfigRulesRequest
import ConfigService.DescribeAggregateComplianceByConfigRulesResponse
import ConfigService.DescribeAggregationAuthorizationsRequest
import ConfigService.DescribeAggregationAuthorizationsResponse
import ConfigService.DescribeComplianceByConfigRuleRequest
import ConfigService.DescribeComplianceByConfigRuleResponse
import ConfigService.DescribeComplianceByResourceRequest
import ConfigService.DescribeComplianceByResourceResponse
import ConfigService.DescribeConfigRuleEvaluationStatusRequest
import ConfigService.DescribeConfigRuleEvaluationStatusResponse
import ConfigService.DescribeConfigRulesRequest
import ConfigService.DescribeConfigRulesResponse
import ConfigService.DescribeConfigurationAggregatorSourcesStatusRequest
import ConfigService.DescribeConfigurationAggregatorSourcesStatusResponse
import ConfigService.DescribeConfigurationAggregatorsRequest
import ConfigService.DescribeConfigurationAggregatorsResponse
import ConfigService.DescribeConfigurationRecorderStatusRequest
import ConfigService.DescribeConfigurationRecorderStatusResponse
import ConfigService.DescribeConfigurationRecordersRequest
import ConfigService.DescribeConfigurationRecordersResponse
import ConfigService.DescribeConformancePackComplianceRequest
import ConfigService.DescribeConformancePackComplianceResponse
import ConfigService.DescribeConformancePackStatusRequest
import ConfigService.DescribeConformancePackStatusResponse
import ConfigService.DescribeConformancePacksRequest
import ConfigService.DescribeConformancePacksResponse
import ConfigService.DescribeDeliveryChannelStatusRequest
import ConfigService.DescribeDeliveryChannelStatusResponse
import ConfigService.DescribeDeliveryChannelsRequest
import ConfigService.DescribeDeliveryChannelsResponse
import ConfigService.DescribeOrganizationConfigRuleStatusesRequest
import ConfigService.DescribeOrganizationConfigRuleStatusesResponse
import ConfigService.DescribeOrganizationConfigRulesRequest
import ConfigService.DescribeOrganizationConfigRulesResponse
import ConfigService.DescribeOrganizationConformancePackStatusesRequest
import ConfigService.DescribeOrganizationConformancePackStatusesResponse
import ConfigService.DescribeOrganizationConformancePacksRequest
import ConfigService.DescribeOrganizationConformancePacksResponse
import ConfigService.DescribePendingAggregationRequestsRequest
import ConfigService.DescribePendingAggregationRequestsResponse
import ConfigService.DescribeRemediationConfigurationsRequest
import ConfigService.DescribeRemediationConfigurationsResponse
import ConfigService.DescribeRemediationExceptionsRequest
import ConfigService.DescribeRemediationExceptionsResponse
import ConfigService.DescribeRemediationExecutionStatusRequest
import ConfigService.DescribeRemediationExecutionStatusResponse
import ConfigService.DescribeRetentionConfigurationsRequest
import ConfigService.DescribeRetentionConfigurationsResponse
import ConfigService.GetAggregateComplianceDetailsByConfigRuleRequest
import ConfigService.GetAggregateComplianceDetailsByConfigRuleResponse
import ConfigService.GetAggregateConfigRuleComplianceSummaryRequest
import ConfigService.GetAggregateConfigRuleComplianceSummaryResponse
import ConfigService.GetAggregateDiscoveredResourceCountsRequest
import ConfigService.GetAggregateDiscoveredResourceCountsResponse
import ConfigService.GetAggregateResourceConfigRequest
import ConfigService.GetAggregateResourceConfigResponse
import ConfigService.GetComplianceDetailsByConfigRuleRequest
import ConfigService.GetComplianceDetailsByConfigRuleResponse
import ConfigService.GetComplianceDetailsByResourceRequest
import ConfigService.GetComplianceDetailsByResourceResponse
import ConfigService.GetComplianceSummaryByConfigRuleResponse
import ConfigService.GetComplianceSummaryByResourceTypeRequest
import ConfigService.GetComplianceSummaryByResourceTypeResponse
import ConfigService.GetConformancePackComplianceDetailsRequest
import ConfigService.GetConformancePackComplianceDetailsResponse
import ConfigService.GetConformancePackComplianceSummaryRequest
import ConfigService.GetConformancePackComplianceSummaryResponse
import ConfigService.GetDiscoveredResourceCountsRequest
import ConfigService.GetDiscoveredResourceCountsResponse
import ConfigService.GetOrganizationConfigRuleDetailedStatusRequest
import ConfigService.GetOrganizationConfigRuleDetailedStatusResponse
import ConfigService.GetOrganizationConformancePackDetailedStatusRequest
import ConfigService.GetOrganizationConformancePackDetailedStatusResponse
import ConfigService.GetResourceConfigHistoryRequest
import ConfigService.GetResourceConfigHistoryResponse
import ConfigService.ListAggregateDiscoveredResourcesRequest
import ConfigService.ListAggregateDiscoveredResourcesResponse
import ConfigService.ListDiscoveredResourcesRequest
import ConfigService.ListDiscoveredResourcesResponse
import ConfigService.ListTagsForResourceRequest
import ConfigService.ListTagsForResourceResponse
import ConfigService.PutAggregationAuthorizationRequest
import ConfigService.PutAggregationAuthorizationResponse
import ConfigService.PutConfigRuleRequest
import ConfigService.PutConfigurationAggregatorRequest
import ConfigService.PutConfigurationAggregatorResponse
import ConfigService.PutConfigurationRecorderRequest
import ConfigService.PutConformancePackRequest
import ConfigService.PutConformancePackResponse
import ConfigService.PutDeliveryChannelRequest
import ConfigService.PutEvaluationsRequest
import ConfigService.PutEvaluationsResponse
import ConfigService.PutOrganizationConfigRuleRequest
import ConfigService.PutOrganizationConfigRuleResponse
import ConfigService.PutOrganizationConformancePackRequest
import ConfigService.PutOrganizationConformancePackResponse
import ConfigService.PutRemediationConfigurationsRequest
import ConfigService.PutRemediationConfigurationsResponse
import ConfigService.PutRemediationExceptionsRequest
import ConfigService.PutRemediationExceptionsResponse
import ConfigService.PutResourceConfigRequest
import ConfigService.PutRetentionConfigurationRequest
import ConfigService.PutRetentionConfigurationResponse
import ConfigService.SelectAggregateResourceConfigRequest
import ConfigService.SelectAggregateResourceConfigResponse
import ConfigService.SelectResourceConfigRequest
import ConfigService.SelectResourceConfigResponse
import ConfigService.StartConfigRulesEvaluationRequest
import ConfigService.StartConfigRulesEvaluationResponse
import ConfigService.StartConfigurationRecorderRequest
import ConfigService.StartRemediationExecutionRequest
import ConfigService.StartRemediationExecutionResponse
import ConfigService.StopConfigurationRecorderRequest
import ConfigService.TagResourceRequest
import ConfigService.UntagResourceRequest
import ConfigService.Compliance
import ConfigService.ComplianceSummary
import ConfigService.EvaluationResultIdentifier
import ConfigService.SupplementaryConfiguration
import ConfigService.ComplianceContributorCount
import ConfigService.Scope
import ConfigService.Source
import ConfigService.OrganizationAggregationSource
import ConfigService.Tags
import ConfigService.RecordingGroup
import ConfigService.ConfigSnapshotDeliveryProperties
import ConfigService.ConfigExportDeliveryInfo
import ConfigService.ConfigStreamDeliveryInfo
import ConfigService.ConfigRuleComplianceFilters
import ConfigService.ConformancePackComplianceFilters
import ConfigService.EvaluationResultQualifier
import ConfigService.SsmControls
import ConfigService.ConfigRuleComplianceSummaryFilters
import ConfigService.ResourceCountFilters
import ConfigService.ConformancePackEvaluationFilters
import ConfigService.StatusDetailFilters
import ConfigService.OrganizationResourceDetailedStatusFilters
import ConfigService.ResourceFilters
import ConfigService.OrganizationManagedRuleMetadata
import ConfigService.OrganizationCustomRuleMetadata
import ConfigService.RemediationParameters
import ConfigService.ExecutionControls
import ConfigService.ResourceValue
import ConfigService.StaticValue
import ConfigService.RemediationParameterValue
import ConfigService.QueryInfo
typealias ARN = String
typealias AccountAggregationSourceAccountList = Array<AccountId>
typealias AccountAggregationSourceList = Array<AccountAggregationSource>
typealias AccountId = String
typealias AggregateComplianceByConfigRuleList = Array<AggregateComplianceByConfigRule>
typealias AggregateComplianceCountList = Array<AggregateComplianceCount>
typealias AggregateEvaluationResultList = Array<AggregateEvaluationResult>
typealias AggregatedSourceStatusList = Array<AggregatedSourceStatus>
typealias AggregatedSourceStatusTypeList = Array<String /* "FAILED" | "SUCCEEDED" | "OUTDATED" | String */>
typealias AggregationAuthorizationList = Array<AggregationAuthorization>
typealias AggregatorRegionList = Array<String>
typealias AllSupported = Boolean
typealias AmazonResourceName = String
typealias Annotation = String
typealias AutoRemediationAttemptSeconds = Number
typealias AutoRemediationAttempts = Number
typealias AvailabilityZone = String
typealias AwsRegion = String
typealias BaseConfigurationItems = Array<BaseConfigurationItem>
typealias BaseResourceId = String
typealias Boolean = Boolean
typealias ChannelName = String
typealias ComplianceByConfigRules = Array<ComplianceByConfigRule>
typealias ComplianceByResources = Array<ComplianceByResource>
typealias ComplianceResourceTypes = Array<StringWithCharLimit256>
typealias ComplianceSummariesByResourceType = Array<ComplianceSummaryByResourceType>
typealias ComplianceTypes = Array<String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */>
typealias ConfigRuleEvaluationStatusList = Array<ConfigRuleEvaluationStatus>
typealias ConfigRuleName = String
typealias ConfigRuleNames = Array<ConfigRuleName>
typealias ConfigRules = Array<ConfigRule>
typealias Configuration = String
typealias ConfigurationAggregatorArn = String
typealias ConfigurationAggregatorList = Array<ConfigurationAggregator>
typealias ConfigurationAggregatorName = String
typealias ConfigurationAggregatorNameList = Array<ConfigurationAggregatorName>
typealias ConfigurationItemCaptureTime = Date
typealias ConfigurationItemList = Array<ConfigurationItem>
typealias ConfigurationItemMD5Hash = String
typealias ConfigurationRecorderList = Array<ConfigurationRecorder>
typealias ConfigurationRecorderNameList = Array<RecorderName>
typealias ConfigurationRecorderStatusList = Array<ConfigurationRecorderStatus>
typealias ConfigurationStateId = String
typealias ConformancePackArn = String
typealias ConformancePackComplianceResourceIds = Array<StringWithCharLimit256>
typealias ConformancePackComplianceSummaryList = Array<ConformancePackComplianceSummary>
typealias ConformancePackConfigRuleNames = Array<StringWithCharLimit64>
typealias ConformancePackDetailList = Array<ConformancePackDetail>
typealias ConformancePackId = String
typealias ConformancePackInputParameters = Array<ConformancePackInputParameter>
typealias ConformancePackName = String
typealias ConformancePackNamesList = Array<ConformancePackName>
typealias ConformancePackNamesToSummarizeList = Array<ConformancePackName>
typealias ConformancePackRuleComplianceList = Array<ConformancePackRuleCompliance>
typealias ConformancePackRuleEvaluationResultsList = Array<ConformancePackEvaluationResult>
typealias ConformancePackStatusDetailsList = Array<ConformancePackStatusDetail>
typealias ConformancePackStatusReason = String
typealias CosmosPageLimit = Number
typealias _Date = Date
typealias DeliveryChannelList = Array<DeliveryChannel>
typealias DeliveryChannelNameList = Array<ChannelName>
typealias DeliveryChannelStatusList = Array<DeliveryChannelStatus>
typealias DeliveryS3Bucket = String
typealias DeliveryS3KeyPrefix = String
typealias DescribeConformancePackComplianceLimit = Number
typealias DescribePendingAggregationRequestsLimit = Number
typealias DiscoveredResourceIdentifierList = Array<AggregateResourceIdentifier>
typealias EarlierTime = Date
typealias EmptiableStringWithCharLimit256 = String
typealias EvaluationResults = Array<EvaluationResult>
typealias Evaluations = Array<Evaluation>
typealias ExcludedAccounts = Array<AccountId>
typealias Expression = String
typealias FailedDeleteRemediationExceptionsBatches = Array<FailedDeleteRemediationExceptionsBatch>
typealias FailedRemediationBatches = Array<FailedRemediationBatch>
typealias FailedRemediationExceptionBatches = Array<FailedRemediationExceptionBatch>
typealias FieldInfoList = Array<FieldInfo>
typealias FieldName = String
typealias GetConformancePackComplianceDetailsLimit = Number
typealias GroupByAPILimit = Number
typealias GroupedResourceCountList = Array<GroupedResourceCount>
typealias IncludeGlobalResourceTypes = Boolean
typealias Integer = Number
typealias LaterTime = Date
typealias Limit = Number
typealias Long = Number
typealias Name = String
typealias NextToken = String
typealias OrderingTimestamp = Date
typealias OrganizationConfigRuleDetailedStatus = Array<MemberAccountStatus>
typealias OrganizationConfigRuleName = String
typealias OrganizationConfigRuleNames = Array<StringWithCharLimit64>
typealias OrganizationConfigRuleStatuses = Array<OrganizationConfigRuleStatus>
typealias OrganizationConfigRuleTriggerTypes = Array<String /* "ConfigurationItemChangeNotification" | "OversizedConfigurationItemChangeNotification" | "ScheduledNotification" | String */>
typealias OrganizationConfigRules = Array<OrganizationConfigRule>
typealias OrganizationConformancePackDetailedStatuses = Array<OrganizationConformancePackDetailedStatus>
typealias OrganizationConformancePackName = String
typealias OrganizationConformancePackNames = Array<OrganizationConformancePackName>
typealias OrganizationConformancePackStatuses = Array<OrganizationConformancePackStatus>
typealias OrganizationConformancePacks = Array<OrganizationConformancePack>
typealias PageSizeLimit = Number
typealias ParameterName = String
typealias ParameterValue = String
typealias PendingAggregationRequestList = Array<PendingAggregationRequest>
typealias Percentage = Number
typealias RecorderName = String
typealias ReevaluateConfigRuleNames = Array<ConfigRuleName>
typealias RelatedEvent = String
typealias RelatedEventList = Array<RelatedEvent>
typealias RelationshipList = Array<Relationship>
typealias RelationshipName = String
typealias RemediationConfigurations = Array<RemediationConfiguration>
typealias RemediationExceptionResourceKeys = Array<RemediationExceptionResourceKey>
typealias RemediationExceptions = Array<RemediationException>
typealias RemediationExecutionStatuses = Array<RemediationExecutionStatus>
typealias RemediationExecutionSteps = Array<RemediationExecutionStep>
typealias ResourceCounts = Array<ResourceCount>
typealias ResourceCreationTime = Date
typealias ResourceDeletionTime = Date
typealias ResourceId = String
typealias ResourceIdList = Array<ResourceId>
typealias ResourceIdentifierList = Array<ResourceIdentifier>
typealias ResourceIdentifiersList = Array<AggregateResourceIdentifier>
typealias ResourceKeys = Array<ResourceKey>
typealias ResourceName = String
typealias ResourceTypeList = Array<String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */>
typealias ResourceTypeString = String
typealias ResourceTypes = Array<StringWithCharLimit256>
typealias ResourceTypesScope = Array<StringWithCharLimit256>
typealias Results = Array<String>
typealias RetentionConfigurationList = Array<RetentionConfiguration>
typealias RetentionConfigurationName = String
typealias RetentionConfigurationNameList = Array<RetentionConfigurationName>
typealias RetentionPeriodInDays = Number
typealias RuleLimit = Number
typealias SchemaVersionId = String
typealias SourceDetails = Array<SourceDetail>
typealias StackArn = String
typealias StaticParameterValues = Array<StringWithCharLimit256>
typealias String = String
typealias StringWithCharLimit1024 = String
typealias StringWithCharLimit128 = String
typealias StringWithCharLimit2048 = String
typealias StringWithCharLimit256 = String
typealias StringWithCharLimit256Min0 = String
typealias StringWithCharLimit64 = String
typealias StringWithCharLimit768 = String
typealias SupplementaryConfigurationName = String
typealias SupplementaryConfigurationValue = String
typealias TagKey = String
typealias TagKeyList = Array<TagKey>
typealias TagList = Array<Tag>
typealias TagValue = String
typealias TagsList = Array<Tag>
typealias TemplateBody = String
typealias TemplateS3Uri = String
typealias UnprocessedResourceIdentifierList = Array<AggregateResourceIdentifier>
typealias Value = String
typealias Version = String
@JsModule("aws-sdk")
external open class ConfigService(options: ServiceConfigurationOptions /* ServiceConfigurationOptions & ClientApiVersions */ = definedExternally) : Service {
open var config: ConfigBase /* Config & ConfigService.Types.ClientConfiguration */
open fun batchGetAggregateResourceConfig(params: BatchGetAggregateResourceConfigRequest, callback: (err: AWSError, data: BatchGetAggregateResourceConfigResponse) -> Unit = definedExternally): Request<BatchGetAggregateResourceConfigResponse, AWSError>
open fun batchGetAggregateResourceConfig(callback: (err: AWSError, data: BatchGetAggregateResourceConfigResponse) -> Unit = definedExternally): Request<BatchGetAggregateResourceConfigResponse, AWSError>
open fun batchGetResourceConfig(params: BatchGetResourceConfigRequest, callback: (err: AWSError, data: BatchGetResourceConfigResponse) -> Unit = definedExternally): Request<BatchGetResourceConfigResponse, AWSError>
open fun batchGetResourceConfig(callback: (err: AWSError, data: BatchGetResourceConfigResponse) -> Unit = definedExternally): Request<BatchGetResourceConfigResponse, AWSError>
open fun deleteAggregationAuthorization(params: DeleteAggregationAuthorizationRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteAggregationAuthorization(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConfigRule(params: DeleteConfigRuleRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConfigRule(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConfigurationAggregator(params: DeleteConfigurationAggregatorRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConfigurationAggregator(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConfigurationRecorder(params: DeleteConfigurationRecorderRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConfigurationRecorder(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConformancePack(params: DeleteConformancePackRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteConformancePack(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteDeliveryChannel(params: DeleteDeliveryChannelRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteDeliveryChannel(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteEvaluationResults(params: DeleteEvaluationResultsRequest, callback: (err: AWSError, data: DeleteEvaluationResultsResponse) -> Unit = definedExternally): Request<DeleteEvaluationResultsResponse, AWSError>
open fun deleteEvaluationResults(callback: (err: AWSError, data: DeleteEvaluationResultsResponse) -> Unit = definedExternally): Request<DeleteEvaluationResultsResponse, AWSError>
open fun deleteOrganizationConfigRule(params: DeleteOrganizationConfigRuleRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteOrganizationConfigRule(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteOrganizationConformancePack(params: DeleteOrganizationConformancePackRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteOrganizationConformancePack(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deletePendingAggregationRequest(params: DeletePendingAggregationRequestRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deletePendingAggregationRequest(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteRemediationConfiguration(params: DeleteRemediationConfigurationRequest, callback: (err: AWSError, data: DeleteRemediationConfigurationResponse) -> Unit = definedExternally): Request<DeleteRemediationConfigurationResponse, AWSError>
open fun deleteRemediationConfiguration(callback: (err: AWSError, data: DeleteRemediationConfigurationResponse) -> Unit = definedExternally): Request<DeleteRemediationConfigurationResponse, AWSError>
open fun deleteRemediationExceptions(params: DeleteRemediationExceptionsRequest, callback: (err: AWSError, data: DeleteRemediationExceptionsResponse) -> Unit = definedExternally): Request<DeleteRemediationExceptionsResponse, AWSError>
open fun deleteRemediationExceptions(callback: (err: AWSError, data: DeleteRemediationExceptionsResponse) -> Unit = definedExternally): Request<DeleteRemediationExceptionsResponse, AWSError>
open fun deleteResourceConfig(params: DeleteResourceConfigRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteResourceConfig(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteRetentionConfiguration(params: DeleteRetentionConfigurationRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deleteRetentionConfiguration(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun deliverConfigSnapshot(params: DeliverConfigSnapshotRequest, callback: (err: AWSError, data: DeliverConfigSnapshotResponse) -> Unit = definedExternally): Request<DeliverConfigSnapshotResponse, AWSError>
open fun deliverConfigSnapshot(callback: (err: AWSError, data: DeliverConfigSnapshotResponse) -> Unit = definedExternally): Request<DeliverConfigSnapshotResponse, AWSError>
open fun describeAggregateComplianceByConfigRules(params: DescribeAggregateComplianceByConfigRulesRequest, callback: (err: AWSError, data: DescribeAggregateComplianceByConfigRulesResponse) -> Unit = definedExternally): Request<DescribeAggregateComplianceByConfigRulesResponse, AWSError>
open fun describeAggregateComplianceByConfigRules(callback: (err: AWSError, data: DescribeAggregateComplianceByConfigRulesResponse) -> Unit = definedExternally): Request<DescribeAggregateComplianceByConfigRulesResponse, AWSError>
open fun describeAggregationAuthorizations(params: DescribeAggregationAuthorizationsRequest, callback: (err: AWSError, data: DescribeAggregationAuthorizationsResponse) -> Unit = definedExternally): Request<DescribeAggregationAuthorizationsResponse, AWSError>
open fun describeAggregationAuthorizations(callback: (err: AWSError, data: DescribeAggregationAuthorizationsResponse) -> Unit = definedExternally): Request<DescribeAggregationAuthorizationsResponse, AWSError>
open fun describeComplianceByConfigRule(params: DescribeComplianceByConfigRuleRequest, callback: (err: AWSError, data: DescribeComplianceByConfigRuleResponse) -> Unit = definedExternally): Request<DescribeComplianceByConfigRuleResponse, AWSError>
open fun describeComplianceByConfigRule(callback: (err: AWSError, data: DescribeComplianceByConfigRuleResponse) -> Unit = definedExternally): Request<DescribeComplianceByConfigRuleResponse, AWSError>
open fun describeComplianceByResource(params: DescribeComplianceByResourceRequest, callback: (err: AWSError, data: DescribeComplianceByResourceResponse) -> Unit = definedExternally): Request<DescribeComplianceByResourceResponse, AWSError>
open fun describeComplianceByResource(callback: (err: AWSError, data: DescribeComplianceByResourceResponse) -> Unit = definedExternally): Request<DescribeComplianceByResourceResponse, AWSError>
open fun describeConfigRuleEvaluationStatus(params: DescribeConfigRuleEvaluationStatusRequest, callback: (err: AWSError, data: DescribeConfigRuleEvaluationStatusResponse) -> Unit = definedExternally): Request<DescribeConfigRuleEvaluationStatusResponse, AWSError>
open fun describeConfigRuleEvaluationStatus(callback: (err: AWSError, data: DescribeConfigRuleEvaluationStatusResponse) -> Unit = definedExternally): Request<DescribeConfigRuleEvaluationStatusResponse, AWSError>
open fun describeConfigRules(params: DescribeConfigRulesRequest, callback: (err: AWSError, data: DescribeConfigRulesResponse) -> Unit = definedExternally): Request<DescribeConfigRulesResponse, AWSError>
open fun describeConfigRules(callback: (err: AWSError, data: DescribeConfigRulesResponse) -> Unit = definedExternally): Request<DescribeConfigRulesResponse, AWSError>
open fun describeConfigurationAggregatorSourcesStatus(params: DescribeConfigurationAggregatorSourcesStatusRequest, callback: (err: AWSError, data: DescribeConfigurationAggregatorSourcesStatusResponse) -> Unit = definedExternally): Request<DescribeConfigurationAggregatorSourcesStatusResponse, AWSError>
open fun describeConfigurationAggregatorSourcesStatus(callback: (err: AWSError, data: DescribeConfigurationAggregatorSourcesStatusResponse) -> Unit = definedExternally): Request<DescribeConfigurationAggregatorSourcesStatusResponse, AWSError>
open fun describeConfigurationAggregators(params: DescribeConfigurationAggregatorsRequest, callback: (err: AWSError, data: DescribeConfigurationAggregatorsResponse) -> Unit = definedExternally): Request<DescribeConfigurationAggregatorsResponse, AWSError>
open fun describeConfigurationAggregators(callback: (err: AWSError, data: DescribeConfigurationAggregatorsResponse) -> Unit = definedExternally): Request<DescribeConfigurationAggregatorsResponse, AWSError>
open fun describeConfigurationRecorderStatus(params: DescribeConfigurationRecorderStatusRequest, callback: (err: AWSError, data: DescribeConfigurationRecorderStatusResponse) -> Unit = definedExternally): Request<DescribeConfigurationRecorderStatusResponse, AWSError>
open fun describeConfigurationRecorderStatus(callback: (err: AWSError, data: DescribeConfigurationRecorderStatusResponse) -> Unit = definedExternally): Request<DescribeConfigurationRecorderStatusResponse, AWSError>
open fun describeConfigurationRecorders(params: DescribeConfigurationRecordersRequest, callback: (err: AWSError, data: DescribeConfigurationRecordersResponse) -> Unit = definedExternally): Request<DescribeConfigurationRecordersResponse, AWSError>
open fun describeConfigurationRecorders(callback: (err: AWSError, data: DescribeConfigurationRecordersResponse) -> Unit = definedExternally): Request<DescribeConfigurationRecordersResponse, AWSError>
open fun describeConformancePackCompliance(params: DescribeConformancePackComplianceRequest, callback: (err: AWSError, data: DescribeConformancePackComplianceResponse) -> Unit = definedExternally): Request<DescribeConformancePackComplianceResponse, AWSError>
open fun describeConformancePackCompliance(callback: (err: AWSError, data: DescribeConformancePackComplianceResponse) -> Unit = definedExternally): Request<DescribeConformancePackComplianceResponse, AWSError>
open fun describeConformancePackStatus(params: DescribeConformancePackStatusRequest, callback: (err: AWSError, data: DescribeConformancePackStatusResponse) -> Unit = definedExternally): Request<DescribeConformancePackStatusResponse, AWSError>
open fun describeConformancePackStatus(callback: (err: AWSError, data: DescribeConformancePackStatusResponse) -> Unit = definedExternally): Request<DescribeConformancePackStatusResponse, AWSError>
open fun describeConformancePacks(params: DescribeConformancePacksRequest, callback: (err: AWSError, data: DescribeConformancePacksResponse) -> Unit = definedExternally): Request<DescribeConformancePacksResponse, AWSError>
open fun describeConformancePacks(callback: (err: AWSError, data: DescribeConformancePacksResponse) -> Unit = definedExternally): Request<DescribeConformancePacksResponse, AWSError>
open fun describeDeliveryChannelStatus(params: DescribeDeliveryChannelStatusRequest, callback: (err: AWSError, data: DescribeDeliveryChannelStatusResponse) -> Unit = definedExternally): Request<DescribeDeliveryChannelStatusResponse, AWSError>
open fun describeDeliveryChannelStatus(callback: (err: AWSError, data: DescribeDeliveryChannelStatusResponse) -> Unit = definedExternally): Request<DescribeDeliveryChannelStatusResponse, AWSError>
open fun describeDeliveryChannels(params: DescribeDeliveryChannelsRequest, callback: (err: AWSError, data: DescribeDeliveryChannelsResponse) -> Unit = definedExternally): Request<DescribeDeliveryChannelsResponse, AWSError>
open fun describeDeliveryChannels(callback: (err: AWSError, data: DescribeDeliveryChannelsResponse) -> Unit = definedExternally): Request<DescribeDeliveryChannelsResponse, AWSError>
open fun describeOrganizationConfigRuleStatuses(params: DescribeOrganizationConfigRuleStatusesRequest, callback: (err: AWSError, data: DescribeOrganizationConfigRuleStatusesResponse) -> Unit = definedExternally): Request<DescribeOrganizationConfigRuleStatusesResponse, AWSError>
open fun describeOrganizationConfigRuleStatuses(callback: (err: AWSError, data: DescribeOrganizationConfigRuleStatusesResponse) -> Unit = definedExternally): Request<DescribeOrganizationConfigRuleStatusesResponse, AWSError>
open fun describeOrganizationConfigRules(params: DescribeOrganizationConfigRulesRequest, callback: (err: AWSError, data: DescribeOrganizationConfigRulesResponse) -> Unit = definedExternally): Request<DescribeOrganizationConfigRulesResponse, AWSError>
open fun describeOrganizationConfigRules(callback: (err: AWSError, data: DescribeOrganizationConfigRulesResponse) -> Unit = definedExternally): Request<DescribeOrganizationConfigRulesResponse, AWSError>
open fun describeOrganizationConformancePackStatuses(params: DescribeOrganizationConformancePackStatusesRequest, callback: (err: AWSError, data: DescribeOrganizationConformancePackStatusesResponse) -> Unit = definedExternally): Request<DescribeOrganizationConformancePackStatusesResponse, AWSError>
open fun describeOrganizationConformancePackStatuses(callback: (err: AWSError, data: DescribeOrganizationConformancePackStatusesResponse) -> Unit = definedExternally): Request<DescribeOrganizationConformancePackStatusesResponse, AWSError>
open fun describeOrganizationConformancePacks(params: DescribeOrganizationConformancePacksRequest, callback: (err: AWSError, data: DescribeOrganizationConformancePacksResponse) -> Unit = definedExternally): Request<DescribeOrganizationConformancePacksResponse, AWSError>
open fun describeOrganizationConformancePacks(callback: (err: AWSError, data: DescribeOrganizationConformancePacksResponse) -> Unit = definedExternally): Request<DescribeOrganizationConformancePacksResponse, AWSError>
open fun describePendingAggregationRequests(params: DescribePendingAggregationRequestsRequest, callback: (err: AWSError, data: DescribePendingAggregationRequestsResponse) -> Unit = definedExternally): Request<DescribePendingAggregationRequestsResponse, AWSError>
open fun describePendingAggregationRequests(callback: (err: AWSError, data: DescribePendingAggregationRequestsResponse) -> Unit = definedExternally): Request<DescribePendingAggregationRequestsResponse, AWSError>
open fun describeRemediationConfigurations(params: DescribeRemediationConfigurationsRequest, callback: (err: AWSError, data: DescribeRemediationConfigurationsResponse) -> Unit = definedExternally): Request<DescribeRemediationConfigurationsResponse, AWSError>
open fun describeRemediationConfigurations(callback: (err: AWSError, data: DescribeRemediationConfigurationsResponse) -> Unit = definedExternally): Request<DescribeRemediationConfigurationsResponse, AWSError>
open fun describeRemediationExceptions(params: DescribeRemediationExceptionsRequest, callback: (err: AWSError, data: DescribeRemediationExceptionsResponse) -> Unit = definedExternally): Request<DescribeRemediationExceptionsResponse, AWSError>
open fun describeRemediationExceptions(callback: (err: AWSError, data: DescribeRemediationExceptionsResponse) -> Unit = definedExternally): Request<DescribeRemediationExceptionsResponse, AWSError>
open fun describeRemediationExecutionStatus(params: DescribeRemediationExecutionStatusRequest, callback: (err: AWSError, data: DescribeRemediationExecutionStatusResponse) -> Unit = definedExternally): Request<DescribeRemediationExecutionStatusResponse, AWSError>
open fun describeRemediationExecutionStatus(callback: (err: AWSError, data: DescribeRemediationExecutionStatusResponse) -> Unit = definedExternally): Request<DescribeRemediationExecutionStatusResponse, AWSError>
open fun describeRetentionConfigurations(params: DescribeRetentionConfigurationsRequest, callback: (err: AWSError, data: DescribeRetentionConfigurationsResponse) -> Unit = definedExternally): Request<DescribeRetentionConfigurationsResponse, AWSError>
open fun describeRetentionConfigurations(callback: (err: AWSError, data: DescribeRetentionConfigurationsResponse) -> Unit = definedExternally): Request<DescribeRetentionConfigurationsResponse, AWSError>
open fun getAggregateComplianceDetailsByConfigRule(params: GetAggregateComplianceDetailsByConfigRuleRequest, callback: (err: AWSError, data: GetAggregateComplianceDetailsByConfigRuleResponse) -> Unit = definedExternally): Request<GetAggregateComplianceDetailsByConfigRuleResponse, AWSError>
open fun getAggregateComplianceDetailsByConfigRule(callback: (err: AWSError, data: GetAggregateComplianceDetailsByConfigRuleResponse) -> Unit = definedExternally): Request<GetAggregateComplianceDetailsByConfigRuleResponse, AWSError>
open fun getAggregateConfigRuleComplianceSummary(params: GetAggregateConfigRuleComplianceSummaryRequest, callback: (err: AWSError, data: GetAggregateConfigRuleComplianceSummaryResponse) -> Unit = definedExternally): Request<GetAggregateConfigRuleComplianceSummaryResponse, AWSError>
open fun getAggregateConfigRuleComplianceSummary(callback: (err: AWSError, data: GetAggregateConfigRuleComplianceSummaryResponse) -> Unit = definedExternally): Request<GetAggregateConfigRuleComplianceSummaryResponse, AWSError>
open fun getAggregateDiscoveredResourceCounts(params: GetAggregateDiscoveredResourceCountsRequest, callback: (err: AWSError, data: GetAggregateDiscoveredResourceCountsResponse) -> Unit = definedExternally): Request<GetAggregateDiscoveredResourceCountsResponse, AWSError>
open fun getAggregateDiscoveredResourceCounts(callback: (err: AWSError, data: GetAggregateDiscoveredResourceCountsResponse) -> Unit = definedExternally): Request<GetAggregateDiscoveredResourceCountsResponse, AWSError>
open fun getAggregateResourceConfig(params: GetAggregateResourceConfigRequest, callback: (err: AWSError, data: GetAggregateResourceConfigResponse) -> Unit = definedExternally): Request<GetAggregateResourceConfigResponse, AWSError>
open fun getAggregateResourceConfig(callback: (err: AWSError, data: GetAggregateResourceConfigResponse) -> Unit = definedExternally): Request<GetAggregateResourceConfigResponse, AWSError>
open fun getComplianceDetailsByConfigRule(params: GetComplianceDetailsByConfigRuleRequest, callback: (err: AWSError, data: GetComplianceDetailsByConfigRuleResponse) -> Unit = definedExternally): Request<GetComplianceDetailsByConfigRuleResponse, AWSError>
open fun getComplianceDetailsByConfigRule(callback: (err: AWSError, data: GetComplianceDetailsByConfigRuleResponse) -> Unit = definedExternally): Request<GetComplianceDetailsByConfigRuleResponse, AWSError>
open fun getComplianceDetailsByResource(params: GetComplianceDetailsByResourceRequest, callback: (err: AWSError, data: GetComplianceDetailsByResourceResponse) -> Unit = definedExternally): Request<GetComplianceDetailsByResourceResponse, AWSError>
open fun getComplianceDetailsByResource(callback: (err: AWSError, data: GetComplianceDetailsByResourceResponse) -> Unit = definedExternally): Request<GetComplianceDetailsByResourceResponse, AWSError>
open fun getComplianceSummaryByConfigRule(callback: (err: AWSError, data: GetComplianceSummaryByConfigRuleResponse) -> Unit = definedExternally): Request<GetComplianceSummaryByConfigRuleResponse, AWSError>
open fun getComplianceSummaryByResourceType(params: GetComplianceSummaryByResourceTypeRequest, callback: (err: AWSError, data: GetComplianceSummaryByResourceTypeResponse) -> Unit = definedExternally): Request<GetComplianceSummaryByResourceTypeResponse, AWSError>
open fun getComplianceSummaryByResourceType(callback: (err: AWSError, data: GetComplianceSummaryByResourceTypeResponse) -> Unit = definedExternally): Request<GetComplianceSummaryByResourceTypeResponse, AWSError>
open fun getConformancePackComplianceDetails(params: GetConformancePackComplianceDetailsRequest, callback: (err: AWSError, data: GetConformancePackComplianceDetailsResponse) -> Unit = definedExternally): Request<GetConformancePackComplianceDetailsResponse, AWSError>
open fun getConformancePackComplianceDetails(callback: (err: AWSError, data: GetConformancePackComplianceDetailsResponse) -> Unit = definedExternally): Request<GetConformancePackComplianceDetailsResponse, AWSError>
open fun getConformancePackComplianceSummary(params: GetConformancePackComplianceSummaryRequest, callback: (err: AWSError, data: GetConformancePackComplianceSummaryResponse) -> Unit = definedExternally): Request<GetConformancePackComplianceSummaryResponse, AWSError>
open fun getConformancePackComplianceSummary(callback: (err: AWSError, data: GetConformancePackComplianceSummaryResponse) -> Unit = definedExternally): Request<GetConformancePackComplianceSummaryResponse, AWSError>
open fun getDiscoveredResourceCounts(params: GetDiscoveredResourceCountsRequest, callback: (err: AWSError, data: GetDiscoveredResourceCountsResponse) -> Unit = definedExternally): Request<GetDiscoveredResourceCountsResponse, AWSError>
open fun getDiscoveredResourceCounts(callback: (err: AWSError, data: GetDiscoveredResourceCountsResponse) -> Unit = definedExternally): Request<GetDiscoveredResourceCountsResponse, AWSError>
open fun getOrganizationConfigRuleDetailedStatus(params: GetOrganizationConfigRuleDetailedStatusRequest, callback: (err: AWSError, data: GetOrganizationConfigRuleDetailedStatusResponse) -> Unit = definedExternally): Request<GetOrganizationConfigRuleDetailedStatusResponse, AWSError>
open fun getOrganizationConfigRuleDetailedStatus(callback: (err: AWSError, data: GetOrganizationConfigRuleDetailedStatusResponse) -> Unit = definedExternally): Request<GetOrganizationConfigRuleDetailedStatusResponse, AWSError>
open fun getOrganizationConformancePackDetailedStatus(params: GetOrganizationConformancePackDetailedStatusRequest, callback: (err: AWSError, data: GetOrganizationConformancePackDetailedStatusResponse) -> Unit = definedExternally): Request<GetOrganizationConformancePackDetailedStatusResponse, AWSError>
open fun getOrganizationConformancePackDetailedStatus(callback: (err: AWSError, data: GetOrganizationConformancePackDetailedStatusResponse) -> Unit = definedExternally): Request<GetOrganizationConformancePackDetailedStatusResponse, AWSError>
open fun getResourceConfigHistory(params: GetResourceConfigHistoryRequest, callback: (err: AWSError, data: GetResourceConfigHistoryResponse) -> Unit = definedExternally): Request<GetResourceConfigHistoryResponse, AWSError>
open fun getResourceConfigHistory(callback: (err: AWSError, data: GetResourceConfigHistoryResponse) -> Unit = definedExternally): Request<GetResourceConfigHistoryResponse, AWSError>
open fun listAggregateDiscoveredResources(params: ListAggregateDiscoveredResourcesRequest, callback: (err: AWSError, data: ListAggregateDiscoveredResourcesResponse) -> Unit = definedExternally): Request<ListAggregateDiscoveredResourcesResponse, AWSError>
open fun listAggregateDiscoveredResources(callback: (err: AWSError, data: ListAggregateDiscoveredResourcesResponse) -> Unit = definedExternally): Request<ListAggregateDiscoveredResourcesResponse, AWSError>
open fun listDiscoveredResources(params: ListDiscoveredResourcesRequest, callback: (err: AWSError, data: ListDiscoveredResourcesResponse) -> Unit = definedExternally): Request<ListDiscoveredResourcesResponse, AWSError>
open fun listDiscoveredResources(callback: (err: AWSError, data: ListDiscoveredResourcesResponse) -> Unit = definedExternally): Request<ListDiscoveredResourcesResponse, AWSError>
open fun listTagsForResource(params: ListTagsForResourceRequest, callback: (err: AWSError, data: ListTagsForResourceResponse) -> Unit = definedExternally): Request<ListTagsForResourceResponse, AWSError>
open fun listTagsForResource(callback: (err: AWSError, data: ListTagsForResourceResponse) -> Unit = definedExternally): Request<ListTagsForResourceResponse, AWSError>
open fun putAggregationAuthorization(params: PutAggregationAuthorizationRequest, callback: (err: AWSError, data: PutAggregationAuthorizationResponse) -> Unit = definedExternally): Request<PutAggregationAuthorizationResponse, AWSError>
open fun putAggregationAuthorization(callback: (err: AWSError, data: PutAggregationAuthorizationResponse) -> Unit = definedExternally): Request<PutAggregationAuthorizationResponse, AWSError>
open fun putConfigRule(params: PutConfigRuleRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putConfigRule(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putConfigurationAggregator(params: PutConfigurationAggregatorRequest, callback: (err: AWSError, data: PutConfigurationAggregatorResponse) -> Unit = definedExternally): Request<PutConfigurationAggregatorResponse, AWSError>
open fun putConfigurationAggregator(callback: (err: AWSError, data: PutConfigurationAggregatorResponse) -> Unit = definedExternally): Request<PutConfigurationAggregatorResponse, AWSError>
open fun putConfigurationRecorder(params: PutConfigurationRecorderRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putConfigurationRecorder(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putConformancePack(params: PutConformancePackRequest, callback: (err: AWSError, data: PutConformancePackResponse) -> Unit = definedExternally): Request<PutConformancePackResponse, AWSError>
open fun putConformancePack(callback: (err: AWSError, data: PutConformancePackResponse) -> Unit = definedExternally): Request<PutConformancePackResponse, AWSError>
open fun putDeliveryChannel(params: PutDeliveryChannelRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putDeliveryChannel(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putEvaluations(params: PutEvaluationsRequest, callback: (err: AWSError, data: PutEvaluationsResponse) -> Unit = definedExternally): Request<PutEvaluationsResponse, AWSError>
open fun putEvaluations(callback: (err: AWSError, data: PutEvaluationsResponse) -> Unit = definedExternally): Request<PutEvaluationsResponse, AWSError>
open fun putOrganizationConfigRule(params: PutOrganizationConfigRuleRequest, callback: (err: AWSError, data: PutOrganizationConfigRuleResponse) -> Unit = definedExternally): Request<PutOrganizationConfigRuleResponse, AWSError>
open fun putOrganizationConfigRule(callback: (err: AWSError, data: PutOrganizationConfigRuleResponse) -> Unit = definedExternally): Request<PutOrganizationConfigRuleResponse, AWSError>
open fun putOrganizationConformancePack(params: PutOrganizationConformancePackRequest, callback: (err: AWSError, data: PutOrganizationConformancePackResponse) -> Unit = definedExternally): Request<PutOrganizationConformancePackResponse, AWSError>
open fun putOrganizationConformancePack(callback: (err: AWSError, data: PutOrganizationConformancePackResponse) -> Unit = definedExternally): Request<PutOrganizationConformancePackResponse, AWSError>
open fun putRemediationConfigurations(params: PutRemediationConfigurationsRequest, callback: (err: AWSError, data: PutRemediationConfigurationsResponse) -> Unit = definedExternally): Request<PutRemediationConfigurationsResponse, AWSError>
open fun putRemediationConfigurations(callback: (err: AWSError, data: PutRemediationConfigurationsResponse) -> Unit = definedExternally): Request<PutRemediationConfigurationsResponse, AWSError>
open fun putRemediationExceptions(params: PutRemediationExceptionsRequest, callback: (err: AWSError, data: PutRemediationExceptionsResponse) -> Unit = definedExternally): Request<PutRemediationExceptionsResponse, AWSError>
open fun putRemediationExceptions(callback: (err: AWSError, data: PutRemediationExceptionsResponse) -> Unit = definedExternally): Request<PutRemediationExceptionsResponse, AWSError>
open fun putResourceConfig(params: PutResourceConfigRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putResourceConfig(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun putRetentionConfiguration(params: PutRetentionConfigurationRequest, callback: (err: AWSError, data: PutRetentionConfigurationResponse) -> Unit = definedExternally): Request<PutRetentionConfigurationResponse, AWSError>
open fun putRetentionConfiguration(callback: (err: AWSError, data: PutRetentionConfigurationResponse) -> Unit = definedExternally): Request<PutRetentionConfigurationResponse, AWSError>
open fun selectAggregateResourceConfig(params: SelectAggregateResourceConfigRequest, callback: (err: AWSError, data: SelectAggregateResourceConfigResponse) -> Unit = definedExternally): Request<SelectAggregateResourceConfigResponse, AWSError>
open fun selectAggregateResourceConfig(callback: (err: AWSError, data: SelectAggregateResourceConfigResponse) -> Unit = definedExternally): Request<SelectAggregateResourceConfigResponse, AWSError>
open fun selectResourceConfig(params: SelectResourceConfigRequest, callback: (err: AWSError, data: SelectResourceConfigResponse) -> Unit = definedExternally): Request<SelectResourceConfigResponse, AWSError>
open fun selectResourceConfig(callback: (err: AWSError, data: SelectResourceConfigResponse) -> Unit = definedExternally): Request<SelectResourceConfigResponse, AWSError>
open fun startConfigRulesEvaluation(params: StartConfigRulesEvaluationRequest, callback: (err: AWSError, data: StartConfigRulesEvaluationResponse) -> Unit = definedExternally): Request<StartConfigRulesEvaluationResponse, AWSError>
open fun startConfigRulesEvaluation(callback: (err: AWSError, data: StartConfigRulesEvaluationResponse) -> Unit = definedExternally): Request<StartConfigRulesEvaluationResponse, AWSError>
open fun startConfigurationRecorder(params: StartConfigurationRecorderRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun startConfigurationRecorder(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun startRemediationExecution(params: StartRemediationExecutionRequest, callback: (err: AWSError, data: StartRemediationExecutionResponse) -> Unit = definedExternally): Request<StartRemediationExecutionResponse, AWSError>
open fun startRemediationExecution(callback: (err: AWSError, data: StartRemediationExecutionResponse) -> Unit = definedExternally): Request<StartRemediationExecutionResponse, AWSError>
open fun stopConfigurationRecorder(params: StopConfigurationRecorderRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun stopConfigurationRecorder(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun tagResource(params: TagResourceRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun tagResource(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun untagResource(params: UntagResourceRequest, callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
open fun untagResource(callback: (err: AWSError, data: Any) -> Unit = definedExternally): Request<Any, AWSError>
interface AccountAggregationSource {
var AccountIds: AccountAggregationSourceAccountList
var AllAwsRegions: Boolean?
get() = definedExternally
set(value) = definedExternally
var AwsRegions: AggregatorRegionList?
get() = definedExternally
set(value) = definedExternally
}
interface AggregateComplianceByConfigRule {
var ConfigRuleName: ConfigRuleName?
get() = definedExternally
set(value) = definedExternally
var Compliance: Compliance?
get() = definedExternally
set(value) = definedExternally
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var AwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface AggregateComplianceCount {
var GroupName: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ComplianceSummary: ComplianceSummary?
get() = definedExternally
set(value) = definedExternally
}
interface AggregateEvaluationResult {
var EvaluationResultIdentifier: EvaluationResultIdentifier?
get() = definedExternally
set(value) = definedExternally
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */
var ResultRecordedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var ConfigRuleInvokedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var Annotation: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var AwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface AggregateResourceIdentifier {
var SourceAccountId: AccountId
var SourceRegion: AwsRegion
var ResourceId: ResourceId
var ResourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var ResourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
}
interface AggregatedSourceStatus {
var SourceId: String?
get() = definedExternally
set(value) = definedExternally
var SourceType: String /* "ACCOUNT" | "ORGANIZATION" | String */
var AwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
var LastUpdateStatus: String /* "FAILED" | "SUCCEEDED" | "OUTDATED" | String */
var LastUpdateTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var LastErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
}
interface AggregationAuthorization {
var AggregationAuthorizationArn: String?
get() = definedExternally
set(value) = definedExternally
var AuthorizedAccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var AuthorizedAwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
var CreationTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface BaseConfigurationItem {
var version: Version?
get() = definedExternally
set(value) = definedExternally
var accountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var configurationItemCaptureTime: ConfigurationItemCaptureTime?
get() = definedExternally
set(value) = definedExternally
var configurationItemStatus: String /* "OK" | "ResourceDiscovered" | "ResourceNotRecorded" | "ResourceDeleted" | "ResourceDeletedNotRecorded" | String */
var configurationStateId: ConfigurationStateId?
get() = definedExternally
set(value) = definedExternally
var arn: ARN?
get() = definedExternally
set(value) = definedExternally
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceId: ResourceId?
get() = definedExternally
set(value) = definedExternally
var resourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var awsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
var availabilityZone: AvailabilityZone?
get() = definedExternally
set(value) = definedExternally
var resourceCreationTime: ResourceCreationTime?
get() = definedExternally
set(value) = definedExternally
var configuration: Configuration?
get() = definedExternally
set(value) = definedExternally
var supplementaryConfiguration: SupplementaryConfiguration?
get() = definedExternally
set(value) = definedExternally
}
interface BatchGetAggregateResourceConfigRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var ResourceIdentifiers: ResourceIdentifiersList
}
interface BatchGetAggregateResourceConfigResponse {
var BaseConfigurationItems: BaseConfigurationItems?
get() = definedExternally
set(value) = definedExternally
var UnprocessedResourceIdentifiers: UnprocessedResourceIdentifierList?
get() = definedExternally
set(value) = definedExternally
}
interface BatchGetResourceConfigRequest {
var resourceKeys: ResourceKeys
}
interface BatchGetResourceConfigResponse {
var baseConfigurationItems: BaseConfigurationItems?
get() = definedExternally
set(value) = definedExternally
var unprocessedResourceKeys: ResourceKeys?
get() = definedExternally
set(value) = definedExternally
}
interface Compliance {
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */
var ComplianceContributorCount: ComplianceContributorCount?
get() = definedExternally
set(value) = definedExternally
}
interface ComplianceByConfigRule {
var ConfigRuleName: StringWithCharLimit64?
get() = definedExternally
set(value) = definedExternally
var Compliance: Compliance?
get() = definedExternally
set(value) = definedExternally
}
interface ComplianceByResource {
var ResourceType: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ResourceId: BaseResourceId?
get() = definedExternally
set(value) = definedExternally
var Compliance: Compliance?
get() = definedExternally
set(value) = definedExternally
}
interface ComplianceContributorCount {
var CappedCount: Integer?
get() = definedExternally
set(value) = definedExternally
var CapExceeded: Boolean?
get() = definedExternally
set(value) = definedExternally
}
interface ComplianceSummary {
var CompliantResourceCount: ComplianceContributorCount?
get() = definedExternally
set(value) = definedExternally
var NonCompliantResourceCount: ComplianceContributorCount?
get() = definedExternally
set(value) = definedExternally
var ComplianceSummaryTimestamp: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface ComplianceSummaryByResourceType {
var ResourceType: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ComplianceSummary: ComplianceSummary?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigExportDeliveryInfo {
var lastStatus: String /* "Success" | "Failure" | "Not_Applicable" | String */
var lastErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var lastErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var lastAttemptTime: _Date?
get() = definedExternally
set(value) = definedExternally
var lastSuccessfulTime: _Date?
get() = definedExternally
set(value) = definedExternally
var nextDeliveryTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigRule {
var ConfigRuleName: ConfigRuleName?
get() = definedExternally
set(value) = definedExternally
var ConfigRuleArn: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ConfigRuleId: StringWithCharLimit64?
get() = definedExternally
set(value) = definedExternally
var Description: EmptiableStringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var Scope: Scope?
get() = definedExternally
set(value) = definedExternally
var Source: Source
var InputParameters: StringWithCharLimit1024?
get() = definedExternally
set(value) = definedExternally
var MaximumExecutionFrequency: String /* "One_Hour" | "Three_Hours" | "Six_Hours" | "Twelve_Hours" | "TwentyFour_Hours" | String */
var ConfigRuleState: String /* "ACTIVE" | "DELETING" | "DELETING_RESULTS" | "EVALUATING" | String */
var CreatedBy: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigRuleComplianceFilters {
var ConfigRuleName: ConfigRuleName?
get() = definedExternally
set(value) = definedExternally
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var AwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigRuleComplianceSummaryFilters {
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var AwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigRuleEvaluationStatus {
var ConfigRuleName: ConfigRuleName?
get() = definedExternally
set(value) = definedExternally
var ConfigRuleArn: String?
get() = definedExternally
set(value) = definedExternally
var ConfigRuleId: String?
get() = definedExternally
set(value) = definedExternally
var LastSuccessfulInvocationTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastFailedInvocationTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastSuccessfulEvaluationTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastFailedEvaluationTime: _Date?
get() = definedExternally
set(value) = definedExternally
var FirstActivatedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastDeactivatedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var LastErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var FirstEvaluationStarted: Boolean?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigSnapshotDeliveryProperties {
var deliveryFrequency: String /* "One_Hour" | "Three_Hours" | "Six_Hours" | "Twelve_Hours" | "TwentyFour_Hours" | String */
}
interface ConfigStreamDeliveryInfo {
var lastStatus: String /* "Success" | "Failure" | "Not_Applicable" | String */
var lastErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var lastErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var lastStatusChangeTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigurationAggregator {
var ConfigurationAggregatorName: ConfigurationAggregatorName?
get() = definedExternally
set(value) = definedExternally
var ConfigurationAggregatorArn: ConfigurationAggregatorArn?
get() = definedExternally
set(value) = definedExternally
var AccountAggregationSources: AccountAggregationSourceList?
get() = definedExternally
set(value) = definedExternally
var OrganizationAggregationSource: OrganizationAggregationSource?
get() = definedExternally
set(value) = definedExternally
var CreationTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastUpdatedTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigurationItem {
var version: Version?
get() = definedExternally
set(value) = definedExternally
var accountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var configurationItemCaptureTime: ConfigurationItemCaptureTime?
get() = definedExternally
set(value) = definedExternally
var configurationItemStatus: String /* "OK" | "ResourceDiscovered" | "ResourceNotRecorded" | "ResourceDeleted" | "ResourceDeletedNotRecorded" | String */
var configurationStateId: ConfigurationStateId?
get() = definedExternally
set(value) = definedExternally
var configurationItemMD5Hash: ConfigurationItemMD5Hash?
get() = definedExternally
set(value) = definedExternally
var arn: ARN?
get() = definedExternally
set(value) = definedExternally
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceId: ResourceId?
get() = definedExternally
set(value) = definedExternally
var resourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var awsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
var availabilityZone: AvailabilityZone?
get() = definedExternally
set(value) = definedExternally
var resourceCreationTime: ResourceCreationTime?
get() = definedExternally
set(value) = definedExternally
var tags: Tags?
get() = definedExternally
set(value) = definedExternally
var relatedEvents: RelatedEventList?
get() = definedExternally
set(value) = definedExternally
var relationships: RelationshipList?
get() = definedExternally
set(value) = definedExternally
var configuration: Configuration?
get() = definedExternally
set(value) = definedExternally
var supplementaryConfiguration: SupplementaryConfiguration?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigurationRecorder {
var name: RecorderName?
get() = definedExternally
set(value) = definedExternally
var roleARN: String?
get() = definedExternally
set(value) = definedExternally
var recordingGroup: RecordingGroup?
get() = definedExternally
set(value) = definedExternally
}
interface ConfigurationRecorderStatus {
var name: String?
get() = definedExternally
set(value) = definedExternally
var lastStartTime: _Date?
get() = definedExternally
set(value) = definedExternally
var lastStopTime: _Date?
get() = definedExternally
set(value) = definedExternally
var recording: Boolean?
get() = definedExternally
set(value) = definedExternally
var lastStatus: String /* "Pending" | "Success" | "Failure" | String */
var lastErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var lastErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var lastStatusChangeTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface ConformancePackComplianceFilters {
var ConfigRuleNames: ConformancePackConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | String */
}
interface ConformancePackComplianceSummary {
var ConformancePackName: ConformancePackName
var ConformancePackComplianceStatus: String /* "COMPLIANT" | "NON_COMPLIANT" | String */
}
interface ConformancePackDetail {
var ConformancePackName: ConformancePackName
var ConformancePackArn: ConformancePackArn
var ConformancePackId: ConformancePackId
var DeliveryS3Bucket: DeliveryS3Bucket
var DeliveryS3KeyPrefix: DeliveryS3KeyPrefix?
get() = definedExternally
set(value) = definedExternally
var ConformancePackInputParameters: ConformancePackInputParameters?
get() = definedExternally
set(value) = definedExternally
var LastUpdateRequestedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var CreatedBy: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
}
interface ConformancePackEvaluationFilters {
var ConfigRuleNames: ConformancePackConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | String */
var ResourceType: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ResourceIds: ConformancePackComplianceResourceIds?
get() = definedExternally
set(value) = definedExternally
}
interface ConformancePackEvaluationResult {
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | String */
var EvaluationResultIdentifier: EvaluationResultIdentifier
var ConfigRuleInvokedTime: _Date
var ResultRecordedTime: _Date
var Annotation: Annotation?
get() = definedExternally
set(value) = definedExternally
}
interface ConformancePackInputParameter {
var ParameterName: ParameterName
var ParameterValue: ParameterValue
}
interface ConformancePackRuleCompliance {
var ConfigRuleName: ConfigRuleName?
get() = definedExternally
set(value) = definedExternally
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | String */
}
interface ConformancePackStatusDetail {
var ConformancePackName: ConformancePackName
var ConformancePackId: ConformancePackId
var ConformancePackArn: ConformancePackArn
var ConformancePackState: String /* "CREATE_IN_PROGRESS" | "CREATE_COMPLETE" | "CREATE_FAILED" | "DELETE_IN_PROGRESS" | "DELETE_FAILED" | String */
var StackArn: StackArn
var ConformancePackStatusReason: ConformancePackStatusReason?
get() = definedExternally
set(value) = definedExternally
var LastUpdateRequestedTime: _Date
var LastUpdateCompletedTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface DeleteAggregationAuthorizationRequest {
var AuthorizedAccountId: AccountId
var AuthorizedAwsRegion: AwsRegion
}
interface DeleteConfigRuleRequest {
var ConfigRuleName: ConfigRuleName
}
interface DeleteConfigurationAggregatorRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
}
interface DeleteConfigurationRecorderRequest {
var ConfigurationRecorderName: RecorderName
}
interface DeleteConformancePackRequest {
var ConformancePackName: ConformancePackName
}
interface DeleteDeliveryChannelRequest {
var DeliveryChannelName: ChannelName
}
interface DeleteEvaluationResultsRequest {
var ConfigRuleName: StringWithCharLimit64
}
interface DeleteEvaluationResultsResponse
interface DeleteOrganizationConfigRuleRequest {
var OrganizationConfigRuleName: OrganizationConfigRuleName
}
interface DeleteOrganizationConformancePackRequest {
var OrganizationConformancePackName: OrganizationConformancePackName
}
interface DeletePendingAggregationRequestRequest {
var RequesterAccountId: AccountId
var RequesterAwsRegion: AwsRegion
}
interface DeleteRemediationConfigurationRequest {
var ConfigRuleName: ConfigRuleName
var ResourceType: String?
get() = definedExternally
set(value) = definedExternally
}
interface DeleteRemediationConfigurationResponse
interface DeleteRemediationExceptionsRequest {
var ConfigRuleName: ConfigRuleName
var ResourceKeys: RemediationExceptionResourceKeys
}
interface DeleteRemediationExceptionsResponse {
var FailedBatches: FailedDeleteRemediationExceptionsBatches?
get() = definedExternally
set(value) = definedExternally
}
interface DeleteResourceConfigRequest {
var ResourceType: ResourceTypeString
var ResourceId: ResourceId
}
interface DeleteRetentionConfigurationRequest {
var RetentionConfigurationName: RetentionConfigurationName
}
interface DeliverConfigSnapshotRequest {
var deliveryChannelName: ChannelName
}
interface DeliverConfigSnapshotResponse {
var configSnapshotId: String?
get() = definedExternally
set(value) = definedExternally
}
interface DeliveryChannel {
var name: ChannelName?
get() = definedExternally
set(value) = definedExternally
var s3BucketName: String?
get() = definedExternally
set(value) = definedExternally
var s3KeyPrefix: String?
get() = definedExternally
set(value) = definedExternally
var snsTopicARN: String?
get() = definedExternally
set(value) = definedExternally
var configSnapshotDeliveryProperties: ConfigSnapshotDeliveryProperties?
get() = definedExternally
set(value) = definedExternally
}
interface DeliveryChannelStatus {
var name: String?
get() = definedExternally
set(value) = definedExternally
var configSnapshotDeliveryInfo: ConfigExportDeliveryInfo?
get() = definedExternally
set(value) = definedExternally
var configHistoryDeliveryInfo: ConfigExportDeliveryInfo?
get() = definedExternally
set(value) = definedExternally
var configStreamDeliveryInfo: ConfigStreamDeliveryInfo?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeAggregateComplianceByConfigRulesRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var Filters: ConfigRuleComplianceFilters?
get() = definedExternally
set(value) = definedExternally
var Limit: GroupByAPILimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeAggregateComplianceByConfigRulesResponse {
var AggregateComplianceByConfigRules: AggregateComplianceByConfigRuleList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeAggregationAuthorizationsRequest {
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeAggregationAuthorizationsResponse {
var AggregationAuthorizations: AggregationAuthorizationList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeComplianceByConfigRuleRequest {
var ConfigRuleNames: ConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var ComplianceTypes: ComplianceTypes?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeComplianceByConfigRuleResponse {
var ComplianceByConfigRules: ComplianceByConfigRules?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeComplianceByResourceRequest {
var ResourceType: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ResourceId: BaseResourceId?
get() = definedExternally
set(value) = definedExternally
var ComplianceTypes: ComplianceTypes?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeComplianceByResourceResponse {
var ComplianceByResources: ComplianceByResources?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigRuleEvaluationStatusRequest {
var ConfigRuleNames: ConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
var Limit: RuleLimit?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigRuleEvaluationStatusResponse {
var ConfigRulesEvaluationStatus: ConfigRuleEvaluationStatusList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigRulesRequest {
var ConfigRuleNames: ConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigRulesResponse {
var ConfigRules: ConfigRules?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationAggregatorSourcesStatusRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var UpdateStatus: AggregatedSourceStatusTypeList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationAggregatorSourcesStatusResponse {
var AggregatedSourceStatusList: AggregatedSourceStatusList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationAggregatorsRequest {
var ConfigurationAggregatorNames: ConfigurationAggregatorNameList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationAggregatorsResponse {
var ConfigurationAggregators: ConfigurationAggregatorList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationRecorderStatusRequest {
var ConfigurationRecorderNames: ConfigurationRecorderNameList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationRecorderStatusResponse {
var ConfigurationRecordersStatus: ConfigurationRecorderStatusList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationRecordersRequest {
var ConfigurationRecorderNames: ConfigurationRecorderNameList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConfigurationRecordersResponse {
var ConfigurationRecorders: ConfigurationRecorderList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConformancePackComplianceRequest {
var ConformancePackName: ConformancePackName
var Filters: ConformancePackComplianceFilters?
get() = definedExternally
set(value) = definedExternally
var Limit: DescribeConformancePackComplianceLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConformancePackComplianceResponse {
var ConformancePackName: ConformancePackName
var ConformancePackRuleComplianceList: ConformancePackRuleComplianceList
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConformancePackStatusRequest {
var ConformancePackNames: ConformancePackNamesList?
get() = definedExternally
set(value) = definedExternally
var Limit: PageSizeLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConformancePackStatusResponse {
var ConformancePackStatusDetails: ConformancePackStatusDetailsList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConformancePacksRequest {
var ConformancePackNames: ConformancePackNamesList?
get() = definedExternally
set(value) = definedExternally
var Limit: PageSizeLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeConformancePacksResponse {
var ConformancePackDetails: ConformancePackDetailList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeDeliveryChannelStatusRequest {
var DeliveryChannelNames: DeliveryChannelNameList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeDeliveryChannelStatusResponse {
var DeliveryChannelsStatus: DeliveryChannelStatusList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeDeliveryChannelsRequest {
var DeliveryChannelNames: DeliveryChannelNameList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeDeliveryChannelsResponse {
var DeliveryChannels: DeliveryChannelList?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConfigRuleStatusesRequest {
var OrganizationConfigRuleNames: OrganizationConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var Limit: CosmosPageLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConfigRuleStatusesResponse {
var OrganizationConfigRuleStatuses: OrganizationConfigRuleStatuses?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConfigRulesRequest {
var OrganizationConfigRuleNames: OrganizationConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
var Limit: CosmosPageLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConfigRulesResponse {
var OrganizationConfigRules: OrganizationConfigRules?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConformancePackStatusesRequest {
var OrganizationConformancePackNames: OrganizationConformancePackNames?
get() = definedExternally
set(value) = definedExternally
var Limit: CosmosPageLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConformancePackStatusesResponse {
var OrganizationConformancePackStatuses: OrganizationConformancePackStatuses?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConformancePacksRequest {
var OrganizationConformancePackNames: OrganizationConformancePackNames?
get() = definedExternally
set(value) = definedExternally
var Limit: CosmosPageLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeOrganizationConformancePacksResponse {
var OrganizationConformancePacks: OrganizationConformancePacks?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribePendingAggregationRequestsRequest {
var Limit: DescribePendingAggregationRequestsLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribePendingAggregationRequestsResponse {
var PendingAggregationRequests: PendingAggregationRequestList?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRemediationConfigurationsRequest {
var ConfigRuleNames: ConfigRuleNames
}
interface DescribeRemediationConfigurationsResponse {
var RemediationConfigurations: RemediationConfigurations?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRemediationExceptionsRequest {
var ConfigRuleName: ConfigRuleName
var ResourceKeys: RemediationExceptionResourceKeys?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRemediationExceptionsResponse {
var RemediationExceptions: RemediationExceptions?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRemediationExecutionStatusRequest {
var ConfigRuleName: ConfigRuleName
var ResourceKeys: ResourceKeys?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRemediationExecutionStatusResponse {
var RemediationExecutionStatuses: RemediationExecutionStatuses?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRetentionConfigurationsRequest {
var RetentionConfigurationNames: RetentionConfigurationNameList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface DescribeRetentionConfigurationsResponse {
var RetentionConfigurations: RetentionConfigurationList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface Evaluation {
var ComplianceResourceType: StringWithCharLimit256
var ComplianceResourceId: BaseResourceId
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */
var Annotation: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var OrderingTimestamp: OrderingTimestamp
}
interface EvaluationResult {
var EvaluationResultIdentifier: EvaluationResultIdentifier?
get() = definedExternally
set(value) = definedExternally
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */
var ResultRecordedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var ConfigRuleInvokedTime: _Date?
get() = definedExternally
set(value) = definedExternally
var Annotation: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ResultToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface EvaluationResultIdentifier {
var EvaluationResultQualifier: EvaluationResultQualifier?
get() = definedExternally
set(value) = definedExternally
var OrderingTimestamp: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface EvaluationResultQualifier {
var ConfigRuleName: ConfigRuleName?
get() = definedExternally
set(value) = definedExternally
var ResourceType: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ResourceId: BaseResourceId?
get() = definedExternally
set(value) = definedExternally
}
interface ExecutionControls {
var SsmControls: SsmControls?
get() = definedExternally
set(value) = definedExternally
}
interface FailedDeleteRemediationExceptionsBatch {
var FailureMessage: String?
get() = definedExternally
set(value) = definedExternally
var FailedItems: RemediationExceptionResourceKeys?
get() = definedExternally
set(value) = definedExternally
}
interface FailedRemediationBatch {
var FailureMessage: String?
get() = definedExternally
set(value) = definedExternally
var FailedItems: RemediationConfigurations?
get() = definedExternally
set(value) = definedExternally
}
interface FailedRemediationExceptionBatch {
var FailureMessage: String?
get() = definedExternally
set(value) = definedExternally
var FailedItems: RemediationExceptions?
get() = definedExternally
set(value) = definedExternally
}
interface FieldInfo {
var Name: FieldName?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateComplianceDetailsByConfigRuleRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var ConfigRuleName: ConfigRuleName
var AccountId: AccountId
var AwsRegion: AwsRegion
var ComplianceType: String /* "COMPLIANT" | "NON_COMPLIANT" | "NOT_APPLICABLE" | "INSUFFICIENT_DATA" | String */
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateComplianceDetailsByConfigRuleResponse {
var AggregateEvaluationResults: AggregateEvaluationResultList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateConfigRuleComplianceSummaryRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var Filters: ConfigRuleComplianceSummaryFilters?
get() = definedExternally
set(value) = definedExternally
var GroupByKey: String /* "ACCOUNT_ID" | "AWS_REGION" | String */
var Limit: GroupByAPILimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateConfigRuleComplianceSummaryResponse {
var GroupByKey: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var AggregateComplianceCounts: AggregateComplianceCountList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateDiscoveredResourceCountsRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var Filters: ResourceCountFilters?
get() = definedExternally
set(value) = definedExternally
var GroupByKey: String /* "RESOURCE_TYPE" | "ACCOUNT_ID" | "AWS_REGION" | String */
var Limit: GroupByAPILimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateDiscoveredResourceCountsResponse {
var TotalDiscoveredResources: Long
var GroupByKey: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var GroupedResourceCounts: GroupedResourceCountList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetAggregateResourceConfigRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var ResourceIdentifier: AggregateResourceIdentifier
}
interface GetAggregateResourceConfigResponse {
var ConfigurationItem: ConfigurationItem?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceDetailsByConfigRuleRequest {
var ConfigRuleName: StringWithCharLimit64
var ComplianceTypes: ComplianceTypes?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceDetailsByConfigRuleResponse {
var EvaluationResults: EvaluationResults?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceDetailsByResourceRequest {
var ResourceType: StringWithCharLimit256
var ResourceId: BaseResourceId
var ComplianceTypes: ComplianceTypes?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceDetailsByResourceResponse {
var EvaluationResults: EvaluationResults?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceSummaryByConfigRuleResponse {
var ComplianceSummary: ComplianceSummary?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceSummaryByResourceTypeRequest {
var ResourceTypes: ResourceTypes?
get() = definedExternally
set(value) = definedExternally
}
interface GetComplianceSummaryByResourceTypeResponse {
var ComplianceSummariesByResourceType: ComplianceSummariesByResourceType?
get() = definedExternally
set(value) = definedExternally
}
interface GetConformancePackComplianceDetailsRequest {
var ConformancePackName: ConformancePackName
var Filters: ConformancePackEvaluationFilters?
get() = definedExternally
set(value) = definedExternally
var Limit: GetConformancePackComplianceDetailsLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetConformancePackComplianceDetailsResponse {
var ConformancePackName: ConformancePackName
var ConformancePackRuleEvaluationResults: ConformancePackRuleEvaluationResultsList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetConformancePackComplianceSummaryRequest {
var ConformancePackNames: ConformancePackNamesToSummarizeList
var Limit: PageSizeLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetConformancePackComplianceSummaryResponse {
var ConformancePackComplianceSummaryList: ConformancePackComplianceSummaryList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetDiscoveredResourceCountsRequest {
var resourceTypes: ResourceTypes?
get() = definedExternally
set(value) = definedExternally
var limit: Limit?
get() = definedExternally
set(value) = definedExternally
var nextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetDiscoveredResourceCountsResponse {
var totalDiscoveredResources: Long?
get() = definedExternally
set(value) = definedExternally
var resourceCounts: ResourceCounts?
get() = definedExternally
set(value) = definedExternally
var nextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetOrganizationConfigRuleDetailedStatusRequest {
var OrganizationConfigRuleName: OrganizationConfigRuleName
var Filters: StatusDetailFilters?
get() = definedExternally
set(value) = definedExternally
var Limit: CosmosPageLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface GetOrganizationConfigRuleDetailedStatusResponse {
var OrganizationConfigRuleDetailedStatus: OrganizationConfigRuleDetailedStatus?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface GetOrganizationConformancePackDetailedStatusRequest {
var OrganizationConformancePackName: OrganizationConformancePackName
var Filters: OrganizationResourceDetailedStatusFilters?
get() = definedExternally
set(value) = definedExternally
var Limit: CosmosPageLimit?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface GetOrganizationConformancePackDetailedStatusResponse {
var OrganizationConformancePackDetailedStatuses: OrganizationConformancePackDetailedStatuses?
get() = definedExternally
set(value) = definedExternally
var NextToken: String?
get() = definedExternally
set(value) = definedExternally
}
interface GetResourceConfigHistoryRequest {
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceId: ResourceId
var laterTime: LaterTime?
get() = definedExternally
set(value) = definedExternally
var earlierTime: EarlierTime?
get() = definedExternally
set(value) = definedExternally
var chronologicalOrder: String /* "Reverse" | "Forward" | String */
var limit: Limit?
get() = definedExternally
set(value) = definedExternally
var nextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GetResourceConfigHistoryResponse {
var configurationItems: ConfigurationItemList?
get() = definedExternally
set(value) = definedExternally
var nextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface GroupedResourceCount {
var GroupName: StringWithCharLimit256
var ResourceCount: Long
}
interface ListAggregateDiscoveredResourcesRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var ResourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var Filters: ResourceFilters?
get() = definedExternally
set(value) = definedExternally
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface ListAggregateDiscoveredResourcesResponse {
var ResourceIdentifiers: DiscoveredResourceIdentifierList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface ListDiscoveredResourcesRequest {
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceIds: ResourceIdList?
get() = definedExternally
set(value) = definedExternally
var resourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var limit: Limit?
get() = definedExternally
set(value) = definedExternally
var includeDeletedResources: Boolean?
get() = definedExternally
set(value) = definedExternally
var nextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface ListDiscoveredResourcesResponse {
var resourceIdentifiers: ResourceIdentifierList?
get() = definedExternally
set(value) = definedExternally
var nextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface ListTagsForResourceRequest {
var ResourceArn: AmazonResourceName
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface ListTagsForResourceResponse {
var Tags: TagList?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface MemberAccountStatus {
var AccountId: AccountId
var ConfigRuleName: StringWithCharLimit64
var MemberAccountRuleStatus: String /* "CREATE_SUCCESSFUL" | "CREATE_IN_PROGRESS" | "CREATE_FAILED" | "DELETE_SUCCESSFUL" | "DELETE_FAILED" | "DELETE_IN_PROGRESS" | "UPDATE_SUCCESSFUL" | "UPDATE_IN_PROGRESS" | "UPDATE_FAILED" | String */
var ErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var ErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var LastUpdateTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationAggregationSource {
var RoleArn: String
var AwsRegions: AggregatorRegionList?
get() = definedExternally
set(value) = definedExternally
var AllAwsRegions: Boolean?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationConfigRule {
var OrganizationConfigRuleName: OrganizationConfigRuleName
var OrganizationConfigRuleArn: StringWithCharLimit256
var OrganizationManagedRuleMetadata: OrganizationManagedRuleMetadata?
get() = definedExternally
set(value) = definedExternally
var OrganizationCustomRuleMetadata: OrganizationCustomRuleMetadata?
get() = definedExternally
set(value) = definedExternally
var ExcludedAccounts: ExcludedAccounts?
get() = definedExternally
set(value) = definedExternally
var LastUpdateTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationConfigRuleStatus {
var OrganizationConfigRuleName: OrganizationConfigRuleName
var OrganizationRuleStatus: String /* "CREATE_SUCCESSFUL" | "CREATE_IN_PROGRESS" | "CREATE_FAILED" | "DELETE_SUCCESSFUL" | "DELETE_FAILED" | "DELETE_IN_PROGRESS" | "UPDATE_SUCCESSFUL" | "UPDATE_IN_PROGRESS" | "UPDATE_FAILED" | String */
var ErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var ErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var LastUpdateTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationConformancePack {
var OrganizationConformancePackName: OrganizationConformancePackName
var OrganizationConformancePackArn: StringWithCharLimit256
var DeliveryS3Bucket: DeliveryS3Bucket
var DeliveryS3KeyPrefix: DeliveryS3KeyPrefix?
get() = definedExternally
set(value) = definedExternally
var ConformancePackInputParameters: ConformancePackInputParameters?
get() = definedExternally
set(value) = definedExternally
var ExcludedAccounts: ExcludedAccounts?
get() = definedExternally
set(value) = definedExternally
var LastUpdateTime: _Date
}
interface OrganizationConformancePackDetailedStatus {
var AccountId: AccountId
var ConformancePackName: StringWithCharLimit256
var Status: String /* "CREATE_SUCCESSFUL" | "CREATE_IN_PROGRESS" | "CREATE_FAILED" | "DELETE_SUCCESSFUL" | "DELETE_FAILED" | "DELETE_IN_PROGRESS" | "UPDATE_SUCCESSFUL" | "UPDATE_IN_PROGRESS" | "UPDATE_FAILED" | String */
var ErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var ErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var LastUpdateTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationConformancePackStatus {
var OrganizationConformancePackName: OrganizationConformancePackName
var Status: String /* "CREATE_SUCCESSFUL" | "CREATE_IN_PROGRESS" | "CREATE_FAILED" | "DELETE_SUCCESSFUL" | "DELETE_FAILED" | "DELETE_IN_PROGRESS" | "UPDATE_SUCCESSFUL" | "UPDATE_IN_PROGRESS" | "UPDATE_FAILED" | String */
var ErrorCode: String?
get() = definedExternally
set(value) = definedExternally
var ErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var LastUpdateTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationCustomRuleMetadata {
var Description: StringWithCharLimit256Min0?
get() = definedExternally
set(value) = definedExternally
var LambdaFunctionArn: StringWithCharLimit256
var OrganizationConfigRuleTriggerTypes: OrganizationConfigRuleTriggerTypes
var InputParameters: StringWithCharLimit2048?
get() = definedExternally
set(value) = definedExternally
var MaximumExecutionFrequency: String /* "One_Hour" | "Three_Hours" | "Six_Hours" | "Twelve_Hours" | "TwentyFour_Hours" | String */
var ResourceTypesScope: ResourceTypesScope?
get() = definedExternally
set(value) = definedExternally
var ResourceIdScope: StringWithCharLimit768?
get() = definedExternally
set(value) = definedExternally
var TagKeyScope: StringWithCharLimit128?
get() = definedExternally
set(value) = definedExternally
var TagValueScope: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationManagedRuleMetadata {
var Description: StringWithCharLimit256Min0?
get() = definedExternally
set(value) = definedExternally
var RuleIdentifier: StringWithCharLimit256
var InputParameters: StringWithCharLimit2048?
get() = definedExternally
set(value) = definedExternally
var MaximumExecutionFrequency: String /* "One_Hour" | "Three_Hours" | "Six_Hours" | "Twelve_Hours" | "TwentyFour_Hours" | String */
var ResourceTypesScope: ResourceTypesScope?
get() = definedExternally
set(value) = definedExternally
var ResourceIdScope: StringWithCharLimit768?
get() = definedExternally
set(value) = definedExternally
var TagKeyScope: StringWithCharLimit128?
get() = definedExternally
set(value) = definedExternally
var TagValueScope: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
}
interface OrganizationResourceDetailedStatusFilters {
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var Status: String /* "CREATE_SUCCESSFUL" | "CREATE_IN_PROGRESS" | "CREATE_FAILED" | "DELETE_SUCCESSFUL" | "DELETE_FAILED" | "DELETE_IN_PROGRESS" | "UPDATE_SUCCESSFUL" | "UPDATE_IN_PROGRESS" | "UPDATE_FAILED" | String */
}
interface PendingAggregationRequest {
var RequesterAccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var RequesterAwsRegion: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface PutAggregationAuthorizationRequest {
var AuthorizedAccountId: AccountId
var AuthorizedAwsRegion: AwsRegion
var Tags: TagsList?
get() = definedExternally
set(value) = definedExternally
}
interface PutAggregationAuthorizationResponse {
var AggregationAuthorization: AggregationAuthorization?
get() = definedExternally
set(value) = definedExternally
}
interface PutConfigRuleRequest {
var ConfigRule: ConfigRule
var Tags: TagsList?
get() = definedExternally
set(value) = definedExternally
}
interface PutConfigurationAggregatorRequest {
var ConfigurationAggregatorName: ConfigurationAggregatorName
var AccountAggregationSources: AccountAggregationSourceList?
get() = definedExternally
set(value) = definedExternally
var OrganizationAggregationSource: OrganizationAggregationSource?
get() = definedExternally
set(value) = definedExternally
var Tags: TagsList?
get() = definedExternally
set(value) = definedExternally
}
interface PutConfigurationAggregatorResponse {
var ConfigurationAggregator: ConfigurationAggregator?
get() = definedExternally
set(value) = definedExternally
}
interface PutConfigurationRecorderRequest {
var ConfigurationRecorder: ConfigurationRecorder
}
interface PutConformancePackRequest {
var ConformancePackName: ConformancePackName
var TemplateS3Uri: TemplateS3Uri?
get() = definedExternally
set(value) = definedExternally
var TemplateBody: TemplateBody?
get() = definedExternally
set(value) = definedExternally
var DeliveryS3Bucket: DeliveryS3Bucket
var DeliveryS3KeyPrefix: DeliveryS3KeyPrefix?
get() = definedExternally
set(value) = definedExternally
var ConformancePackInputParameters: ConformancePackInputParameters?
get() = definedExternally
set(value) = definedExternally
}
interface PutConformancePackResponse {
var ConformancePackArn: ConformancePackArn?
get() = definedExternally
set(value) = definedExternally
}
interface PutDeliveryChannelRequest {
var DeliveryChannel: DeliveryChannel
}
interface PutEvaluationsRequest {
var Evaluations: Evaluations?
get() = definedExternally
set(value) = definedExternally
var ResultToken: String
var TestMode: Boolean?
get() = definedExternally
set(value) = definedExternally
}
interface PutEvaluationsResponse {
var FailedEvaluations: Evaluations?
get() = definedExternally
set(value) = definedExternally
}
interface PutOrganizationConfigRuleRequest {
var OrganizationConfigRuleName: OrganizationConfigRuleName
var OrganizationManagedRuleMetadata: OrganizationManagedRuleMetadata?
get() = definedExternally
set(value) = definedExternally
var OrganizationCustomRuleMetadata: OrganizationCustomRuleMetadata?
get() = definedExternally
set(value) = definedExternally
var ExcludedAccounts: ExcludedAccounts?
get() = definedExternally
set(value) = definedExternally
}
interface PutOrganizationConfigRuleResponse {
var OrganizationConfigRuleArn: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
}
interface PutOrganizationConformancePackRequest {
var OrganizationConformancePackName: OrganizationConformancePackName
var TemplateS3Uri: TemplateS3Uri?
get() = definedExternally
set(value) = definedExternally
var TemplateBody: TemplateBody?
get() = definedExternally
set(value) = definedExternally
var DeliveryS3Bucket: DeliveryS3Bucket
var DeliveryS3KeyPrefix: DeliveryS3KeyPrefix?
get() = definedExternally
set(value) = definedExternally
var ConformancePackInputParameters: ConformancePackInputParameters?
get() = definedExternally
set(value) = definedExternally
var ExcludedAccounts: ExcludedAccounts?
get() = definedExternally
set(value) = definedExternally
}
interface PutOrganizationConformancePackResponse {
var OrganizationConformancePackArn: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
}
interface PutRemediationConfigurationsRequest {
var RemediationConfigurations: RemediationConfigurations
}
interface PutRemediationConfigurationsResponse {
var FailedBatches: FailedRemediationBatches?
get() = definedExternally
set(value) = definedExternally
}
interface PutRemediationExceptionsRequest {
var ConfigRuleName: ConfigRuleName
var ResourceKeys: RemediationExceptionResourceKeys
var Message: StringWithCharLimit1024?
get() = definedExternally
set(value) = definedExternally
var ExpirationTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface PutRemediationExceptionsResponse {
var FailedBatches: FailedRemediationExceptionBatches?
get() = definedExternally
set(value) = definedExternally
}
interface PutResourceConfigRequest {
var ResourceType: ResourceTypeString
var SchemaVersionId: SchemaVersionId
var ResourceId: ResourceId
var ResourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var Configuration: Configuration
var Tags: Tags?
get() = definedExternally
set(value) = definedExternally
}
interface PutRetentionConfigurationRequest {
var RetentionPeriodInDays: RetentionPeriodInDays
}
interface PutRetentionConfigurationResponse {
var RetentionConfiguration: RetentionConfiguration?
get() = definedExternally
set(value) = definedExternally
}
interface QueryInfo {
var SelectFields: FieldInfoList?
get() = definedExternally
set(value) = definedExternally
}
interface RecordingGroup {
var allSupported: AllSupported?
get() = definedExternally
set(value) = definedExternally
var includeGlobalResourceTypes: IncludeGlobalResourceTypes?
get() = definedExternally
set(value) = definedExternally
var resourceTypes: ResourceTypeList?
get() = definedExternally
set(value) = definedExternally
}
interface Relationship {
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceId: ResourceId?
get() = definedExternally
set(value) = definedExternally
var resourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var relationshipName: RelationshipName?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationConfiguration {
var ConfigRuleName: ConfigRuleName
var TargetType: String /* "SSM_DOCUMENT" | String */
var TargetId: StringWithCharLimit256
var TargetVersion: String?
get() = definedExternally
set(value) = definedExternally
var Parameters: RemediationParameters?
get() = definedExternally
set(value) = definedExternally
var ResourceType: String?
get() = definedExternally
set(value) = definedExternally
var Automatic: Boolean?
get() = definedExternally
set(value) = definedExternally
var ExecutionControls: ExecutionControls?
get() = definedExternally
set(value) = definedExternally
var MaximumAutomaticAttempts: AutoRemediationAttempts?
get() = definedExternally
set(value) = definedExternally
var RetryAttemptSeconds: AutoRemediationAttemptSeconds?
get() = definedExternally
set(value) = definedExternally
var Arn: StringWithCharLimit1024?
get() = definedExternally
set(value) = definedExternally
var CreatedByService: StringWithCharLimit1024?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationException {
var ConfigRuleName: ConfigRuleName
var ResourceType: StringWithCharLimit256
var ResourceId: StringWithCharLimit1024
var Message: StringWithCharLimit1024?
get() = definedExternally
set(value) = definedExternally
var ExpirationTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationExceptionResourceKey {
var ResourceType: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ResourceId: StringWithCharLimit1024?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationExecutionStatus {
var ResourceKey: ResourceKey?
get() = definedExternally
set(value) = definedExternally
var State: String /* "QUEUED" | "IN_PROGRESS" | "SUCCEEDED" | "FAILED" | String */
var StepDetails: RemediationExecutionSteps?
get() = definedExternally
set(value) = definedExternally
var InvocationTime: _Date?
get() = definedExternally
set(value) = definedExternally
var LastUpdatedTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationExecutionStep {
var Name: String?
get() = definedExternally
set(value) = definedExternally
var State: String /* "SUCCEEDED" | "PENDING" | "FAILED" | String */
var ErrorMessage: String?
get() = definedExternally
set(value) = definedExternally
var StartTime: _Date?
get() = definedExternally
set(value) = definedExternally
var StopTime: _Date?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationParameterValue {
var ResourceValue: ResourceValue?
get() = definedExternally
set(value) = definedExternally
var StaticValue: StaticValue?
get() = definedExternally
set(value) = definedExternally
}
interface RemediationParameters {
@nativeGetter
operator fun get(key: String): RemediationParameterValue?
@nativeSetter
operator fun set(key: String, value: RemediationParameterValue)
}
interface ResourceCount {
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var count: Long?
get() = definedExternally
set(value) = definedExternally
}
interface ResourceCountFilters {
var ResourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var Region: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface ResourceFilters {
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var ResourceId: ResourceId?
get() = definedExternally
set(value) = definedExternally
var ResourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var Region: AwsRegion?
get() = definedExternally
set(value) = definedExternally
}
interface ResourceIdentifier {
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceId: ResourceId?
get() = definedExternally
set(value) = definedExternally
var resourceName: ResourceName?
get() = definedExternally
set(value) = definedExternally
var resourceDeletionTime: ResourceDeletionTime?
get() = definedExternally
set(value) = definedExternally
}
interface ResourceKey {
var resourceType: String /* "AWS::EC2::CustomerGateway" | "AWS::EC2::EIP" | "AWS::EC2::Host" | "AWS::EC2::Instance" | "AWS::EC2::InternetGateway" | "AWS::EC2::NetworkAcl" | "AWS::EC2::NetworkInterface" | "AWS::EC2::RouteTable" | "AWS::EC2::SecurityGroup" | "AWS::EC2::Subnet" | "AWS::CloudTrail::Trail" | "AWS::EC2::Volume" | "AWS::EC2::VPC" | "AWS::EC2::VPNConnection" | "AWS::EC2::VPNGateway" | "AWS::EC2::RegisteredHAInstance" | "AWS::EC2::NatGateway" | "AWS::EC2::EgressOnlyInternetGateway" | "AWS::EC2::VPCEndpoint" | "AWS::EC2::VPCEndpointService" | "AWS::EC2::FlowLog" | "AWS::EC2::VPCPeeringConnection" | "AWS::Elasticsearch::Domain" | "AWS::IAM::Group" | "AWS::IAM::Policy" | "AWS::IAM::Role" | "AWS::IAM::User" | "AWS::ElasticLoadBalancingV2::LoadBalancer" | "AWS::ACM::Certificate" | "AWS::RDS::DBInstance" | "AWS::RDS::DBSubnetGroup" | "AWS::RDS::DBSecurityGroup" | "AWS::RDS::DBSnapshot" | "AWS::RDS::DBCluster" | "AWS::RDS::DBClusterSnapshot" | "AWS::RDS::EventSubscription" | "AWS::S3::Bucket" | "AWS::S3::AccountPublicAccessBlock" | "AWS::Redshift::Cluster" | "AWS::Redshift::ClusterSnapshot" | "AWS::Redshift::ClusterParameterGroup" | "AWS::Redshift::ClusterSecurityGroup" | "AWS::Redshift::ClusterSubnetGroup" | "AWS::Redshift::EventSubscription" | "AWS::SSM::ManagedInstanceInventory" | "AWS::CloudWatch::Alarm" | "AWS::CloudFormation::Stack" | "AWS::ElasticLoadBalancing::LoadBalancer" | "AWS::AutoScaling::AutoScalingGroup" | "AWS::AutoScaling::LaunchConfiguration" | "AWS::AutoScaling::ScalingPolicy" | "AWS::AutoScaling::ScheduledAction" | "AWS::DynamoDB::Table" | "AWS::CodeBuild::Project" | "AWS::WAF::RateBasedRule" | "AWS::WAF::Rule" | "AWS::WAF::RuleGroup" | "AWS::WAF::WebACL" | "AWS::WAFRegional::RateBasedRule" | "AWS::WAFRegional::Rule" | "AWS::WAFRegional::RuleGroup" | "AWS::WAFRegional::WebACL" | "AWS::CloudFront::Distribution" | "AWS::CloudFront::StreamingDistribution" | "AWS::Lambda::Function" | "AWS::ElasticBeanstalk::Application" | "AWS::ElasticBeanstalk::ApplicationVersion" | "AWS::ElasticBeanstalk::Environment" | "AWS::WAFv2::WebACL" | "AWS::WAFv2::RuleGroup" | "AWS::WAFv2::IPSet" | "AWS::WAFv2::RegexPatternSet" | "AWS::WAFv2::ManagedRuleSet" | "AWS::XRay::EncryptionConfig" | "AWS::SSM::AssociationCompliance" | "AWS::SSM::PatchCompliance" | "AWS::Shield::Protection" | "AWS::ShieldRegional::Protection" | "AWS::Config::ResourceCompliance" | "AWS::ApiGateway::Stage" | "AWS::ApiGateway::RestApi" | "AWS::ApiGatewayV2::Stage" | "AWS::ApiGatewayV2::Api" | "AWS::CodePipeline::Pipeline" | "AWS::ServiceCatalog::CloudFormationProvisionedProduct" | "AWS::ServiceCatalog::CloudFormationProduct" | "AWS::ServiceCatalog::Portfolio" | "AWS::SQS::Queue" | "AWS::KMS::Key" | "AWS::QLDB::Ledger" | String */
var resourceId: ResourceId
}
interface ResourceValue {
var Value: String /* "RESOURCE_ID" | String */
}
interface RetentionConfiguration {
var Name: RetentionConfigurationName
var RetentionPeriodInDays: RetentionPeriodInDays
}
interface Scope {
var ComplianceResourceTypes: ComplianceResourceTypes?
get() = definedExternally
set(value) = definedExternally
var TagKey: StringWithCharLimit128?
get() = definedExternally
set(value) = definedExternally
var TagValue: StringWithCharLimit256?
get() = definedExternally
set(value) = definedExternally
var ComplianceResourceId: BaseResourceId?
get() = definedExternally
set(value) = definedExternally
}
interface SelectAggregateResourceConfigRequest {
var Expression: Expression
var ConfigurationAggregatorName: ConfigurationAggregatorName
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var MaxResults: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface SelectAggregateResourceConfigResponse {
var Results: Results?
get() = definedExternally
set(value) = definedExternally
var QueryInfo: QueryInfo?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface SelectResourceConfigRequest {
var Expression: Expression
var Limit: Limit?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface SelectResourceConfigResponse {
var Results: Results?
get() = definedExternally
set(value) = definedExternally
var QueryInfo: QueryInfo?
get() = definedExternally
set(value) = definedExternally
var NextToken: NextToken?
get() = definedExternally
set(value) = definedExternally
}
interface Source {
var Owner: String /* "CUSTOM_LAMBDA" | "AWS" | String */
var SourceIdentifier: StringWithCharLimit256
var SourceDetails: SourceDetails?
get() = definedExternally
set(value) = definedExternally
}
interface SourceDetail {
var EventSource: String /* "aws.config" | String */
var MessageType: String /* "ConfigurationItemChangeNotification" | "ConfigurationSnapshotDeliveryCompleted" | "ScheduledNotification" | "OversizedConfigurationItemChangeNotification" | String */
var MaximumExecutionFrequency: String /* "One_Hour" | "Three_Hours" | "Six_Hours" | "Twelve_Hours" | "TwentyFour_Hours" | String */
}
interface SsmControls {
var ConcurrentExecutionRatePercentage: Percentage?
get() = definedExternally
set(value) = definedExternally
var ErrorPercentage: Percentage?
get() = definedExternally
set(value) = definedExternally
}
interface StartConfigRulesEvaluationRequest {
var ConfigRuleNames: ReevaluateConfigRuleNames?
get() = definedExternally
set(value) = definedExternally
}
interface StartConfigRulesEvaluationResponse
interface StartConfigurationRecorderRequest {
var ConfigurationRecorderName: RecorderName
}
interface StartRemediationExecutionRequest {
var ConfigRuleName: ConfigRuleName
var ResourceKeys: ResourceKeys
}
interface StartRemediationExecutionResponse {
var FailureMessage: String?
get() = definedExternally
set(value) = definedExternally
var FailedItems: ResourceKeys?
get() = definedExternally
set(value) = definedExternally
}
interface StaticValue {
var Values: StaticParameterValues
}
interface StatusDetailFilters {
var AccountId: AccountId?
get() = definedExternally
set(value) = definedExternally
var MemberAccountRuleStatus: String /* "CREATE_SUCCESSFUL" | "CREATE_IN_PROGRESS" | "CREATE_FAILED" | "DELETE_SUCCESSFUL" | "DELETE_FAILED" | "DELETE_IN_PROGRESS" | "UPDATE_SUCCESSFUL" | "UPDATE_IN_PROGRESS" | "UPDATE_FAILED" | String */
}
interface StopConfigurationRecorderRequest {
var ConfigurationRecorderName: RecorderName
}
interface SupplementaryConfiguration {
@nativeGetter
operator fun get(key: String): SupplementaryConfigurationValue?
@nativeSetter
operator fun set(key: String, value: SupplementaryConfigurationValue)
}
interface Tag {
var Key: TagKey?
get() = definedExternally
set(value) = definedExternally
var Value: TagValue?
get() = definedExternally
set(value) = definedExternally
}
interface TagResourceRequest {
var ResourceArn: AmazonResourceName
var Tags: TagList
}
interface Tags {
@nativeGetter
operator fun get(key: String): Value?
@nativeSetter
operator fun set(key: String, value: Value)
}
interface UntagResourceRequest {
var ResourceArn: AmazonResourceName
var TagKeys: TagKeyList
}
interface ClientApiVersions {
var apiVersion: String /* "2014-11-12" | "latest" | String */
}
} | 0 | Kotlin | 0 | 0 | 6c20e6277ea66e531b4b46017faa10270b25b8bc | 169,832 | kt-js-lambda-cdk-test | Apache License 2.0 |
app/src/main/java/com/flexcode/jetweather/presentation/compossables/screens/home/HomeScreen.kt | Felix-Kariuki | 503,790,694 | false | {"Kotlin": 61879} | package com.flexcode.jetweather.presentation.compossables.screens.home
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
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.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.flexcode.jetweather.data.models.Forecastday
import com.flexcode.jetweather.domain.model.Locations
import com.flexcode.jetweather.presentation.compossables.screens.home.components.DailyItem
import com.flexcode.jetweather.ui.theme.Blue
import com.flexcode.jetweather.ui.theme.DarkBackground
import com.flexcode.jetweather.ui.theme.Gray
import com.flexcode.jetweather.utils.dayOfTheWeek
import com.hitanshudhawan.circularprogressbar.CircularProgressBar
import com.ramcosta.composedestinations.annotation.Destination
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
@Destination(start = true)
@Composable
fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel()
) {
val state = viewModel.state.value
val context = LocalContext.current
val locationDialog = remember { mutableStateOf(false) }
val localLocations: List<Locations> =
viewModel.allLocations.observeAsState().value ?: emptyList()
/**
* Remember to implement delete a city
*/
if (state.isLoading) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Gray),
contentAlignment = Alignment.Center
) {
CircularProgressBar(
modifier = Modifier.size(120.dp),
progress = 30f,
progressMax = 100f,
progressBarColor = Color.Blue,
progressBarWidth = 20.dp,
backgroundProgressBarColor = Color.Gray,
backgroundProgressBarWidth = 10.dp,
roundBorder = true,
startAngle = 90f
)
}
}
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.background(DarkBackground),
) {
Row(
modifier = Modifier.fillMaxWidth()
) {
LazyRow(
contentPadding = PaddingValues(end = 8.dp),
content = {
items(localLocations) { location ->
Card(
modifier = Modifier
.padding(start = 4.dp)
.height(30.dp)
.clickable {
viewModel.saveToSharedPrefs(location.locationName)
Toast
.makeText(
context, "${location.locationName} set as Default",
Toast.LENGTH_LONG
)
.show()
},
backgroundColor = if (location.locationName == viewModel.currentLocation.value) {
Blue
} else Gray,
elevation = 5.dp,
shape = RoundedCornerShape(8.dp)
) {
Row(
modifier = Modifier
.padding(start = 8.dp, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = location.locationName,
color = Color.White
)
IconButton(onClick = {
GlobalScope.launch(Dispatchers.Main) {
viewModel.deleteLocation(Locations(locationName = location.locationName))
}
Toast.makeText(context,"${location.locationName} Deleted..",
Toast.LENGTH_LONG).show()
}) {
Icon(
imageVector = Icons.Default.Clear,
tint = Color.White,
contentDescription = null
)
}
}
}
}
}
)
Card(
modifier = Modifier
.padding(start = 4.dp)
.height(30.dp)
.clickable {
locationDialog.value = true
}
.background(Blue)
.width(30.dp)
) {
Icon(
Icons.Default.Add,
contentDescription = "Add City",
modifier = Modifier.size(ButtonDefaults.IconSize)
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.Start
) {
Icon(
modifier = Modifier.size(16.dp),
imageVector = Icons.Outlined.LocationOn,
contentDescription = null,
tint = Color.White
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "${state.data?.location?.name}, ${state.data?.location?.country} ",
color = Color.White,
fontSize = 20.sp
)
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(
modifier = Modifier.padding(start = 16.dp),
horizontalAlignment = Alignment.Start
) {
Text(
text = "${state.data?.current?.tempC}${0x00B0.toChar()}",
style = MaterialTheme.typography.h2.merge(),
color = Color.White,
textAlign = TextAlign.Start,
modifier = Modifier
.padding(
start = 18.dp,
end = 18.dp,
)
)
Text(
text = "${state.data?.current?.condition?.text}",
style = MaterialTheme.typography.body1.merge(),
color = Color.White,
textAlign = TextAlign.Start,
modifier = Modifier
.padding(
start = 18.dp,
bottom = 8.dp
)
)
}
Column(
modifier = Modifier
.aspectRatio(2f)
.padding(end = 16.dp),
horizontalAlignment = Alignment.End
) {
AsyncImage(
model = ImageRequest.Builder(context)
.data("https:${state.data?.current?.condition?.icon}")
.crossfade(true)
.build(),
contentDescription = "${state.data?.current?.condition?.text}",
modifier = Modifier
.size(100.dp)
)
}
}
Column(
modifier = Modifier
.clip(
shape = RoundedCornerShape(10.dp)
)
.background(DarkBackground)
) {
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
DetailsItem(
text1 = "Feels Like",
textValue = "${state.data?.current?.feelslikeC}${0x00B0.toChar()}"
)
Spacer(modifier = Modifier.width(8.dp))
DetailsItem(
text1 = "Wind Speed",
textValue = "${state.data?.current?.windKph} kp/h"
)
Spacer(modifier = Modifier.width(8.dp))
DetailsItem(
text1 = "Pressure",
textValue = "${state.data?.current?.pressureMb} Mb"
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(4.dp),
horizontalArrangement = Arrangement.Center
) {
DetailsItem(
text1 = "Humidity",
textValue = "${state.data?.current?.humidity}%"
)
Spacer(modifier = Modifier.width(8.dp))
//val windDir = "${state.data?.current?.windDir}"
DetailsItem(
text1 = "Wind direction",
textValue = "${state.data?.current?.windDir}"
)
Spacer(modifier = Modifier.width(8.dp))
DetailsItem(
text1 = "Uv Index",
textValue = "${state.data?.current?.uv}"
)
}
}
LazyRow(
contentPadding = PaddingValues(horizontal = 8.dp),
content = {
val hourForecast: List<Forecastday> =
state.data?.forecast?.forecastday ?: emptyList()
items(hourForecast) {
it.hour.forEach { hour ->
HourItem(
icon = "https:${hour.condition?.icon}",
degrees = hour.tempC?.toFloat() ?: 0F,
time = hour.time!!,
)
}
}
}
)
Column(
modifier = Modifier
.size(height = 250.dp, width = 480.dp)
.padding(start = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
LazyColumn(
contentPadding = PaddingValues(vertical = 2.dp),
content = {
val dailyForecast: List<Forecastday> =
state.data?.forecast?.forecastday ?: emptyList()
items(dailyForecast) { details ->
details.day.avgtempC?.toFloat()?.let { it1 ->
DailyItem(
day = dayOfTheWeek(details.date!!),
degrees = it1,
icon = "https:${details.day.condition?.icon}"
)
}
}
})
}
if (locationDialog.value) {
AlertDialog(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
onDismissRequest = { locationDialog.value = false },
title = {
Text(
style = TextStyle(
color = Color.White,
fontSize = 16.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold
),
text = "Add a Location",
modifier = Modifier.padding(8.dp),
)
},
text = {
TextField(
value = viewModel.locationDialogValue.value,
onValueChange = {
viewModel.setLocationDialogValue(it)
},
textStyle = TextStyle(color = Color.White),
placeholder = { Text(text = "Nairobi", color = Color.LightGray) },
)
},
confirmButton = {
Button(
colors = ButtonDefaults.buttonColors(Blue),
onClick = {
viewModel.addLocation()
locationDialog.value = false
Toast.makeText(context, "Locations added", Toast.LENGTH_LONG).show()
}
) {
Text(text = "Add", color = Color.White)
}
},
backgroundColor = Gray,
contentColor = Color.White,
shape = RoundedCornerShape(12.dp)
)
}
}
}
| 1 | Kotlin | 0 | 7 | d307a4d9a0c874c90f8e6e14bf1428237eb7b077 | 14,469 | JetWeather | MIT License |
src/jvmTest/kotlin/com/github/kotlinizer/mqtt/Actual.kt | kotlinizer | 182,853,094 | false | null | package com.github.kotlinizer.mqtt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking
import java.io.File
import java.io.IOException
import java.lang.System.currentTimeMillis
import java.lang.System.getProperty
import java.nio.file.Paths.get
actual class Process actual constructor(private val commands: List<String>) {
private lateinit var process: java.lang.Process
actual fun start() {
process = ProcessBuilder(commands).inheritIO().start()
Thread.sleep(1000) // Wait for process to start
}
actual fun stop() {
process.destroyForcibly()
}
}
actual class TmpFile {
actual val path = get(
getProperty("java.io.tmpdir"),
currentTimeMillis().toString()
).toAbsolutePath().toString()
private val file = File(path)
init {
if (!file.createNewFile()) {
throw IOException("Unable to create new file.")
}
Thread.sleep(10) // await before new file can be created
}
actual fun write(data: String) {
file.outputStream().use {
it.write(data.toByteArray())
}
}
actual fun delete() {
file.delete()
}
}
actual fun blockThread(method: suspend CoroutineScope.() -> Unit) {
runBlocking {
method(this)
}
}
actual val milliseconds: Long
get() = currentTimeMillis() | 0 | Kotlin | 3 | 3 | 54d1894d1712750d71d5fc65e394730704c2981f | 1,375 | kotlin-mqtt-client | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinInterfaceDerivedInnerClasses.1.kt | ingokegel | 72,937,917 | false | null | class Outer {
open class B : A() {
}
open class C : Y {
}
class Inner {
open class Z : A() {
}
open class U : Z() {
}
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 185 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/PuppyDetails.kt | bentrengrove | 342,062,576 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import android.app.Activity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.ui.theme.MyTheme
private const val START_TOP_PADDING = 160
@Composable
fun PuppyDetails(puppy: Puppy, modifier: Modifier = Modifier) {
val context = LocalContext.current as? Activity
val scrollState = rememberScrollState()
// Calculate the offset of the background image to make it scroll with a parallax effect
val imageOffset = (-scrollState.value * 0.2f).dp
// Calculate the alpha used in the background of the back arrow
val iconBackgroundAlpha = ((scrollState.value / START_TOP_PADDING.toFloat()) * 0.2f).coerceAtMost(0.2f)
Box {
Image(
painter = painterResource(id = puppy.resId),
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.offset(y = imageOffset)
.height(200.dp)
.fillMaxWidth()
)
Column(
Modifier
.verticalScroll(scrollState)
.padding(top = START_TOP_PADDING.dp)
.background(
MaterialTheme.colors.surface,
RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp)
)
.fillMaxHeight()
.fillMaxWidth()
.padding(all = 32.dp)
) {
Text("Hello my name is", style = MaterialTheme.typography.h6)
Text(text = puppy.name, style = MaterialTheme.typography.h3)
Spacer(Modifier.size(16.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
Detail("Breed 🐶", "Spoodle")
Detail("Weight ⚖️", "8 kg")
Detail("Sex ⚤", detail = "Female")
}
Spacer(modifier = Modifier.size(16.dp))
Text(text = "${puppy.name} is a lively 12 week old Spoodle. She is very playful, friendly and gentle. She would be great with little children.\n\n$LORIM")
}
IconButton(onClick = { context?.onBackPressed() }, modifier = Modifier.padding(8.dp).background(Color.Black.copy(alpha = iconBackgroundAlpha), shape = CircleShape)) {
Icon(
painter = painterResource(id = R.drawable.ic_arrow_back_24),
contentDescription = null,
modifier = Modifier
.size(32.dp),
tint = Color.White
)
}
}
}
@Composable
private fun Detail(heading: String, detail: String, modifier: Modifier = Modifier) {
Column(modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Text(heading, style = MaterialTheme.typography.h6)
Text(detail, style = MaterialTheme.typography.subtitle1)
}
}
@Preview
@Composable
private fun PuppyPreview() {
MyTheme {
PuppyDetails(puppy = PuppyRepo.puppies.first())
}
}
private const val LORIM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nulla ipsum, dignissim ut finibus eu, ultricies non velit. Mauris pharetra leo ligula, eget consequat ipsum suscipit molestie. Cras diam orci, imperdiet et sem in, pharetra euismod nunc. Nullam placerat odio mollis dignissim lacinia. Etiam odio lorem, interdum eu fermentum ut, hendrerit sed orci. Integer non cursus ligula. Ut bibendum turpis sit amet placerat ullamcorper. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque dolor mi, consectetur ut justo at, venenatis aliquam nisl. Donec congue lacus non ipsum luctus, vitae finibus dolor suscipit. Aenean sed lectus porta, ullamcorper quam non, pulvinar sem. Sed lectus lorem, cursus eget vestibulum id, volutpat non felis. Sed pulvinar, justo non finibus consectetur, nunc sem convallis sapien, a scelerisque massa elit eget ex.\n" +
"\n" +
"Vestibulum feugiat neque faucibus risus bibendum pulvinar. Nulla viverra mi at risus egestas fermentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Proin facilisis arcu ut commodo pulvinar. Sed dapibus nisi ac mi accumsan mollis. Integer id sagittis sem, a dictum libero. Sed eget aliquet nisi. Fusce venenatis pulvinar elementum. Suspendisse in nibh scelerisque, lobortis sapien sed, tempor nunc. Sed vitae faucibus tortor. Donec finibus enim et porta consectetur."
| 0 | Kotlin | 1 | 4 | 02bc5dbbf2797de40366e7c9f4d093f51233d147 | 6,453 | composedevchallenge-week1 | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/Algebraics.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: Algebraics
*
* Full name: System`Algebraics
*
* Usage: Algebraics represents the domain of algebraic numbers, as in x ∈ Algebraics.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/Algebraics
* Documentation: web: http://reference.wolfram.com/language/ref/Algebraics.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun algebraics(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("Algebraics", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 994 | mathemagika | Apache License 2.0 |
community/src/main/java/com/ekoapp/ekosdk/uikit/community/edit/EkoCommunityProfileActivity.kt | amadeus-n | 467,842,651 | true | {"Kotlin": 1114879} | package com.ekoapp.ekosdk.uikit.community.edit
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.ekoapp.ekosdk.uikit.community.R
import com.ekoapp.ekosdk.uikit.community.ui.viewModel.EkoCreateCommunityViewModel
import com.ekoapp.ekosdk.uikit.components.EkoToolBarClickListener
import kotlinx.android.synthetic.main.amity_activity_create_community.*
import kotlinx.android.synthetic.main.amity_activity_edit_community.*
class EkoCommunityProfileActivity : AppCompatActivity(), EkoToolBarClickListener {
private lateinit var mFragment: EkoCommunityProfileEditFragment
private val mViewModel: EkoCreateCommunityViewModel by viewModels()
private var communityId = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.amity_activity_edit_community)
communityId = intent?.getStringExtra(COMMUNITY_ID) ?: ""
setUpToolbar()
loadFragment()
mViewModel.initialStateChanged.observe(this, Observer {
editCommunityToolbar.setRightStringActive(it)
})
}
private fun setUpToolbar() {
editCommunityToolbar.setLeftDrawable(
ContextCompat.getDrawable(this, R.drawable.amity_ic_arrow_back)
)
editCommunityToolbar.setLeftString(getString(R.string.amity_edit_profile))
editCommunityToolbar.setRightString(getString(R.string.amity_save))
editCommunityToolbar.setClickListener(this)
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
setSupportActionBar(communityToolbar)
}
private fun loadFragment() {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
mFragment = EkoCommunityProfileEditFragment.Builder().edit(communityId).build(this)
fragmentTransaction.replace(R.id.fragmentContainer, mFragment)
fragmentTransaction.commit()
}
override fun leftIconClick() {
mFragment.onLeftIconClick()
}
override fun rightIconClick() {
mFragment.onRightIconClick()
}
companion object {
private const val COMMUNITY_ID = "COMMUNITY_ID"
fun newIntent(context: Context, communityId: String = "") =
Intent(context, EkoCommunityProfileActivity::class.java).apply {
putExtra(COMMUNITY_ID, communityId)
}
}
} | 0 | null | 0 | 0 | d4fe097da96f71ab281c9b39fafdaa901aed377c | 2,664 | ASC-UIKit-Android | Microsoft Public License |
tests/test-interfaces/src/androidInstrumentedTest/kotlin/io/deepmedia/tools/knee/tests/InterfaceTests.kt | deepmedia | 552,404,398 | false | {"Kotlin": 544280} | package io.deepmedia.tools.knee.tests
import org.junit.Test
import java.lang.System.identityHashCode
// TODO: test garbage collection
class InterfaceTests {
companion object {
init {
System.loadLibrary("test_interfaces")
}
}
val jvm = object : Callback {
override var counter: UInt = 0u
override val description: String get() = "[JVM::description, ${toString()}]"
override fun describe(): String = "[JVM::describe(), ${toString()}]".also { counter++ }
override fun describeNullable(actuallyDescribe: Boolean?): String? {
return if (actuallyDescribe == true) describe() else null
}
override fun hashCode(): Int = 999999
override fun toString(): String = "Item@${identityHashCode(this)}"
}
@Test
fun testCodecPreservesObject() {
callback = jvm
require(callback === jvm)
}
@Test
fun testEncodedFunctions() {
jvm.counter = 3u
require(invokeCallbackDescribe(jvm) == jvm.describe())
require(invokeCallbackDescription(jvm) == jvm.description)
require(invokeCallbackGetCounter(jvm) == jvm.counter)
}
@Test
fun testEncodedDefaultFunctions() {
require(invokeCallbackHashCode(jvm) == jvm.hashCode())
require(invokeCallbackToString(jvm) == jvm.toString())
require(invokeCallbackEquals(jvm, jvm))
}
@Test
fun testEncodedFunctions_native() {
val kn = createCallback()
kn.counter = 5u
require(invokeCallbackDescribe(kn) == kn.describe())
require(invokeCallbackDescription(kn) == kn.description)
require(invokeCallbackGetCounter(kn) == kn.counter)
}
@Test
fun testEncodedDefaultFunctions_native() {
val kn = createCallback()
require(invokeCallbackHashCode(kn) == kn.hashCode())
require(invokeCallbackToString(kn) == kn.toString())
require(invokeCallbackEquals(kn, kn))
}
@Test
fun testNullableArguments() {
check(null == invokeCallbackDescribeNullable(jvm, false))
check(null == invokeCallbackDescribeNullable(jvm, null))
check(jvm.describe() == invokeCallbackDescribeNullable(jvm, true))
val kn = createCallback()
check(null == kn.describeNullable(false))
check(null == kn.describeNullable(null))
check(invokeCallbackDescribe(kn) == kn.describeNullable(true))
}
@Test
fun testCounterUpdate() {
val kn = createCallback()
// update on JVM, retreive natively
jvm.counter = 100u
kn.counter = 100u
require(jvm.counter == invokeCallbackGetCounter(kn))
// update on KN, retreive natively
invokeCallbackSetCounter(jvm, 200u)
invokeCallbackSetCounter(kn, 200u)
require(jvm.counter == invokeCallbackGetCounter(kn))
}
@Test
fun testCounterRetreival() {
val kn = createCallback()
// update natively, retreive on JVM
jvm.counter = 300u
invokeCallbackSetCounter(kn, 300u)
require(jvm.counter == kn.counter)
require(jvm.counter == 300u)
// update natively, retreive on KN
jvm.counter = 400u
invokeCallbackSetCounter(kn, 400u)
require(invokeCallbackGetCounter(jvm) == invokeCallbackGetCounter(kn))
require(invokeCallbackGetCounter(kn) == 400u)
}
}
| 5 | Kotlin | 2 | 76 | 033fe352320a38b882381929fecb7b1811e00ebb | 3,400 | Knee | Apache License 2.0 |
app/src/main/java/com/kaelesty/shoppinglist/data/ShopItemDbModel.kt | Kaelesty | 669,493,927 | false | null | package com.kaelesty.shoppinglist.data
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.kaelesty.shoppinglist.domain.SHOP_ITEM_EMPTY_ID
import com.kaelesty.shoppinglist.domain.ShopItem
@Entity(tableName = "shop_items")
data class ShopItemDbModel(
@PrimaryKey(autoGenerate = true) var id: Int = SHOP_ITEM_EMPTY_ID,
val name: String,
val quantity: Int,
val isActive: Boolean,
) | 0 | Kotlin | 0 | 0 | da6f5104647f1373c12799470ffe2fa478324f82 | 405 | study-android-shopping_list | The Unlicense |
data/src/main/java/com/bottlerocketstudios/brarchitecture/data/network/BitbucketFailure.kt | BottleRocketStudios | 323,985,026 | false | null | package com.bottlerocketstudios.brarchitecture.data.network
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Common wrapper for bitbucket error responses.
* Example api docs showing definitions of below values at https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/src#get
*/
@JsonClass(generateAdapter = true)
internal data class BitbucketFailure(
/** Base type for most resource objects. It defines the common type element that identifies an object's type. It also identifies the element as Swagger's discriminator. */
@Json(name = "type") val type: String? = "",
@Json(name = "error") val error: BitbucketError? = null
)
@JsonClass(generateAdapter = true)
internal data class BitbucketError(
@Json(name = "message") val message: String? = ""
)
| 1 | Kotlin | 1 | 9 | e3014001732516e9feab58c862e0d84de9911c83 | 853 | Android-ArchitectureDemo | Apache License 2.0 |
slink-zero/src/main/kotlin/io/slink/string/strings.kt | cosmin-marginean | 632,549,322 | false | null | package io.slink.string
import java.net.URLEncoder
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.regex.Pattern
val REGEX_NON_ALPHA = "[^a-zA-Z\\d]+".toRegex()
val REGEX_WHITESPACE = "\\s+".toRegex()
fun String.urlEncode(charset: Charset = StandardCharsets.UTF_8): String {
return URLEncoder.encode(this, charset.name())
}
fun String.cleanWhitespace(): String {
return replace(REGEX_WHITESPACE, " ").trim()
}
fun String.titleCaseFirstChar(locale: Locale = Locale.getDefault()): String {
return replaceFirstChar { it.titlecase(locale) }
}
fun String.cleanEmail(): String {
return cleanWhitespace().lowercase()
}
fun String.ellipsis(maxLength: Int): String {
return if (this.length > maxLength) {
this.take(maxLength - 3) + "..."
} else {
this
}
}
fun String?.nullIfBlank(): String? {
return if (this != null && this.isBlank()) {
null
} else {
this
}
}
fun String.anonymizeEmail(visibleEndChars: Int = 0): String {
val elements = this.split("@")
return elements[0].anonymize(visibleEndChars) + "@" + elements[1].anonymize(visibleEndChars)
}
fun String.anonymize(visibleEndChars: Int = 0): String {
val visibleStartIndex = (this.length - visibleEndChars).coerceAtLeast(0)
return String(this
.toCharArray()
.mapIndexed { index, char ->
if (index < visibleStartIndex) '*' else char
}
.toCharArray()
)
}
private val DOMAIN_COLON_SLASHES = ".*://".toRegex()
private val DOMAIN_PORT = ":.*".toRegex()
private val DOMAIN_REST_OF_PATH = "/.*".toRegex()
fun String.domain(): String {
return this
.lowercase()
.replace(DOMAIN_COLON_SLASHES, "")
.replace(DOMAIN_PORT, "")
.replace(DOMAIN_REST_OF_PATH, "")
}
fun String.toLines(): List<String> {
return this.split("\n")
.map { it.trim() }
.filter { it.isNotEmpty() }
}
fun <E : Enum<E>> Enum<E>.enumLabel(): String {
return this.name.enumLabel()
}
fun String.enumLabel(): String {
return this.replace("_", " ").lowercase().titleCaseFirstChar()
}
private val PATTERN_KEBAB = Pattern.compile("-([a-z])")
private val REGEX_CAMEL = "([a-z0-9])([A-Z])".toRegex()
fun String.camelToKebabCase(): String {
return this.replace(REGEX_CAMEL, "$1-$2").lowercase()
}
fun String.kebabToCamelCase(): String {
return PATTERN_KEBAB
.matcher(this)
.replaceAll { mr -> mr.group(1).uppercase() }
}
| 0 | Kotlin | 0 | 0 | f212cb1b674673b8144cc816c3f0406420dbc8df | 2,517 | slink | Apache License 2.0 |
app/src/main/kotlin/com/optimizely/app/data/Models.kt | jophde | 192,637,682 | false | {"Gradle": 3, "XML": 923, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Java": 2, "Kotlin": 10} | @file:Suppress("unused")
package com.optimizely.app.data
import io.realm.RealmObject
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
/**
* Created by jdeffibaugh on 12/9/15 for Optimizely.
*
* Models for app
*
* Realm objects can not be used across. Since view manipulation can be done on the UI thread
* and I/O should be on a background thread we need a separate UI only model. The conversion should
* happen inside of a map function in an RxJava chain.
*/
open class Project(
@PrimaryKey open var id: Long = -1,
open var projectName: String = "",
@Index open var accountId: Long = -1,
open var ipAnonymization: Boolean = false,
open var projectStatus: String = "",
open var created: String = "",
open var lastModified: String = ""
) : RealmObject() {
override fun equals(other: Any?): Boolean {
if (other is Project) {
return id.equals(other.id);
}
return false;
}
override fun hashCode(): Int {
return id.hashCode();
}
}
open class Token(
@PrimaryKey open var accessToken: String = "",
open var expiresIn: Long = -1,
open var tokenType: String = "",
open var refreshToken: String = ""
) : RealmObject()
| 0 | Kotlin | 0 | 0 | e2d352143943dd4f1ba748e942ccd44526d1fd45 | 1,296 | kotlin-demo-app | Apache License 2.0 |
core/src/main/kotlin/com/vinaysshenoy/chronicle/EventRecord.kt | vinaysshenoy | 113,081,530 | false | null | package com.vinaysshenoy.chronicle
data class EventRecord(val event: String, val eventTimeMillis: Long) | 7 | Kotlin | 0 | 1 | b100128ada83fa4767ba28830d46b0784a74ab99 | 104 | Chronicle | Apache License 2.0 |
RefactoringToDesignPatterns/StrategyPatternPractice/task/src/main/kotlin/jetbrains/refactoring/course/patterns/strategy/CreditCardPayment.kt | Nikolay1580 | 772,660,955 | false | {"Kotlin": 16061} | package jetbrains.refactoring.course.patterns.strategy
class CreditCardPayment : PaymentStrategy {
override fun processPayment(amount: Double) {
println("Processing credit card payment amount: $amount")
}
}
| 0 | Kotlin | 0 | 0 | c8ca3ab60fd7ce382ac10c28b9e13c9e9a5d10da | 224 | Refactoring_Course | MIT License |
composeApp/src/commonMain/kotlin/com/beatrice/rickmortycast/presentation/App.kt | BKinya | 853,739,471 | false | {"Kotlin": 58750, "Swift": 737, "Shell": 206} | package com.beatrice.rickmortycast.presentation
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.beatrice.rickmortycast.presentation.navigation.RickMortyNavHost
import com.beatrice.rickmortycast.presentation.theme.RickMortyTheme
import org.koin.compose.KoinContext
@Composable
fun App(modifier: Modifier = Modifier) {
RickMortyTheme {
KoinContext {
Scaffold(modifier = modifier.fillMaxSize()) {
RickMortyNavHost()
}
}
}
}
| 1 | Kotlin | 0 | 9 | 1803b451173cdae7f37ba9c09843dc9b08987bb3 | 631 | RickAndMorty-KMP | Apache License 2.0 |
flowbinding-common/src/main/java/reactivecircus/flowbinding/common/SafeOffer.kt | mochadwi | 326,126,160 | true | {"Kotlin": 469647, "Shell": 2411} | package reactivecircus.flowbinding.common
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.SendChannel
@RestrictTo(LIBRARY_GROUP)
@UseExperimental(ExperimentalCoroutinesApi::class)
fun <E> SendChannel<E>.safeOffer(value: E): Boolean {
return runCatching { offer(value) }.getOrDefault(false)
}
| 0 | null | 0 | 0 | d9ff4b7a1c3c05e15b68d30f9eb4e99c8f925481 | 433 | FlowBinding | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.