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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BroadcastOff.kt | walter-juan | 868,046,028 | false | null | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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 com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.BroadcastOff: ImageVector
get() {
if (_broadcastOff != null) {
return _broadcastOff!!
}
_broadcastOff = Builder(name = "BroadcastOff", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.364f, 19.364f)
arcToRelative(9.0f, 9.0f, 0.0f, false, false, -9.721f, -14.717f)
moveToRelative(-2.488f, 1.509f)
arcToRelative(9.0f, 9.0f, 0.0f, false, false, -0.519f, 13.208f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.536f, 16.536f)
arcToRelative(5.0f, 5.0f, 0.0f, false, false, -3.536f, -8.536f)
moveToRelative(-3.0f, 1.0f)
arcToRelative(5.0f, 5.0f, 0.0f, false, false, -0.535f, 7.536f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 12.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 1.0f, 1.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 3.0f)
lineToRelative(18.0f, 18.0f)
}
}
.build()
return _broadcastOff!!
}
private var _broadcastOff: ImageVector? = null
| 0 | null | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,978 | compose-icon-collections | MIT License |
src/test/kotlin/no/digdir/servicecatalog/integration/RDF.kt | Informasjonsforvaltning | 706,104,096 | false | {"Kotlin": 67014, "Dockerfile": 208} | package no.digdir.servicecatalog.integration
import no.digdir.servicecatalog.utils.ApiTestContext
import no.digdir.servicecatalog.utils.TestResponseReader
import no.digdir.servicecatalog.utils.apiAuthorizedRequest
import org.apache.jena.rdf.model.ModelFactory
import org.apache.jena.riot.Lang
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.context.ContextConfiguration
import org.springframework.util.MimeType
import java.io.StringReader
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = ["spring.profiles.active=test"])
@ContextConfiguration(initializers = [ApiTestContext.Initializer::class])
@Tag("integration")
class RDF: ApiTestContext() {
val responseReader = TestResponseReader()
@Nested
internal inner class GetCatalogRDF {
private val catalogPath = "/rdf/catalogs/910244132"
@Test
fun `able to get rdf catalog`() {
val response = apiAuthorizedRequest(
catalogPath,
port,
null,
null,
HttpMethod.GET,
MediaType.asMediaType(MimeType.valueOf(Lang.TURTLE.headerString))
)
Assertions.assertEquals(HttpStatus.OK.value(), response["status"])
val expected = responseReader.parseFile("service_catalog.ttl", Lang.TURTLE.name)
val result = ModelFactory
.createDefaultModel()
.read(StringReader(response["body"] as String), null, Lang.TURTLE.name)
Assertions.assertTrue(expected.isIsomorphicWith(result))
}
@Test
fun `able to get rdf catalog with media type xml`() {
val response = apiAuthorizedRequest(
catalogPath,
port,
null,
null,
HttpMethod.GET,
MediaType.asMediaType(MimeType.valueOf(Lang.RDFXML.headerString))
)
Assertions.assertEquals(HttpStatus.OK.value(), response["status"])
val expected = responseReader.parseFile("service_catalog.ttl", Lang.TURTLE.name)
val result = ModelFactory
.createDefaultModel()
.read(StringReader(response["body"] as String), null, Lang.RDFXML.name)
Assertions.assertTrue(expected.isIsomorphicWith(result))
}
@Test
fun `not acceptable for media type jason`() {
val response = apiAuthorizedRequest(
catalogPath,
port,
null,
null,
HttpMethod.GET,
MediaType.APPLICATION_JSON
)
Assertions.assertEquals(HttpStatus.NOT_ACCEPTABLE.value(), response["status"])
}
}
@Nested
internal inner class GetPublicServiceRDF {
private val publicServicePath = "/rdf/catalogs/910244132/public-services/0"
private val notExistingPublicServicePath = "/rdf/catalogs/910244132/public-services/1000"
@Test
fun `able to get rdf for public service`() {
val response = apiAuthorizedRequest(
publicServicePath,
port,
null,
null,
HttpMethod.GET,
MediaType.asMediaType(MimeType.valueOf(Lang.TURTLE.headerString)))
Assertions.assertEquals(HttpStatus.OK.value(), response["status"])
val expected = responseReader.parseFile("public_service.ttl", Lang.TURTLE.name)
val result = ModelFactory.createDefaultModel().read(StringReader(response["body"] as String), null, Lang.TURTLE.name)
Assertions.assertTrue(expected.isIsomorphicWith(result))
}
@Test
fun `not found when public service not in database`() {
val response = apiAuthorizedRequest(
notExistingPublicServicePath,
port,
null,
null,
HttpMethod.GET,
MediaType.asMediaType(MimeType.valueOf(Lang.TURTLE.headerString)))
Assertions.assertEquals(HttpStatus.NOT_FOUND.value(), response["status"])
}
@Test
fun `not acceptable for media type jason`() {
val response = apiAuthorizedRequest(
publicServicePath,
port,
null,
null,
HttpMethod.GET,
MediaType.APPLICATION_JSON
)
Assertions.assertEquals(HttpStatus.NOT_ACCEPTABLE.value(), response["status"])
}
@Test
fun `able to get rdf for public service with media type xml`() {
val response = apiAuthorizedRequest(
publicServicePath,
port,
null,
null,
HttpMethod.GET,
MediaType.asMediaType(MimeType.valueOf(Lang.RDFXML.headerString))
)
Assertions.assertEquals(HttpStatus.OK.value(), response["status"])
val expected = responseReader.parseFile("public_service.ttl", Lang.TURTLE.name)
val result = ModelFactory
.createDefaultModel()
.read(StringReader(response["body"] as String), null, Lang.RDFXML.name)
Assertions.assertTrue(expected.isIsomorphicWith(result))
}
}
}
| 4 | Kotlin | 0 | 0 | e016d5db1087c15b488ebf0f0b4f10483d99682b | 5,785 | service-catalog | Apache License 2.0 |
app/src/main/java/cc/sovellus/vrcaa/ui/screen/login/MfaScreen.kt | Nyabsi | 745,635,224 | false | null | package cc.sovellus.vrcaa.ui.screen.login
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.core.model.rememberNavigatorScreenModel
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.core.screen.uniqueScreenKey
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import cc.sovellus.vrcaa.R
import cc.sovellus.vrcaa.api.http.ApiContext
import cc.sovellus.vrcaa.ui.components.input.CodeInput
class TwoAuthScreen(
private val otpType: ApiContext.TwoFactorType
) : Screen {
override val key = uniqueScreenKey
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val context = LocalContext.current
val screenModel = navigator.rememberNavigatorScreenModel { TwoAuthScreenModel(context, otpType, navigator) }
Column(
modifier = Modifier
.fillMaxHeight()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = if (otpType == ApiContext.TwoFactorType.EMAIL_OTP) {
stringResource(R.string.auth_text_email)
} else {
stringResource(R.string.auth_text_app)
}
)
CodeInput(
input = screenModel.code
)
Button(
modifier = Modifier
.height(48.dp)
.width(200.dp)
.padding(1.dp),
onClick = {
screenModel.verify()
}
) {
Text(text = stringResource(R.string.auth_button_text))
}
Button(
modifier = Modifier
.height(48.dp)
.width(200.dp)
.padding(1.dp),
onClick = {
val clipboard: ClipboardManager? = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
if (clipboard?.hasPrimaryClip() == true) {
val clipData = clipboard.primaryClip
if ((clipData?.itemCount ?: 0) > 0) {
val clipItem = clipData?.getItemAt(0)
val clipText = clipItem?.text?.toString()
if (clipText?.length == 6) {
screenModel.code.value = clipText
}
}
}
}
) {
Text(text = "Paste")
}
}
Column(
modifier = Modifier
.fillMaxHeight()
.padding(vertical = 16.dp),
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.legal_disclaimer),
textAlign = TextAlign.Center,
maxLines = 1,
fontSize = 12.sp
)
}
}
} | 1 | null | 3 | 38 | b45497cd686df2583ceb7b9cdefdd7ac2ee39b14 | 3,979 | VRCAA | Apache License 2.0 |
core/src/com/mygdx/game/FileHandler.kt | freddyblockchain | 791,340,797 | false | {"Kotlin": 132447, "OpenEdge ABL": 2029, "Java": 835} | package com.mygdx.game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.files.FileHandle
import java.io.BufferedWriter
import java.io.File
class FileHandler {
companion object{
var handle = Gdx.files.internal("SaveFiles/CurrentSave")
private val file: File = handle.file()
private lateinit var fileWriter: BufferedWriter
fun savePlayerState(playerState: String){
val lines = readFromFile().toMutableList()
if (lines.isEmpty()){
lines.add(playerState)
}else{
lines[0] = playerState
}
fileWriter = file.bufferedWriter()
fileWriter.use { writer -> lines.forEach { writer.write(it)
writer.newLine()}}
}
fun readFromFile(): List<String>{
return file.useLines { it.toList() }
}
fun getFileJson(fileName: String): String{
val handle: FileHandle = Gdx.files.internal(fileName);
return handle.readString()
}
}
}
| 0 | Kotlin | 0 | 0 | fe938937d9758116ee4cdea24b32ae2149201ee7 | 1,045 | Elemental-Brawl-Online | The Unlicense |
compiler/fir/resolve/src/org/jetbrains/kotlin/fir/scopes/impl/FirClassUseSiteMemberScope.kt | android | 263,405,600 | false | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.scopes.impl
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.scopes.FirScope
import org.jetbrains.kotlin.fir.scopes.FirTypeScope
import org.jetbrains.kotlin.fir.symbols.impl.FirVariableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.isStatic
import org.jetbrains.kotlin.name.Name
class FirClassUseSiteMemberScope(
session: FirSession,
superTypesScope: FirTypeScope,
declaredMemberScope: FirScope
) : AbstractFirUseSiteMemberScope(session, FirStandardOverrideChecker(session), superTypesScope, declaredMemberScope) {
override fun processPropertiesByName(name: Name, processor: (FirVariableSymbol<*>) -> Unit) {
val seen = mutableSetOf<FirVariableSymbol<*>>()
declaredMemberScope.processPropertiesByName(name) l@{
if (it.isStatic) return@l
seen += it
processor(it)
}
superTypesScope.processPropertiesByName(name) {
val overriddenBy = it.getOverridden(seen)
if (overriddenBy == null) {
processor(it)
}
}
}
}
| 1 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 1,330 | kotlin | Apache License 2.0 |
ktor-server/ktor-server-core/jvm/src/io/ktor/util/Parameters.kt | jakobkmar | 323,173,348 | true | {"Kotlin": 5039593, "Python": 948, "JavaScript": 775, "HTML": 165} | /*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util
import io.ktor.features.*
import io.ktor.http.*
import java.lang.reflect.*
import kotlin.reflect.*
import kotlin.reflect.full.*
import kotlin.reflect.jvm.*
/**
* Operator function that allows to delegate variables by call parameters.
* It does conversion to type [R] using [DefaultConversionService]
*
* Example
*
* ```
* get("/") {
* val page: Int by call.request.queryParameters
* val query: String by call.request.queryParameters
* // ...
* }
* ```
*
* @throws MissingRequestParameterException if no values associated with name
* @throws ParameterConversionException when conversion from String to [R] fails
*/
public inline operator fun <reified R : Any> Parameters.getValue(thisRef: Any?, property: KProperty<*>): R {
return getOrFail<R>(property.name)
}
/**
* Get parameters value associated with this [name] or fail with [MissingRequestParameterException]
* @throws MissingRequestParameterException if no values associated with this [name]
*/
@Suppress("NOTHING_TO_INLINE")
public inline fun Parameters.getOrFail(name: String): String {
return get(name) ?: throw MissingRequestParameterException(name)
}
/**
* Get parameters value associated with this [name] converting to type [R] using [DefaultConversionService]
* or fail with [MissingRequestParameterException]
* @throws MissingRequestParameterException if no values associated with this [name]
* @throws ParameterConversionException when conversion from String to [R] fails
*/
@OptIn(ExperimentalStdlibApi::class)
public inline fun <reified R : Any> Parameters.getOrFail(name: String): R {
return getOrFailImpl(name, R::class, typeOf<R>().toJavaType())
}
@PublishedApi
internal fun <R : Any> Parameters.getOrFailImpl(name: String, type: KClass<R>, javaType: Type): R {
val values = getAll(name) ?: throw MissingRequestParameterException(name)
return try {
type.cast(DefaultConversionService.fromValues(values, javaType))
} catch (cause: Exception) {
throw ParameterConversionException(name, type.jvmName, cause)
}
}
| 0 | Kotlin | 0 | 7 | ea35658a05cc085b97297a303a7c0de37efe0024 | 2,212 | ktor | Apache License 2.0 |
app/src/main/java/com/apiguave/tinderclonecompose/data/profile/repository/ProfileRepository.kt | alejandro-piguave | 567,907,964 | false | {"Kotlin": 190150, "Java": 427} | package com.apiguave.tinderclonecompose.data.profile.repository
import com.apiguave.tinderclonecompose.data.picture.repository.Picture
interface ProfileRepository {
suspend fun createProfile(profile: CreateUserProfile)
suspend fun createProfile(userId: String, profile: CreateUserProfile)
suspend fun updateProfile(bio: String, gender: Gender, orientation: Orientation, pictures: List<Picture>): UserProfile
suspend fun getProfile(): UserProfile
} | 1 | Kotlin | 7 | 21 | f30af595c58dea07ca329b70289d1e45a2b19a98 | 465 | TinderCloneCompose | MIT License |
nugu-android-helper/src/main/java/com/skt/nugu/sdk/external/silvertray/NuguOpusPlayer.kt | nugu-developers | 214,067,023 | false | null | /**
* Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved.
*
* 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.skt.nugu.sdk.external.silvertray
import android.util.Log
import com.skt.nugu.sdk.agent.mediaplayer.*
import com.skt.nugu.silvertray.player.EventListener
import com.skt.nugu.silvertray.player.Player
import com.skt.nugu.silvertray.player.Status
import com.skt.nugu.sdk.core.interfaces.attachment.Attachment
import com.skt.nugu.silvertray.player.DurationListener
/**
* Porting class silvertray's [Player] to use in NUGU SDK
*/
class NuguOpusPlayer(private val streamType: Int) :
AttachmentPlayablePlayer {
companion object {
private const val TAG = "NuguOpusPlayer"
}
private val player = Player()
private var currentSourceId: SourceId = SourceId.ERROR()
private var status = Status.IDLE
private var playbackEventListener: MediaPlayerControlInterface.PlaybackEventListener? = null
private var bufferEventListener: MediaPlayerControlInterface.BufferEventListener? = null
private var durationListener: MediaPlayerControlInterface.OnDurationListener? = null
init {
player.addListener(object : EventListener {
override fun onError(message: String) {
playbackEventListener?.onPlaybackError(currentSourceId, ErrorType.MEDIA_ERROR_INTERNAL_DEVICE_ERROR, message)
}
override fun onStatusChanged(status: Status) {
Log.d(TAG, "[onStatusChanged] status: $status")
handleStatusChanged(status)
}
})
player.addDurationListener(object : DurationListener {
override fun onFoundDuration(duration: Long) {
Log.d(TAG, "[onFoundDuration] duration: $duration")
durationListener?.onRetrieved(currentSourceId, duration)
}
})
}
private fun handleStatusChanged(status: Status) {
val prevStatus = this.status
this.status = status
val listener = this.playbackEventListener ?: return
when (status) {
Status.IDLE -> {
if(prevStatus == Status.READY) {
listener.onPlaybackStarted(currentSourceId)
}
listener.onPlaybackStopped(currentSourceId)
}
Status.STARTED -> {
if (prevStatus == Status.PAUSED) {
listener.onPlaybackResumed(currentSourceId)
} else {
listener.onPlaybackStarted(currentSourceId)
}
}
Status.PAUSED -> {
listener.onPlaybackPaused(currentSourceId)
}
Status.ENDED -> {
if(prevStatus == Status.READY) {
listener.onPlaybackStarted(currentSourceId)
}
listener.onPlaybackFinished(currentSourceId)
}
else -> {
}
}
}
override fun setSource(attachmentReader: Attachment.Reader): SourceId {
val source = RawCBRStreamSource(attachmentReader)
player.prepare(source, streamType)
currentSourceId.id++
Log.d(TAG, "[setSource] ${currentSourceId.id}")
return currentSourceId
}
override fun play(id: SourceId): Boolean {
if(currentSourceId.id != id.id) {
return false
}
Log.d(TAG, "[play] $id")
player.start()
return true
}
override fun stop(id: SourceId): Boolean {
if(currentSourceId.id != id.id) {
return false
}
Log.d(TAG, "[stop] $id")
player.reset()
return true
}
override fun pause(id: SourceId): Boolean {
if(currentSourceId.id != id.id) {
return false
}
if(this.status == Status.ENDED) {
return false
}
Log.d(TAG, "[pause] $id")
player.pause()
return true
}
override fun resume(id: SourceId): Boolean {
if(currentSourceId.id != id.id) {
return false
}
player.start()
return true
}
override fun seekTo(id: SourceId, offsetInMilliseconds: Long): Boolean {
// TODO : Impl
return false
}
override fun getOffset(id: SourceId): Long {
return player.currentPosition
}
override fun setPlaybackEventListener(listener: MediaPlayerControlInterface.PlaybackEventListener) {
this.playbackEventListener = listener
}
override fun setBufferEventListener(listener: MediaPlayerControlInterface.BufferEventListener) {
this.bufferEventListener = listener
}
override fun setOnDurationListener(listener: MediaPlayerControlInterface.OnDurationListener) {
this.durationListener = listener
}
} | 3 | null | 18 | 27 | 53ebf6b8b17afeff6fdb3a8741f345f2fbe0d649 | 5,342 | nugu-android | Apache License 2.0 |
save-frontend/src/main/kotlin/com/saveourtool/save/frontend/components/basic/projects/ProjectSecurityMenu.kt | saveourtool | 300,279,336 | false | null | @file:Suppress(
"FILE_NAME_MATCH_CLASS",
"HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE",
)
package com.saveourtool.save.frontend.components.basic.projects
import com.saveourtool.save.entities.ProjectDto
import com.saveourtool.save.entities.ProjectProblemDto
import com.saveourtool.save.filters.ProjectProblemFilter
import com.saveourtool.save.frontend.common.components.tables.TableProps
import com.saveourtool.save.frontend.common.components.tables.columns
import com.saveourtool.save.frontend.common.components.tables.tableComponent
import com.saveourtool.save.frontend.common.components.tables.value
import com.saveourtool.save.frontend.common.externals.fontawesome.*
import com.saveourtool.save.frontend.common.utils.*
import com.saveourtool.save.info.UserInfo
import react.*
import react.dom.html.ReactHTML.div
import react.dom.html.ReactHTML.form
import react.dom.html.ReactHTML.nav
import react.dom.html.ReactHTML.td
import react.router.dom.Link
import web.cssom.ClassName
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/**
* SECURITY tab in ProjectView
*/
val projectSecurityMenu = projectSecurityMenu()
/**
* Enum that contains values for project
*/
@Suppress("WRONG_DECLARATIONS_ORDER")
enum class ProjectProblemListTab {
OPEN,
CLOSED,
;
}
/**
* ProjectSecurityMenu component props
*/
external interface ProjectSecurityMenuProps : Props {
/**
* Current project settings
*/
var project: ProjectDto
/**
* Information about current user
*/
var currentUserInfo: UserInfo
}
@Suppress(
"TOO_LONG_FUNCTION",
"LongMethod",
)
private fun projectSecurityMenu() = FC<ProjectSecurityMenuProps> { props ->
val (projectProblems, setProjectProblems) = useState<Array<ProjectProblemDto>>(emptyArray())
val (selectedMenu, setSelectedMenu) = useState(ProjectProblemListTab.OPEN)
val (filters, setFilters) = useState(ProjectProblemFilter(props.project.organizationName, props.project.name, false))
val getUsersFromGroup = useDeferredRequest {
val problems = post(
url = "$apiUrl/projects/problem/by-filters",
body = Json.encodeToString(filters),
headers = jsonHeaders,
loadingHandler = ::loadingHandler,
)
.unsafeMap {
it.decodeFromJsonString<Array<ProjectProblemDto>>()
}
setProjectProblems(problems)
}
useRequest {
getUsersFromGroup()
}
@Suppress(
"TYPE_ALIAS",
"MAGIC_NUMBER",
)
val problemsTable: FC<TableProps<ProjectProblemDto>> = tableComponent(
columns = {
columns {
column(id = "name", header = "Name", { name }) { cellContext ->
val problem = cellContext.row.original
Fragment.create {
td {
Link {
to = "/project/${problem.organizationName}/${problem.projectName}/security/problems/${problem.id}"
+cellContext.value
}
}
}
}
column(id = "passed", header = "Description") { cellContext ->
Fragment.create {
td {
+(cellContext.value.description.ifEmpty { "Description not provided" })
}
}
}
column(id = "critical", header = "Critical") { cellContext ->
Fragment.create {
td {
+cellContext.value.critical.toString()
}
}
}
}
},
initialPageSize = 10,
useServerPaging = false,
isTransparentGrid = true,
) {
arrayOf(filters)
}
div {
className = ClassName("row justify-content-center")
// ===================== LEFT COLUMN =======================================================================
div {
className = ClassName("col-2 mr-3")
div {
className = ClassName("card card-body mt-0 pt-0 pr-0 pl-0 border-secondary")
div {
className = ClassName("col mr-2 pr-0 pl-0")
nav {
div {
className = ClassName("pl-3 ui vertical menu profile-setting")
form {
div {
className = ClassName("item mt-2")
div {
className = ClassName("header")
+"Reporting"
}
div {
className = ClassName("menu")
div {
className = ClassName("mt-2 item")
fontAwesomeIcon(icon = faShieldVirus) {
it.className = "fas fa-sm fa-fw mr-2 text-gray-600"
}
Link {
to = "/project/${props.project.organizationName}/${props.project.name}/security"
+"Problems"
}
}
}
}
}
}
}
}
}
}
// ===================== RIGHT COLUMN =======================================================================
div {
className = ClassName("col-6")
div {
className = ClassName("d-flex justify-content-end")
withNavigate { navigateContext ->
buttonBuilder(label = "New problem") {
navigateContext.navigate("/project/${props.project.organizationName}/${props.project.name}/security/problems/new")
}
}
}
tab(selectedMenu.name, ProjectProblemListTab.values().map { it.name }, "nav nav-tabs mt-3") {
setSelectedMenu(ProjectProblemListTab.valueOf(it))
val filter = when (ProjectProblemListTab.valueOf(it)) {
ProjectProblemListTab.OPEN -> ProjectProblemFilter(props.project.organizationName, props.project.name, false)
ProjectProblemListTab.CLOSED -> ProjectProblemFilter(props.project.organizationName, props.project.name, true)
}
setFilters(filter)
getUsersFromGroup()
}
problemsTable {
getData = { _, _ ->
projectProblems
}
}
}
}
}
| 202 | null | 3 | 38 | 9d11f7c01c65905f968fba82b9ca5a9f52af88a8 | 7,203 | save-cloud | MIT License |
sample-app/src/main/java/com/joinforage/android/example/network/model/PaymentResponse.kt | teamforage | 554,343,430 | false | null | package com.joinforage.android.example.network.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class PaymentResponse(
@Json(name = "ref")
var ref: String?,
@Json(name = "merchant")
var merchant: String?,
@Json(name = "funding_type")
var fundingType: String?,
var amount: String?,
var description: String?,
var metadata: Map<String, String>?,
@Json(name = "payment_method")
var paymentMethod: String?,
@Json(name = "delivery_address")
var deliveryAddress: Address?,
@Json(name = "is_delivery")
var isDelivery: Boolean?,
var created: String?,
var updated: String?,
var status: String?,
@Json(name = "last_processing_error")
var lastProcessingError: String?,
@Json(name = "success_date")
var successDate: String?,
var refunds: List<String>,
@Json(name = "customer_id")
var customerId: String?
)
| 6 | Kotlin | 0 | 0 | f430751747f0e8887ab6ca218c8db92a7552d1ef | 959 | forage-android-sdk | MIT License |
src/jsMain/kotlin/sicher/model.kt | SkDeWw | 328,365,535 | false | null | package sicher
import dev.fritz2.lenses.Lens
import dev.fritz2.lenses.buildLens
// import dev.fritz2.styling.theme.IconDefinition
/* TEST */
data class Names(
val id: Int,
val text: String
)
/* End */
data class NavIndex(
var index: Int = 0
)
data class QuestionnaireData(
val user: User = User(),
val agency: Agency = Agency(),
val questions: MutableList<Question> = mutableListOf(),
val currentQuestionIndex: Int = 0
)
data class User(
val name: String = "",
val yearOfBirth: Int = 1900,
val email: String = ""
)
data class Agency(
val nummer: String = "",
val strasse: String = "",
val fax: String = "",
val email: String = "",
val hpName: String = "",
val tel: String = "",
val name: String = "",
val ort: String = "",
val plz: String = "",
val kanalType: String = "",
val firma: String = ""
)
data class Question(
val index: Int,
// val icon: IconDefinition,
val name: String,
val textVariants: TextVariants,
val answerOptions: AnswerOptions,
val previousIndex: Int = 0,
val currentIndex: Int = 0,
val nextIndex: Int = 0
)
data class TextVariants(
val young: String,
val personal: String,
val formal: String
)
data class AnswerOptions(
val type: String,
val expected: String,
val items: List<SelectItem>?
)
data class SelectItem(
val index: String = "",
val selected: Boolean = false,
// val icon: IconDefinition,
val name: String = "",
val textVariants: TextVariants,
val points: Points
)
data class Points(
val f: Int = 0,
val g: Int = 0,
val h: Int = 0,
val i: Int = 0,
val j: Int = 0,
val k: Int = 0,
val l: Int = 0,
val m: Int = 0,
val n: Int = 0,
val o: Int = 0,
val p: Int = 0,
val q: Int = 0,
val r: Int = 0,
val s: Int = 0,
val t: Int = 0,
val u: Int = 0,
val v: Int = 0,
val w: Int = 0,
val x: Int = 0,
val y: Int = 0,
val z: Int = 0,
val aa: Int = 0,
val ab: Int = 0,
val ac: Int = 0,
val ad: Int = 0,
val ae: Int = 0,
val af: Int = 0,
val ag: Int = 0,
val ah: Int = 0,
val ai: Int = 0,
val aj: Int = 0,
val ak: Int = 0,
val al: Int = 0,
val am: Int = 0,
val an: Int = 0
)
/* "Semi-manually" created lenses */
object L {
object Agency {
val email: Lens<sicher.Agency, String> = buildLens("email", { it.email },{ p, v -> p.copy(email
= v)})
val fax: Lens<sicher.Agency, String> = buildLens("fax", { it.fax },{ p, v -> p.copy(fax = v)})
val firma: Lens<sicher.Agency, String> = buildLens("firma", { it.firma },{ p, v -> p.copy(firma
= v)})
val hpName: Lens<sicher.Agency, String> = buildLens("hpName", { it.hpName },{ p, v ->
p.copy(hpName = v)})
val kanalType: Lens<sicher.Agency, String> = buildLens("kanalType", { it.kanalType },{ p, v ->
p.copy(kanalType = v)})
val name: Lens<sicher.Agency, String> = buildLens("name", { it.name },{ p, v -> p.copy(name =
v)})
val nummer: Lens<sicher.Agency, String> = buildLens("nummer", { it.nummer },{ p, v ->
p.copy(nummer = v)})
val ort: Lens<sicher.Agency, String> = buildLens("ort", { it.ort },{ p, v -> p.copy(ort = v)})
val plz: Lens<sicher.Agency, String> = buildLens("plz", { it.plz },{ p, v -> p.copy(plz = v)})
val strasse: Lens<sicher.Agency, String> = buildLens("strasse", { it.strasse },{ p, v ->
p.copy(strasse = v)})
val tel: Lens<sicher.Agency, String> = buildLens("tel", { it.tel },{ p, v -> p.copy(tel = v)})
}
object TextVariants {
val formal: Lens<sicher.TextVariants, String> = buildLens("formal", { it.formal },{ p, v ->
p.copy(formal = v)})
val personal: Lens<sicher.TextVariants, String> = buildLens("personal", { it.personal },{ p,
v -> p.copy(personal = v)})
val young: Lens<sicher.TextVariants, String> = buildLens("young", { it.young },{ p, v ->
p.copy(young = v)})
}
object User {
val email: Lens<sicher.User, String> = buildLens("email", { it.email },{ p, v -> p.copy(email =
v)})
val name: Lens<sicher.User, String> = buildLens("name", { it.name },{ p, v -> p.copy(name = v)})
val yearOfBirth: Lens<sicher.User, Int> = buildLens("yearOfBirth", { it.yearOfBirth },{ p, v ->
p.copy(yearOfBirth = v)})
}
object Points {
val aa: Lens<sicher.Points, Int> = buildLens("aa", { it.aa },{ p, v -> p.copy(aa = v)})
val ab: Lens<sicher.Points, Int> = buildLens("ab", { it.ab },{ p, v -> p.copy(ab = v)})
val ac: Lens<sicher.Points, Int> = buildLens("ac", { it.ac },{ p, v -> p.copy(ac = v)})
val ad: Lens<sicher.Points, Int> = buildLens("ad", { it.ad },{ p, v -> p.copy(ad = v)})
val ae: Lens<sicher.Points, Int> = buildLens("ae", { it.ae },{ p, v -> p.copy(ae = v)})
val af: Lens<sicher.Points, Int> = buildLens("af", { it.af },{ p, v -> p.copy(af = v)})
val ag: Lens<sicher.Points, Int> = buildLens("ag", { it.ag },{ p, v -> p.copy(ag = v)})
val ah: Lens<sicher.Points, Int> = buildLens("ah", { it.ah },{ p, v -> p.copy(ah = v)})
val ai: Lens<sicher.Points, Int> = buildLens("ai", { it.ai },{ p, v -> p.copy(ai = v)})
val aj: Lens<sicher.Points, Int> = buildLens("aj", { it.aj },{ p, v -> p.copy(aj = v)})
val ak: Lens<sicher.Points, Int> = buildLens("ak", { it.ak },{ p, v -> p.copy(ak = v)})
val al: Lens<sicher.Points, Int> = buildLens("al", { it.al },{ p, v -> p.copy(al = v)})
val am: Lens<sicher.Points, Int> = buildLens("am", { it.am },{ p, v -> p.copy(am = v)})
val an: Lens<sicher.Points, Int> = buildLens("an", { it.an },{ p, v -> p.copy(an = v)})
val f: Lens<sicher.Points, Int> = buildLens("f", { it.f },{ p, v -> p.copy(f = v)})
val g: Lens<sicher.Points, Int> = buildLens("g", { it.g },{ p, v -> p.copy(g = v)})
val h: Lens<sicher.Points, Int> = buildLens("h", { it.h },{ p, v -> p.copy(h = v)})
val i: Lens<sicher.Points, Int> = buildLens("i", { it.i },{ p, v -> p.copy(i = v)})
val j: Lens<sicher.Points, Int> = buildLens("j", { it.j },{ p, v -> p.copy(j = v)})
val k: Lens<sicher.Points, Int> = buildLens("k", { it.k },{ p, v -> p.copy(k = v)})
val l: Lens<sicher.Points, Int> = buildLens("l", { it.l },{ p, v -> p.copy(l = v)})
val m: Lens<sicher.Points, Int> = buildLens("m", { it.m },{ p, v -> p.copy(m = v)})
val n: Lens<sicher.Points, Int> = buildLens("n", { it.n },{ p, v -> p.copy(n = v)})
val o: Lens<sicher.Points, Int> = buildLens("o", { it.o },{ p, v -> p.copy(o = v)})
val p: Lens<sicher.Points, Int> = buildLens("p", { it.p },{ p, v -> p.copy(p = v)})
val q: Lens<sicher.Points, Int> = buildLens("q", { it.q },{ p, v -> p.copy(q = v)})
val r: Lens<sicher.Points, Int> = buildLens("r", { it.r },{ p, v -> p.copy(r = v)})
val s: Lens<sicher.Points, Int> = buildLens("s", { it.s },{ p, v -> p.copy(s = v)})
val t: Lens<sicher.Points, Int> = buildLens("t", { it.t },{ p, v -> p.copy(t = v)})
val u: Lens<sicher.Points, Int> = buildLens("u", { it.u },{ p, v -> p.copy(u = v)})
val v: Lens<sicher.Points, Int> = buildLens("v", { it.v },{ p, v -> p.copy(v = v)})
val w: Lens<sicher.Points, Int> = buildLens("w", { it.w },{ p, v -> p.copy(w = v)})
val x: Lens<sicher.Points, Int> = buildLens("x", { it.x },{ p, v -> p.copy(x = v)})
val y: Lens<sicher.Points, Int> = buildLens("y", { it.y },{ p, v -> p.copy(y = v)})
val z: Lens<sicher.Points, Int> = buildLens("z", { it.z },{ p, v -> p.copy(z = v)})
}
object SelectItem {
val index: Lens<sicher.SelectItem, String> = buildLens("index", { it.index },{ p, v ->
p.copy(index = v)})
val name: Lens<sicher.SelectItem, String> = buildLens("name", { it.name },{ p, v -> p.copy(name
= v)})
val points: Lens<sicher.SelectItem, sicher.Points> = buildLens("points", { it.points },{ p, v ->
p.copy(points = v)})
val selected: Lens<sicher.SelectItem, Boolean> = buildLens("selected", { it.selected },{ p, v ->
p.copy(selected = v)})
// val icon: Lens<sicher.SelectItem, IconDefinition> = buildLens("icon", { it.icon },{ p, v ->
// p.copy(icon = v)})
val textVariants: Lens<sicher.SelectItem, sicher.TextVariants> = buildLens("textVariants", {
it.textVariants },{ p, v -> p.copy(textVariants = v)})
}
object NavIndex {
val index: Lens<sicher.NavIndex, Int> = buildLens("index", { it.index },{ p, v -> p.copy(index =
v)})
}
object Question {
val answerOptions: Lens<sicher.Question, sicher.AnswerOptions> = buildLens("answerOptions", {
it.answerOptions },{ p, v -> p.copy(answerOptions = v)})
val currentIndex: Lens<sicher.Question, Int> = buildLens("currentIndex", { it.currentIndex },{
p, v -> p.copy(currentIndex = v)})
val index: Lens<sicher.Question, Int> = buildLens("index", { it.index },{ p, v -> p.copy(index =
v)})
// val icon: Lens<sicher.Question, IconDefinition> = buildLens("icon", { it.icon },{ p, v ->
// p.copy(icon = v)})
val name: Lens<sicher.Question, String> = buildLens("name", { it.name },{ p, v -> p.copy(name =
v)})
val nextIndex: Lens<sicher.Question, Int> = buildLens("nextIndex", { it.nextIndex },{ p, v ->
p.copy(nextIndex = v)})
val previousIndex: Lens<sicher.Question, Int> = buildLens("previousIndex", { it.previousIndex
},{ p, v -> p.copy(previousIndex = v)})
val textVariants: Lens<sicher.Question, sicher.TextVariants> = buildLens("textVariants", {
it.textVariants },{ p, v -> p.copy(textVariants = v)})
}
object QuestionnaireData {
val agency: Lens<sicher.QuestionnaireData, sicher.Agency> = buildLens("agency", { it.agency },{
p, v -> p.copy(agency = v)})
val questions: Lens<sicher.QuestionnaireData, MutableList<sicher.Question>> =
buildLens("questions", { it.questions },{ p, v -> p.copy(questions = v)})
val currentQuestionIndex: Lens<sicher.QuestionnaireData,Int> = buildLens("currentQuestionIndex",{ it.currentQuestionIndex },{p,v -> p.copy(currentQuestionIndex = v)})
val user: Lens<sicher.QuestionnaireData, sicher.User> = buildLens("user", { it.user },{ p, v ->
p.copy(user = v)})
}
object AnswerOptions {
val expected: Lens<sicher.AnswerOptions, String> = buildLens("expected", { it.expected },{ p, v ->
p.copy(expected = v)})
val items: Lens<sicher.AnswerOptions, List<sicher.SelectItem>?> = buildLens("items", { it.items
},{ p, v -> p.copy(items = v)})
val type: Lens<sicher.AnswerOptions, String> = buildLens("type", { it.type },{ p, v ->
p.copy(type = v)})
}
object Names {
val id: Lens<sicher.Names, Int> = buildLens("id", { it.id },{ p,v -> p.copy(id = v)})
val text: Lens<sicher.Names, String> = buildLens("text", { it.text },{p,v -> p.copy(text = v) })
}
}
| 0 | Kotlin | 0 | 0 | 5be52a08d19dac16b3de2bcc563eb89042f3b067 | 11,486 | test | MIT License |
lce-data/src/main/java/at/florianschuster/data/lce/DataFlowBuilder.kt | floschu | 215,345,549 | false | null | package at.florianschuster.data.lce
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
/**
* Evaluates the suspending [block] and creates [Data.Success] or [Data.Failure] depending
* on the outcome.
*/
suspend inline fun <T> dataOf(
crossinline block: suspend () -> T
): Data<T> = try {
Data.Success(block())
} catch (e: Throwable) {
Data.Failure(e)
}
/**
* Creates a [Flow] of [Data] that starts with [Data.Loading] and then emits the [block]
* that is evaluated with [dataOf].
*/
inline fun <T> dataFlowOf(
crossinline block: suspend () -> T
): Flow<Data<T>> = flow {
emit(Data.Loading)
emit(dataOf(block))
} | 0 | Kotlin | 1 | 2 | 0aa21d6d3e04cf22f0414def5487c8384b8ee595 | 664 | lce-data | Apache License 2.0 |
app/src/main/java/de/dhbw/mensaapp/database/menu/Menu.kt | SteveBinary | 621,552,225 | false | null | package de.dhbw.mensaapp.database.menu
import androidx.room.*
import kotlin.random.Random
import kotlin.random.nextLong
@Entity(tableName = "menu")
data class MenuEntity(
val menuId: String,
val name: String,
val subTitle: String,
val priceUnit: String,
val priceStudent: Float,
val priceEmployee: Float,
val priceGuest: Float,
val foodAdditivesAndAllergens: String,
val epochDay: Long,
@PrimaryKey
val id: Long = Random.nextLong(0 until Long.MAX_VALUE)
)
@Dao
interface MenuDao {
@Upsert
suspend fun upsertAllMenuEntity(menuEntities: List<MenuEntity>)
@Query("SELECT * FROM menu ORDER BY epochDay ASC;")
fun getMenuEntities(): List<MenuEntity>
}
| 0 | Kotlin | 0 | 1 | 5e581880c96c54b0b20b2bb85e0c13c46157a822 | 714 | mensa-app | MIT License |
app/src/test/java/com/github/grishberg/profiler/NoOpLogger.kt | Grigory-Rylov | 256,819,360 | false | null | package com.github.grishberg.profiler
import com.github.grishberg.profiler.common.AppLogger
object NoOpLogger : AppLogger {
override fun d(msg: String) = Unit
override fun e(msg: String) = Unit
override fun e(msg: String, t: Throwable) = Unit
override fun w(msg: String) = Unit
override fun i(msg: String) = Unit
}
| 19 | Kotlin | 3 | 97 | e0ba609640cea72c301ff1537dc9cdd9b67bfe4c | 340 | android-methods-profiler | Apache License 2.0 |
xml/impl/src/com/intellij/application/options/XmlCodeCompletionConfigurable.kt | ingokegel | 72,937,917 | true | null | package com.intellij.application.options
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.UiDslUnnamedConfigurable
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.xml.XmlBundle
class XmlCodeCompletionConfigurable : UiDslUnnamedConfigurable.Simple(), Configurable {
override fun getDisplayName(): String {
return XmlBundle.message("options.html.display.name")
}
override fun Panel.createContent() {
val htmlSettings = HtmlSettings.getInstance()
group(XmlBundle.message("options.html.display.name")) {
row {
checkBox(XmlBundle.message("checkbox.enable.completion.html.auto.popup.code.completion.on.typing.in.text"))
.bindSelected({ htmlSettings.AUTO_POPUP_TAG_CODE_COMPLETION_ON_TYPING_IN_TEXT }, { htmlSettings.AUTO_POPUP_TAG_CODE_COMPLETION_ON_TYPING_IN_TEXT = it })
}
}
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 931 | intellij-community | Apache License 2.0 |
server/src/main/kotlin/net/horizonsend/ion/server/features/sidebar/command/SidebarCommand.kt | HorizonsEndMC | 461,042,096 | false | {"Kotlin": 2629890, "Java": 13759, "Shell": 1414, "JavaScript": 78} | package net.horizonsend.ion.server.features.sidebar.command
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.Default
import co.aikar.commands.annotation.Optional
import net.horizonsend.ion.common.utils.text.colors.HEColorScheme.Companion.HE_LIGHT_ORANGE
import net.horizonsend.ion.common.utils.text.formatPaginatedMenu
import net.horizonsend.ion.common.utils.text.lineBreak
import net.horizonsend.ion.common.utils.text.lineBreakWithCenterText
import net.horizonsend.ion.common.utils.text.ofChildren
import net.horizonsend.ion.server.command.SLCommand
import net.horizonsend.ion.server.features.cache.PlayerCache
import net.horizonsend.ion.server.features.sidebar.Sidebar
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.BOOKMARK_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.COMPASS_NEEDLE_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.GENERIC_STARSHIP_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.GUNSHIP_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.HYPERSPACE_BEACON_ENTER_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.LIST_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.PLANET_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.ROUTE_SEGMENT_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.STAR_ICON
import net.horizonsend.ion.server.features.sidebar.SidebarIcon.STATION_ICON
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.Component.newline
import net.kyori.adventure.text.Component.text
import net.kyori.adventure.text.format.NamedTextColor
import net.kyori.adventure.text.format.NamedTextColor.AQUA
import net.kyori.adventure.text.format.NamedTextColor.GOLD
import net.kyori.adventure.text.format.NamedTextColor.GRAY
import net.kyori.adventure.text.format.NamedTextColor.GREEN
import net.kyori.adventure.text.format.NamedTextColor.WHITE
import org.bukkit.entity.Player
@CommandAlias("sidebar")
object SidebarCommand : SLCommand() {
@Default
@Suppress("unused")
fun defaultCase(sender: Player, @Optional page: Int?) {
val body = formatPaginatedMenu(
entries = listOf(starshipComponents(sender), contactsComponents(sender), routeComponents(sender)),
command = "/sidebar",
currentPage = page ?: 1,
maxPerPage = 1,
)
sender.sendMessage(body)
}
private fun starshipComponents(player: Player) : Component {
val starshipsComponentsEnabled = PlayerCache[player.uniqueId].starshipsEnabled
val advancedStarshipInfo = PlayerCache[player.uniqueId].advancedStarshipInfo
val rotateCompass = PlayerCache[player.uniqueId].rotateCompass
return ofChildren(
lineBreakWithCenterText(
text("Starship - Information about your current starship", HE_LIGHT_ORANGE),
width = 1
),
newline(),
text("Starship information visible: $starshipsComponentsEnabled", WHITE),
newline(),
text("\\ N /", GRAY).append(text(" Cruise Compass", WHITE)),
newline(),
text("W ^ E", GRAY).append(text(" Indicates current and desired cruise direction", WHITE)),
newline(),
text("/ S \\", GRAY).append(text(" GOLD", GOLD)).append(text(" - Current cruise direction vector, ", WHITE))
.append(text("AQUA", AQUA)).append(text(" - Desired cruise direction vector, ", WHITE))
.append(text("GREEN", GREEN))
.append(text(" - Current and desired cruise direction vectors matching", WHITE)),
newline(),
newline(),
text("HULL: ", GRAY).append(text("Current hull percentage and block count", WHITE)),
newline(),
text("SPD: ", GRAY).append(text("Current speed, maximum speed, acceleration, and cruise/DC status", WHITE)),
newline(),
text("PM: ", GRAY).append(text("Current power mode for shields, weapons, and thrusters", WHITE)),
newline(),
text("CAP: ", GRAY).append(text("Current light weapons energy within ship capacitor", WHITE)),
newline(),
text("HVY: ", GRAY).append(text("Cooldown for heavy weapons", WHITE)),
newline(),
text("ACTIVE: ", GRAY).append(text("Active weapon sets and ship modules", WHITE)),
newline(),
newline(),
text("Settings: "),
newline(),
text(LIST_ICON.text, getColor(advancedStarshipInfo)).font(Sidebar.fontKey),
text(" advanced - Displays advanced information: $advancedStarshipInfo", WHITE),
newline(),
text(COMPASS_NEEDLE_ICON.text, getColor(rotateCompass)).font(Sidebar.fontKey),
text(" rotatecompass - Top of compass faces direction that ship is facing: $rotateCompass", WHITE),
newline(),
lineBreak(47),
)
}
private fun contactsComponents(player: Player) : Component {
val contactsComponentsEnabled = PlayerCache[player.uniqueId].contactsEnabled
val starshipsEnabled = PlayerCache[player.uniqueId].contactsStarships
val lastStarshipEnabled = PlayerCache[player.uniqueId].lastStarshipEnabled
val planetsEnabled = PlayerCache[player.uniqueId].planetsEnabled
val starsEnabled = PlayerCache[player.uniqueId].starsEnabled
val beaconsEnabled = PlayerCache[player.uniqueId].beaconsEnabled
val stationsEnabled = PlayerCache[player.uniqueId].stationsEnabled
val bookmarksEnabled = PlayerCache[player.uniqueId].bookmarksEnabled
return ofChildren(
lineBreakWithCenterText(
text("Contacts - View nearby objects and their status", HE_LIGHT_ORANGE),
width = 3
),
newline(),
text("Contacts information visible: $contactsComponentsEnabled", WHITE),
newline(),
text(GUNSHIP_ICON.text, getColor(starshipsEnabled)).font(Sidebar.fontKey),
text(" starship - Other starships visible: $starshipsEnabled", WHITE),
newline(),
text(GENERIC_STARSHIP_ICON.text, getColor(lastStarshipEnabled)).font(Sidebar.fontKey),
text(" laststarship - Last piloted starship visible: $lastStarshipEnabled", WHITE),
newline(),
text(PLANET_ICON.text, getColor(planetsEnabled)).font(Sidebar.fontKey),
text(" planet - Planets visible: $planetsEnabled", WHITE),
newline(),
text(STAR_ICON.text, getColor(starsEnabled)).font(Sidebar.fontKey),
text(" stars - Stars visible: $starsEnabled", WHITE),
newline(),
text(HYPERSPACE_BEACON_ENTER_ICON.text, getColor(beaconsEnabled)).font(Sidebar.fontKey),
text(" beacons - Hyperspace beacons visible: $beaconsEnabled", WHITE),
newline(),
text(STATION_ICON.text, getColor(stationsEnabled)).font(Sidebar.fontKey),
text(" stations - Stations and siege stations visible: $stationsEnabled", WHITE),
newline(),
text(BOOKMARK_ICON.text, getColor(bookmarksEnabled)).font(Sidebar.fontKey),
text(" bookmarks - Bookmarks visible: $bookmarksEnabled", WHITE),
newline(),
lineBreak(47),
)
}
private fun routeComponents(player: Player) : Component {
val waypointsComponentsEnabled = PlayerCache[player.uniqueId].waypointsEnabled
val compactWaypoints = PlayerCache[player.uniqueId].compactWaypoints
return ofChildren(
lineBreakWithCenterText(text("Route - Current plotted route", HE_LIGHT_ORANGE), width = 9),
newline(),
text("Route information visible: $waypointsComponentsEnabled", WHITE),
newline(),
text(ROUTE_SEGMENT_ICON.text, getColor(compactWaypoints)).font(Sidebar.fontKey),
text(" compactwaypoints - Display route segments between destinations: $compactWaypoints"),
newline(),
lineBreak(47),
)
}
private fun getColor(enabled: Boolean): NamedTextColor {
return if (enabled) AQUA else GRAY
}
} | 16 | Kotlin | 26 | 9 | 4887e1d25ed39f3fad9b6ab91eb125648797889b | 8,216 | Ion | MIT License |
tmp/arrays/youTrackTests/4688.kt | DaniilStepanov | 228,623,440 | false | {"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4} | // Original bug: KT-30244
fun decodeValue(value: String) =
when (value) {
"F" -> String::toFloat
"B" -> String::toBoolean
else -> TODO()
}
| 1 | null | 12 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 192 | bbfgradle | Apache License 2.0 |
wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/-Platform.kt | square | 12,274,147 | false | null | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.wire.internal
import kotlin.reflect.KClass
import okio.IOException
expect interface Serializable
// TODO(egorand): Remove when https://youtrack.jetbrains.com/issue/KT-26283 lands
@OptionalExpectation
@OptIn(ExperimentalMultiplatform::class)
expect annotation class Throws(vararg val exceptionClasses: KClass<out Throwable>)
@OptionalExpectation
@OptIn(ExperimentalMultiplatform::class)
expect annotation class JvmDefaultWithCompatibility()
expect annotation class JvmField()
expect annotation class JvmStatic()
expect abstract class ObjectStreamException : IOException
expect class ProtocolException(host: String) : IOException
expect fun <T> MutableList<T>.toUnmodifiableList(): List<T>
expect fun <K, V> MutableMap<K, V>.toUnmodifiableMap(): Map<K, V>
/**
* Convert [string], from snake case to camel case.
*
* When [upperCamel] is true, this should mirror the logic of `fieldNameToJsonName` in
* `com/google/protobuf/Descriptors.java`, except it lower cases the first character as well (protoc
* seems to do this step earlier).
*
* See https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/Descriptors.java
*
* @param upperCamel true to uppercase the first character.
*/
expect fun camelCase(string: String, upperCamel: Boolean = false): String
| 150 | null | 600 | 4,229 | b5782414ea6ed71d635b22580c40e35123960611 | 1,938 | wire | Apache License 2.0 |
superwall/src/main/java/com/superwall/sdk/paywall/presentation/internal/request/PresentationInfo.kt | superwall | 642,585,064 | false | {"Kotlin": 1190760} | package com.superwall.sdk.paywall.presentation.internal.request
import com.superwall.sdk.models.events.EventData
// EventData should be defined in Kotlin before this.
// Assuming it is defined, and it contains a property 'name'
sealed class PresentationInfo {
data class ImplicitTrigger(
override val eventData: EventData,
) : PresentationInfo()
data class ExplicitTrigger(
override val eventData: EventData,
) : PresentationInfo()
data class FromIdentifier(
override val identifier: String,
override val freeTrialOverride: Boolean,
) : PresentationInfo()
open val freeTrialOverride: Boolean?
get() =
when (this) {
is FromIdentifier -> freeTrialOverride
else -> null
}
open val eventData: EventData?
get() =
when (this) {
is ImplicitTrigger -> eventData
is ExplicitTrigger -> eventData
else -> null
}
val eventName: String?
get() =
when (this) {
is ImplicitTrigger -> eventData.name
is ExplicitTrigger -> eventData.name
else -> null
}
open val identifier: String?
get() =
when (this) {
is FromIdentifier -> identifier
else -> null
}
}
| 6 | Kotlin | 3 | 9 | 2582de8d48af7c0ad080e30949d920e8a34d9219 | 1,404 | Superwall-Android | MIT License |
src/main/kotlin/xyz/gnarbot/gnar/Credentials.kt | nutspanther | 123,030,514 | true | {"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Java": 68, "Kotlin": 56, "XML": 1} | package xyz.gnarbot.gnar
import ninja.leaping.configurate.commented.CommentedConfigurationNode
import ninja.leaping.configurate.hocon.HoconConfigurationLoader
import ninja.leaping.configurate.loader.ConfigurationLoader
import okhttp3.Request
import org.json.JSONObject
import org.json.JSONTokener
import xyz.gnarbot.gnar.utils.HttpUtils
import xyz.gnarbot.gnar.utils.get
import java.io.File
import java.io.IOException
class Credentials(file: File) {
val loader: ConfigurationLoader<CommentedConfigurationNode> = HoconConfigurationLoader.builder()
.setPath(file.toPath()).build()
val config: CommentedConfigurationNode = loader.load()
val token: String = config["token"].string.takeIf { !it.isNullOrBlank() } ?: error("Bot token can't be null or blank.")
val shards = kotlin.run {
val request = Request.Builder().url("https://discordapp.com/api/gateway/bot")
.header("Authorization", "Bot " + token)
.header("Content-Type", "application/json")
.build()
try {
HttpUtils.CLIENT.newCall(request).execute().use { response ->
val jso = JSONObject(JSONTokener(response.body()!!.byteStream()))
response.close()
jso.getInt("shards")
}
} catch (e: IOException) {
e.printStackTrace()
1
}
}
val dbAddr: String = config["database", "addr"].getString("localhost")
val dbPort: Int = config["database", "port"].getInt(28015)
val dbName: String = config["database", "name"].getString("bot")
val dbUser: String = config["database", "user"].getString("admin")
val dbPass: String = config["database", "pass"].getString("")
val abal: String? = config["server counts", "abal"].string
val carbonitex: String? = config["server counts", "carbonitex"].string
val discordBots: String? = config["server counts", "discordbots"].string
val cat: String? = config["cat"].string
val imgFlip: String? = config["imgflip"].string
val mashape: String? = config["mashape"].string
val malUser: String? = config["mal_creds", "username"].string
val malPass: String? = config["mal_creds", "password"].string
}
| 0 | Kotlin | 0 | 0 | d0cbb9df60a12473378e0a8f9c4f49f993a8ad54 | 2,238 | Music-Bot | MIT License |
data/RF02343/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF02343"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
3 to 6
170 to 173
}
value = "#689bea"
}
color {
location {
11 to 16
29 to 34
}
value = "#192f02"
}
color {
location {
43 to 46
130 to 133
}
value = "#ad1aab"
}
color {
location {
55 to 58
64 to 67
}
value = "#597183"
}
color {
location {
70 to 74
122 to 126
}
value = "#3833ed"
}
color {
location {
77 to 79
94 to 96
}
value = "#1ef7cf"
}
color {
location {
80 to 82
90 to 92
}
value = "#7d65ab"
}
color {
location {
98 to 100
114 to 116
}
value = "#d0c2ac"
}
color {
location {
144 to 151
159 to 166
}
value = "#94c2e8"
}
color {
location {
7 to 10
35 to 42
134 to 143
167 to 169
}
value = "#cbb17f"
}
color {
location {
17 to 28
}
value = "#cd37d8"
}
color {
location {
47 to 54
68 to 69
127 to 129
}
value = "#3f18fa"
}
color {
location {
59 to 63
}
value = "#8531ea"
}
color {
location {
75 to 76
97 to 97
117 to 121
}
value = "#a9f66e"
}
color {
location {
80 to 79
93 to 93
}
value = "#8463e1"
}
color {
location {
83 to 89
}
value = "#964684"
}
color {
location {
101 to 113
}
value = "#b0c5d0"
}
color {
location {
152 to 158
}
value = "#db1d97"
}
color {
location {
1 to 2
}
value = "#5bbe85"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 3,004 | Rfam-for-RNArtist | MIT License |
idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveWhenBranchFix.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class RemoveWhenBranchFix(element: KtWhenEntry) : KotlinQuickFixAction<KtWhenEntry>(element) {
override fun getFamilyName() = if (element?.isElse == true) {
KotlinBundle.message("remove.else.branch")
} else {
KotlinBundle.message("remove.branch")
}
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveWhenBranchFix? {
return when (diagnostic.factory) {
Errors.REDUNDANT_ELSE_IN_WHEN ->
(diagnostic.psiElement as? KtWhenEntry)?.let { RemoveWhenBranchFix(it) }
Errors.SENSELESS_NULL_IN_WHEN ->
diagnostic.psiElement.getStrictParentOfType<KtWhenEntry>()?.let { RemoveWhenBranchFix(it) }
else ->
null
}
}
}
}
| 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 2,024 | intellij-kotlin | Apache License 2.0 |
glfw/src/main/kotlin/imgui/impl/glfw/ImplGlfw.kt | kotlin-graphics | 59,469,938 | false | null | package imgui.impl.glfw
import glm_.b
import glm_.c
import glm_.f
import glm_.vec2.Vec2
import glm_.vec2.Vec2d
import glm_.vec2.Vec2i
import imgui.*
import imgui.ImGui.io
import imgui.ImGui.mouseCursor
import imgui.Key
import imgui.api.g
import imgui.impl.*
import imgui.windowsIme.imeListener
import kool.cap
import kool.lim
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.system.MemoryUtil.NULL
import org.lwjgl.system.Platform
import uno.glfw.*
import uno.glfw.GlfwWindow.CursorMode
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import kotlin.collections.set
// GLFW callbacks
// - When calling Init with 'install_callbacks=true': GLFW callbacks will be installed for you. They will call user's previously installed callbacks, if any.
// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call those function yourself from your own GLFW callbacks.
class ImplGlfw @JvmOverloads constructor(
/** Main window */
val window: GlfwWindow, installCallbacks: Boolean = true,
/** for vr environment */
val vrTexSize: Vec2i? = null,
clientApi: GlfwClientApi = GlfwClientApi.OpenGL) {
/** for passing inputs in vr */
var vrCursorPos: Vec2? = null
init {
with(io) {
// Setup back-end capabilities flags
backendFlags = backendFlags or BackendFlag.HasMouseCursors // We can honor GetMouseCursor() values (optional)
backendFlags = backendFlags or BackendFlag.HasSetMousePos // We can honor io.WantSetMousePos requests (optional, rarely used)
backendPlatformName = "imgui_impl_glfw"
// Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array.
keyMap[Key.Tab] = GLFW_KEY_TAB
keyMap[Key.LeftArrow] = GLFW_KEY_LEFT
keyMap[Key.RightArrow] = GLFW_KEY_RIGHT
keyMap[Key.UpArrow] = GLFW_KEY_UP
keyMap[Key.DownArrow] = GLFW_KEY_DOWN
keyMap[Key.PageUp] = GLFW_KEY_PAGE_UP
keyMap[Key.PageDown] = GLFW_KEY_PAGE_DOWN
keyMap[Key.Home] = GLFW_KEY_HOME
keyMap[Key.End] = GLFW_KEY_END
keyMap[Key.Insert] = GLFW_KEY_INSERT
keyMap[Key.Delete] = GLFW_KEY_DELETE
keyMap[Key.Backspace] = GLFW_KEY_BACKSPACE
keyMap[Key.Space] = GLFW_KEY_SPACE
keyMap[Key.Enter] = GLFW_KEY_ENTER
keyMap[Key.Escape] = GLFW_KEY_ESCAPE
keyMap[Key.KeyPadEnter] = GLFW_KEY_KP_ENTER
keyMap[Key.A] = GLFW_KEY_A
keyMap[Key.C] = GLFW_KEY_C
keyMap[Key.V] = GLFW_KEY_V
keyMap[Key.X] = GLFW_KEY_X
keyMap[Key.Y] = GLFW_KEY_Y
keyMap[Key.Z] = GLFW_KEY_Z
backendRendererName = null
backendPlatformName = null
backendLanguageUserData = null
backendRendererUserData = null
backendPlatformUserData = null
setClipboardTextFn = { _, text -> glfwSetClipboardString(clipboardUserData as Long, text) }
getClipboardTextFn = { glfwGetClipboardString(clipboardUserData as Long) }
clipboardUserData = window.handle.value
if (Platform.get() == Platform.WINDOWS)
imeWindowHandle = window.hwnd
}
// Create mouse cursors
// (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
// GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
// Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
val prevErrorCallback = glfwSetErrorCallback(null)
mouseCursors[MouseCursor.Arrow.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR)
mouseCursors[MouseCursor.TextInput.i] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR)
mouseCursors[MouseCursor.ResizeAll.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this. [JVM] TODO
// mouseCursors[MouseCursor.ResizeAll.i] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR)
mouseCursors[MouseCursor.ResizeNS.i] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR)
mouseCursors[MouseCursor.ResizeEW.i] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR)
mouseCursors[MouseCursor.ResizeNESW.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this.
mouseCursors[MouseCursor.ResizeNWSE.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this.
// mouseCursors[MouseCursor.ResizeNESW.i] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR)
// mouseCursors[MouseCursor.ResizeNWSE.i] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR)
mouseCursors[MouseCursor.Hand.i] = glfwCreateStandardCursor(GLFW_HAND_CURSOR)
mouseCursors[MouseCursor.NotAllowed.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR)
// mouseCursors[MouseCursor.NotAllowed.i] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR)
glfwSetErrorCallback(prevErrorCallback)
// [JVM] Chain GLFW callbacks: our callbacks will be installed in parallel with any other already existing
if (installCallbacks) {
// native callbacks will be added at the GlfwWindow creation via default parameter
window.mouseButtonCBs["imgui"] = mouseButtonCallback
window.scrollCBs["imgui"] = scrollCallback
window.keyCBs["imgui"] = keyCallback
window.charCBs["imgui"] = charCallback
imeListener.install(window)
}
imgui.impl.clientApi = clientApi
}
fun shutdown() {
mouseCursors.forEach(::glfwDestroyCursor)
mouseCursors.fill(NULL)
clientApi = GlfwClientApi.Unknown
}
private fun updateMousePosAndButtons() {
// Update buttons
repeat(io.mouseDown.size) {
/* If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release
events that are shorter than 1 frame. */
io.mouseDown[it] = mouseJustPressed[it] || glfwGetMouseButton(window.handle.value, it) != 0
mouseJustPressed[it] = false
}
// Update mouse position
val mousePosBackup = Vec2d(io.mousePos)
io.mousePos put -Float.MAX_VALUE
if (window.isFocused)
if (io.wantSetMousePos)
window.cursorPos = mousePosBackup
else
io.mousePos put (vrCursorPos ?: window.cursorPos)
else
vrCursorPos?.let(io.mousePos::put) // window is usually unfocused in vr
}
private fun updateMouseCursor() {
if (io.configFlags has ConfigFlag.NoMouseCursorChange || window.cursorMode == CursorMode.disabled)
return
val imguiCursor = mouseCursor
if (imguiCursor == MouseCursor.None || io.mouseDrawCursor)
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
window.cursorMode = CursorMode.hidden
else {
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
window.cursor = GlfwCursor(mouseCursors[imguiCursor.i].takeIf { it != NULL }
?: mouseCursors[MouseCursor.Arrow.i])
window.cursorMode = CursorMode.normal
}
}
fun updateGamepads() {
io.navInputs.fill(0f)
if (io.configFlags has ConfigFlag.NavEnableGamepad) {
// Update gamepad inputs
val buttons = Joystick._1.buttons ?: ByteBuffer.allocate(0)
val buttonsCount = buttons.lim
val axes = Joystick._1.axes ?: FloatBuffer.allocate(0)
val axesCount = axes.lim
fun mapButton(nav: NavInput, button: Int) {
if (buttonsCount > button && buttons[button] == GLFW_PRESS.b)
io.navInputs[nav] = 1f
}
fun mapAnalog(nav: NavInput, axis: Int, v0: Float, v1: Float) {
var v = if (axesCount > axis) axes[axis] else v0
v = (v - v0) / (v1 - v0)
if (v > 1f) v = 1f
if (io.navInputs[nav] < v)
io.navInputs[nav] = v
}
mapButton(NavInput.Activate, 0) // Cross / A
mapButton(NavInput.Cancel, 1) // Circle / B
mapButton(NavInput.Menu, 2) // Square / X
mapButton(NavInput.Input, 3) // Triangle / Y
mapButton(NavInput.DpadLeft, 13) // D-Pad Left
mapButton(NavInput.DpadRight, 11) // D-Pad Right
mapButton(NavInput.DpadUp, 10) // D-Pad Up
mapButton(NavInput.DpadDown, 12) // D-Pad Down
mapButton(NavInput.FocusPrev, 4) // L1 / LB
mapButton(NavInput.FocusNext, 5) // R1 / RB
mapButton(NavInput.TweakSlow, 4) // L1 / LB
mapButton(NavInput.TweakFast, 5) // R1 / RB
mapAnalog(NavInput.LStickLeft, 0, -0.3f, -0.9f)
mapAnalog(NavInput.LStickRight, 0, +0.3f, +0.9f)
mapAnalog(NavInput.LStickUp, 1, +0.3f, +0.9f)
mapAnalog(NavInput.LStickDown, 1, -0.3f, -0.9f)
io.backendFlags = when {
axesCount > 0 && buttonsCount > 0 -> io.backendFlags or BackendFlag.HasGamepad
else -> io.backendFlags wo BackendFlag.HasGamepad
}
}
}
fun newFrame() {
assert(io.fonts.isBuilt) { "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()." }
// Setup display size (every frame to accommodate for window resizing)
val size = window.size
val displaySize = window.framebufferSize
io.displaySize put (vrTexSize ?: window.size)
if (size allGreaterThan 0)
io.displayFramebufferScale put (displaySize / size)
// Setup time step
val currentTime = glfw.time
io.deltaTime = if (time > 0) (currentTime - time).f else 1f / 60f
time = currentTime
updateMousePosAndButtons()
updateMouseCursor()
// Update game controllers (if enabled and available)
updateGamepads()
}
companion object {
lateinit var instance: ImplGlfw
fun init(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null) {
instance = ImplGlfw(window, installCallbacks, vrTexSize)
}
fun newFrame() = instance.newFrame()
fun shutdown() = instance.shutdown()
val mouseButtonCallback: MouseButtonCB = { button: Int, action: Int, _: Int ->
if (action == GLFW_PRESS && button in 0..2)
mouseJustPressed[button] = true
}
val scrollCallback: ScrollCB = { offset: Vec2d ->
io.mouseWheelH += offset.x.f
io.mouseWheel += offset.y.f
}
val keyCallback: KeyCB = { key: Int, _: Int, action: Int, _: Int ->
with(io) {
if (key in keysDown.indices)
if (action == GLFW_PRESS)
keysDown[key] = true
else if (action == GLFW_RELEASE)
keysDown[key] = false
// Modifiers are not reliable across systems
keyCtrl = keysDown[GLFW_KEY_LEFT_CONTROL] || keysDown[GLFW_KEY_RIGHT_CONTROL]
keyShift = keysDown[GLFW_KEY_LEFT_SHIFT] || keysDown[GLFW_KEY_RIGHT_SHIFT]
keyAlt = keysDown[GLFW_KEY_LEFT_ALT] || keysDown[GLFW_KEY_RIGHT_ALT]
keySuper = when(Platform.get()) {
Platform.WINDOWS -> false
else -> keysDown[GLFW_KEY_LEFT_SUPER] || keysDown[GLFW_KEY_RIGHT_SUPER]
}
}
}
val charCallback: CharCB = { c: Int -> if (!imeInProgress) io.addInputCharacter(c.c) }
fun initForOpengl(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null): ImplGlfw =
ImplGlfw(window, installCallbacks, vrTexSize, GlfwClientApi.OpenGL)
fun initForVulkan(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null): ImplGlfw =
ImplGlfw(window, installCallbacks, vrTexSize, GlfwClientApi.Vulkan)
}
} | 23 | null | 34 | 531 | 0091e9b297eb940cd91a78bb71c3036bb4463269 | 12,571 | imgui | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/TextureButton.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.VariantType.BOOL
import godot.core.VariantType.JVM_INT
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.memory.TransferContext
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
/**
* Texture-based button. Supports Pressed, Hover, Disabled and Focused states.
*
* Tutorials:
* [https://godotengine.org/asset-library/asset/676](https://godotengine.org/asset-library/asset/676)
*
* [godot.TextureButton] has the same functionality as [godot.Button], except it uses sprites instead of Godot's [godot.Theme] resource. It is faster to create, but it doesn't support localization like more complex [godot.Control]s.
*
* The "normal" state must contain a texture ([textureNormal]); other textures are optional.
*
* See also [godot.BaseButton] which contains common properties and methods associated with this node.
*/
@GodotBaseType
public open class TextureButton : BaseButton() {
/**
* Texture to display by default, when the node is **not** in the disabled, focused, hover or pressed state.
*/
public var textureNormal: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_TEXTURE_NORMAL,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_TEXTURE_NORMAL,
NIL)
}
/**
* Texture to display on mouse down over the node, if the node has keyboard focus and the player presses the Enter key or if the player presses the [godot.BaseButton.shortcut] key.
*/
public var texturePressed: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_TEXTURE_PRESSED,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_TEXTURE_PRESSED,
NIL)
}
/**
* Texture to display when the mouse hovers the node.
*/
public var textureHover: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_TEXTURE_HOVER,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_TEXTURE_HOVER,
NIL)
}
/**
* Texture to display when the node is disabled. See [godot.BaseButton.disabled].
*/
public var textureDisabled: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_TEXTURE_DISABLED, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_TEXTURE_DISABLED, NIL)
}
/**
* Texture to display when the node has mouse or keyboard focus. [textureFocused] is displayed *over* the base texture, so a partially transparent texture should be used to ensure the base texture remains visible. A texture that represents an outline or an underline works well for this purpose. To disable the focus visual effect, assign a fully transparent texture of any size. Note that disabling the focus visual effect will harm keyboard/controller navigation usability, so this is not recommended for accessibility reasons.
*/
public var textureFocused: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_TEXTURE_FOCUSED,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Texture2D?
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_TEXTURE_FOCUSED,
NIL)
}
/**
* Pure black and white [godot.BitMap] image to use for click detection. On the mask, white pixels represent the button's clickable area. Use it to create buttons with curved shapes.
*/
public var textureClickMask: BitMap?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_CLICK_MASK,
OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as BitMap?
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_CLICK_MASK, NIL)
}
/**
* If `true`, the size of the texture won't be considered for minimum size calculation, so the [godot.TextureButton] can be shrunk down past the texture size.
*/
public var ignoreTextureSize: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_IGNORE_TEXTURE_SIZE, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_IGNORE_TEXTURE_SIZE, NIL)
}
/**
* Controls the texture's behavior when you resize the node's bounding rectangle. See the [enum StretchMode] constants for available options.
*/
public var stretchMode: StretchMode
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_GET_STRETCH_MODE,
LONG)
return TextureButton.StretchMode.values()[TransferContext.readReturnValue(JVM_INT) as Int]
}
set(`value`) {
TransferContext.writeArguments(LONG to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_STRETCH_MODE,
NIL)
}
/**
* If `true`, texture is flipped horizontally.
*/
public var flipH: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_IS_FLIPPED_H, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_FLIP_H, NIL)
}
/**
* If `true`, texture is flipped vertically.
*/
public var flipV: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_IS_FLIPPED_V, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_TEXTUREBUTTON_SET_FLIP_V, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_TEXTUREBUTTON, scriptIndex)
return true
}
public enum class StretchMode(
id: Long,
) {
/**
* Scale to fit the node's bounding rectangle.
*/
STRETCH_SCALE(0),
/**
* Tile inside the node's bounding rectangle.
*/
STRETCH_TILE(1),
/**
* The texture keeps its original size and stays in the bounding rectangle's top-left corner.
*/
STRETCH_KEEP(2),
/**
* The texture keeps its original size and stays centered in the node's bounding rectangle.
*/
STRETCH_KEEP_CENTERED(3),
/**
* Scale the texture to fit the node's bounding rectangle, but maintain the texture's aspect ratio.
*/
STRETCH_KEEP_ASPECT(4),
/**
* Scale the texture to fit the node's bounding rectangle, center it, and maintain its aspect ratio.
*/
STRETCH_KEEP_ASPECT_CENTERED(5),
/**
* Scale the texture so that the shorter side fits the bounding rectangle. The other side clips to the node's limits.
*/
STRETCH_KEEP_ASPECT_COVERED(6),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = values().single { it.id == `value` }
}
}
public companion object
}
| 60 | null | 28 | 412 | fe7379a450ed32ad069f3b672709a2520b86f092 | 9,195 | godot-kotlin-jvm | MIT License |
src/jsMain/kotlin/mapbox/Declarations.kt | dellisd | 597,549,419 | false | null | package mapbox
typealias quat = Array<Number>
typealias vec3 = Array<Number>
typealias TransformRequestFunction = (url: String, resourceType: String /* "Unknown" | "Style" | "Source" | "Tile" | "Glyphs" | "SpriteImage" | "SpriteJSON" | "Image" */) -> RequestParameters
typealias ExpressionSpecification = Array<Any>
typealias EventedListener = (obj: Any) -> Any
| 0 | Kotlin | 1 | 1 | 0393b3eae4f14cb9c6579d2092f047734ce200c6 | 367 | compose-web-mapbox | MIT License |
xmlschema/src/commonMain/kotlin/io/github/pdvrieze/formats/xmlschema/resolved/SyntheticSequence.kt | pdvrieze | 143,553,364 | false | {"Kotlin": 3481762} | /*
* Copyright (c) 2023.
*
* This file is part of xmlutil.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.formats.xmlschema.resolved
import io.github.pdvrieze.formats.xmlschema.datatypes.primitiveInstances.VNonNegativeInteger
import io.github.pdvrieze.formats.xmlschema.resolved.checking.CheckHelper
import io.github.pdvrieze.formats.xmlschema.types.VAllNNI
import nl.adaptivity.xmlutil.QName
class SyntheticAll(
override val mdlMinOccurs: VNonNegativeInteger,
override val mdlMaxOccurs: VAllNNI,
override val mdlParticles: List<ResolvedParticle<ResolvedTerm>>,
) : ResolvedParticle<SyntheticAll>, IResolvedAll {
init {
require(mdlMinOccurs<=mdlMaxOccurs) { "Invalid bounds: ! (${mdlMinOccurs}<=$mdlMaxOccurs)" }
}
override val model: ResolvedAnnotated.IModel get() = ResolvedAnnotated.Empty
override val mdlTerm: SyntheticAll get() = this
override fun flatten(checkHelper: CheckHelper): FlattenedParticle {
return super<ResolvedParticle>.flatten(checkHelper)
}
override fun isSiblingName(name: QName): Boolean {
return super<IResolvedAll>.isSiblingName(name)
}
}
| 35 | Kotlin | 31 | 378 | c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79 | 1,803 | xmlutil | Apache License 2.0 |
src/nl/hannahsten/texifyidea/lang/commands/LatexRegularCommand.kt | Hannah-Sten | 62,398,769 | false | null | package nl.hannahsten.texifyidea.lang.commands
/**
* @author <NAME>, <NAME>
*/
object LatexRegularCommand {
val GENERIC: Set<LatexCommand> = LatexGenericRegularCommand.values().toSet()
val TEXTCOMP: Set<LatexCommand> = LatexTextcompCommand.values().toSet()
val EURO: Set<LatexCommand> = LatexEuroCommand.values().toSet()
val TEXT_SYMBOLS: Set<LatexCommand> = LatexTextSymbolCommand.values().toSet()
val NEW_DEFINITIONS: Set<LatexCommand> = LatexNewDefinitionCommand.values().toSet()
val MATHTOOLS: Set<LatexCommand> = LatexMathtoolsRegularCommand.values().toSet()
val XCOLOR: Set<LatexCommand> = LatexColorDefinitionCommand.values().toSet()
val XPARSE: Set<LatexCommand> = LatexXparseCommand.values().toSet()
val NATBIB: Set<LatexCommand> = LatexNatbibCommand.values().toSet()
val BIBLATEX: Set<LatexCommand> = LatexBiblatexCommand.values().toSet()
val SIUNITX: Set<LatexCommand> = LatexSiunitxCommand.values().toSet()
val ALGORITHMICX: Set<LatexCommand> = LatexAlgorithmicxCommand.values().toSet()
val IFS: Set<LatexCommand> = LatexIfCommand.values().toSet()
val LISTINGS: Set<LatexCommand> = LatexListingCommand.values().toSet()
val LOREM_IPSUM: Set<LatexCommand> = LatexLoremIpsumCommand.values().toSet()
val ALL: Set<LatexCommand> = GENERIC + TEXTCOMP + EURO + TEXT_SYMBOLS + NEW_DEFINITIONS + MATHTOOLS +
XCOLOR + XPARSE + NATBIB + BIBLATEX + SIUNITX + ALGORITHMICX + IFS + LISTINGS + LOREM_IPSUM
private val lookup = HashMap<String, MutableSet<LatexCommand>>()
private val lookupDisplay = HashMap<String, MutableSet<LatexCommand>>()
init {
ALL.forEach {
lookup.getOrPut(it.command) { mutableSetOf() }.add(it)
if (it.display != null) {
lookupDisplay.putIfAbsent(it.display!!, mutableSetOf(it))?.add(it)
}
}
}
@JvmStatic
fun values() = ALL
@JvmStatic
operator fun get(command: String) = lookup[command]?.toSet()
@JvmStatic
fun findByDisplay(display: String) = lookupDisplay[display]?.toSet()
}
| 4 | Kotlin | 60 | 640 | 897da43f3815432e9b3b307a8af8be74e7a50895 | 2,092 | TeXiFy-IDEA | MIT License |
app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt | robbinhan | 150,848,366 | false | null | package com.simplemobiletools.notes.activities
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.text.method.ArrowKeyMovementMethod
import android.text.method.LinkMovementMethod
import android.util.Log
import android.util.TypedValue
import android.view.ActionMode
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import com.facebook.stetho.Stetho
import com.simplemobiletools.commons.BuildConfig
import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.models.Release
import com.simplemobiletools.commons.views.MyEditText
import com.simplemobiletools.notes.R
import com.simplemobiletools.notes.adapters.NotesPagerAdapter
import com.simplemobiletools.notes.dialogs.*
import com.simplemobiletools.notes.extensions.config
import com.simplemobiletools.notes.extensions.dbHelper
import com.simplemobiletools.notes.extensions.getTextSize
import com.simplemobiletools.notes.extensions.updateWidgets
import com.simplemobiletools.notes.helpers.MARKDOWN_TEXT
import com.simplemobiletools.notes.helpers.MIME_TEXT_PLAIN
import com.simplemobiletools.notes.helpers.OPEN_NOTE_ID
import com.simplemobiletools.notes.helpers.TYPE_NOTE
import com.simplemobiletools.notes.models.ChangeLog
import com.simplemobiletools.notes.models.Note
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.nio.charset.Charset
class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener {
private var mAdapter: NotesPagerAdapter? = null
private lateinit var mCurrentNote: Note
private var mNotes = ArrayList<Note>()
private var noteViewWithTextSelected: MyEditText? = null
private var wasInit = false
private var storedEnableLineWrap = true
private var showSaveButton = false
private var showUndoButton = false
private var showRedoButton = false
private var saveNoteButton: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Stetho.initializeWithDefaults(this)
setContentView(R.layout.activity_main)
appLaunched(BuildConfig.APPLICATION_ID)
initViewPager()
pager_title_strip.setTextSize(TypedValue.COMPLEX_UNIT_PX, getTextSize())
pager_title_strip.layoutParams.height = (pager_title_strip.height + resources.getDimension(R.dimen.activity_margin) * 2).toInt()
if (dbHelper.getChangeLog().size < 0
|| (dbHelper.getChangeLog().size > 0 && dbHelper.getChangeLog().last().changeLogId < BuildConfig.VERSION_CODE)
) {
checkWhatsNewDialog()
config.avoidWhatsNew = true
dbHelper.insertChangeLog(ChangeLog(BuildConfig.VERSION_CODE, "New ChangeLog"))
}
intent.apply {
if (action == Intent.ACTION_SEND && type == MIME_TEXT_PLAIN) {
getStringExtra(Intent.EXTRA_TEXT)?.let {
handleText(it)
intent.removeExtra(Intent.EXTRA_TEXT)
}
}
if (action == Intent.ACTION_VIEW) {
handleUri(data)
intent.removeCategory(Intent.CATEGORY_DEFAULT)
intent.action = null
}
}
storeStateVariables()
if (config.showNotePicker && savedInstanceState == null) {
displayOpenNoteDialog()
}
wasInit = true
checkAppOnSDCard()
}
override fun onResume() {
super.onResume()
if (storedEnableLineWrap != config.enableLineWrap) {
initViewPager()
}
invalidateOptionsMenu()
pager_title_strip.apply {
setTextSize(TypedValue.COMPLEX_UNIT_PX, getTextSize())
setGravity(Gravity.CENTER_VERTICAL)
setNonPrimaryAlpha(0.4f)
setTextColor(config.textColor)
}
updateTextColors(view_pager)
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
menu.apply {
findItem(R.id.undo).isVisible = showUndoButton
findItem(R.id.redo).isVisible = showRedoButton
}
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val shouldBeVisible = mNotes.size > 1
menu.apply {
findItem(R.id.rename_note).isVisible = shouldBeVisible
findItem(R.id.open_note).isVisible = shouldBeVisible
findItem(R.id.delete_note).isVisible = shouldBeVisible
findItem(R.id.export_all_notes).isVisible = shouldBeVisible
saveNoteButton = findItem(R.id.save_note)
saveNoteButton!!.isVisible = !config.autosaveNotes && showSaveButton
}
pager_title_strip.beVisibleIf(shouldBeVisible)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (config.autosaveNotes) {
saveCurrentNote(false)
}
when (item.itemId) {
R.id.open_note -> displayOpenNoteDialog()
R.id.save_note -> saveNote()
R.id.undo -> undo()
R.id.redo -> redo()
R.id.new_note -> displayNewNoteDialog()
R.id.rename_note -> displayRenameDialog()
R.id.share -> shareText()
R.id.open_file -> tryOpenFile()
R.id.import_folder -> tryOpenFolder()
R.id.export_as_file -> tryExportAsFile()
R.id.export_all_notes -> tryExportAllNotes()
R.id.delete_note -> displayDeleteNotePrompt()
R.id.settings -> startActivity(Intent(applicationContext, SettingsActivity::class.java))
R.id.about -> launchAbout()
R.id.markdown -> markdown()
else -> return super.onOptionsItemSelected(item)
}
return true
}
// https://code.google.com/p/android/issues/detail?id=191430 quickfix
override fun onActionModeStarted(mode: ActionMode?) {
super.onActionModeStarted(mode)
if (wasInit) {
currentNotesView()?.apply {
if (config.clickableLinks || movementMethod is LinkMovementMethod) {
movementMethod = ArrowKeyMovementMethod.getInstance()
noteViewWithTextSelected = this
}
}
}
}
override fun onActionModeFinished(mode: ActionMode?) {
super.onActionModeFinished(mode)
if (config.clickableLinks) {
noteViewWithTextSelected?.movementMethod = LinkMovementMethod.getInstance()
}
}
override fun onBackPressed() {
if (!config.autosaveNotes && mAdapter?.anyHasUnsavedChanges() == true) {
ConfirmationAdvancedDialog(this, "", R.string.unsaved_changes_warning, R.string.save, R.string.discard) {
if (it) {
mAdapter?.saveAllFragmentTexts()
super.onBackPressed()
} else {
super.onBackPressed()
}
}
} else {
super.onBackPressed()
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
view_pager.currentItem = getWantedNoteIndex()
}
private fun storeStateVariables() {
config.apply {
storedEnableLineWrap = enableLineWrap
}
}
private fun handleText(text: String) {
val notes = dbHelper.getNotes()
val list = arrayListOf<RadioItem>().apply {
add(RadioItem(0, getString(R.string.create_new_note)))
notes.forEachIndexed { index, note ->
add(RadioItem(index + 1, note.title))
}
}
RadioGroupDialog(this, list, -1, R.string.add_to_note) {
if (it as Int == 0) {
displayNewNoteDialog(text)
} else {
updateSelectedNote(notes[it - 1].id)
addTextToCurrentNote(if (mCurrentNote.value.isEmpty()) text else "\n$text")
}
}
}
private fun handleUri(uri: Uri) {
val id = dbHelper.getNoteId(uri.path)
if (dbHelper.isValidId(id)) {
updateSelectedNote(id)
return
}
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
importFileWithSync(uri)
}
}
}
private fun initViewPager() {
mNotes = dbHelper.getNotes()
mCurrentNote = mNotes[0]
mAdapter = NotesPagerAdapter(supportFragmentManager, mNotes, this)
view_pager.apply {
adapter = mAdapter
currentItem = getWantedNoteIndex()
addOnPageChangeListener(this@MainActivity)
}
if (!config.showKeyboard) {
hideKeyboard()
}
}
private fun getWantedNoteIndex(): Int {
var wantedNoteId = intent.getIntExtra(OPEN_NOTE_ID, -1)
if (wantedNoteId == -1) {
wantedNoteId = config.currentNoteId
}
return getNoteIndexWithId(wantedNoteId)
}
private fun currentNotesView() = if (view_pager == null) {
null
} else {
mAdapter?.getCurrentNotesView(view_pager.currentItem)
}
private fun displayRenameDialog() {
RenameNoteDialog(this, mCurrentNote) {
mCurrentNote = it
initViewPager()
}
}
private fun updateSelectedNote(id: Int) {
config.currentNoteId = id
val index = getNoteIndexWithId(id)
view_pager.currentItem = index
mCurrentNote = mNotes[index]
}
private fun displayNewNoteDialog(value: String = "") {
NewNoteDialog(this, dbHelper) {
val newNote = Note(0, it, value, TYPE_NOTE)
addNewNote(newNote)
}
}
private fun addNewNote(note: Note) {
val id = dbHelper.insertNote(note)
mNotes = dbHelper.getNotes()
showSaveButton = false
invalidateOptionsMenu()
initViewPager()
updateSelectedNote(id)
view_pager.onGlobalLayout {
mAdapter?.focusEditText(getNoteIndexWithId(id))
}
}
private fun launchAbout() {
val licenses = LICENSE_STETHO or LICENSE_RTL or LICENSE_LEAK_CANARY
val faqItems = arrayListOf(
FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons),
FAQItem(R.string.faq_4_title_commons, R.string.faq_4_text_commons),
FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons)
)
startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true)
}
private fun tryOpenFile() {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
openFile()
}
}
}
private fun openFile() {
FilePickerDialog(this) {
openFile(it, true) {
OpenFileDialog(this, it.path) {
addNewNote(it)
}
}
}
}
private fun openFile(path: String, checkTitle: Boolean, onChecksPassed: (file: File) -> Unit) {
val file = File(path)
if (path.isMediaFile()) {
toast(R.string.invalid_file_format)
} else if (file.length() > 10 * 1000 * 1000) {
toast(R.string.file_too_large)
} else if (checkTitle && dbHelper.doesNoteTitleExist(path.getFilenameFromPath())) {
toast(R.string.title_taken)
} else {
onChecksPassed(file)
}
}
private fun openFolder(path: String, onChecksPassed: (file: File) -> Unit) {
val file = File(path)
if (file.isDirectory) {
onChecksPassed(file)
}
}
private fun importFileWithSync(uri: Uri) {
when (uri.scheme) {
"file" -> openPath(uri.path)
"content" -> {
val realPath = getRealPathFromURI(uri)
if (realPath != null) {
openPath(realPath)
} else {
R.string.unknown_error_occurred
}
}
}
}
private fun openPath(path: String) {
openFile(path, false) {
var title = path.getFilenameFromPath()
if (dbHelper.doesNoteTitleExist(title))
title += " (file)"
val note = Note(0, title, "", TYPE_NOTE, path)
addNewNote(note)
}
}
private fun tryOpenFolder() {
handlePermission(PERMISSION_READ_STORAGE) {
if (it) {
openFolder()
}
}
}
private fun openFolder() {
FilePickerDialog(this, pickFile = false) {
openFolder(it) {
ImportFolderDialog(this, it.path) {
mNotes = dbHelper.getNotes()
showSaveButton = false
invalidateOptionsMenu()
initViewPager()
updateSelectedNote(it)
view_pager.onGlobalLayout {
mAdapter?.focusEditText(getNoteIndexWithId(it))
}
}
}
}
}
private fun tryExportAsFile() {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
exportAsFile()
}
}
}
private fun exportAsFile() {
ExportFileDialog(this, mCurrentNote) {
if (getCurrentNoteText()?.isNotEmpty() == true) {
exportNoteValueToFile(it, getCurrentNoteText()!!, true)
}
}
}
private fun tryExportAllNotes() {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
exportAllNotes()
}
}
}
private fun exportAllNotes() {
ExportFilesDialog(this, mNotes) { parent, extension ->
var failCount = 0
mNotes = dbHelper.getNotes()
mNotes.forEachIndexed { index, note ->
val filename = if (extension.isEmpty()) note.title else "${note.title}.$extension"
val file = File(parent, filename)
if (!filename.isAValidFilename()) {
toast(String.format(getString(R.string.filename_invalid_characters_placeholder, filename)))
} else {
exportNoteValueToFile(file.absolutePath, note.value, false) {
if (!it) {
failCount++
}
if (index == mNotes.size - 1) {
toast(if (failCount == 0) R.string.exporting_successful else R.string.exporting_some_entries_failed)
}
}
}
}
}
}
fun exportNoteValueToFile(path: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) {
try {
if (getIsPathDirectory(path)) {
toast(R.string.name_taken)
return
}
if (needsStupidWritePermissions(path)) {
handleSAFDialog(path) {
var document = getDocumentFile(path) ?: return@handleSAFDialog
if (!getDoesFilePathExist(path)) {
document = document.createFile("", path.getFilenameFromPath())
}
contentResolver.openOutputStream(document.uri).apply {
write(content.toByteArray(Charset.forName("UTF-8")), 0, content.length)
flush()
close()
}
if (showSuccessToasts) {
noteExportedSuccessfully(path.getFilenameFromPath())
}
callback?.invoke(true)
}
} else {
val file = File(path)
file.printWriter().use { out ->
out.write(content)
}
if (showSuccessToasts) {
noteExportedSuccessfully(path.getFilenameFromPath())
}
callback?.invoke(true)
}
} catch (e: Exception) {
showErrorToast(e)
callback?.invoke(false)
}
}
private fun noteExportedSuccessfully(title: String) {
val message = String.format(getString(R.string.note_exported_successfully), title)
toast(message)
}
fun noteSavedSuccessfully(title: String) {
if (config.displaySuccess) {
val message = String.format(getString(R.string.note_saved_successfully), title)
toast(message)
}
}
private fun getCurrentNoteText() = (view_pager.adapter as NotesPagerAdapter).getCurrentNoteViewText(view_pager.currentItem)
private fun addTextToCurrentNote(text: String) = (view_pager.adapter as NotesPagerAdapter).appendText(view_pager.currentItem, text)
private fun saveCurrentNote(force: Boolean) = (view_pager.adapter as NotesPagerAdapter).saveCurrentNote(view_pager.currentItem, force)
private fun displayDeleteNotePrompt() {
DeleteNoteDialog(this, mCurrentNote) {
deleteNote(it)
}
}
fun deleteNote(deleteFile: Boolean) {
if (mNotes.size <= 1) {
return
}
if (!deleteFile) {
doDeleteNote(mCurrentNote, deleteFile)
} else {
handleSAFDialog(mCurrentNote.path) {
doDeleteNote(mCurrentNote, deleteFile)
}
}
}
private fun doDeleteNote(note: Note, deleteFile: Boolean) {
dbHelper.deleteNote(mCurrentNote.id)
mNotes = dbHelper.getNotes()
val firstNoteId = mNotes[0].id
updateSelectedNote(firstNoteId)
if (config.widgetNoteId == note.id) {
config.widgetNoteId = mCurrentNote.id
updateWidgets()
}
invalidateOptionsMenu()
initViewPager()
if (deleteFile) {
deleteFile(FileDirItem(note.path, note.title)) {
if (!it) {
toast(R.string.unknown_error_occurred)
}
}
}
}
private fun displayOpenNoteDialog() {
OpenNoteDialog(this) {
updateSelectedNote(it)
}
}
private fun saveNote() {
saveCurrentNote(true)
showSaveButton = false
invalidateOptionsMenu()
}
private fun undo() {
mAdapter?.undo(view_pager.currentItem)
}
private fun redo() {
mAdapter?.redo(view_pager.currentItem)
}
private fun markdown() {
mAdapter?.markdown(view_pager.currentItem)
}
fun markdownActivityOpen(text: String) {
// Log.d("markdownActivityOpen", text)
val intent = Intent(this, MarkdownActivity::class.java)
intent.putExtra(MARKDOWN_TEXT, text)
startActivity(intent)
}
private fun getNoteIndexWithId(id: Int): Int {
for (i in 0 until mNotes.count()) {
if (mNotes[i].id == id) {
mCurrentNote = mNotes[i]
return i
}
}
return 0
}
private fun shareText() {
val text = getCurrentNoteText()
if (text == null || text.isEmpty()) {
toast(R.string.cannot_share_empty_text)
return
}
val res = resources
val shareTitle = res.getString(R.string.share_via)
Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_SUBJECT, mCurrentNote.title)
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
startActivity(Intent.createChooser(this, shareTitle))
}
}
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
mCurrentNote = mNotes[position]
config.currentNoteId = mCurrentNote.id
}
fun currentNoteTextChanged(newText: String, showUndo: Boolean, showRedo: Boolean) {
var shouldRecreateMenu = false
if (showUndo != showUndoButton) {
showUndoButton = showUndo
shouldRecreateMenu = true
}
if (showRedo != showRedoButton) {
showRedoButton = showRedo
shouldRecreateMenu = true
}
if (!config.autosaveNotes) {
showSaveButton = newText != mCurrentNote.value
if (showSaveButton != saveNoteButton?.isVisible) {
shouldRecreateMenu = true
}
}
if (shouldRecreateMenu) {
invalidateOptionsMenu()
}
}
private fun checkWhatsNewDialog() {
arrayListOf<Release>().apply {
add(Release(25, R.string.release_25))
add(Release(28, R.string.release_28))
add(Release(29, R.string.release_29))
add(Release(39, R.string.release_39))
add(Release(45, R.string.release_45))
add(Release(49, R.string.release_49))
add(Release(51, R.string.release_51))
checkWhatsNew(this, BuildConfig.VERSION_CODE)
}
}
}
| 0 | null | 0 | 1 | 4bb1db7c50b07149dc8b5c7e7edd37bbbd9df238 | 21,962 | Simple-Notes | Apache License 2.0 |
platform/lang-impl/src/com/intellij/codeInspection/ex/ApplicationInspectionProfileManager.kt | ingokegel | 284,920,751 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.ex
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInsight.daemon.InspectionProfileConvertor
import com.intellij.codeInsight.daemon.impl.HighlightInfoType
import com.intellij.codeInsight.daemon.impl.SeveritiesProvider
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.processOpenedProjects
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.IconLoader
import com.intellij.profile.codeInspection.InspectionProfileManager
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.serviceContainer.NonInjectable
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
@State(name = "InspectionProfileManager", storages = [Storage("editor.xml")], additionalExportDirectory = InspectionProfileManager.INSPECTION_DIR)
open class ApplicationInspectionProfileManager @TestOnly @NonInjectable constructor(schemeManagerFactory: SchemeManagerFactory) : ApplicationInspectionProfileManagerBase(schemeManagerFactory),
PersistentStateComponent<Element> {
open val converter: InspectionProfileConvertor
get() = InspectionProfileConvertor(this)
val rootProfileName: String
get() = schemeManager.currentSchemeName ?: DEFAULT_PROFILE_NAME
constructor() : this(SchemeManagerFactory.getInstance())
companion object {
@JvmStatic
fun getInstanceImpl() = service<InspectionProfileManager>() as ApplicationInspectionProfileManager
private fun registerProvidedSeverities() {
val map = HashMap<String, HighlightInfoType>()
SeveritiesProvider.EP_NAME.forEachExtensionSafe { provider ->
for (t in provider.severitiesHighlightInfoTypes) {
val highlightSeverity = t.getSeverity(null)
val icon = when (t) {
is HighlightInfoType.Iconable -> {
IconLoader.createLazy { (t as HighlightInfoType.Iconable).icon }
}
else -> null
}
map.put(highlightSeverity.name, t)
HighlightDisplayLevel.registerSeverity(highlightSeverity, t.attributesKey, icon)
}
}
if (map.isNotEmpty()) {
SeverityRegistrar.registerStandard(map)
}
}
}
init {
registerProvidedSeverities()
}
@TestOnly
fun forceInitProfiles(flag: Boolean) {
LOAD_PROFILES = flag
profilesAreInitialized
}
override fun getState(): Element? {
val state = Element("state")
severityRegistrar.writeExternal(state)
return state
}
override fun loadState(state: Element) {
severityRegistrar.readExternal(state)
}
override fun fireProfileChanged(profile: InspectionProfileImpl) {
processOpenedProjects { project ->
ProjectInspectionProfileManager.getInstance(project).fireProfileChanged(profile)
}
}
@Throws(IOException::class, JDOMException::class)
override fun loadProfile(path: String): InspectionProfileImpl? {
try {
return super.loadProfile(path)
}
catch (e: IOException) {
throw e
}
catch (e: JDOMException) {
throw e
}
catch (ignored: Exception) {
val file = Paths.get(path)
ApplicationManager.getApplication().invokeLater({
Messages.showErrorDialog(
InspectionsBundle.message("inspection.error.loading.message", 0, file),
InspectionsBundle.message("inspection.errors.occurred.dialog.title"))
}, ModalityState.NON_MODAL)
}
return getProfile(path, false)
}
}
| 284 | null | 5162 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 4,498 | intellij-community | Apache License 2.0 |
idea/src/org/jetbrains/kotlin/idea/PluginStartupService.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.psi.search.searches.IndexPatternSearch
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinTodoSearcher
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
class PluginStartupService : Disposable {
fun register(project: Project) {
val eventMulticaster = EditorFactory.getInstance().eventMulticaster
val documentListener: DocumentListener = object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
FileDocumentManager.getInstance().getFile(e.document)?.let { virtualFile ->
if (virtualFile.fileType === KotlinFileType.INSTANCE) {
KotlinPluginUpdater.getInstance().kotlinFileEdited(virtualFile)
}
}
}
}
eventMulticaster.addDocumentListener(documentListener, this)
val indexPatternSearch = ServiceManager.getService(IndexPatternSearch::class.java)
val kotlinTodoSearcher = KotlinTodoSearcher()
indexPatternSearch.registerExecutor(kotlinTodoSearcher)
Disposer.register(this, {
eventMulticaster.removeDocumentListener(documentListener)
indexPatternSearch.unregisterExecutor(kotlinTodoSearcher)
})
}
override fun dispose() {
}
companion object {
fun getInstance(project: Project): PluginStartupService = project.getServiceSafe()
}
} | 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 2,087 | intellij-kotlin | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/new-mpp-parallel/src/commonMain/kotlin/A.kt | damenez | 176,209,431 | true | {"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1} | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package common
class A(val x: Int)
| 0 | Kotlin | 0 | 2 | 9a2178d96bd736c67ba914b0f595e42d1bba374d | 201 | kotlin | Apache License 2.0 |
modules/jooby-openapi/src/test/kotlin/kt/KtRouteImport.kt | jooby-project | 25,446,835 | false | null | package kt
import examples.RouteA
import io.jooby.Kooby
import io.jooby.require
class KtRouteImport : Kooby({
use(RouteA())
path("/main") {
use(RouteA())
use("/submain", RouteA())
}
use(RouteA())
use("/require", require(RouteA::class))
use("/subroute", RouteA())
})
| 51 | null | 175 | 1,439 | 1a0252d5dac7d3730f3e7017008c65a9ae4e5dd3 | 291 | jooby | Apache License 2.0 |
moove/application/src/main/kotlin/io/charlescd/moove/application/build/response/ComponentResponse.kt | ZupIT | 249,519,503 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.charlescd.moove.application.build.response
import com.fasterxml.jackson.annotation.JsonFormat
import io.charlescd.moove.domain.Component
import io.charlescd.moove.domain.ComponentSnapshot
import java.time.LocalDateTime
data class ComponentResponse(
val id: String,
val name: String,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
val createdAt: LocalDateTime,
val errorThreshold: Int? = null,
val latencyThreshold: Int? = null
) {
companion object {
fun from(component: ComponentSnapshot): ComponentResponse {
return ComponentResponse(
id = component.componentId,
name = component.name,
createdAt = component.createdAt
)
}
fun from(component: Component): ComponentResponse {
return ComponentResponse(
id = component.id,
name = component.name,
createdAt = component.createdAt,
errorThreshold = component.errorThreshold,
latencyThreshold = component.latencyThreshold
)
}
}
}
| 93 | TypeScript | 76 | 343 | a65319e3712dba1612731b44346100e89cd26a60 | 1,786 | charlescd | Apache License 2.0 |
sourceamazing-schema/src/test/kotlin/org/codeblessing/sourceamazing/schema/util/EnumUtilTest.kt | code-blessing | 695,574,460 | false | {"Kotlin": 659707} | package org.codeblessing.sourceamazing.schema.util
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class EnumUtilTest {
private enum class MyEnum { FOO, BAR; }
private enum class MyOtherEnum { FOO, BUL; }
private enum class MySubsetEnumEnum { @Suppress("UNUSED") BAR; }
private enum class MySameEnum { @Suppress("UNUSED") FOO, @Suppress("UNUSED") BAR; }
private enum class MyEmptyEnum
@Test
fun fromStringToEnum() {
assertEquals(MyEnum.BAR, EnumUtil.fromStringToEnum("BAR", MyEnum::class))
assertEquals(MyEnum.FOO, EnumUtil.fromStringToEnum("FOO", MyEnum::class))
assertEquals(MyOtherEnum.BUL, EnumUtil.fromStringToEnum("BUL", MyOtherEnum::class))
assertEquals(MyOtherEnum.FOO, EnumUtil.fromStringToEnum("FOO", MyOtherEnum::class))
assertNull(EnumUtil.fromStringToEnum("BAZ", MyEnum::class))
}
@Test
fun isEnumerationType() {
assertTrue(EnumUtil.isEnumerationType(MyEnum.FOO, MyEnum::class))
assertTrue(EnumUtil.isEnumerationType(MyEnum.BAR, MyEnum::class))
assertFalse(EnumUtil.isEnumerationType(MyOtherEnum.FOO, MyEnum::class))
assertFalse(EnumUtil.isEnumerationType(MyOtherEnum.BUL, MyEnum::class))
assertFalse(EnumUtil.isEnumerationType("FOO", MyEnum::class))
assertFalse(EnumUtil.isEnumerationType("x", MyEnum::class))
assertFalse(EnumUtil.isEnumerationType(42, MyEnum::class))
assertFalse(EnumUtil.isEnumerationType(false, MyEnum::class))
}
@Test
fun isSameOrSubsetEnumerationClass() {
assertTrue(EnumUtil.isSameOrSubsetEnumerationClass(fullEnumClass = MyEnum::class, fullOrSubsetEnumClass = MySameEnum::class))
assertTrue(EnumUtil.isSameOrSubsetEnumerationClass(fullEnumClass = MyEnum::class, fullOrSubsetEnumClass = MySubsetEnumEnum::class))
assertTrue(EnumUtil.isSameOrSubsetEnumerationClass(fullEnumClass = MyEnum::class, fullOrSubsetEnumClass = MyEmptyEnum::class))
assertFalse(EnumUtil.isSameOrSubsetEnumerationClass(fullEnumClass = MyEnum::class, fullOrSubsetEnumClass = MyOtherEnum::class))
assertFalse(EnumUtil.isSameOrSubsetEnumerationClass(fullEnumClass = MyEnum::class, fullOrSubsetEnumClass = Any::class))
}
} | 3 | Kotlin | 0 | 1 | 784e827214308144c22639946c34b99b6b591a8a | 2,426 | sourceamazing | MIT License |
anti_swindle/src/main/kotlin/com/magina/antiswindle/AntiSwindleApplication.kt | dongzhixuanyuan | 306,818,640 | false | null | package com.magina.antiswindle
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
@SpringBootApplication
class AntiSwindleApplication
fun main(args: Array<String>) {
runApplication<AntiSwindleApplication>(*args)
}
| 0 | Kotlin | 0 | 0 | 923a2495bf4fa9d20d5db4c369f275b74f1172f8 | 375 | server_learning_project | Apache License 2.0 |
app/src/main/java/io/redgreen/benchpress/hellostranger/HelloStrangerActivity.kt | kkrishna001 | 440,793,337 | false | null | package io.redgreen.benchpress.hellostranger
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import com.spotify.mobius.Next
import io.reactivex.ObservableTransformer
import io.redgreen.benchpress.architecture.BaseActivity
import kotlinx.android.synthetic.main.hello_stranger_activity.*
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
class HelloStrangerActivity :
BaseActivity<HelloStrangerModel, HelloStrangerEvent, HelloStrangerEffect>(), Interactor2 {
companion object {
fun start(context: Context) {
context.startActivity(Intent(context, HelloStrangerActivity::class.java))
}
}
override fun layoutResId(): Int {
return io.redgreen.benchpress.R.layout.hello_stranger_activity
}
override fun setup() {
nameEditText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
}
override fun beforeTextChanged(
s: CharSequence, start: Int,
count: Int, after: Int
) {
}
override fun onTextChanged(
s: CharSequence, start: Int,
before: Int, count: Int
) {
if (s.isEmpty()) {
eventSource.notifyEvent(EmptyNameEvent)
} else {
eventSource.notifyEvent(ChangeNameEvent(s.toString()))
}
}
})
}
override fun initialModel(): HelloStrangerModel {
return HelloStrangerModel.EMPTY
}
override fun updateFunction(
model: HelloStrangerModel,
event: HelloStrangerEvent
): Next<HelloStrangerModel, HelloStrangerEffect> {
return HelloStrangerLogic.update(model, event)
}
@SuppressLint("SetTextI18n")
override fun render(model: HelloStrangerModel) {
if (model.name.isEmpty()) {
greetingTextView.text = "Hello, Stranger"
} else if (model.name.isEmpty().not()) {
greetingTextView.text = "Hello, ${model.name}"
}
}
override fun effectHandler(): ObservableTransformer<HelloStrangerEffect, HelloStrangerEvent> {
return HelloStrangerEffectHandler().createEffectHandler(
interact = this@HelloStrangerActivity
)
}
override fun showError() {
Toast.makeText(this, "Hello Stranger", Toast.LENGTH_SHORT).show()
}
}
interface Interactor2 {
fun showError()
}
| 0 | Kotlin | 0 | 0 | 6e669c813cd4090a4f78cc9b59db56ad32515a53 | 2,560 | MYBENCHPRESS | Apache License 2.0 |
protoc-gen-kroto-plus/src/main/kotlin/com/github/marcoferrer/krotoplus/generators/builders/UnaryStubExtsBuilder.kt | marcoferrer | 124,468,545 | false | null | /*
* Copyright 2019 Kroto+ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.marcoferrer.krotoplus.generators.builders
import com.github.marcoferrer.krotoplus.config.GrpcStubExtsGenOptions
import com.github.marcoferrer.krotoplus.generators.GeneratorContext
import com.github.marcoferrer.krotoplus.proto.ProtoMethod
import com.github.marcoferrer.krotoplus.utils.CommonClassNames
import com.github.marcoferrer.krotoplus.utils.builderLambdaTypeName
import com.github.marcoferrer.krotoplus.utils.requestParamSpec
import com.github.marcoferrer.krotoplus.utils.requestValueBuilderCodeBlock
import com.github.marcoferrer.krotoplus.utils.requestValueMethodSigCodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.UNIT
class UnaryStubExtsBuilder(val context: GeneratorContext){
fun buildStubExts(method: ProtoMethod, options: GrpcStubExtsGenOptions): List<FunSpec> {
val funSpecs = mutableListOf<FunSpec>()
// Add method signature exts
if(method.methodSignatureVariants.isNotEmpty()){
funSpecs += buildAsyncMethodSigExt(method)
funSpecs += buildFutureMethodSigExt(method)
funSpecs += buildBlockingMethodSigExt(method)
}
// Add lambda builder exts
funSpecs += buildAsyncLambdaBuilderExt(method)
funSpecs += buildFutureLambdaBuilderExt(method)
funSpecs += buildBlockingLambdaBuilderExt(method)
// Add default arg exts
funSpecs += buildAsyncDefaultArgExt(method)
funSpecs += buildFutureDefaultArgExt(method)
funSpecs += buildBlockingDefaultArgExt(method)
if(options.supportCoroutines)
addCoroutineStubExts(funSpecs, method)
return funSpecs
}
private fun addCoroutineStubExts(funSpecs: MutableList<FunSpec>, method: ProtoMethod){
if(method.methodSignatureVariants.isNotEmpty()) {
funSpecs += buildCoroutineMethodSigExt(method)
}
funSpecs += buildCoroutineExt(method)
funSpecs += buildCoroutineLambdaBuilderExt(method)
}
// Coroutine Extension
private fun buildCoroutineExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.addModifiers(KModifier.SUSPEND)
.receiver(protoService.asyncStubClassName)
.addParameter(requestClassName.requestParamSpec)
.returns(responseClassName)
.addStatement(
"return %T(request, %T.%N())",
CommonClassNames.ClientCalls.clientCallUnary,
protoService.enclosingServiceClassName,
methodDefinitionGetterName
)
.build()
}
// Method Signature Extensions
private fun buildAsyncMethodSigExt(protoMethod: ProtoMethod): List<FunSpec> = with(protoMethod){
methodSignatureVariants.map { variant ->
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.receiver(protoService.asyncStubClassName)
.addMethodSignatureParameter(variant, context.schema)
.addResponseObserverParameter(responseClassName)
.returns(UNIT)
.addCode(requestClassName.requestValueMethodSigCodeBlock(variant))
.addStatement("%N(request, responseObserver)",functionName)
.build()
}
}
private fun buildCoroutineMethodSigExt(protoMethod: ProtoMethod): List<FunSpec> = with(protoMethod){
methodSignatureVariants.map { variant ->
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.addModifiers(KModifier.SUSPEND)
.receiver(protoService.asyncStubClassName)
.returns(responseClassName)
.addMethodSignatureParameter(variant, context.schema)
.addCode(requestClassName.requestValueMethodSigCodeBlock(variant))
.addStatement("return %N(request)",functionName)
.build()
}
}
private fun buildFutureMethodSigExt(protoMethod: ProtoMethod): List<FunSpec> = with(protoMethod){
methodSignatureVariants.map { variant ->
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.receiver(protoService.futureStubClassName)
.addMethodSignatureParameter(variant, context.schema)
.returns(CommonClassNames.listenableFuture.parameterizedBy(responseClassName))
.addCode(requestClassName.requestValueMethodSigCodeBlock(variant))
.addStatement("return %N(request)",functionName)
.build()
}
}
private fun buildBlockingMethodSigExt(protoMethod: ProtoMethod): List<FunSpec> = with(protoMethod){
methodSignatureVariants.map { variant ->
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.receiver(protoService.blockingStubClassName)
.returns(responseClassName)
.addMethodSignatureParameter(variant, context.schema)
.addCode(requestClassName.requestValueMethodSigCodeBlock(variant))
.addStatement("return %N(request)", functionName)
.build()
}
}
// Lambda Builder Extensions
private fun buildAsyncLambdaBuilderExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.receiver(protoService.asyncStubClassName)
.addModifiers(KModifier.INLINE)
.addResponseObserverParameter(responseClassName)
.addParameter("block", requestClassName.builderLambdaTypeName)
.returns(UNIT)
.addCode(requestClassName.requestValueBuilderCodeBlock)
.addStatement("%N(request, responseObserver)", functionName)
.build()
}
private fun buildCoroutineLambdaBuilderExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.receiver(protoService.asyncStubClassName)
.addModifiers(KModifier.INLINE, KModifier.SUSPEND)
.addParameter("block", requestClassName.builderLambdaTypeName)
.returns(responseClassName)
.addCode(requestClassName.requestValueBuilderCodeBlock)
.addStatement("return %N(request)", functionName)
.build()
}
private fun buildFutureLambdaBuilderExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.addModifiers(KModifier.INLINE)
.receiver(protoService.futureStubClassName)
.addParameter("block", requestClassName.builderLambdaTypeName)
.returns(CommonClassNames.listenableFuture.parameterizedBy(responseClassName))
.addCode(requestClassName.requestValueBuilderCodeBlock)
.addStatement("return %N(request)", functionName)
.build()
}
private fun buildBlockingLambdaBuilderExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.addModifiers(KModifier.INLINE)
.addCode(requestClassName.requestValueBuilderCodeBlock)
.addParameter("block", requestClassName.builderLambdaTypeName)
.addStatement("return %N(request)", functionName)
.receiver(protoService.blockingStubClassName)
.returns(responseClassName)
.build()
}
// Default Argument Extensions
private fun buildAsyncDefaultArgExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.receiver(protoService.asyncStubClassName)
.addResponseObserverParameter(responseClassName)
.addStatement("%N(%T.getDefaultInstance(),responseObserver)", functionName, requestClassName)
.returns(UNIT)
.build()
}
private fun buildFutureDefaultArgExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.addStatement("return %N(%T.getDefaultInstance())", functionName, requestClassName)
.receiver(protoService.futureStubClassName)
.returns(CommonClassNames.listenableFuture.parameterizedBy(responseClassName))
.build()
}
private fun buildBlockingDefaultArgExt(protoMethod: ProtoMethod): FunSpec = with(protoMethod){
FunSpec.builder(functionName)
.addKdoc(attachedComments)
.addStatement("return %N(%T.getDefaultInstance())", functionName, requestClassName)
.receiver(protoService.blockingStubClassName)
.returns(responseClassName)
.build()
}
}
| 32 | Kotlin | 27 | 486 | 2b0b447d47f14da93b536ef238b379eb4cc6075c | 9,705 | kroto-plus | Apache License 2.0 |
reposilite-backend/src/main/kotlin/com/reposilite/console/infrastructure/ConsoleWebSocketHandler.kt | dzikoysk | 96,474,388 | false | null | /*
* Copyright (c) 2022 dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reposilite.console.infrastructure
import com.reposilite.ReposiliteJournalist
import com.reposilite.auth.AuthenticationFacade
import com.reposilite.auth.api.AuthenticationRequest
import com.reposilite.console.ConsoleFacade
import com.reposilite.token.AccessTokenFacade
import com.reposilite.token.AccessTokenPermission.MANAGER
import com.reposilite.web.http.ErrorResponse
import com.reposilite.web.http.extractFromString
import com.reposilite.web.http.unauthorized
import com.reposilite.web.http.unauthorizedError
import io.javalin.openapi.HttpMethod
import io.javalin.openapi.OpenApi
import io.javalin.websocket.WsConfig
import io.javalin.websocket.WsContext
import io.javalin.websocket.WsMessageContext
import panda.std.Result
import panda.std.reactive.Reference
import panda.utilities.StringUtils
import java.util.function.Consumer
private const val AUTHORIZATION_PREFIX = "Authorization:"
internal class CliEndpoint(
private val journalist: ReposiliteJournalist,
private val accessTokenFacade: AccessTokenFacade,
private val authenticationFacade: AuthenticationFacade,
private val consoleFacade: ConsoleFacade,
private val forwardedIp: Reference<String>
) : Consumer<WsConfig> {
@OpenApi(
path = "/api/console/sock",
methods = [HttpMethod.PATCH],
tags = ["Console"]
)
override fun accept(ws: WsConfig) {
ws.onConnect { connection ->
ws.onMessage { messageContext ->
authenticateContext(messageContext)
.peek {
journalist.logger.info("CLI | $it accessed remote console")
initializeAuthenticatedContext(ws, connection, it)
}
.onError {
connection.send(it)
connection.session.disconnect()
}
}
}
}
private fun authenticateContext(connection: WsMessageContext): Result<String, ErrorResponse> {
val authMessage = connection.message()
if (!authMessage.startsWith(AUTHORIZATION_PREFIX)) {
journalist.logger.info("CLI | Unauthorized CLI access request from ${address(connection)} (missing credentials)")
return unauthorizedError("Unauthorized connection request")
}
return authenticationMessageToCredentials(authMessage)
.map { (name, secret) -> AuthenticationRequest(name, secret) }
.flatMap { authenticationFacade.authenticateByCredentials(it) }
.filter({ accessTokenFacade.hasPermission(it.identifier, MANAGER) }, {
journalist.logger.info("CLI | Unauthorized CLI access request from ${address(connection)}")
unauthorized("Unauthorized connection request")
})
.map { "${it.name}@${address(connection)}" }
}
private fun authenticationMessageToCredentials(message: String): Result<AuthenticationRequest, ErrorResponse> =
extractFromString(StringUtils.replaceFirst(message, AUTHORIZATION_PREFIX, ""))
.map { (name, secret) -> AuthenticationRequest(name, secret) }
private fun initializeAuthenticatedContext(ws: WsConfig, connection: WsContext, session: String) {
ws.onMessage {
when(val message = it.message()) {
"keep-alive" -> connection.send("keep-alive")
else -> {
journalist.logger.info("CLI | $session> $message")
consoleFacade.executeCommand(message)
}
}
}
val subscriberId = journalist.subscribe {
connection.send(it.value)
}
ws.onClose {
journalist.logger.info("CLI | $session closed connection")
journalist.unsubscribe(subscriberId)
}
for (message in journalist.cachedLogger.messages) {
connection.send(message.value)
}
}
private fun address(context: WsContext): String =
context.header(forwardedIp.get()) ?: context.session.remoteAddress.toString()
} | 27 | null | 85 | 631 | a4ad03ca8e060282308c1e9b63c454171cded47e | 4,692 | reposilite | Apache License 2.0 |
app/src/main/java/com/gmail/fattazzo/meteo/activity/stazioni/meteo/StazioniMeteoViewModel.kt | fattazzo | 182,333,126 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 278, "Kotlin": 219, "Java": 1, "JSON": 4} | /*
* Project: meteo
* File: StazioniMeteoViewModel.kt
*
* Created by fattazzo
* Copyright © 2019 <NAME>. All rights reserved.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.gmail.fattazzo.meteo.activity.stazioni.meteo
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.gmail.fattazzo.meteo.activity.stazioni.meteo.rilevazioni.TipoDatoStazione
import com.gmail.fattazzo.meteo.app.services.StazioniService
import com.gmail.fattazzo.meteo.data.db.entities.StazioneMeteo
import com.gmail.fattazzo.meteo.data.stazioni.meteo.domain.datistazione.DatiStazione
import com.gmail.fattazzo.meteo.utils.ioJob
import com.gmail.fattazzo.meteo.utils.uiJob
import javax.inject.Inject
/**
* @author fattazzo
* <p/>
* date: 01/10/19
*/
class StazioniMeteoViewModel @Inject constructor(private val stazioniService: StazioniService) :
ViewModel() {
private val stazioniDisabilitate = MutableLiveData<Boolean>(false)
val tipoDato = MutableLiveData<TipoDatoStazione>(
TipoDatoStazione.TEMPERATURA
)
val graficoFormat = MutableLiveData<Boolean>(false)
val stazioniMeteo = MutableLiveData<List<StazioneMeteo>>()
val codiceStazioneSelezionata = MutableLiveData<String>("")
val datiStazione = MediatorLiveData<DatiStazione>().apply {
addSource(codiceStazioneSelezionata) { caricaDatiStazione() }
addSource(tipoDato) { caricaDatiStazione() }
}
fun caricaAnagrafica(forceDownload: Boolean) {
ioJob {
val result = stazioniService.caricaAnagraficaStazioniMeteo(
stazioniDisabilitate.value ?: false,
forceDownload
)
uiJob {
stazioniMeteo.postValue(result.value)
}
}
}
private fun caricaDatiStazione() {
if (codiceStazioneSelezionata.value.orEmpty().isNotBlank()) {
ioJob {
val result = stazioniService.caricaDatiStazione(codiceStazioneSelezionata.value!!)
uiJob {
datiStazione.postValue(result.value)
}
}
}
}
} | 1 | null | 1 | 1 | 8345a9a1b0d0dcb87922262c1691cd6ec8d058fc | 3,257 | meteo | MIT License |
advent-of-code2016/src/main/kotlin/day20/Advent20.kt | REDNBLACK | 128,669,137 | false | {"Text": 41, "Ignore List": 1, "Markdown": 6, "Kotlin": 167, "Scala": 64, "INI": 2, "XML": 49, "HTML": 43, "Java": 3} | package day20
import parseInput
import splitToLines
import java.util.stream.LongStream
/**
--- Day 20: Firewall Rules ---
You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the corporate firewall only allows communication with certain external IP addresses.
You've retrieved the list of blocked IPs from the firewall, but the list seems to be messy and poorly maintained, and it's not clear which IPs are allowed. Also, rather than being written in dot-decimal notation, they are written as plain 32-bit integers, which can have any value from 0 through 4294967295, inclusive.
For example, suppose only the values 0 through 9 were valid, and that you retrieved the following blacklist:
5-8
0-2
4-7
The blacklist specifies ranges of IPs (inclusive of both the start and end value) that are not allowed. Then, the only IPs that this firewall allows are 3 and 9, since those are the only numbers not in any range.
Given the list of blocked IPs you retrieved from the firewall (your puzzle input), what is the lowest-valued IP that is not blocked?
--- Part Two ---
How many IPs are allowed by the blacklist?
*/
fun main(args: Array<String>) {
val test = """5-8
|0-2
|4-7""".trimMargin()
val input = parseInput("day20-input.txt")
println(findLowestIP(test) == 3L)
println(countWhitelisted(test))
println(findLowestIP(input))
println(countWhitelisted(input))
}
fun findLowestIP(input: String): Long? {
val ranges = parseRanges(input)
return (0..4294967295).first { number -> ranges.none { range -> range.contains(number) } }
}
fun countWhitelisted(input: String): Long {
val ranges = parseRanges(input)
// For speedup
return LongStream.rangeClosed(0, 4294967295L)
.parallel()
.filter { number -> ranges.none { range -> range.contains(number) } }
.count()
}
private fun parseRanges(input: String) = input.splitToLines()
.map { it ->
val (min, max) = it.split("-")
min.toLong()..max.toLong()
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 2,121 | courses | MIT License |
modules/meta/arrow-meta/src/test/resources/arrow/ap/objects/iso/Iso.kt | Krishan14sharma | 183,217,828 | true | {"Kotlin": 2391225, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Java": 4465, "Shell": 3043, "Ruby": 1598} | package `arrow`.`ap`.`objects`.`iso`
inline val `arrow`.`ap`.`objects`.`iso`.`Iso`.Companion.iso: arrow.optics.Iso<`arrow`.`ap`.`objects`.`iso`.`Iso`, arrow.core.Tuple3<`kotlin`.`String`, `kotlin`.`String`?, `arrow`.`core`.`Option`<`kotlin`.`String`>>> get()= arrow.optics.Iso(
get = { iso: `arrow`.`ap`.`objects`.`iso`.`Iso` -> arrow.core.Tuple3(iso.`field`, iso.`nullable`, iso.`option`) },
reverseGet = { tuple: arrow.core.Tuple3<`kotlin`.`String`, `kotlin`.`String`?, `arrow`.`core`.`Option`<`kotlin`.`String`>> -> `arrow`.`ap`.`objects`.`iso`.`Iso`(tuple.a, tuple.b, tuple.c) }
)
| 0 | Kotlin | 0 | 1 | 2b26976e1a8fbf29b7a3786074d56612440692a8 | 602 | arrow | Apache License 2.0 |
android/app/src/main/java/com/emergetools/hackernews/features/bookmarks/BookmarksScreen.kt | EmergeTools | 682,684,464 | false | {"Kotlin": 174590, "Swift": 30430, "Ruby": 5422} | package com.emergetools.hackernews.features.bookmarks
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import com.emergetools.hackernews.features.bookmarks.components.BookmarksEducationCard
import com.emergetools.hackernews.features.comments.CommentsDestinations
import com.emergetools.hackernews.features.stories.StoriesDestinations
import com.emergetools.hackernews.features.stories.StoryItem
import com.emergetools.hackernews.ui.components.ColumnSeparator
import com.emergetools.hackernews.ui.components.StoryRow
import com.emergetools.hackernews.ui.preview.AppStoreSnapshot
import com.emergetools.hackernews.ui.preview.SnapshotPreview
import com.emergetools.hackernews.ui.theme.HackerNewsTheme
import com.emergetools.snapshots.annotations.EmergeAppStoreSnapshot
import java.time.Instant
@Composable
fun BookmarksScreen(
state: BookmarksState,
actions: (BookmarksAction) -> Unit,
navigator: (BookmarksNavigation) -> Unit,
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(color = MaterialTheme.colorScheme.background),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "Bookmarks",
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
color = MaterialTheme.colorScheme.onBackground,
style = MaterialTheme.typography.titleMedium
)
if (state.bookmarks.isEmpty()) {
Box(modifier = Modifier
.fillMaxWidth()
.weight(1f), contentAlignment = Alignment.Center) {
BookmarksEducationCard()
}
} else {
LazyColumn {
itemsIndexed(items = state.bookmarks, key = { _, item -> item.id }) { index, item ->
StoryRow(
item = item,
onClick = {
if (it.url != null) {
navigator(BookmarksNavigation.GoToStory(StoriesDestinations.Closeup(it.url)))
} else {
navigator(BookmarksNavigation.GoToComments(CommentsDestinations.Comments(it.id)))
}
},
onBookmark = { actions(BookmarksAction.RemoveBookmark(it)) },
onCommentClicked = {
navigator(BookmarksNavigation.GoToComments(CommentsDestinations.Comments(it.id)))
}
)
if (index != state.bookmarks.lastIndex) {
ColumnSeparator(
lineColor = MaterialTheme.colorScheme.surfaceContainerHighest,
)
}
}
}
}
}
}
@SnapshotPreview
@Composable
fun BookmarksScreenPreview() {
HackerNewsTheme {
BookmarksScreen(
state = BookmarksState(
bookmarks = listOf(
StoryItem.Content(
id = 1L,
title = "Show HN: A new Android client",
author = "heyrikin",
score = 10,
commentCount = 45,
epochTimestamp = Instant.now().minusSeconds(60 * 60 * 3).epochSecond,
bookmarked = true,
url = ""
),
StoryItem.Content(
id = 2L,
title = "Can we stop the decline of monarch butterflies and other pollinators?",
author = "rbro112",
score = 40,
commentCount = 23,
epochTimestamp = Instant.now().minusSeconds(60 * 60 * 2).epochSecond,
bookmarked = true,
url = ""
),
StoryItem.Content(
id = 3L,
title = "Andy Warhol's lost Amiga art found",
author = "telkins",
score = 332,
commentCount = 103,
epochTimestamp = Instant.now().minusSeconds(60 * 60 * 7).epochSecond,
bookmarked = true,
url = ""
),
)
),
actions = {},
navigator = {}
)
}
}
@SnapshotPreview
@Composable
fun BookmarksScreenEmptyPreview() {
HackerNewsTheme {
BookmarksScreen(
state = BookmarksState(
bookmarks = emptyList()
),
actions = {},
navigator = {}
)
}
}
@OptIn(EmergeAppStoreSnapshot::class)
@AppStoreSnapshot
@Composable
fun BookmarksScreenAppStorePreview() {
val stories = listOf(
StoryItem.Content(
id = 1L,
title = "Why is the Oral-B iOS app almost 300 MB? And why is Colgate's app even bigger..?",
author = "heyrikin",
score = 252,
commentCount = 229,
epochTimestamp = Instant.now().minusSeconds(60 * 60 * 5).epochSecond,
bookmarked = true,
url = ""
),
StoryItem.Content(
id = 2L,
title = "Can we stop the decline of monarch butterflies and other pollinators?",
author = "rbro112",
score = 40,
commentCount = 23,
epochTimestamp = Instant.now().minusSeconds(60 * 60 * 2).epochSecond,
bookmarked = true,
url = ""
),
StoryItem.Content(
id = 3L,
title = "Andy Warhol's lost Amiga art found",
author = "telkins",
score = 332,
commentCount = 103,
epochTimestamp = Instant.now().minusSeconds(60 * 60 * 7).epochSecond,
bookmarked = true,
url = ""
),
)
HackerNewsTheme {
BookmarksScreen(
state = BookmarksState(
bookmarks = stories,
),
actions = {},
navigator = {}
)
}
}
| 3 | Kotlin | 8 | 72 | 2cc224a3ee355f4b0044bbae74b20b6a3f820dd7 | 5,909 | hackernews | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BuildingPavilion.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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 com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.BuildingPavilion: ImageVector
get() {
if (_buildingPavilion != null) {
return _buildingPavilion!!
}
_buildingPavilion = Builder(name = "BuildingPavilion", defaultWidth = 24.0.dp, defaultHeight
= 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 21.0f)
horizontalLineToRelative(7.0f)
verticalLineToRelative(-3.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 4.0f, 0.0f)
verticalLineToRelative(3.0f)
horizontalLineToRelative(7.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 21.0f)
lineToRelative(0.0f, -9.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 21.0f)
lineToRelative(0.0f, -9.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 12.0f)
horizontalLineToRelative(12.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, 3.0f, -3.0f)
arcToRelative(9.0f, 8.0f, 0.0f, false, true, -9.0f, -6.0f)
arcToRelative(9.0f, 8.0f, 0.0f, false, true, -9.0f, 6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, 3.0f, 3.0f)
}
}
.build()
return _buildingPavilion!!
}
private var _buildingPavilion: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,159 | compose-icon-collections | MIT License |
backend/src/main/kotlin/de/debuglevel/walkingdinner/backend/cli/Main.kt | debuglevel | 133,810,544 | false | null | //package de.debuglevel.walkingdinner.cli
//
//import com.github.ajalt.clikt.core.CliktCommand
//import com.github.ajalt.clikt.parameters.options.option
//import de.debuglevel.walkingdinner.rest.common.TimeMeasurement
//import de.debuglevel.walkingdinner.backend.BuildVersion
//import de.debuglevel.walkingdinner.backend.Team
//import de.debuglevel.walkingdinner.backend.Database
//import de.debuglevel.walkingdinner.backend.Plan
//import de.debuglevel.walkingdinner.planners.geneticplanner.GeneticPlanner
//import de.debuglevel.walkingdinner.planners.geneticplanner.GeneticPlannerOptions
//import de.debuglevel.walkingdinner.backend.SummaryReporter
//import io.jenetics.EnumGene
//import io.jenetics.engine.EvolutionResult
//import io.jenetics.engine.EvolutionStatistics
//import io.jenetics.stat.DoubleMomentStatistics
//import mu.KotlinLogging
//import org.apache.commons.validator.routines.UrlValidator
//import java.net.URL
//import java.nio.file.Paths
//import java.util.function.Consumer
//
//class Cli : CliktCommand() {
// private val logger = KotlinLogging.logger {}
//
// private val csvFilename by option(help = "URL or file name of CSV file")
//
// override fun run() {
// println("=== ${BuildVersion.buildTitle} ${BuildVersion.buildVersion} ===")
//
// val evolutionStatistics = EvolutionStatistics.ofNumber<Double>()
// val consumers: Consumer<EvolutionResult<EnumGene<Team>, Double>>? = Consumer {
// evolutionStatistics.accept(it)
// printIntermediary(it)
// }
//
// val database = buildDatabase()
//
// val options = GeneticPlannerOptions(
// evolutionResultConsumer = consumers,
// teams = database.teams
// )
//
// val result = GeneticPlanner(options).plan()
//
// //processResults(result, evolutionStatistics)
// processResults(result, evolutionStatistics)
// }
//
// private fun processResults(
// result: Plan,
// evolutionStatistics: EvolutionStatistics<Double, DoubleMomentStatistics>?
// ) {
// println()
// println(evolutionStatistics)
//
// println()
// println(result.additionalInformation)
//
// SummaryReporter().generateReports(result.meetings)
// //GmailDraftReporter().generateReports(result.meetings)
// }
//
//// private fun processResults(result: EvolutionResult<EnumGene<Team>, Double>, evolutionStatistics: EvolutionStatistics<Double, DoubleMomentStatistics>?) {
//// println()
//// println("Best in Generation: " + result.generation)
//// println("Best with Fitness: " + result.bestFitness)
////
//// println()
//// println(evolutionStatistics)
////
//// println()
//// val courses = CoursesProblem(result.bestPhenotype.genotype.gene.validAlleles)
//// .codec()
//// .decode(result.bestPhenotype.genotype)
//// val meetings = courses.toMeetings()
////
//// SummaryReporter().generateReports(meetings)
//// GmailDraftReporter().generateReports(meetings)
//// }
//
// private fun buildDatabase(): Database {
// val csvFilename: String = this.csvFilename ?: "Teams_aufbereitet.csv"
// val csvUrl = when {
// UrlValidator().isValid(csvFilename) -> URL(csvFilename)
// else -> Paths.get(csvFilename).toUri().toURL()
// }
// val csv = csvUrl.readText()
//
// val database = Database(csv, "Bamberg, Germany")
//
// return database
// }
//
// private fun printIntermediary(e: EvolutionResult<EnumGene<Team>, Double>) {
// TimeMeasurement.add("evolveDuration", e.durations.evolveDuration.toNanos(), 500)
// if (e.generation % 500 == 0L) {
// logger.trace("${Math.round(1 / (e.durations.evolveDuration.toNanos() / 1_000_000_000.0))}gen/s\t| Generation: ${e.generation}\t| Best Fitness: ${e.bestFitness}")
// }
// }
//}
//
//fun main(args: Array<String>) = Cli().main(args)
| 36 | Kotlin | 0 | 0 | 2ddc1054723e79282320eb5aa950dcfe50f407ef | 4,008 | walkingdinner-geneticplanner | The Unlicense |
app/src/main/java/com/example/android/todoapp/navigation/intro/IntroNavGraph.kt | dvird | 728,990,328 | false | {"Kotlin": 206364, "Java": 231} | package com.example.android.todoapp.navigation.intro
import androidx.compose.material.DrawerState
import androidx.compose.ui.Modifier
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import com.example.android.todoapp.module.intro.login.LoginScreen
import com.example.android.todoapp.navigation.TodoDestinations
import com.example.android.todoapp.navigation.TodoNavigationActions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
fun NavGraphBuilder.introNavGraph(
modifier: Modifier = Modifier,
navController: NavHostController,
coroutineScope: CoroutineScope,
drawerState: DrawerState,
route: String,
navActions: TodoNavigationActions,
) {
composable(TodoDestinations.LOGIN_ROUTE) {
LoginScreen(onAuthSuccess = { coroutineScope.launch { drawerState.open() } })
}
} | 0 | Kotlin | 0 | 5 | 2b98923152268462337ded16468239e01e4d2467 | 918 | android-template-starter | MIT License |
data/src/test/java/com/mariomanzano/nasaexplorer/repositories/DailyEarthRepositoryTest.kt | MarioManzanoCulebras | 463,844,402 | false | null | package com.mariomanzano.nasaexplorer.repositories
import arrow.core.right
import com.devexperto.architectcoders.testshared.sampleEarth
import com.mariomanzano.domain.Error
import com.mariomanzano.domain.entities.EarthItem
import com.mariomanzano.nasaexplorer.datasource.EarthLocalDataSource
import com.mariomanzano.nasaexplorer.datasource.EarthRemoteDataSource
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.argThat
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@RunWith(MockitoJUnitRunner::class)
class DailyEarthRepositoryTest {
@Mock
lateinit var earthLocalDataSource: EarthLocalDataSource
@Mock
lateinit var earthRemoteDataSource: EarthRemoteDataSource
private lateinit var earthRepository: DailyEarthRepository
private val localEarthList = flowOf(listOf(sampleEarth.copy(1)))
@Before
fun setUp() {
whenever(earthLocalDataSource.earthList).thenReturn(localEarthList)
earthRepository = DailyEarthRepository(earthLocalDataSource, earthRemoteDataSource)
}
@Test
fun `Earth items are taken from local data source if available`(): Unit = runBlocking {
val result = earthRepository.earthList
assertEquals(localEarthList, result)
}
@Test
fun `Pod items are saved to local data source when list come from the server`(): Unit =
runBlocking {
val remoteItems = listOf(sampleEarth.copy(2))
whenever(earthRemoteDataSource.findEarthItems()).thenReturn(remoteItems.right())
earthRepository.requestEarthList()
verify(earthLocalDataSource).saveEarthList(remoteItems)
}
@Test
fun `Error NoData is sended when empty list come from the server`(): Unit = runBlocking {
val remoteItems = listOf(sampleEarth.copy(2))
whenever(earthRemoteDataSource.findEarthItems()).thenReturn(emptyList<EarthItem>().right())
val result = earthRepository.requestEarthList()
verify(earthLocalDataSource, never()).saveEarthList(remoteItems)
assertEquals(Error.NoData, result)
}
@Test
fun `Finding a Earth of the Day by id is done in local data source`(): Unit = runBlocking {
val earth = flowOf(sampleEarth.copy(id = 5))
whenever(earthLocalDataSource.findEarthById(5)).thenReturn(earth)
val result = earthRepository.findById(5)
assertEquals(earth, result)
}
@Test
fun `Switching favorite updates local data source`(): Unit = runBlocking {
val element = sampleEarth.copy(id = 3)
earthRepository.switchFavorite(element)
verify(earthLocalDataSource).saveEarthFavoriteList(argThat { get(0).id == 3 })
}
@Test
fun `Switching favorite marks as favorite an unfavorite item`(): Unit = runBlocking {
val element = sampleEarth.copy(favorite = false)
earthRepository.switchFavorite(element)
verify(earthLocalDataSource).saveEarthFavoriteList(argThat { get(0).favorite })
}
@Test
fun `Switching favorite marks as unfavorite a favorite item`(): Unit = runBlocking {
val element = sampleEarth.copy(favorite = true)
earthRepository.switchFavorite(element)
verify(earthLocalDataSource).saveEarthFavoriteList(argThat { !get(0).favorite })
}
} | 50 | Kotlin | 0 | 3 | 9c9d2475aabc7f106446cc7f65b390d5b4903530 | 3,565 | Nasa-Explorer | Apache License 2.0 |
python/testSrc/com/jetbrains/python/console/PydevConsoleRunnerUtilTest.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.console
import com.intellij.execution.Platform
import com.intellij.execution.target.*
import com.intellij.execution.target.value.TargetValue
import com.intellij.execution.target.value.constant
import com.intellij.openapi.progress.ProgressIndicator
import org.assertj.core.api.SoftAssertions
import org.junit.Test
class PydevConsoleRunnerUtilTest {
@Test
fun `test constructPyPathAndWorkingDirCommand`() {
val dummyRequest = DummyTargetEnvironmentRequest()
val dummyEnvironment = DummyTargetEnvironment(dummyRequest)
val pythonPath = mutableListOf(constant("/home/foo/bar's baz"))
val workingDir = constant("/home/foo/bar\\qux")
val consoleStartCommand = PydevConsoleRunnerImpl.CONSOLE_START_COMMAND
SoftAssertions.assertSoftly { softly ->
softly
.assertThat(constructPyPathAndWorkingDirCommand(pythonPath, workingDir, consoleStartCommand).apply(dummyEnvironment))
.isEqualTo(
"""|import sys; print('Python %s on %s' % (sys.version, sys.platform))
|sys.path.extend(['/home/foo/bar\'s baz', '/home/foo/bar\\qux'])
|""".trimMargin()
)
.describedAs("Constructs the command that adds the python paths and working directory to `sys.path`")
}
}
private class DummyTargetEnvironmentRequest : TargetEnvironmentRequest {
override val targetPlatform: TargetPlatform = TargetPlatform(Platform.UNIX)
override val configuration: TargetEnvironmentConfiguration? = null
override var projectPathOnTarget: String = ""
@Deprecated("Use uploadVolumes")
override val defaultVolume: TargetEnvironmentRequest.Volume
get() = throw UnsupportedOperationException()
@Deprecated("Use uploadVolumes")
override fun createUploadRoot(remoteRootPath: String?, temporary: Boolean): TargetEnvironmentRequest.Volume =
throw UnsupportedOperationException()
@Deprecated("Use downloadVolumes")
override fun createDownloadRoot(remoteRootPath: String?): TargetEnvironmentRequest.DownloadableVolume =
throw UnsupportedOperationException()
@Deprecated("Use targetPortBindings")
override fun bindTargetPort(targetPort: Int): TargetValue<Int> = throw UnsupportedOperationException()
@Deprecated("Use localPortBindings")
override fun bindLocalPort(localPort: Int): TargetValue<HostPort> = throw UnsupportedOperationException()
override fun prepareEnvironment(progressIndicator: TargetProgressIndicator): TargetEnvironment = DummyTargetEnvironment(this)
override fun onEnvironmentPrepared(callback: (environment: TargetEnvironment, progressIndicator: TargetProgressIndicator) -> Unit) =
throw UnsupportedOperationException()
}
private class DummyTargetEnvironment(request: DummyTargetEnvironmentRequest) : TargetEnvironment(request) {
override fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process =
throw UnsupportedOperationException()
override val targetPlatform: TargetPlatform = request.targetPlatform
override fun shutdown() = Unit
}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 3,217 | intellij-community | Apache License 2.0 |
app/src/main/java/me/rosuh/easywatermark/ui/dialog/ChangeLogDialogFragment.kt | edgargithub | 293,069,553 | true | {"Kotlin": 160264} | package me.rosuh.easywatermark.ui.dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.edit
import androidx.fragment.app.FragmentManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import me.rosuh.easywatermark.BuildConfig
import me.rosuh.easywatermark.MyApp
import me.rosuh.easywatermark.R
import me.rosuh.easywatermark.ktx.toMD5
import me.rosuh.easywatermark.model.WaterMarkConfig
import me.rosuh.easywatermark.model.WaterMarkConfig.Companion.SP_KEY_CHANGE_LOG
/**
* @author [email protected]
* @date 2020/9/3
* A dialog showing change log, which using [BuildConfig.VERSION_CODE]
* and [R.string.dialog_change_log_content] to generate md5 To decide whether to display
*/
class ChangeLogDialogFragment : BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.dialog_change_log, container, false)
with(root) {
findViewById<TextView>(R.id.tv_content).apply {
setText(R.string.dialog_change_log_content)
}
}
return root
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
MyApp.instance.getSharedPreferences(WaterMarkConfig.SP_NAME, Context.MODE_PRIVATE).edit {
val curMD5 =
"${BuildConfig.VERSION_CODE}${[email protected](R.string.dialog_change_log_content)}".toMD5()
putString(SP_KEY_CHANGE_LOG, curMD5)
}
}
companion object {
private const val TAG = "ChangeLogDialogFragment"
private fun newInstance(): ChangeLogDialogFragment {
return ChangeLogDialogFragment()
}
private fun checkHasUpgraded(): Boolean {
with(
MyApp.instance.getSharedPreferences(
WaterMarkConfig.SP_NAME,
Context.MODE_PRIVATE
)
) {
val savedMD5 = this.getString(SP_KEY_CHANGE_LOG, "")
val curMD5 =
"${BuildConfig.VERSION_CODE}${MyApp.instance.getString(R.string.dialog_change_log_content)}".toMD5()
return savedMD5 != curMD5
}
}
fun safetyHide(manager: FragmentManager) {
kotlin.runCatching {
(manager.findFragmentByTag(TAG) as? ChangeLogDialogFragment)?.dismissAllowingStateLoss()
}
}
fun safetyShow(manager: FragmentManager) {
kotlin.runCatching {
if (!checkHasUpgraded()) {
return
}
val f = manager.findFragmentByTag(TAG) as? ChangeLogDialogFragment
when {
f == null -> {
newInstance().show(manager, TAG)
}
!f.isAdded -> {
f.show(manager, TAG)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | ab153a937824d9a3ff0fa7f5d54b2755a09b7b06 | 3,278 | EasyWatermark | MIT License |
yabapi-core/src/commonMain/kotlin/moe/sdl/yabapi/data/live/commands/SendGiftCmd.kt | SDLMoe | 437,756,989 | false | null | @file:UseSerializers(BooleanJsSerializer::class)
package moe.sdl.yabapi.data.live.commands
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.decodeFromJsonElement
import moe.sdl.yabapi.data.RgbColor
import moe.sdl.yabapi.data.live.GuardLevel
import moe.sdl.yabapi.data.live.GuardLevel.UNKNOWN
import moe.sdl.yabapi.serializer.BooleanJsSerializer
import moe.sdl.yabapi.serializer.data.RgbColorIntSerializerNullable
@Serializable
public data class SendGiftCmd(
@SerialName("cmd") override val operation: String,
@SerialName("data") val data: SendGiftData? = null,
) : LiveCommand {
public companion object : LiveCommandFactory() {
override val operation: String = "SEND_GIFT"
override fun decode(json: Json, data: JsonElement): SendGiftCmd = json.decodeFromJsonElement(data)
}
}
@Serializable
public data class SendGiftData(
@SerialName("action") val action: String? = null,
@SerialName("batch_combo_id") val batchComboId: String? = null,
@SerialName("batch_combo_send") val batchComboSend: BatchComboGift?,
@SerialName("beatId") val beatId: String? = null,
@SerialName("biz_source") val bizSource: String? = null, // "Live" or "live"
@SerialName("blind_gift") val blindGift: BlindGift? = null,
@SerialName("broadcast_id") val broadcastId: Long? = null,
@SerialName("coin_type") val coinType: String? = null,
@SerialName("combo_resources_id") val comboResourcesId: Long? = null,
@SerialName("combo_send") val comboSend: ComboSend? = null,
@SerialName("combo_stay_time") val comboStayTime: Int? = null,
@SerialName("combo_total_coin") val comboTotalCoin: Int? = null,
@SerialName("crit_prob") val criticalRate: Double? = null, // 爆击率
@SerialName("demarcation") val demarcation: Int? = null, // 划界?
@SerialName("discount_price") val discountPrice: Int? = null,
@SerialName("dmscore") val danmakuScore: Int? = null,
@SerialName("draw") val draw: Int? = null,
@SerialName("effect") val effect: Int? = null,
@SerialName("effect_block") val effectBlock: Int? = null,
@SerialName("face") val avatar: String? = null,
@SerialName("float_sc_resource_id") val floatScResourceId: Long? = null,
@SerialName("giftId") val giftId: Long? = null,
@SerialName("giftName") val giftName: String? = null,
@SerialName("giftType") val giftType: Int? = null,
@SerialName("gold") val gold: Int? = null,
@SerialName("guard_level") val guardLevel: GuardLevel = UNKNOWN,
@SerialName("is_first") val isFirst: Boolean? = null,
@SerialName("is_special_batch") val isSpecialBatch: Boolean? = null,
@SerialName("magnification") val magnification: Double? = null,
@SerialName("medal_info") val medalInfo: LiveMedal? = null,
@SerialName("name_color") val nameColor: String? = null,
@SerialName("num") val num: Int? = null,
@SerialName("original_gift_name") val originalGiftName: String? = null,
@SerialName("price") val price: Int? = null,
@SerialName("rcost") val targetCost: Int? = null, // 可能是对目标主播的花费总数?
@SerialName("remain") val remain: Int? = null,
@SerialName("rnd") val rnd: String? = null,
@SerialName("send_master") val sendMaster: JsonElement? = null,
@SerialName("silver") val silver: Int? = null,
@SerialName("super") val superValue: Int? = null, // super 是关键字...
@SerialName("super_batch_gift_num") val superBatchGiftNum: Int? = null,
@SerialName("super_gift_num") val superGiftNum: Int? = null,
@SerialName("svga_block") val svgaBlock: Int? = null,
@SerialName("tag_image") val tagImage: String? = null,
@SerialName("tid") val tid: String? = null,
@SerialName("timestamp") val timestamp: Long? = null,
@SerialName("top_list") val topList: JsonElement? = null, // 似乎恒为 null
@SerialName("total_coin") val totalCoin: Int? = null,
@SerialName("uid") val uid: Long? = null,
@SerialName("uname") val uname: String? = null,
) {
@Serializable
public data class ComboSend(
@SerialName("action") val action: String? = null,
@SerialName("combo_id") val comboId: String? = null,
@SerialName("combo_num") val comboNum: Int? = null,
@SerialName("gift_id") val giftId: Long? = null,
@SerialName("gift_name") val giftName: String? = null,
@SerialName("gift_num") val giftNum: Int? = null,
@SerialName("send_master") val sendMaster: JsonElement? = null,
@SerialName("uid") val uid: Long? = null,
@SerialName("uname") val username: String? = null,
)
@Serializable
public data class LiveMedal(
@SerialName("anchor_roomid") val roomId: Long? = null, // 房间id
@SerialName("anchor_uname") val liverName: String? = null, // 主播名称
@SerialName("guard_level") val guardLevel: GuardLevel = UNKNOWN, // 等级
@SerialName("icon_id") val iconId: Long? = null, // icon id
@SerialName("is_lighted") val isLighted: Boolean? = null, // 是否点亮
@Serializable(RgbColorIntSerializerNullable::class)
@SerialName("medal_color") val medalColor: RgbColor? = null,
@Serializable(RgbColorIntSerializerNullable::class)
@SerialName("medal_color_border") val medalColorBorder: RgbColor? = null,
@Serializable(RgbColorIntSerializerNullable::class)
@SerialName("medal_color_end") val medalColorEnd: RgbColor? = null,
@Serializable(RgbColorIntSerializerNullable::class)
@SerialName("medal_color_start") val medalColorStart: RgbColor? = null,
@SerialName("medal_level") val level: Int? = null,
@SerialName("medal_name") val name: String? = null,
@SerialName("special") val special: String? = null,
@SerialName("score") val score: Int? = null,
@SerialName("target_id") val targetId: Long? = null, // 主播 mid
)
}
| 0 | null | 1 | 26 | c8be46f9b5e4db1e429c33b0821643fd94789fa1 | 6,002 | Yabapi | Creative Commons Zero v1.0 Universal |
android/app/src/main/java/com/utn/frba/mobile/regalapp/joinEvent/JoinEventFragment.kt | UTN-FRBA-Mobile | 542,387,698 | false | null | package com.utn.frba.mobile.regalapp.joinEvent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.navigation.navGraphViewModels
import com.squareup.anvil.annotations.ContributesMultibinding
import com.utn.frba.mobile.domain.di.ActivityScope
import com.utn.frba.mobile.domain.di.FragmentKey
import com.utn.frba.mobile.regalapp.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject
@FragmentKey(JoinEventFragment::class)
@ContributesMultibinding(ActivityScope::class, Fragment::class)
class JoinEventFragment @Inject constructor(
private val viewModelFactory: JoinEventViewModel.Factory
) : Fragment() {
private val args: JoinEventFragmentArgs by navArgs()
private val viewModel: JoinEventViewModel by navGraphViewModels(R.id.navigation_main) { viewModelFactory }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.action(JoinEventActions.LoadEventDetails(args.eventId))
observeEvents()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
val state =
viewModel.observeState()
.collectAsState(initial = JoinEventState.Loading).value
when (state) {
is JoinEventState.Loading -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
is JoinEventState.EventLoaded -> {
JoinEventScreen(
args.invitedBy,
state.event.name,
true,
::goBack,
viewModel::action
)
}
is JoinEventState.Error -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = context.getString(R.string.error_fetching_event))
}
}
is JoinEventState.AlreadyJoined -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = context.getString(
R.string.already_joined,
),
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
}
}
private fun observeEvents() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
viewModel.observeEvents()
.flowOn(Dispatchers.Main)
.collect { event ->
when (event) {
is JoinEventEvents.NavigateToEvent -> {
findNavController().navigate(
JoinEventFragmentDirections.openItemsListFromJoinEvent(
event.eventId,
event.title
)
)
}
}
}
}
}
}
private fun goBack() {
findNavController().popBackStack()
}
} | 0 | Kotlin | 0 | 1 | 2addb3960108d9baab9a12eaeb1c4bdcc8e7e4c9 | 5,313 | RegalApp | MIT License |
module-base/src/main/java/win/techflowing/android/base/runtime/AppRuntimeInit.kt | techflowing | 500,921,879 | false | null | package win.techflowing.android.base.runtime
import android.app.Application
object AppRuntimeInit {
@JvmStatic
fun init(application: Application, debug: Boolean) {
AppRuntime.init(application, debug)
}
} | 0 | Kotlin | 0 | 0 | 3de479a53425f1fe97470ceb71547bfd48c8fce0 | 226 | Universe | Apache License 2.0 |
core/src/main/kotlin/org/neo4j/graphql/handler/QueryHandler.kt | neo4j-graphql | 147,095,795 | false | null | package org.neo4j.graphql.handler
import graphql.language.*
import graphql.schema.DataFetcher
import graphql.schema.DataFetchingEnvironment
import graphql.schema.idl.TypeDefinitionRegistry
import org.atteo.evo.inflector.English
import org.neo4j.cypherdsl.core.Cypher.*
import org.neo4j.cypherdsl.core.Statement
import org.neo4j.graphql.*
import org.neo4j.graphql.handler.filter.OptimizedFilterHandler
/**
* This class handles all the logic related to the querying of nodes and relations.
* This includes the augmentation of the query-fields and the related cypher generation
*/
class QueryHandler private constructor(schemaConfig: SchemaConfig) : BaseDataFetcherForContainer(schemaConfig) {
class Factory(
schemaConfig: SchemaConfig,
typeDefinitionRegistry: TypeDefinitionRegistry,
neo4jTypeDefinitionRegistry: TypeDefinitionRegistry
) : AugmentationHandler(schemaConfig, typeDefinitionRegistry, neo4jTypeDefinitionRegistry) {
override fun augmentType(type: ImplementingTypeDefinition<*>) {
if (!canHandle(type)) {
return
}
val typeName = type.name
val relevantFields = getRelevantFields(type)
val filterTypeName = addFilterType(type)
val arguments = if (schemaConfig.useWhereFilter) {
listOf(input(WHERE, TypeName(filterTypeName)))
} else {
getInputValueDefinitions(relevantFields, true, { true }) +
input(FILTER, TypeName(filterTypeName))
}
var fieldName = if (schemaConfig.capitalizeQueryFields) typeName else typeName.decapitalize()
if (schemaConfig.pluralizeFields) {
fieldName = English.plural(fieldName)
}
val builder = FieldDefinition
.newFieldDefinition()
.name(fieldName)
.inputValueDefinitions(arguments.toMutableList())
.type(NonNullType(ListType(NonNullType(TypeName(type.name)))))
if (schemaConfig.queryOptionStyle == SchemaConfig.InputStyle.INPUT_TYPE) {
val optionsTypeName = addOptions(type)
builder.inputValueDefinition(input(OPTIONS, TypeName(optionsTypeName)))
} else {
builder
.inputValueDefinition(input(FIRST, TypeInt))
.inputValueDefinition(input(OFFSET, TypeInt))
val orderingTypeName = addOrdering(type)
if (orderingTypeName != null) {
builder.inputValueDefinition(input(ORDER_BY, ListType(NonNullType(TypeName(orderingTypeName)))))
}
}
val def = builder.build()
addQueryField(def)
}
override fun createDataFetcher(
operationType: OperationType,
fieldDefinition: FieldDefinition
): DataFetcher<Cypher>? {
if (operationType != OperationType.QUERY) {
return null
}
val cypherDirective = fieldDefinition.cypherDirective()
if (cypherDirective != null) {
return null
}
val type = fieldDefinition.type.inner().resolve() as? ImplementingTypeDefinition<*> ?: return null
if (!canHandle(type)) {
return null
}
return QueryHandler(schemaConfig)
}
private fun canHandle(type: ImplementingTypeDefinition<*>): Boolean {
val typeName = type.name
if (!schemaConfig.query.enabled || schemaConfig.query.exclude.contains(typeName) || isRootType(type)) {
return false
}
if (getRelevantFields(type).isEmpty() && !hasRelationships(type)) {
return false
}
return true
}
private fun hasRelationships(type: ImplementingTypeDefinition<*>): Boolean = type.fieldDefinitions
.filterNot { it.isIgnored() }
.any { it.isRelationship() }
private fun getRelevantFields(type: ImplementingTypeDefinition<*>): List<FieldDefinition> {
return type
.getScalarFields()
.filter { it.dynamicPrefix() == null } // TODO currently we do not support filtering on dynamic properties
}
}
override fun generateCypher(variable: String, field: Field, env: DataFetchingEnvironment): Statement {
val fieldDefinition = env.fieldDefinition
val type = env.typeAsContainer()
val (propertyContainer, match) = when {
type.isRelationType() -> anyNode().relationshipTo(anyNode(), type.label()).named(variable)
.let { rel -> rel to match(rel) }
else -> node(type.label()).named(variable)
.let { node -> node to match(node) }
}
val ongoingReading =
if (env.queryContext().optimizedQuery?.contains(QueryContext.OptimizationStrategy.FILTER_AS_MATCH) == true) {
OptimizedFilterHandler(type, schemaConfig).generateFilterQuery(
variable,
fieldDefinition,
env.arguments,
match,
propertyContainer,
env.variables
)
} else {
val where = where(propertyContainer, fieldDefinition, type, env.arguments, env.variables)
match.where(where)
}
val (projectionEntries, subQueries) = projectFields(propertyContainer, type, env)
val mapProjection = propertyContainer.project(projectionEntries).`as`(field.aliasOrName())
return ongoingReading
.withSubQueries(subQueries)
.returning(mapProjection)
.skipLimitOrder(propertyContainer.requiredSymbolicName, fieldDefinition, env.arguments)
.build()
}
}
| 62 | null | 50 | 99 | 43633def77e1fe6a6b42152fc099b04e9747fa8b | 5,939 | neo4j-graphql-java | Apache License 2.0 |
src/main/kotlin/edu/csh/chase/aggregations/expressions/Constant.kt | chaseberry | 119,105,770 | false | null | package edu.csh.chase.aggregations.expressions
/**
* Used for things like
* $project: {
* _id: 1
* }
*/
class Constant(val constant: Any?) : Expression() | 0 | Kotlin | 0 | 0 | 9ffb0520d7e6aed84e48c4022337dfe11a9ead2a | 160 | Aggregations | MIT License |
app/src/main/java/com/example/legostore_kt/api/APIService.kt | proyeckt | 583,807,261 | false | null | package com.example.legostore_kt.api
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.POST
interface APIService {
@GET("all-products")
suspend fun getProducts() : Response<ProductsResponse>
//fun getProducts() : Call<List<Product>>
//@GET("detail/{id}")
//fun getProductById(@Path("id") id: Int ): Call<Product>
@POST("buy")
suspend fun buy() : Response<ProductsResponse>
} | 0 | Kotlin | 0 | 0 | b6880ea524d4ba1b4c1ac8f54c7f0527b56df236 | 431 | lego-store-kt | Apache License 2.0 |
NewsApp/app/src/main/java/com/mustk/newsapp/util/RetrofitErrorHandler.kt | mustafakamber | 804,916,194 | false | {"Kotlin": 164466} | package com.mustk.newsapp.util
import android.content.Context
import com.mustk.newsapp.R
import com.mustk.newsapp.shared.Constant.STATUS_CODE_400
import com.mustk.newsapp.shared.Constant.STATUS_CODE_401
import com.mustk.newsapp.shared.Constant.STATUS_CODE_403
import com.mustk.newsapp.shared.Constant.STATUS_CODE_404
import com.mustk.newsapp.shared.Constant.STATUS_CODE_500
import com.mustk.newsapp.shared.Constant.STATUS_CODE_502
import com.mustk.newsapp.shared.Constant.STATUS_CODE_503
import com.mustk.newsapp.shared.Constant.STATUS_CODE_504
import com.mustk.newsapp.shared.Constant.STATUS_CODE_UNK
import javax.inject.Inject
enum class RetrofitStatusCode(val code: String, val messageResId: Int) {
BAD_REQUEST(STATUS_CODE_400, R.string.bad_request_message),
UNAUTHORIZED(STATUS_CODE_401, R.string.unauthorized_message),
FORBIDDEN(STATUS_CODE_403, R.string.forbidden_message),
NOT_FOUND(STATUS_CODE_404, R.string.not_found_message),
INTERNAL_SERVER_ERROR(STATUS_CODE_500, R.string.internal_server_message),
BAD_GATEWAY(STATUS_CODE_502, R.string.bad_gateway_message),
SERVICE_UNAVAILABLE(STATUS_CODE_503, R.string.service_unavailable_message),
GATEWAY_TIMEOUT(STATUS_CODE_504, R.string.gateway_timeout_message),
UNKNOWN(STATUS_CODE_UNK, R.string.unknown_error_message)
}
class RetrofitErrorHandler @Inject constructor(private val context: Context) {
fun handleRetrofitCode(code: String): String {
val statusCode = RetrofitStatusCode.values().find {
it.code == code
}
?: RetrofitStatusCode.UNKNOWN
return context.applicationContext.getString(statusCode.messageResId)
}
} | 0 | Kotlin | 0 | 0 | ae635d1614706b1f0f35ca0554f57a4f7d0e98b6 | 1,667 | NewsApp | Apache License 2.0 |
pom-application/app/src/main/java/net/dzikoysk/presenceofmind/model/task/reminder/EventReminderReceiver.kt | dzikoysk | 487,407,030 | false | {"Kotlin": 181237} | package net.dzikoysk.presenceofmind.model.task.reminder
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.NotificationManager.IMPORTANCE_HIGH
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_CANCEL_CURRENT
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_MAX
import net.dzikoysk.presenceofmind.PresenceOfMind
import net.dzikoysk.presenceofmind.PresenceOfMindActivity
import net.dzikoysk.presenceofmind.R
import net.dzikoysk.presenceofmind.model.task.Task
import net.dzikoysk.presenceofmind.model.task.attributes.date.EVENT_DATE_FORMATTER
import net.dzikoysk.presenceofmind.model.task.attributes.date.getHumanReadableInterval
import net.dzikoysk.presenceofmind.model.task.attributes.date.toLocalDateTime
import net.dzikoysk.presenceofmind.shared.DefaultTimeProvider
import net.dzikoysk.presenceofmind.shared.TimeProvider
import java.time.Instant
import java.util.UUID
const val CHANNEL_ID = "pom-event-reminder-channel"
const val EVENT_TASK_EXTRA_ID = "pom-event-reminder-id"
const val EVENT_TASK_REMINDER_TIME = "pom-event-reminder-time"
const val CANCEL_ACTION = "pom-event-reminder-notification-cancelled"
val DEFAULT_VIBRATE_PATTERN = longArrayOf(0, 250, 250, 250)
class EventReminderReceiver(private val timeProvider: TimeProvider = DefaultTimeProvider()) : BroadcastReceiver() {
companion object {
fun createNotification(context: Context, task: Task, ring: Boolean, triggerAtMillis: Long) {
val intent = Intent(context, EventReminderReceiver::class.java)
intent.putExtra(EVENT_TASK_EXTRA_ID, task.id.toString())
intent.putExtra(EVENT_TASK_REMINDER_TIME, triggerAtMillis)
val pendingIntent = PendingIntent.getBroadcast(context, task.id.hashCode(), intent, FLAG_CANCEL_CURRENT or FLAG_IMMUTABLE)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
alarmManager?.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent)
}
}
override fun onReceive(context: Context, intent: Intent) {
val presenceOfMind = PresenceOfMind.getInstance(context)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val task = intent.getStringExtra(EVENT_TASK_EXTRA_ID)
?.let { UUID.fromString(it) }
?.let { presenceOfMind.taskService.findTaskById(it) }
?.takeIf { it.eventAttribute != null }
?: return
val eventAttribute = task.eventAttribute
?.takeIf { it.reminder?.scheduledAt == Instant.ofEpochMilli(intent.getLongExtra(EVENT_TASK_REMINDER_TIME, 0)) }
?.takeUnless { it.eventDate.toLocalDateTime().isBefore(timeProvider.nowAtDefaultZone()) }
?: return
val taskNotificationId = task.id.hashCode()
val nextNotificationTime = Instant.now()
.takeUnless { intent.action == CANCEL_ACTION }
?.plusSeconds(60L)
.also {
presenceOfMind.taskService.saveTask(task.copy(
eventAttribute = eventAttribute.copy(
reminder = eventAttribute.reminder!!.copy(
scheduledAt = it
)
)
))
}
?: run {
notificationManager.cancel(taskNotificationId)
return
}
createNotification(
context = context,
task = task,
ring = false,
triggerAtMillis = nextNotificationTime.toEpochMilli()
)
val deleteIntent = Intent(context, EventReminderReceiver::class.java)
deleteIntent.action = CANCEL_ACTION
deleteIntent.putExtra(EVENT_TASK_EXTRA_ID, task.id.toString())
val pendingDeleteIntent = PendingIntent.getBroadcast(context, taskNotificationId, deleteIntent, FLAG_CANCEL_CURRENT or FLAG_IMMUTABLE)
val presenceOfMindActivityIntent = Intent(context, PresenceOfMindActivity::class.java)
presenceOfMindActivityIntent.putExtra(EVENT_TASK_EXTRA_ID, task.id.toString())
val pendingIntent = PendingIntent.getActivity(context, taskNotificationId, presenceOfMindActivityIntent, FLAG_CANCEL_CURRENT or FLAG_IMMUTABLE)
val notificationBuilder = NotificationCompat.Builder(context, notificationManager.findChannel().id)
.setDeleteIntent(pendingDeleteIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(task.description)
.setContentText("${EVENT_DATE_FORMATTER.format(eventAttribute.eventDate.toLocalDateTime())}, in ${eventAttribute.getHumanReadableInterval()}")
.setVibrate(DEFAULT_VIBRATE_PATTERN)
.setColor(Color.RED)
.setLights(Color.RED, 1000, 1000)
.setPriority(PRIORITY_MAX)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
notificationManager.notify(taskNotificationId, notificationBuilder.build())
}
private fun NotificationManager.findChannel() =
getNotificationChannel(CHANNEL_ID) ?: run {
val channel = NotificationChannel(CHANNEL_ID, "Presence of Mind - Reminder", IMPORTANCE_HIGH)
channel.description = "Alerts for tasks with event attributes"
createNotificationChannel(channel)
channel
}
} | 8 | Kotlin | 5 | 27 | 106597d558bc6b4575c3e050428bce768a6f265f | 5,715 | presence-of-mind | Apache License 2.0 |
app/src/main/java/pl/better/foodzilla/data/repositories/recipe/FavouriteAndRecentRecipesRepositoryImpl.kt | kambed | 612,140,416 | false | null | package pl.better.foodzilla.data.repositories.recipe
import pl.better.foodzilla.data.api.recipe.FavouriteAndRecentRecipesFlowClient
import pl.better.foodzilla.data.models.recipe.Recipe
class FavouriteAndRecentRecipesRepositoryImpl(private val favouriteRecipeFlowClient: FavouriteAndRecentRecipesFlowClient) :
FavouriteAndRecentRecipesRepository {
override suspend fun getFavouriteRecipes(): List<Recipe>? {
return favouriteRecipeFlowClient.getFavouriteRecipes()
}
override suspend fun addRecipeToFavourite(recipeId: Long): List<Recipe>? {
return favouriteRecipeFlowClient.addRecipeToFavourite(recipeId)
}
override suspend fun removeRecipeFromFavourite(recipeId: Long): List<Recipe>? {
return favouriteRecipeFlowClient.removeRecipeFromFavourite(recipeId)
}
override suspend fun getRecentlyViewedRecipes(): List<Recipe>? {
return favouriteRecipeFlowClient.getRecentlyRecipes()
}
} | 1 | Kotlin | 0 | 3 | 94a8993b3aefc6271cea6ffd95546cb8c02802f4 | 951 | FoodzillaFrontendAndroid | Apache License 2.0 |
platform/testFramework/src/com/intellij/testFramework/LightPlatform4TestCase.kt | hieuprogrammer | 284,920,751 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
abstract class LightPlatform4TestCase : LightPlatformTestCase()
| 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 330 | intellij-community | Apache License 2.0 |
analytics/src/main/java/io/appmetrica/analytics/impl/component/processor/event/ReportPrevSessionNativeCrashHandler.kt | appmetrica | 650,662,094 | false | null | package io.appmetrica.analytics.impl.component.processor.event
import io.appmetrica.analytics.impl.CounterReport
import io.appmetrica.analytics.impl.component.ComponentUnit
class ReportPrevSessionNativeCrashHandler(component: ComponentUnit) : ReportComponentHandler(component) {
override fun process(reportData: CounterReport): Boolean {
component.eventSaver.saveReportFromPrevSession(reportData)
return true
}
}
| 1 | null | 5 | 54 | 472d3dfb1e09f4e7f35497e5049f53287ccce7d1 | 439 | appmetrica-sdk-android | MIT License |
app/src/main/java/vn/loitp/a/cv/sb/vertical/VerticalSeekbarActivityFont.kt | tplloi | 126,578,283 | false | null | package vn.loitp.a.cv.sb.vertical
import android.os.Bundle
import android.widget.SeekBar
import com.loitp.annotation.IsFullScreen
import com.loitp.annotation.LogTag
import com.loitp.core.base.BaseActivityFont
import com.loitp.core.ext.setSafeOnClickListenerElastic
import kotlinx.android.synthetic.main.a_sb_vert.*
import vn.loitp.R
// https://github.com/h6ah4i/android-verticalseekbar
@LogTag("VerticalSeekbarActivity")
@IsFullScreen(false)
class VerticalSeekbarActivityFont : BaseActivityFont() {
override fun setLayoutResourceId(): Int {
return R.layout.a_sb_vert
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupViews()
}
private fun setupViews() {
lActionBar.apply {
this.ivIconLeft.setSafeOnClickListenerElastic(
runnable = {
onBaseBackPressed()
}
)
this.ivIconRight?.setImageResource(R.color.transparent)
this.tvTitle?.text = VerticalSeekbarActivityFont::class.java.simpleName
}
seekBar1.max = 100
seekBar1.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
logD("onProgressChanged $progress")
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
logD("onStartTrackingTouch")
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
logD("onStopTrackingTouch")
}
})
btSetProgress.setOnClickListener {
seekBar1.progress = 30
}
}
}
| 0 | Kotlin | 0 | 10 | 333bebaf3287b1633f35d29b8adaf25b19c1859f | 1,734 | base | Apache License 2.0 |
app/src/main/java/ru/rznnike/eyehealthmanager/app/di/GatewayModule.kt | RznNike | 207,148,781 | false | null | package ru.rznnike.eyehealthmanager.app.di
import org.koin.dsl.module
import ru.rznnike.eyehealthmanager.data.gateway.AnalysisGatewayImpl
import ru.rznnike.eyehealthmanager.data.gateway.DevGatewayImpl
import ru.rznnike.eyehealthmanager.data.gateway.NotificationGatewayImpl
import ru.rznnike.eyehealthmanager.data.gateway.TestGatewayImpl
import ru.rznnike.eyehealthmanager.data.gateway.UserGatewayImpl
import ru.rznnike.eyehealthmanager.domain.gateway.AnalysisGateway
import ru.rznnike.eyehealthmanager.domain.gateway.DevGateway
import ru.rznnike.eyehealthmanager.domain.gateway.NotificationGateway
import ru.rznnike.eyehealthmanager.domain.gateway.TestGateway
import ru.rznnike.eyehealthmanager.domain.gateway.UserGateway
val gatewayModule = module {
single<UserGateway> { UserGatewayImpl(get()) }
single<NotificationGateway> { NotificationGatewayImpl() }
single<TestGateway> { TestGatewayImpl(get(), get()) }
single<AnalysisGateway> { AnalysisGatewayImpl(get()) }
single<DevGateway> { DevGatewayImpl(get()) }
}
| 0 | null | 1 | 5 | ea21e191ea3d6797be32f7f5e66e8e0ebae30ab6 | 1,034 | EyeHealthManager | MIT License |
simplecloud-base/src/main/kotlin/eu/thesimplecloud/base/manager/update/converter/VersionConversionManager.kt | theSimpleCloud | 270,085,977 | false | null | /*
* MIT License
*
* Copyright (C) 2020-2022 The SimpleCloud authors
*
* 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 eu.thesimplecloud.base.manager.update.converter
import eu.thesimplecloud.api.directorypaths.DirectoryPaths
import eu.thesimplecloud.jsonlib.JsonLib
import eu.thesimplecloud.launcher.startup.Launcher
import java.io.File
/**
* Created by IntelliJ IDEA.
* Date: 18.06.2020
* Time: 12:38
* @author <NAME>
*/
class VersionConversionManager {
private val converters = listOf(
Converter_2_0_To_2_1(),
Converter_2_2_To_2_3(),
Converter_2_3_To_2_4(),
Converter_2_4_To_2_5(),
Converter_2_6_To_2_7(),
Converter_2_7_To_2_8()
)
private val lastStartedVersionFile = File(DirectoryPaths.paths.storagePath + "versions/lastStartedVersion.json")
fun convertIfNecessary() {
getConvertersToExecute().forEach { converter ->
executeConverter(converter)
}
writeLastStartedVersion()
}
private fun executeConverter(converter: IVersionConverter) {
Launcher.instance.logger.info("Running converter to version 2.${converter.getTargetMinorVersion()}...")
try {
converter.convert()
} catch (e: Exception) {
throw ConversionException(converter.getTargetMinorVersion(), e)
}
Launcher.instance.logger.info("Converted")
}
private fun getConvertersToExecute(): ArrayList<IVersionConverter> {
val lastStartedVersion = getLastStartedVersion()
val currentVersion = Launcher.instance.getCurrentVersion()
val lastMinorVersion = getMinorVersionFromVersionString(lastStartedVersion)
val currentMinorVersion = getMinorVersionFromVersionString(currentVersion)
val list = ArrayList<IVersionConverter>()
for (i in lastMinorVersion until currentMinorVersion) {
val version = getConverterByToVersion(i + 1)
version?.let { list.add(version) }
}
return list
}
private fun getConverterByToVersion(version: Int): IVersionConverter? {
return this.converters.firstOrNull { it.getTargetMinorVersion() == version }
}
private fun getMinorVersionFromVersionString(versionString: String): Int {
return versionString.split(".")[1].toInt()
}
private fun getLastStartedVersion(): String {
this.lastStartedVersionFile.parentFile.mkdirs()
val config = JsonLib.fromJsonFile(this.lastStartedVersionFile) ?: return "1.2.0-BETA"
return config.getObject(String::class.java)
}
private fun writeLastStartedVersion() {
JsonLib.fromObject(Launcher.instance.getCurrentVersion()).saveAsFile(lastStartedVersionFile)
}
fun writeLastStartedVersionIfFileDoesNotExist() {
if (!this.lastStartedVersionFile.exists()) {
writeLastStartedVersion()
}
}
} | 8 | null | 49 | 98 | 8f10768e2be523e9b2e7c170965ca4f52a99bf09 | 3,928 | SimpleCloud | MIT License |
mime/src/main/java/com/jetictors/futures/mime/mime/ui/EditPwdFragment.kt | Jetictors | 118,728,987 | false | {"Java": 170792, "Kotlin": 110014} | package com.jetictors.futures.mime.mime.ui
import android.os.Bundle
import android.view.View
import com.jetictors.futures.common.base.BaseFragment
import com.jetictors.futures.mime.R
/**
* @描述 : 修改密码页面
* @author : Jetictors
* @time : 2018/3/7 11:13
* @version : v1.0.1
*/
class EditPwdFragment : BaseFragment(){
companion object {
fun newInstance() = EditPwdFragment()
}
override fun initInject(savedInstanceState: Bundle?) {
}
override fun getLayoutId(): Int {
return R.layout.frag_edit_pwd
}
override fun initEventAndData(view: View?) {
}
} | 0 | Java | 1 | 3 | 52d6987e6db03e458d220d73491663c1d5c1ebd9 | 619 | Juejin-Kotlin | Apache License 2.0 |
src/test/kotlin/no/fdk/fdk_public_service_harvester/service/HarvestAdminAdapter.kt | Informasjonsforvaltning | 335,976,565 | false | null | package no.fdk.fdk_concept_harvester.service
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import no.fdk.fdk_concept_harvester.adapter.HarvestAdminAdapter
import no.fdk.fdk_concept_harvester.configuration.ApplicationProperties
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import java.net.URL
import kotlin.test.assertEquals
@Tag("unit")
class HarvestAdminAdapterTest {
private val valuesMock: ApplicationProperties = mock()
private val adapter = HarvestAdminAdapter(valuesMock)
@Nested
internal inner class UrlWithParameters {
@Test
fun nullParameters() {
whenever(valuesMock.harvestAdminRootUrl)
.thenReturn("http://www.example.com")
val url = adapter.urlWithParameters(null)
assertEquals(URL("http://www.example.com/datasources"), url)
}
@Test
fun emptyParameters() {
whenever(valuesMock.harvestAdminRootUrl)
.thenReturn("http://www.example.com")
val url = adapter.urlWithParameters(emptyMap())
assertEquals(URL("http://www.example.com/datasources"), url)
}
@Test
fun singleParameter() {
whenever(valuesMock.harvestAdminRootUrl)
.thenReturn("http://www.example.com")
val url = adapter.urlWithParameters(mapOf(Pair("key0", "value0")))
assertEquals(URL("http://www.example.com/datasources?key0=value0"), url)
}
@Test
fun severalParameters() {
whenever(valuesMock.harvestAdminRootUrl)
.thenReturn("http://www.example.com")
val url = adapter.urlWithParameters(
mapOf(Pair("key0", "value0"), Pair("key1", "value1"), Pair("key2", "value2")))
assertEquals(URL("http://www.example.com/datasources?key0=value0&key1=value1&key2=value2"), url)
}
}
} | 1 | Kotlin | 0 | 0 | d4d62e62b5bff73419f0a89b89ce2e9af53c21b0 | 1,992 | fdk-public-service-harvester | Apache License 2.0 |
old/basic/src/main/java/com/dinesh/android/kotlin/activity/floating_window/v0/FloatingWindowService.kt | Dinesh2811 | 745,880,179 | false | {"Kotlin": 1200547, "Java": 206284, "JavaScript": 20260} | package com.dinesh.android.kotlin.activity.floating_window.v0
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
class FloatingWindowService : Service() {
private lateinit var floatingWindowManager: FloatingWindowManager
override fun onCreate() {
super.onCreate()
floatingWindowManager = FloatingWindowManager(applicationContext)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
intent?.let {
val rootWidth = it.getIntExtra("rootWidth", 0)
val rootHeight = it.getIntExtra("rootHeight", 0)
floatingWindowManager.showFloatingWindow(rootWidth, rootHeight)
}
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
floatingWindowManager.removeFloatingWindow()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
}
| 0 | Kotlin | 0 | 1 | d5b4b55728848196c71c351c186df7e57ad4e8c2 | 975 | Android101 | Apache License 2.0 |
sample/database/src/commonMain/kotlin/com/arkivanov/mvikotlin/sample/database/TodoDatabase.kt | arkivanov | 437,014,963 | false | {"Kotlin": 481306, "CSS": 842, "JavaScript": 716, "HTML": 583} | package com.arkivanov.mvikotlin.sample.database
interface TodoDatabase {
fun get(id: String): TodoItem?
fun create(data: TodoItem.Data): TodoItem
fun save(id: String, data: TodoItem.Data)
fun delete(id: String)
fun getAll(): List<TodoItem>
}
| 3 | Kotlin | 32 | 814 | 8ab014968028bc042ed0710c31113537fc9f66ed | 268 | MVIKotlin | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ecs/patterns/ApplicationLoadBalancedEc2ServiceProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 140726596} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.ecs.patterns
import io.cloudshiftdev.awscdk.Duration
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import io.cloudshiftdev.awscdk.services.certificatemanager.ICertificate
import io.cloudshiftdev.awscdk.services.ec2.IVpc
import io.cloudshiftdev.awscdk.services.ecs.CapacityProviderStrategy
import io.cloudshiftdev.awscdk.services.ecs.CloudMapOptions
import io.cloudshiftdev.awscdk.services.ecs.DeploymentCircuitBreaker
import io.cloudshiftdev.awscdk.services.ecs.DeploymentController
import io.cloudshiftdev.awscdk.services.ecs.Ec2TaskDefinition
import io.cloudshiftdev.awscdk.services.ecs.ICluster
import io.cloudshiftdev.awscdk.services.ecs.PlacementConstraint
import io.cloudshiftdev.awscdk.services.ecs.PlacementStrategy
import io.cloudshiftdev.awscdk.services.ecs.PropagatedTagSource
import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.ApplicationProtocol
import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.ApplicationProtocolVersion
import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.IApplicationLoadBalancer
import io.cloudshiftdev.awscdk.services.elasticloadbalancingv2.SslPolicy
import io.cloudshiftdev.awscdk.services.route53.IHostedZone
import kotlin.Boolean
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
/**
* The properties for the ApplicationLoadBalancedEc2Service service.
*
* Example:
*
* ```
* Cluster cluster;
* ApplicationLoadBalancedEc2Service loadBalancedEcsService =
* ApplicationLoadBalancedEc2Service.Builder.create(this, "Service")
* .cluster(cluster)
* .memoryLimitMiB(1024)
* .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
* .image(ContainerImage.fromRegistry("test"))
* .environment(Map.of(
* "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
* "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
* .command(List.of("command"))
* .entryPoint(List.of("entry", "point"))
* .build())
* .desiredCount(2)
* .build();
* ```
*/
public interface ApplicationLoadBalancedEc2ServiceProps : ApplicationLoadBalancedServiceBaseProps {
/**
* The number of cpu units used by the task.
*
* Valid values, which determines your range of valid values for the memory parameter:
*
* 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB
*
* 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB
*
* 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB
*
* 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments
*
* 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments
*
* This default is set in the underlying FargateTaskDefinition construct.
*
* Default: none
*/
public fun cpu(): Number? = unwrap(this).getCpu()
/**
* The hard limit (in MiB) of memory to present to the container.
*
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*
* Default: - No memory limit.
*/
public fun memoryLimitMiB(): Number? = unwrap(this).getMemoryLimitMiB()
/**
* The soft limit (in MiB) of memory to reserve for the container.
*
* When system memory is under contention, Docker attempts to keep the
* container memory within the limit. If the container requires more memory,
* it can consume up to the value specified by the Memory property or all of
* the available memory on the container instance—whichever comes first.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*
* Default: - No memory reserved.
*/
public fun memoryReservationMiB(): Number? = unwrap(this).getMemoryReservationMiB()
/**
* The placement constraints to use for tasks in the service.
*
* For more information, see
* [Amazon ECS Task Placement
* Constraints](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html).
*
* Default: - No constraints.
*/
public fun placementConstraints(): List<PlacementConstraint> =
unwrap(this).getPlacementConstraints()?.map(PlacementConstraint::wrap) ?: emptyList()
/**
* The placement strategies to use for tasks in the service.
*
* For more information, see
* [Amazon ECS Task Placement
* Strategies](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html).
*
* Default: - No strategies.
*/
public fun placementStrategies(): List<PlacementStrategy> =
unwrap(this).getPlacementStrategies()?.map(PlacementStrategy::wrap) ?: emptyList()
/**
* The task definition to use for tasks in the service. TaskDefinition or TaskImageOptions must be
* specified, but not both..
*
* [disable-awslint:ref-via-interface]
*
* Default: - none
*/
public fun taskDefinition(): Ec2TaskDefinition? =
unwrap(this).getTaskDefinition()?.let(Ec2TaskDefinition::wrap)
/**
* A builder for [ApplicationLoadBalancedEc2ServiceProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param capacityProviderStrategies A list of Capacity Provider strategies used to place a
* service.
*/
public
fun capacityProviderStrategies(capacityProviderStrategies: List<CapacityProviderStrategy>)
/**
* @param capacityProviderStrategies A list of Capacity Provider strategies used to place a
* service.
*/
public fun capacityProviderStrategies(vararg
capacityProviderStrategies: CapacityProviderStrategy)
/**
* @param certificate Certificate Manager certificate to associate with the load balancer.
* Setting this option will set the load balancer protocol to HTTPS.
*/
public fun certificate(certificate: ICertificate)
/**
* @param circuitBreaker Whether to enable the deployment circuit breaker.
* If this property is defined, circuit breaker will be implicitly
* enabled.
*/
public fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker)
/**
* @param circuitBreaker Whether to enable the deployment circuit breaker.
* If this property is defined, circuit breaker will be implicitly
* enabled.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f04d2e5d9a3d14216d612afcc98189c281ecc79a0bd0523fe74559e43646c154")
public fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker.Builder.() -> Unit)
/**
* @param cloudMapOptions The options for configuring an Amazon ECS service to use service
* discovery.
*/
public fun cloudMapOptions(cloudMapOptions: CloudMapOptions)
/**
* @param cloudMapOptions The options for configuring an Amazon ECS service to use service
* discovery.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("5babc57607dae275bed00e5e4aec0e15e2dcb5e0180ee0b1dc7dc0d962acc282")
public fun cloudMapOptions(cloudMapOptions: CloudMapOptions.Builder.() -> Unit)
/**
* @param cluster The name of the cluster that hosts the service.
* If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit
* both cluster and vpc.
*/
public fun cluster(cluster: ICluster)
/**
* @param cpu The number of cpu units used by the task.
* Valid values, which determines your range of valid values for the memory parameter:
*
* 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB
*
* 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB
*
* 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB
*
* 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments
*
* 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments
*
* This default is set in the underlying FargateTaskDefinition construct.
*/
public fun cpu(cpu: Number)
/**
* @param deploymentController Specifies which deployment controller to use for the service.
* For more information, see
* [Amazon ECS Deployment
* Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*/
public fun deploymentController(deploymentController: DeploymentController)
/**
* @param deploymentController Specifies which deployment controller to use for the service.
* For more information, see
* [Amazon ECS Deployment
* Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("5ee60f63b0ce40c9345eacd56ba8deff596adf1c805092be3fc6ddb05293d267")
public fun deploymentController(deploymentController: DeploymentController.Builder.() -> Unit)
/**
* @param desiredCount The desired number of instantiations of the task definition to keep
* running on the service.
* The minimum value is 1
*/
public fun desiredCount(desiredCount: Number)
/**
* @param domainName The domain name for the service, e.g. "api.example.com.".
*/
public fun domainName(domainName: String)
/**
* @param domainZone The Route53 hosted zone for the domain, e.g. "example.com.".
*/
public fun domainZone(domainZone: IHostedZone)
/**
* @param enableEcsManagedTags Specifies whether to enable Amazon ECS managed tags for the tasks
* within the service.
* For more information, see
* [Tagging Your Amazon ECS
* Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)
*/
public fun enableEcsManagedTags(enableEcsManagedTags: Boolean)
/**
* @param enableExecuteCommand Whether ECS Exec should be enabled.
*/
public fun enableExecuteCommand(enableExecuteCommand: Boolean)
/**
* @param healthCheckGracePeriod The period of time, in seconds, that the Amazon ECS service
* scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first
* started.
*/
public fun healthCheckGracePeriod(healthCheckGracePeriod: Duration)
/**
* @param idleTimeout The load balancer idle timeout, in seconds.
* Can be between 1 and 4000 seconds
*/
public fun idleTimeout(idleTimeout: Duration)
/**
* @param listenerPort Listener port of the application load balancer that will serve traffic to
* the service.
*/
public fun listenerPort(listenerPort: Number)
/**
* @param loadBalancer The application load balancer that will serve traffic to the service.
* The VPC attribute of a load balancer must be specified for it to be used
* to create a new service with this pattern.
*
* [disable-awslint:ref-via-interface]
*/
public fun loadBalancer(loadBalancer: IApplicationLoadBalancer)
/**
* @param loadBalancerName Name of the load balancer.
*/
public fun loadBalancerName(loadBalancerName: String)
/**
* @param maxHealthyPercent The maximum number of tasks, specified as a percentage of the Amazon
* ECS service's DesiredCount value, that can run in a service during a deployment.
*/
public fun maxHealthyPercent(maxHealthyPercent: Number)
/**
* @param memoryLimitMiB The hard limit (in MiB) of memory to present to the container.
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*/
public fun memoryLimitMiB(memoryLimitMiB: Number)
/**
* @param memoryReservationMiB The soft limit (in MiB) of memory to reserve for the container.
* When system memory is under contention, Docker attempts to keep the
* container memory within the limit. If the container requires more memory,
* it can consume up to the value specified by the Memory property or all of
* the available memory on the container instance—whichever comes first.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*/
public fun memoryReservationMiB(memoryReservationMiB: Number)
/**
* @param minHealthyPercent The minimum number of tasks, specified as a percentage of the Amazon
* ECS service's DesiredCount value, that must continue to run and remain healthy during a
* deployment.
*/
public fun minHealthyPercent(minHealthyPercent: Number)
/**
* @param openListener Determines whether or not the Security Group for the Load Balancer's
* Listener will be open to all traffic by default.
*/
public fun openListener(openListener: Boolean)
/**
* @param placementConstraints The placement constraints to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Constraints](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html).
*/
public fun placementConstraints(placementConstraints: List<PlacementConstraint>)
/**
* @param placementConstraints The placement constraints to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Constraints](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html).
*/
public fun placementConstraints(vararg placementConstraints: PlacementConstraint)
/**
* @param placementStrategies The placement strategies to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Strategies](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html).
*/
public fun placementStrategies(placementStrategies: List<PlacementStrategy>)
/**
* @param placementStrategies The placement strategies to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Strategies](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html).
*/
public fun placementStrategies(vararg placementStrategies: PlacementStrategy)
/**
* @param propagateTags Specifies whether to propagate the tags from the task definition or the
* service to the tasks in the service.
* Tags can only be propagated to the tasks within the service during service creation.
*/
public fun propagateTags(propagateTags: PropagatedTagSource)
/**
* @param protocol The protocol for connections from clients to the load balancer.
* The load balancer port is determined from the protocol (port 80 for
* HTTP, port 443 for HTTPS). If HTTPS, either a certificate or domain
* name and domain zone must also be specified.
*/
public fun protocol(protocol: ApplicationProtocol)
/**
* @param protocolVersion The protocol version to use.
*/
public fun protocolVersion(protocolVersion: ApplicationProtocolVersion)
/**
* @param publicLoadBalancer Determines whether the Load Balancer will be internet-facing.
*/
public fun publicLoadBalancer(publicLoadBalancer: Boolean)
/**
* @param recordType Specifies whether the Route53 record should be a CNAME, an A record using
* the Alias feature or no record at all.
* This is useful if you need to work with DNS systems that do not support alias records.
*/
public fun recordType(recordType: ApplicationLoadBalancedServiceRecordType)
/**
* @param redirectHttp Specifies whether the load balancer should redirect traffic on port 80 to
* port 443 to support HTTP->HTTPS redirects This is only valid if the protocol of the ALB is
* HTTPS.
*/
public fun redirectHttp(redirectHttp: Boolean)
/**
* @param serviceName The name of the service.
*/
public fun serviceName(serviceName: String)
/**
* @param sslPolicy The security policy that defines which ciphers and protocols are supported
* by the ALB Listener.
*/
public fun sslPolicy(sslPolicy: SslPolicy)
/**
* @param targetProtocol The protocol for connections from the load balancer to the ECS tasks.
* The default target port is determined from the protocol (port 80 for
* HTTP, port 443 for HTTPS).
*/
public fun targetProtocol(targetProtocol: ApplicationProtocol)
/**
* @param taskDefinition The task definition to use for tasks in the service. TaskDefinition or
* TaskImageOptions must be specified, but not both..
* [disable-awslint:ref-via-interface]
*/
public fun taskDefinition(taskDefinition: Ec2TaskDefinition)
/**
* @param taskImageOptions The properties required to create a new task definition.
* TaskDefinition or TaskImageOptions must be specified, but not both.
*/
public fun taskImageOptions(taskImageOptions: ApplicationLoadBalancedTaskImageOptions)
/**
* @param taskImageOptions The properties required to create a new task definition.
* TaskDefinition or TaskImageOptions must be specified, but not both.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("34cac82fd517fa20bb01e65d15bc72f5745519ee77ba07d4a45f1d62c61f54d6")
public
fun taskImageOptions(taskImageOptions: ApplicationLoadBalancedTaskImageOptions.Builder.() -> Unit)
/**
* @param vpc The VPC where the container instances will be launched or the elastic network
* interfaces (ENIs) will be deployed.
* If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit
* both vpc and cluster.
*/
public fun vpc(vpc: IVpc)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps.Builder
=
software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps.builder()
/**
* @param capacityProviderStrategies A list of Capacity Provider strategies used to place a
* service.
*/
override
fun capacityProviderStrategies(capacityProviderStrategies: List<CapacityProviderStrategy>) {
cdkBuilder.capacityProviderStrategies(capacityProviderStrategies.map(CapacityProviderStrategy.Companion::unwrap))
}
/**
* @param capacityProviderStrategies A list of Capacity Provider strategies used to place a
* service.
*/
override fun capacityProviderStrategies(vararg
capacityProviderStrategies: CapacityProviderStrategy): Unit =
capacityProviderStrategies(capacityProviderStrategies.toList())
/**
* @param certificate Certificate Manager certificate to associate with the load balancer.
* Setting this option will set the load balancer protocol to HTTPS.
*/
override fun certificate(certificate: ICertificate) {
cdkBuilder.certificate(certificate.let(ICertificate.Companion::unwrap))
}
/**
* @param circuitBreaker Whether to enable the deployment circuit breaker.
* If this property is defined, circuit breaker will be implicitly
* enabled.
*/
override fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker) {
cdkBuilder.circuitBreaker(circuitBreaker.let(DeploymentCircuitBreaker.Companion::unwrap))
}
/**
* @param circuitBreaker Whether to enable the deployment circuit breaker.
* If this property is defined, circuit breaker will be implicitly
* enabled.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f04d2e5d9a3d14216d612afcc98189c281ecc79a0bd0523fe74559e43646c154")
override fun circuitBreaker(circuitBreaker: DeploymentCircuitBreaker.Builder.() -> Unit): Unit =
circuitBreaker(DeploymentCircuitBreaker(circuitBreaker))
/**
* @param cloudMapOptions The options for configuring an Amazon ECS service to use service
* discovery.
*/
override fun cloudMapOptions(cloudMapOptions: CloudMapOptions) {
cdkBuilder.cloudMapOptions(cloudMapOptions.let(CloudMapOptions.Companion::unwrap))
}
/**
* @param cloudMapOptions The options for configuring an Amazon ECS service to use service
* discovery.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("5babc57607dae275bed00e5e4aec0e15e2dcb5e0180ee0b1dc7dc0d962acc282")
override fun cloudMapOptions(cloudMapOptions: CloudMapOptions.Builder.() -> Unit): Unit =
cloudMapOptions(CloudMapOptions(cloudMapOptions))
/**
* @param cluster The name of the cluster that hosts the service.
* If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit
* both cluster and vpc.
*/
override fun cluster(cluster: ICluster) {
cdkBuilder.cluster(cluster.let(ICluster.Companion::unwrap))
}
/**
* @param cpu The number of cpu units used by the task.
* Valid values, which determines your range of valid values for the memory parameter:
*
* 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB
*
* 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB
*
* 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB
*
* 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments
*
* 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments
*
* This default is set in the underlying FargateTaskDefinition construct.
*/
override fun cpu(cpu: Number) {
cdkBuilder.cpu(cpu)
}
/**
* @param deploymentController Specifies which deployment controller to use for the service.
* For more information, see
* [Amazon ECS Deployment
* Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*/
override fun deploymentController(deploymentController: DeploymentController) {
cdkBuilder.deploymentController(deploymentController.let(DeploymentController.Companion::unwrap))
}
/**
* @param deploymentController Specifies which deployment controller to use for the service.
* For more information, see
* [Amazon ECS Deployment
* Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("5ee60f63b0ce40c9345eacd56ba8deff596adf1c805092be3fc6ddb05293d267")
override
fun deploymentController(deploymentController: DeploymentController.Builder.() -> Unit):
Unit = deploymentController(DeploymentController(deploymentController))
/**
* @param desiredCount The desired number of instantiations of the task definition to keep
* running on the service.
* The minimum value is 1
*/
override fun desiredCount(desiredCount: Number) {
cdkBuilder.desiredCount(desiredCount)
}
/**
* @param domainName The domain name for the service, e.g. "api.example.com.".
*/
override fun domainName(domainName: String) {
cdkBuilder.domainName(domainName)
}
/**
* @param domainZone The Route53 hosted zone for the domain, e.g. "example.com.".
*/
override fun domainZone(domainZone: IHostedZone) {
cdkBuilder.domainZone(domainZone.let(IHostedZone.Companion::unwrap))
}
/**
* @param enableEcsManagedTags Specifies whether to enable Amazon ECS managed tags for the tasks
* within the service.
* For more information, see
* [Tagging Your Amazon ECS
* Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)
*/
override fun enableEcsManagedTags(enableEcsManagedTags: Boolean) {
cdkBuilder.enableEcsManagedTags(enableEcsManagedTags)
}
/**
* @param enableExecuteCommand Whether ECS Exec should be enabled.
*/
override fun enableExecuteCommand(enableExecuteCommand: Boolean) {
cdkBuilder.enableExecuteCommand(enableExecuteCommand)
}
/**
* @param healthCheckGracePeriod The period of time, in seconds, that the Amazon ECS service
* scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first
* started.
*/
override fun healthCheckGracePeriod(healthCheckGracePeriod: Duration) {
cdkBuilder.healthCheckGracePeriod(healthCheckGracePeriod.let(Duration.Companion::unwrap))
}
/**
* @param idleTimeout The load balancer idle timeout, in seconds.
* Can be between 1 and 4000 seconds
*/
override fun idleTimeout(idleTimeout: Duration) {
cdkBuilder.idleTimeout(idleTimeout.let(Duration.Companion::unwrap))
}
/**
* @param listenerPort Listener port of the application load balancer that will serve traffic to
* the service.
*/
override fun listenerPort(listenerPort: Number) {
cdkBuilder.listenerPort(listenerPort)
}
/**
* @param loadBalancer The application load balancer that will serve traffic to the service.
* The VPC attribute of a load balancer must be specified for it to be used
* to create a new service with this pattern.
*
* [disable-awslint:ref-via-interface]
*/
override fun loadBalancer(loadBalancer: IApplicationLoadBalancer) {
cdkBuilder.loadBalancer(loadBalancer.let(IApplicationLoadBalancer.Companion::unwrap))
}
/**
* @param loadBalancerName Name of the load balancer.
*/
override fun loadBalancerName(loadBalancerName: String) {
cdkBuilder.loadBalancerName(loadBalancerName)
}
/**
* @param maxHealthyPercent The maximum number of tasks, specified as a percentage of the Amazon
* ECS service's DesiredCount value, that can run in a service during a deployment.
*/
override fun maxHealthyPercent(maxHealthyPercent: Number) {
cdkBuilder.maxHealthyPercent(maxHealthyPercent)
}
/**
* @param memoryLimitMiB The hard limit (in MiB) of memory to present to the container.
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*/
override fun memoryLimitMiB(memoryLimitMiB: Number) {
cdkBuilder.memoryLimitMiB(memoryLimitMiB)
}
/**
* @param memoryReservationMiB The soft limit (in MiB) of memory to reserve for the container.
* When system memory is under contention, Docker attempts to keep the
* container memory within the limit. If the container requires more memory,
* it can consume up to the value specified by the Memory property or all of
* the available memory on the container instance—whichever comes first.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*/
override fun memoryReservationMiB(memoryReservationMiB: Number) {
cdkBuilder.memoryReservationMiB(memoryReservationMiB)
}
/**
* @param minHealthyPercent The minimum number of tasks, specified as a percentage of the Amazon
* ECS service's DesiredCount value, that must continue to run and remain healthy during a
* deployment.
*/
override fun minHealthyPercent(minHealthyPercent: Number) {
cdkBuilder.minHealthyPercent(minHealthyPercent)
}
/**
* @param openListener Determines whether or not the Security Group for the Load Balancer's
* Listener will be open to all traffic by default.
*/
override fun openListener(openListener: Boolean) {
cdkBuilder.openListener(openListener)
}
/**
* @param placementConstraints The placement constraints to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Constraints](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html).
*/
override fun placementConstraints(placementConstraints: List<PlacementConstraint>) {
cdkBuilder.placementConstraints(placementConstraints.map(PlacementConstraint.Companion::unwrap))
}
/**
* @param placementConstraints The placement constraints to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Constraints](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html).
*/
override fun placementConstraints(vararg placementConstraints: PlacementConstraint): Unit =
placementConstraints(placementConstraints.toList())
/**
* @param placementStrategies The placement strategies to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Strategies](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html).
*/
override fun placementStrategies(placementStrategies: List<PlacementStrategy>) {
cdkBuilder.placementStrategies(placementStrategies.map(PlacementStrategy.Companion::unwrap))
}
/**
* @param placementStrategies The placement strategies to use for tasks in the service.
* For more information, see
* [Amazon ECS Task Placement
* Strategies](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html).
*/
override fun placementStrategies(vararg placementStrategies: PlacementStrategy): Unit =
placementStrategies(placementStrategies.toList())
/**
* @param propagateTags Specifies whether to propagate the tags from the task definition or the
* service to the tasks in the service.
* Tags can only be propagated to the tasks within the service during service creation.
*/
override fun propagateTags(propagateTags: PropagatedTagSource) {
cdkBuilder.propagateTags(propagateTags.let(PropagatedTagSource.Companion::unwrap))
}
/**
* @param protocol The protocol for connections from clients to the load balancer.
* The load balancer port is determined from the protocol (port 80 for
* HTTP, port 443 for HTTPS). If HTTPS, either a certificate or domain
* name and domain zone must also be specified.
*/
override fun protocol(protocol: ApplicationProtocol) {
cdkBuilder.protocol(protocol.let(ApplicationProtocol.Companion::unwrap))
}
/**
* @param protocolVersion The protocol version to use.
*/
override fun protocolVersion(protocolVersion: ApplicationProtocolVersion) {
cdkBuilder.protocolVersion(protocolVersion.let(ApplicationProtocolVersion.Companion::unwrap))
}
/**
* @param publicLoadBalancer Determines whether the Load Balancer will be internet-facing.
*/
override fun publicLoadBalancer(publicLoadBalancer: Boolean) {
cdkBuilder.publicLoadBalancer(publicLoadBalancer)
}
/**
* @param recordType Specifies whether the Route53 record should be a CNAME, an A record using
* the Alias feature or no record at all.
* This is useful if you need to work with DNS systems that do not support alias records.
*/
override fun recordType(recordType: ApplicationLoadBalancedServiceRecordType) {
cdkBuilder.recordType(recordType.let(ApplicationLoadBalancedServiceRecordType.Companion::unwrap))
}
/**
* @param redirectHttp Specifies whether the load balancer should redirect traffic on port 80 to
* port 443 to support HTTP->HTTPS redirects This is only valid if the protocol of the ALB is
* HTTPS.
*/
override fun redirectHttp(redirectHttp: Boolean) {
cdkBuilder.redirectHttp(redirectHttp)
}
/**
* @param serviceName The name of the service.
*/
override fun serviceName(serviceName: String) {
cdkBuilder.serviceName(serviceName)
}
/**
* @param sslPolicy The security policy that defines which ciphers and protocols are supported
* by the ALB Listener.
*/
override fun sslPolicy(sslPolicy: SslPolicy) {
cdkBuilder.sslPolicy(sslPolicy.let(SslPolicy.Companion::unwrap))
}
/**
* @param targetProtocol The protocol for connections from the load balancer to the ECS tasks.
* The default target port is determined from the protocol (port 80 for
* HTTP, port 443 for HTTPS).
*/
override fun targetProtocol(targetProtocol: ApplicationProtocol) {
cdkBuilder.targetProtocol(targetProtocol.let(ApplicationProtocol.Companion::unwrap))
}
/**
* @param taskDefinition The task definition to use for tasks in the service. TaskDefinition or
* TaskImageOptions must be specified, but not both..
* [disable-awslint:ref-via-interface]
*/
override fun taskDefinition(taskDefinition: Ec2TaskDefinition) {
cdkBuilder.taskDefinition(taskDefinition.let(Ec2TaskDefinition.Companion::unwrap))
}
/**
* @param taskImageOptions The properties required to create a new task definition.
* TaskDefinition or TaskImageOptions must be specified, but not both.
*/
override fun taskImageOptions(taskImageOptions: ApplicationLoadBalancedTaskImageOptions) {
cdkBuilder.taskImageOptions(taskImageOptions.let(ApplicationLoadBalancedTaskImageOptions.Companion::unwrap))
}
/**
* @param taskImageOptions The properties required to create a new task definition.
* TaskDefinition or TaskImageOptions must be specified, but not both.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("34cac82fd517fa20bb01e65d15bc72f5745519ee77ba07d4a45f1d62c61f54d6")
override
fun taskImageOptions(taskImageOptions: ApplicationLoadBalancedTaskImageOptions.Builder.() -> Unit):
Unit = taskImageOptions(ApplicationLoadBalancedTaskImageOptions(taskImageOptions))
/**
* @param vpc The VPC where the container instances will be launched or the elastic network
* interfaces (ENIs) will be deployed.
* If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit
* both vpc and cluster.
*/
override fun vpc(vpc: IVpc) {
cdkBuilder.vpc(vpc.let(IVpc.Companion::unwrap))
}
public fun build():
software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps,
) : CdkObject(cdkObject), ApplicationLoadBalancedEc2ServiceProps {
/**
* A list of Capacity Provider strategies used to place a service.
*
* Default: - undefined
*/
override fun capacityProviderStrategies(): List<CapacityProviderStrategy> =
unwrap(this).getCapacityProviderStrategies()?.map(CapacityProviderStrategy::wrap) ?:
emptyList()
/**
* Certificate Manager certificate to associate with the load balancer.
*
* Setting this option will set the load balancer protocol to HTTPS.
*
* Default: - No certificate associated with the load balancer, if using
* the HTTP protocol. For HTTPS, a DNS-validated certificate will be
* created for the load balancer's specified domain name if a domain name
* and domain zone are specified.
*/
override fun certificate(): ICertificate? =
unwrap(this).getCertificate()?.let(ICertificate::wrap)
/**
* Whether to enable the deployment circuit breaker.
*
* If this property is defined, circuit breaker will be implicitly
* enabled.
*
* Default: - disabled
*/
override fun circuitBreaker(): DeploymentCircuitBreaker? =
unwrap(this).getCircuitBreaker()?.let(DeploymentCircuitBreaker::wrap)
/**
* The options for configuring an Amazon ECS service to use service discovery.
*
* Default: - AWS Cloud Map service discovery is not enabled.
*/
override fun cloudMapOptions(): CloudMapOptions? =
unwrap(this).getCloudMapOptions()?.let(CloudMapOptions::wrap)
/**
* The name of the cluster that hosts the service.
*
* If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit
* both cluster and vpc.
*
* Default: - create a new cluster; if both cluster and vpc are omitted, a new VPC will be
* created for you.
*/
override fun cluster(): ICluster? = unwrap(this).getCluster()?.let(ICluster::wrap)
/**
* The number of cpu units used by the task.
*
* Valid values, which determines your range of valid values for the memory parameter:
*
* 256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB
*
* 512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB
*
* 1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB
*
* 2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments
*
* 4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments
*
* This default is set in the underlying FargateTaskDefinition construct.
*
* Default: none
*/
override fun cpu(): Number? = unwrap(this).getCpu()
/**
* Specifies which deployment controller to use for the service.
*
* For more information, see
* [Amazon ECS Deployment
* Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*
* Default: - Rolling update (ECS)
*/
override fun deploymentController(): DeploymentController? =
unwrap(this).getDeploymentController()?.let(DeploymentController::wrap)
/**
* The desired number of instantiations of the task definition to keep running on the service.
*
* The minimum value is 1
*
* Default: - The default is 1 for all new services and uses the existing service's desired
* count
* when updating an existing service.
*/
override fun desiredCount(): Number? = unwrap(this).getDesiredCount()
/**
* The domain name for the service, e.g. "api.example.com.".
*
* Default: - No domain name.
*/
override fun domainName(): String? = unwrap(this).getDomainName()
/**
* The Route53 hosted zone for the domain, e.g. "example.com.".
*
* Default: - No Route53 hosted domain zone.
*/
override fun domainZone(): IHostedZone? = unwrap(this).getDomainZone()?.let(IHostedZone::wrap)
/**
* Specifies whether to enable Amazon ECS managed tags for the tasks within the service.
*
* For more information, see
* [Tagging Your Amazon ECS
* Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)
*
* Default: false
*/
override fun enableECSManagedTags(): Boolean? = unwrap(this).getEnableECSManagedTags()
/**
* Whether ECS Exec should be enabled.
*
* Default: - false
*/
override fun enableExecuteCommand(): Boolean? = unwrap(this).getEnableExecuteCommand()
/**
* The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy
* Elastic Load Balancing target health checks after a task has first started.
*
* Default: - defaults to 60 seconds if at least one load balancer is in-use and it is not
* already set
*/
override fun healthCheckGracePeriod(): Duration? =
unwrap(this).getHealthCheckGracePeriod()?.let(Duration::wrap)
/**
* The load balancer idle timeout, in seconds.
*
* Can be between 1 and 4000 seconds
*
* Default: - CloudFormation sets idle timeout to 60 seconds
*/
override fun idleTimeout(): Duration? = unwrap(this).getIdleTimeout()?.let(Duration::wrap)
/**
* Listener port of the application load balancer that will serve traffic to the service.
*
* Default: - The default listener port is determined from the protocol (port 80 for HTTP,
* port 443 for HTTPS). A domain name and zone must be also be specified if using HTTPS.
*/
override fun listenerPort(): Number? = unwrap(this).getListenerPort()
/**
* The application load balancer that will serve traffic to the service.
*
* The VPC attribute of a load balancer must be specified for it to be used
* to create a new service with this pattern.
*
* [disable-awslint:ref-via-interface]
*
* Default: - a new load balancer will be created.
*/
override fun loadBalancer(): IApplicationLoadBalancer? =
unwrap(this).getLoadBalancer()?.let(IApplicationLoadBalancer::wrap)
/**
* Name of the load balancer.
*
* Default: - Automatically generated name.
*/
override fun loadBalancerName(): String? = unwrap(this).getLoadBalancerName()
/**
* The maximum number of tasks, specified as a percentage of the Amazon ECS service's
* DesiredCount value, that can run in a service during a deployment.
*
* Default: - 100 if daemon, otherwise 200
*/
override fun maxHealthyPercent(): Number? = unwrap(this).getMaxHealthyPercent()
/**
* The hard limit (in MiB) of memory to present to the container.
*
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*
* Default: - No memory limit.
*/
override fun memoryLimitMiB(): Number? = unwrap(this).getMemoryLimitMiB()
/**
* The soft limit (in MiB) of memory to reserve for the container.
*
* When system memory is under contention, Docker attempts to keep the
* container memory within the limit. If the container requires more memory,
* it can consume up to the value specified by the Memory property or all of
* the available memory on the container instance—whichever comes first.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required.
*
* Default: - No memory reserved.
*/
override fun memoryReservationMiB(): Number? = unwrap(this).getMemoryReservationMiB()
/**
* The minimum number of tasks, specified as a percentage of the Amazon ECS service's
* DesiredCount value, that must continue to run and remain healthy during a deployment.
*
* Default: - 0 if daemon, otherwise 50
*/
override fun minHealthyPercent(): Number? = unwrap(this).getMinHealthyPercent()
/**
* Determines whether or not the Security Group for the Load Balancer's Listener will be open to
* all traffic by default.
*
* Default: true -- The security group allows ingress from all IP addresses.
*/
override fun openListener(): Boolean? = unwrap(this).getOpenListener()
/**
* The placement constraints to use for tasks in the service.
*
* For more information, see
* [Amazon ECS Task Placement
* Constraints](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html).
*
* Default: - No constraints.
*/
override fun placementConstraints(): List<PlacementConstraint> =
unwrap(this).getPlacementConstraints()?.map(PlacementConstraint::wrap) ?: emptyList()
/**
* The placement strategies to use for tasks in the service.
*
* For more information, see
* [Amazon ECS Task Placement
* Strategies](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html).
*
* Default: - No strategies.
*/
override fun placementStrategies(): List<PlacementStrategy> =
unwrap(this).getPlacementStrategies()?.map(PlacementStrategy::wrap) ?: emptyList()
/**
* Specifies whether to propagate the tags from the task definition or the service to the tasks
* in the service.
*
* Tags can only be propagated to the tasks within the service during service creation.
*
* Default: - none
*/
override fun propagateTags(): PropagatedTagSource? =
unwrap(this).getPropagateTags()?.let(PropagatedTagSource::wrap)
/**
* The protocol for connections from clients to the load balancer.
*
* The load balancer port is determined from the protocol (port 80 for
* HTTP, port 443 for HTTPS). If HTTPS, either a certificate or domain
* name and domain zone must also be specified.
*
* Default: HTTP. If a certificate is specified, the protocol will be
* set by default to HTTPS.
*/
override fun protocol(): ApplicationProtocol? =
unwrap(this).getProtocol()?.let(ApplicationProtocol::wrap)
/**
* The protocol version to use.
*
* Default: ApplicationProtocolVersion.HTTP1
*/
override fun protocolVersion(): ApplicationProtocolVersion? =
unwrap(this).getProtocolVersion()?.let(ApplicationProtocolVersion::wrap)
/**
* Determines whether the Load Balancer will be internet-facing.
*
* Default: true
*/
override fun publicLoadBalancer(): Boolean? = unwrap(this).getPublicLoadBalancer()
/**
* Specifies whether the Route53 record should be a CNAME, an A record using the Alias feature
* or no record at all.
*
* This is useful if you need to work with DNS systems that do not support alias records.
*
* Default: ApplicationLoadBalancedServiceRecordType.ALIAS
*/
override fun recordType(): ApplicationLoadBalancedServiceRecordType? =
unwrap(this).getRecordType()?.let(ApplicationLoadBalancedServiceRecordType::wrap)
/**
* Specifies whether the load balancer should redirect traffic on port 80 to port 443 to support
* HTTP->HTTPS redirects This is only valid if the protocol of the ALB is HTTPS.
*
* Default: false
*/
override fun redirectHTTP(): Boolean? = unwrap(this).getRedirectHTTP()
/**
* The name of the service.
*
* Default: - CloudFormation-generated name.
*/
override fun serviceName(): String? = unwrap(this).getServiceName()
/**
* The security policy that defines which ciphers and protocols are supported by the ALB
* Listener.
*
* Default: - The recommended elastic load balancing security policy
*/
override fun sslPolicy(): SslPolicy? = unwrap(this).getSslPolicy()?.let(SslPolicy::wrap)
/**
* The protocol for connections from the load balancer to the ECS tasks.
*
* The default target port is determined from the protocol (port 80 for
* HTTP, port 443 for HTTPS).
*
* Default: HTTP.
*/
override fun targetProtocol(): ApplicationProtocol? =
unwrap(this).getTargetProtocol()?.let(ApplicationProtocol::wrap)
/**
* The task definition to use for tasks in the service. TaskDefinition or TaskImageOptions must
* be specified, but not both..
*
* [disable-awslint:ref-via-interface]
*
* Default: - none
*/
override fun taskDefinition(): Ec2TaskDefinition? =
unwrap(this).getTaskDefinition()?.let(Ec2TaskDefinition::wrap)
/**
* The properties required to create a new task definition.
*
* TaskDefinition or TaskImageOptions must be specified, but not both.
*
* Default: none
*/
override fun taskImageOptions(): ApplicationLoadBalancedTaskImageOptions? =
unwrap(this).getTaskImageOptions()?.let(ApplicationLoadBalancedTaskImageOptions::wrap)
/**
* The VPC where the container instances will be launched or the elastic network interfaces
* (ENIs) will be deployed.
*
* If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit
* both vpc and cluster.
*
* Default: - uses the VPC defined in the cluster or creates a new VPC.
*/
override fun vpc(): IVpc? = unwrap(this).getVpc()?.let(IVpc::wrap)
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}):
ApplicationLoadBalancedEc2ServiceProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps):
ApplicationLoadBalancedEc2ServiceProps = CdkObjectWrappers.wrap(cdkObject) as?
ApplicationLoadBalancedEc2ServiceProps ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: ApplicationLoadBalancedEc2ServiceProps):
software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps =
(wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedEc2ServiceProps
}
}
| 4 | Kotlin | 0 | 4 | ddf2bfd2275b50bb86a667c4298dd92f59d7e342 | 49,239 | kotlin-cdk-wrapper | Apache License 2.0 |
src/commonMain/kotlin/baaahs/gl/GlManager.kt | lucgirardin | 290,413,324 | true | {"Kotlin": 1134726, "C++": 479123, "JavaScript": 365308, "GLSL": 120375, "C": 100546, "CMake": 25514, "HTML": 10796, "CSS": 10322, "Shell": 663} | package baaahs.gl
abstract class GlManager {
abstract val available: Boolean
abstract fun createContext(): GlContext
} | 0 | null | 0 | 0 | 80865b7141d4ab8fcaafcc1c58402afb02561ecc | 128 | sparklemotion | MIT License |
debug-app/src/main/java/io/rover/app/debug/fcm/FirebaseInstanceIdReceiver.kt | mkj-gram | 167,372,309 | true | {"Gradle": 12, "Shell": 2, "Text": 3, "Ignore List": 8, "Batchfile": 1, "Markdown": 8, "Proguard": 9, "JSON": 5, "Kotlin": 239, "XML": 216, "Java": 255, "Java Properties": 1, "Checksums": 1292} | package io.rover.app.debug.fcm
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.iid.FirebaseInstanceIdService
import io.rover.core.Rover
import io.rover.notifications.PushReceiverInterface
class FirebaseInstanceIdReceiver : FirebaseInstanceIdService() {
override fun onTokenRefresh() {
Rover.shared?.resolve(PushReceiverInterface::class.java)?.onTokenRefresh(
FirebaseInstanceId.getInstance().token
)
}
}
| 0 | Java | 0 | 0 | a5e155a1ed7d19b1cecd9a7b075e2852623a06bf | 471 | rover-android | Apache License 2.0 |
app/src/main/java/com/raassh/gemastik15/local/db/ChatDao.kt | raassh-23 | 540,716,155 | false | null | package com.raassh.gemastik15.local.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface ChatDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertChats(chats: List<ChatEntity>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertMessages(messages: List<MessageEntity>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertChat(chat: ChatEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertMessage(message: MessageEntity)
@Query("SELECT * FROM chats")
fun getChats(): Flow<List<ChatEntity>>
@Query("SELECT * FROM messages WHERE chatId = :chatId ORDER BY timestamp ASC")
fun getMessages(chatId: String): Flow<List<MessageEntity>>
@Query("SELECT * FROM messages WHERE chatId = :chatId ORDER BY timestamp DESC LIMIT 1")
fun getLastMessage(chatId: String): Flow<MessageEntity>
@Query("SELECT * FROM messages WHERE content LIKE '%' || :query || '%'")
fun searchChat(query: String): Flow<List<MessageEntity>>
@Query("SELECT * FROM chats WHERE id IN (:chatIds)")
fun getChatByIds(chatIds: List<String>): List<ChatEntity>
@Query("SELECT * FROM chats WHERE users = :sender")
fun getChatByUserId(sender: String): ChatEntity?
} | 4 | Kotlin | 0 | 1 | b374d5fe9636db1af6623804b2bdcce301aa55d3 | 1,400 | PPL-Gemastik-15-Android | MIT License |
jetbrains-core/src/software/aws/toolkits/jetbrains/services/lambda/steps/LambdaWorkflows.kt | smooth80stech | 384,458,101 | false | null | // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.lambda.upload.steps
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import software.aws.toolkits.jetbrains.core.awsClient
import software.aws.toolkits.jetbrains.core.credentials.AwsConnectionManager
import software.aws.toolkits.jetbrains.core.credentials.toEnvironmentVariables
import software.aws.toolkits.jetbrains.core.utils.buildList
import software.aws.toolkits.jetbrains.services.lambda.deploy.CreateCapabilities
import software.aws.toolkits.jetbrains.services.lambda.execution.sam.ValidateDocker
import software.aws.toolkits.jetbrains.services.lambda.sam.SamCommon
import software.aws.toolkits.jetbrains.services.lambda.sam.SamOptions
import software.aws.toolkits.jetbrains.services.lambda.sam.SamTemplateUtils
import software.aws.toolkits.jetbrains.services.lambda.upload.FunctionDetails
import software.aws.toolkits.jetbrains.services.lambda.upload.ImageBasedCode
import software.aws.toolkits.jetbrains.services.lambda.upload.ZipBasedCode
import software.aws.toolkits.jetbrains.utils.execution.steps.StepWorkflow
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
fun createLambdaWorkflowForZip(
project: Project,
functionDetails: FunctionDetails,
codeDetails: ZipBasedCode,
buildDir: Path,
buildEnvVars: Map<String, String>,
codeStorageLocation: String,
samOptions: SamOptions
): StepWorkflow {
val (dummyTemplate, dummyLogicalId) = createTemporaryZipTemplate(buildDir, codeDetails)
val packagedTemplate = buildDir.resolve("packaged-temp-template.yaml")
val builtTemplate = buildDir.resolve("template.yaml")
val envVars = createAwsEnvVars(project)
return StepWorkflow(
buildList {
if (samOptions.buildInContainer) {
add(ValidateDocker())
}
add(
BuildLambda(
templatePath = dummyTemplate,
buildDir = buildDir,
buildEnvVars = buildEnvVars,
samOptions = samOptions
),
)
add(
PackageLambda(
templatePath = builtTemplate,
packagedTemplatePath = packagedTemplate,
logicalId = dummyLogicalId,
envVars = envVars,
s3Bucket = codeStorageLocation
),
)
add(
CreateLambda(
lambdaClient = project.awsClient(),
details = functionDetails
)
)
}
)
}
fun createLambdaWorkflowForImage(
project: Project,
functionDetails: FunctionDetails,
codeDetails: ImageBasedCode,
codeStorageLocation: String,
samOptions: SamOptions
): StepWorkflow {
val (dummyTemplate, dummyLogicalId) = createTemporaryImageTemplate(codeDetails)
val buildDir = codeDetails.dockerfile.resolveSibling(".aws-sam").resolve("build")
val builtTemplate = buildDir.resolve("template.yaml")
val packagedTemplate = buildDir.resolve("packaged-temp-template.yaml")
val envVars = createAwsEnvVars(project)
return StepWorkflow(
ValidateDocker(),
BuildLambda(
templatePath = dummyTemplate,
buildDir = buildDir,
samOptions = samOptions
),
PackageLambda(
templatePath = builtTemplate,
packagedTemplatePath = packagedTemplate,
logicalId = dummyLogicalId,
envVars = envVars,
ecrRepo = codeStorageLocation
),
CreateLambda(project.awsClient(), functionDetails)
)
}
/**
* Creates a [StepWorkflow] for updating a Lambda's code and optionally its handler
*
* @param updatedHandler If provided, we will call update function configuration with the provided handler.
*/
fun updateLambdaCodeWorkflowForZip(
project: Project,
functionName: String,
codeDetails: ZipBasedCode,
buildDir: Path,
buildEnvVars: Map<String, String>,
codeStorageLocation: String,
samOptions: SamOptions,
updatedHandler: String?
): StepWorkflow {
val (dummyTemplate, dummyLogicalId) = createTemporaryZipTemplate(buildDir, codeDetails)
val builtTemplate = buildDir.resolve("template.yaml")
val packagedTemplate = buildDir.resolve("packaged-temp-template.yaml")
val envVars = createAwsEnvVars(project)
return StepWorkflow(
buildList {
if (samOptions.buildInContainer) {
add(ValidateDocker())
}
add(
BuildLambda(
templatePath = dummyTemplate,
buildDir = buildDir,
buildEnvVars = buildEnvVars,
samOptions = samOptions
),
)
add(
PackageLambda(
templatePath = builtTemplate,
packagedTemplatePath = packagedTemplate,
logicalId = dummyLogicalId,
envVars = envVars,
s3Bucket = codeStorageLocation
),
)
add(
UpdateLambdaCode(
lambdaClient = project.awsClient(),
functionName = functionName,
updatedHandler = updatedHandler
)
)
}
)
}
fun updateLambdaCodeWorkflowForImage(
project: Project,
functionName: String,
codeDetails: ImageBasedCode,
codeStorageLocation: String,
samOptions: SamOptions
): StepWorkflow {
val (dummyTemplate, dummyLogicalId) = createTemporaryImageTemplate(codeDetails)
val buildDir = codeDetails.dockerfile.resolveSibling(".aws-sam").resolve("build")
val builtTemplate = buildDir.resolve("template.yaml")
val packagedTemplate = buildDir.resolve("packaged-temp-template.yaml")
val envVars = createAwsEnvVars(project)
return StepWorkflow(
ValidateDocker(),
BuildLambda(
templatePath = dummyTemplate,
buildDir = buildDir,
samOptions = samOptions
),
PackageLambda(
templatePath = builtTemplate,
packagedTemplatePath = packagedTemplate,
logicalId = dummyLogicalId,
envVars = envVars,
ecrRepo = codeStorageLocation
),
UpdateLambdaCode(
lambdaClient = project.awsClient(),
functionName = functionName,
updatedHandler = null
)
)
}
fun createDeployWorkflow(
project: Project,
stackName: String,
template: VirtualFile,
s3Bucket: String,
ecrRepo: String?,
useContainer: Boolean,
parameters: Map<String, String>,
capabilities: List<CreateCapabilities>
): StepWorkflow {
val envVars = createAwsEnvVars(project)
val region = AwsConnectionManager.getInstance(project).activeRegion
val buildDir = Paths.get(template.parent.path, SamCommon.SAM_BUILD_DIR, "build")
val builtTemplate = buildDir.resolve("template.yaml")
val packagedTemplate = builtTemplate.parent.resolve("packaged-${builtTemplate.fileName}")
val templatePath = Paths.get(template.path)
Files.createDirectories(buildDir)
return StepWorkflow(
buildList {
if (useContainer) {
add(ValidateDocker())
}
add(
BuildLambda(
templatePath = templatePath,
logicalId = null,
buildDir = buildDir,
buildEnvVars = envVars,
samOptions = SamOptions(buildInContainer = useContainer)
)
)
add(
PackageLambda(
templatePath = builtTemplate,
packagedTemplatePath = packagedTemplate,
logicalId = null,
envVars = envVars,
s3Bucket = s3Bucket,
ecrRepo = ecrRepo
)
)
add(
DeployLambda(
packagedTemplateFile = packagedTemplate,
stackName = stackName,
ecrRepo = ecrRepo,
s3Bucket = s3Bucket,
capabilities = capabilities,
parameters = parameters,
envVars = envVars,
region = region
)
)
}
)
}
private fun createAwsEnvVars(project: Project): Map<String, String> {
val connectSettings = AwsConnectionManager.getInstance(project).connectionSettings()
?: throw IllegalStateException("Tried to update a lambda without valid AWS connection")
return connectSettings.credentials.resolveCredentials().toEnvironmentVariables() + connectSettings.region.toEnvironmentVariables()
}
private fun createTemporaryZipTemplate(buildDir: Path, codeDetails: ZipBasedCode): Pair<Path, String> {
Files.createDirectories(buildDir)
val dummyTemplate = Files.createTempFile("temp-template", ".yaml")
val dummyLogicalId = "Function"
SamTemplateUtils.writeDummySamTemplate(
tempFile = dummyTemplate,
logicalId = dummyLogicalId,
runtime = codeDetails.runtime,
handler = codeDetails.handler,
codeUri = codeDetails.baseDir.toString()
)
return Pair(dummyTemplate, dummyLogicalId)
}
private fun createTemporaryImageTemplate(codeDetails: ImageBasedCode): Pair<Path, String> {
val dummyTemplate = Files.createTempFile("temp-template", ".yaml")
val dummyLogicalId = "Function"
SamTemplateUtils.writeDummySamImageTemplate(
tempFile = dummyTemplate,
logicalId = dummyLogicalId,
dockerfile = codeDetails.dockerfile
)
return Pair(dummyTemplate, dummyLogicalId)
}
| 1 | null | 1 | 1 | 73a50130bf90b23069334db6e07bb2b968eeac75 | 10,058 | aws-toolkit-jetbrains | Apache License 2.0 |
db/src/main/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/db/InntektsmeldingUtils.kt | navikt | 495,713,363 | false | {"Kotlin": 1293757, "PLpgSQL": 153, "Dockerfile": 68} | package no.nav.helsearbeidsgiver.inntektsmelding.db
import no.nav.helsearbeidsgiver.domene.inntektsmelding.deprecated.Inntektsmelding
import no.nav.helsearbeidsgiver.domene.inntektsmelding.v1.skjema.SkjemaInntektsmelding
fun Inntektsmelding.erDuplikatAv(other: Inntektsmelding): Boolean =
this ==
other.copy(
vedtaksperiodeId = vedtaksperiodeId,
tidspunkt = tidspunkt,
årsakInnsending = årsakInnsending,
innsenderNavn = innsenderNavn,
telefonnummer = telefonnummer,
)
fun SkjemaInntektsmelding.erDuplikatAv(other: SkjemaInntektsmelding): Boolean =
this ==
other.copy(
avsenderTlf = avsenderTlf,
)
| 12 | Kotlin | 0 | 2 | f8e33771e305712986eeb7c9d38edfd8d5f24a7b | 712 | helsearbeidsgiver-inntektsmelding | MIT License |
presentation/src/main/java/com/glowka/rafal/topmusic/presentation/flow/dashboard/country/CountryDialogFragment.kt | RafalGlowka | 523,115,375 | false | null | package com.glowka.rafal.topmusic.presentation.flow.dashboard.country
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.glowka.rafal.topmusic.presentation.architecture.BaseBottomSheetDialogFragment
import com.glowka.rafal.topmusic.presentation.flow.dashboard.country.CountryDialogViewModelToViewInterface.ViewEvents
import com.glowka.rafal.topmusic.presentation.flow.dashboard.country.CountryDialogViewModelToViewInterface.ViewState
class CountryDialogFragment :
BaseBottomSheetDialogFragment<ViewState, ViewEvents, CountryDialogViewModelToViewInterface>() {
override val content: @Composable () -> Unit = {
val viewState by viewModel.viewState.collectAsState()
CountryScreenDialog(
viewState = viewState,
onViewEvent = viewModel::onViewEvent
)
}
} | 0 | Kotlin | 0 | 0 | 1177a4bd83fa54570dce15c119985896c229d81c | 873 | TopMusic | Apache License 2.0 |
features/timeline/src/main/java/com/chesire/nekome/app/timeline/TimelineViewModel.kt | Chesire | 223,272,337 | false | null | package com.chesire.nekome.app.timeline
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.chesire.nekome.datasource.activity.ActivityDomain
import com.chesire.nekome.datasource.activity.ActivityRepository
import com.chesire.nekome.datasource.activity.UserActivityResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import javax.inject.Inject
/**
* ViewModel for the [TimelineFragment].
*/
@HiltViewModel
class TimelineViewModel @Inject constructor(
private val activityRepository: ActivityRepository
) : ViewModel() {
val latestActivity = liveData {
activityRepository
.userActivity
.onStart { emit(ViewState.Loading) }
.map {
if (it is UserActivityResult.RetrievedValues) {
ViewState.GotActivities(it.newValues)
} else {
ViewState.Failure
}
}
.collect { emit(it) }
}
}
/**
* The current state of the view.
*/
sealed class ViewState {
/**
* View is in a loading state.
*/
object Loading : ViewState()
/**
* View has got the [ActivityDomain] required to display.
*/
data class GotActivities(val activities: List<ActivityDomain>) : ViewState()
/**
* A failure to retrieve the activity domains has occurred.
*/
object Failure : ViewState()
}
| 24 | Kotlin | 31 | 269 | d9747aeb6ca7dab5fa3ed6925b5cb7715915c3e0 | 1,523 | Nekome | Apache License 2.0 |
app/src/main/java/com/mafqud/android/notification/NotificationViewModel.kt | MafQud | 483,257,198 | false | null | package com.mafqud.android.notification
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.cachedIn
import androidx.paging.map
import com.mafqud.android.base.viewModel.BaseViewModel
import com.mafqud.android.notification.models.NotificationsResponse
import com.mafqud.android.util.network.Result
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import javax.inject.Inject
@HiltViewModel
class NotificationViewModel @Inject constructor(private val notificationUseCase: NotificationUseCase) :
BaseViewModel<NotificationIntent, NotificationViewState>(NotificationViewState(isLoading = true)) {
init {
handleIntents {
when (it) {
NotificationIntent.GetAllData -> getAllData(false)
NotificationIntent.RefreshData -> refreshData()
is NotificationIntent.MarkNotificationAsRead -> markNotificationRead(it)
}
}
}
private fun markNotificationRead(it: NotificationIntent.MarkNotificationAsRead) {
launchViewModelScope {
notificationUseCase.markNotificationAsRead(it.id)
}
}
private fun refreshData() {
emitRefreshingState()
getAllData(true)
}
private fun emitRefreshingState() {
_stateChannel.tryEmit(
stateChannel.value.copy(
isLoading = false,
errorMessage = null,
networkError = null,
isRefreshing = true,
)
)
}
private fun getAllData(isRefreshing: Boolean) {
launchViewModelScope {
if (!isRefreshing) {
emitLoadingState()
}
getNotifications()
}
}
private suspend fun getNotifications() {
val notifications = notificationUseCase.getNotifications()?.distinctUntilChangedBy {
}?.cachedIn(viewModelScope)
_stateChannel.tryEmit(
stateChannel.value.copy(
isLoading = false,
errorMessage = null,
networkError = null,
isRefreshing = false,
notifications = notifications
)
)
}
private fun emitLoadingState() {
_stateChannel.tryEmit(
stateChannel.value.copy(
isLoading = true,
errorMessage = null,
networkError = null,
isRefreshing = false,
)
)
}
} | 0 | Kotlin | 6 | 35 | 309e82d51d6c1c776365643ef48ecb78fd243c23 | 2,623 | MafQud-Android | MIT License |
app/src/main/java/com/mafqud/android/notification/NotificationViewModel.kt | MafQud | 483,257,198 | false | null | package com.mafqud.android.notification
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.cachedIn
import androidx.paging.map
import com.mafqud.android.base.viewModel.BaseViewModel
import com.mafqud.android.notification.models.NotificationsResponse
import com.mafqud.android.util.network.Result
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import javax.inject.Inject
@HiltViewModel
class NotificationViewModel @Inject constructor(private val notificationUseCase: NotificationUseCase) :
BaseViewModel<NotificationIntent, NotificationViewState>(NotificationViewState(isLoading = true)) {
init {
handleIntents {
when (it) {
NotificationIntent.GetAllData -> getAllData(false)
NotificationIntent.RefreshData -> refreshData()
is NotificationIntent.MarkNotificationAsRead -> markNotificationRead(it)
}
}
}
private fun markNotificationRead(it: NotificationIntent.MarkNotificationAsRead) {
launchViewModelScope {
notificationUseCase.markNotificationAsRead(it.id)
}
}
private fun refreshData() {
emitRefreshingState()
getAllData(true)
}
private fun emitRefreshingState() {
_stateChannel.tryEmit(
stateChannel.value.copy(
isLoading = false,
errorMessage = null,
networkError = null,
isRefreshing = true,
)
)
}
private fun getAllData(isRefreshing: Boolean) {
launchViewModelScope {
if (!isRefreshing) {
emitLoadingState()
}
getNotifications()
}
}
private suspend fun getNotifications() {
val notifications = notificationUseCase.getNotifications()?.distinctUntilChangedBy {
}?.cachedIn(viewModelScope)
_stateChannel.tryEmit(
stateChannel.value.copy(
isLoading = false,
errorMessage = null,
networkError = null,
isRefreshing = false,
notifications = notifications
)
)
}
private fun emitLoadingState() {
_stateChannel.tryEmit(
stateChannel.value.copy(
isLoading = true,
errorMessage = null,
networkError = null,
isRefreshing = false,
)
)
}
} | 0 | Kotlin | 6 | 35 | 309e82d51d6c1c776365643ef48ecb78fd243c23 | 2,623 | MafQud-Android | MIT License |
src/test/kotlin/test/tests/extractors/ExtractorTest.kt | gyandroid | 113,510,869 | true | {"Kotlin": 217689, "Shell": 4820, "Groovy": 1445} | // Copyright 2017 Sourcerer Inc. All Rights Reserved.
// Author: <NAME> (<EMAIL>)
package test.tests.extractors
import app.extractors.*
import junit.framework.TestCase.assertTrue
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertEquals
fun assertExtractsLineLibraries(expectedLibrary: String, actualLine: String,
extractor: ExtractorInterface) {
val actualLineLibraries =
extractor.getLineLibraries(actualLine, listOf(expectedLibrary))
assertTrue(expectedLibrary in actualLineLibraries)
}
fun assertExtractsNoLibraries(actualLine: String,
extractor: ExtractorInterface) {
val actualLineLibraries =
extractor.getLineLibraries(actualLine, listOf())
assertEquals(listOf(), actualLineLibraries)
}
fun assertExtractsImport(expectedImport: String, actualLine: String,
extractor: ExtractorInterface) {
val actualLineImport = extractor.extractImports(listOf(actualLine))
assertTrue(expectedImport in actualLineImport)
}
class ExtractorTest : Spek({
given(" code line contains library code" ) {
it("python extractor extracts the library") {
val line = "with tf.Session() as sess"
assertExtractsLineLibraries("tensorflow",
line, PythonExtractor())
}
it("java extractor extracts the library") {
val line = "private JdbcTemplate jdbcTemplate=new JdbcTemplate();"
assertExtractsLineLibraries("org.springframework",
line, JavaExtractor())
}
it("javascript extractor extracts the library") {
val line = "new Vue({"
assertExtractsLineLibraries("vue",
line, JavascriptExtractor())
}
it("ruby extractor extracts the library") {
val line1 = "img = Magick::Image.read_inline(Base64.encode64(image)).first"
assertExtractsLineLibraries("RMagick",
line1, RubyExtractor())
val line2 = "fximages << {image: img.adaptive_threshold(3, 3, 0), name: \"Adaptive Threshold\"}"
assertExtractsLineLibraries("RMagick",
line2, RubyExtractor())
}
it("go extractor extracts the library") {
val line = "if DB, found = revel.Config.String(\"bloggo.db\"); !found {"
assertExtractsLineLibraries("revel",
line, GoExtractor())
}
it("objectiveC extractor extracts the library") {
val line = "[[NSFileManager defaultManager] removeItemAtURL:[RLMRealmConfiguration defaultConfiguration].fileURL error:nil];"
assertExtractsLineLibraries("Realm",
line, ObjectiveCExtractor())
}
it("swift extractor extracts the library") {
val line = "class City: RLMObject {"
assertExtractsLineLibraries("Realm",
line, SwiftExtractor())
}
it("cpp extractor extracts the library") {
val line1 = "leveldb::Options options;"
assertExtractsLineLibraries("leveldb",
line1, CppExtractor())
val line2 = "leveldb::Status status = leveldb::DB::Open(options, \"./testdb\", &tmp);"
assertExtractsLineLibraries("leveldb",
line2, CppExtractor())
}
it("csharp extractor extracts the library") {
val line = "Algorithm = (h, v, i) => new ContrastiveDivergenceLearning(h, v)"
assertExtractsLineLibraries("Accord",
line, CSharpExtractor())
}
it("php extractor extracts the library") {
val line = "public function listRepos(string \$user, int \$limit): Call;"
assertExtractsLineLibraries("Tebru\\Retrofit",
line, PhpExtractor())
}
it("c extractor extracts the library") {
val line = "grpc_test_init(argc, argv);"
assertExtractsLineLibraries("grpc",
line, CExtractor())
}
}
given("code line doesn't use libraries" ) {
it("python extractor returns empty list") {
val line = "from collections import Counter"
assertExtractsNoLibraries(line, PythonExtractor())
}
it("java extractor returns empty list") {
val line = "throw new RuntimeException(e);"
assertExtractsNoLibraries(line, JavaExtractor())
}
it("javascript extractor returns empty list") {
val line = "console.log(self.commits[0].html_url)"
assertExtractsNoLibraries(line, JavascriptExtractor())
}
it("ruby extractor returns empty list") {
val line = "require \"RMagick\""
assertExtractsNoLibraries(line, RubyExtractor())
}
it("go extractor returns empty list") {
val line = "var found bool"
assertExtractsNoLibraries(line, GoExtractor())
}
it("objectivec extractor returns empty list") {
val line = "@end"
assertExtractsNoLibraries(line, ObjectiveCExtractor())
}
it("php extractor returns empty list") {
val line = "<?php"
assertExtractsNoLibraries(line, PhpExtractor())
}
it("swift extractor returns empty list") {
val line = "import Foundation"
assertExtractsNoLibraries(line, SwiftExtractor())
}
it("csharp extractor returns empty list") {
val line = "static void Main(string[] args)"
assertExtractsNoLibraries(line, CSharpExtractor())
}
it("cpp extractor returns empty list") {
val line = "std::cerr << status.ToString() << std::endl;"
assertExtractsNoLibraries(line, CppExtractor())
}
it("c extractor returns empty list") {
val line = "int main(int argc, char **argv) {"
assertExtractsNoLibraries(line, CExtractor())
}
}
given("import name.h") {
it("imports name") {
assertExtractsImport("protobuf", "#include \"protobuf.h\"", CppExtractor())
}
}
given("import library with multiple ways to import") {
it("imports in both cases") {
var lib = "opencv"
val line1 = "#include \"opencv/module/header.h\""
assertExtractsImport(lib, line1, CppExtractor())
val line2 = "#include \"opencv2/module/header.h\""
assertExtractsImport(lib, line2, CppExtractor())
}
}
given("import cv2 or cv") {
it("imports opencv") {
val lib = "opencv"
val line1 = "import cv2"
assertExtractsImport(lib, line1, PythonExtractor())
val line2 = "import cv"
assertExtractsImport(lib, line2, PythonExtractor())
}
}
})
| 0 | Kotlin | 0 | 0 | 0ffa58ea7266a6e9561bde0c71b1611c281acd64 | 7,022 | sourcerer-app | MIT License |
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/UnsupportedGradleVersionIssueChecker.kt | StingNevermore | 113,538,568 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.issue
import com.intellij.build.issue.BuildIssue
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.externalSystem.issue.quickfix.ReimportQuickFix
import org.gradle.util.GradleVersion
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.issue.quickfix.GradleVersionQuickFix
import org.jetbrains.plugins.gradle.issue.quickfix.GradleWrapperSettingsOpenQuickFix
import org.jetbrains.plugins.gradle.jvmcompat.GradleJvmSupportMatrix
import org.jetbrains.plugins.gradle.service.GradleInstallationManager
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionErrorHandler.getRootCauseAndLocation
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper
import org.jetbrains.plugins.gradle.util.GradleBundle
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
import org.jetbrains.plugins.gradle.util.GradleUtil
/**
* Provides the check for errors caused by dropped support in Gradle tooling API of the old Gradle versions
*
* @author Vladislav.Soroka
*/
@ApiStatus.Internal
class UnsupportedGradleVersionIssueChecker : GradleIssueChecker {
override fun check(issueData: GradleIssueData): BuildIssue? {
val rootCause = getRootCauseAndLocation(issueData.error).first
val rootCauseText = rootCause.toString()
var gradleVersion: GradleVersion? = null
if (issueData.error is GradleExecutionHelper.UnsupportedGradleVersionByIdeaException) {
gradleVersion = issueData.error.gradleVersion
}
if (gradleVersion == null && issueData.buildEnvironment != null) {
gradleVersion = GradleVersion.version(issueData.buildEnvironment.gradle.gradleVersion)
}
val isOldGradleClasspathInfererIssue = causedByOldGradleClasspathInferer(rootCause)
val isUnsupportedModelBuilderApi = rootCauseText.endsWith(UNSUPPORTED_MODEL_BUILDER_API_EXCEPTION_TEXT)
val isUnsupportedByIdea = gradleVersion != null && !GradleJvmSupportMatrix.isGradleSupportedByIdea(gradleVersion)
if (isOldGradleClasspathInfererIssue || isUnsupportedModelBuilderApi || isUnsupportedByIdea) {
return UnsupportedGradleVersionIssue(gradleVersion, issueData.projectPath)
}
if (rootCauseText.startsWith(UNSUPPORTED_VERSION_EXCEPTION_MESSAGE_PREFIX)) {
val minimumRequiredGradleVersionCandidateString = rootCauseText.substringAfter(UNSUPPORTED_VERSION_EXCEPTION_MESSAGE_PREFIX)
.substringBefore(" ", "")
val minimumRequiredGradleVersionCandidate = GradleInstallationManager.getGradleVersionSafe(
minimumRequiredGradleVersionCandidateString
)
return UnsupportedGradleVersionIssue(gradleVersion, issueData.projectPath, minimumRequiredGradleVersionCandidate)
}
return null
}
private fun causedByOldGradleClasspathInferer(rootCause: Throwable): Boolean {
val message = rootCause.message ?: return false
if (!message.startsWith("Cannot determine classpath for resource")) return false
return rootCause.stackTrace.find { it.className == "org.gradle.tooling.internal.provider.ClasspathInferer" } != null
}
companion object {
private const val UNSUPPORTED_MODEL_BUILDER_API_EXCEPTION_TEXT =
"does not support the ModelBuilder API. Support for this is available in Gradle 1.2 and all later versions."
private const val UNSUPPORTED_VERSION_EXCEPTION_MESSAGE_PREFIX =
"org.gradle.tooling.UnsupportedVersionException: Support for builds using Gradle versions older than "
}
}
@ApiStatus.Internal
class UnsupportedGradleVersionIssue(
gradleVersion: GradleVersion?,
projectPath: String,
minimumRequiredGradleVersionCandidate: GradleVersion? = null
) : AbstractGradleVersionIssue(gradleVersion, projectPath) {
private val minimumSupportedGradleVersion: GradleVersion =
GradleJvmSupportMatrix.getOldestSupportedGradleVersionByIdea()
override val minimumRequiredGradleVersion: GradleVersion = when {
minimumRequiredGradleVersionCandidate == null -> minimumSupportedGradleVersion
minimumRequiredGradleVersionCandidate < minimumSupportedGradleVersion -> minimumSupportedGradleVersion
else -> minimumRequiredGradleVersionCandidate
}
init {
if (gradleVersion != null) {
setTitle(GradleBundle.message("gradle.build.issue.gradle.unsupported.title", gradleVersion.version, ideVersionName))
addDescription(GradleBundle.message(
"gradle.build.issue.gradle.unsupported.description", gradleVersion.version, ideVersionName,
minimumRequiredGradleVersion.version
))
}
else {
setTitle(GradleBundle.message("gradle.build.issue.gradle.unsupported.title.unknown", ideVersionName))
addDescription(GradleBundle.message(
"gradle.build.issue.gradle.unsupported.description.unknown", ideVersionName,
minimumRequiredGradleVersion.version
))
}
initBuildIssue()
}
}
@ApiStatus.Internal
class DeprecatedGradleVersionIssue(
gradleVersion: GradleVersion,
projectPath: String
) : AbstractGradleVersionIssue(gradleVersion, projectPath) {
override val minimumRequiredGradleVersion: GradleVersion =
GradleJvmSupportMatrix.getOldestRecommendedGradleVersionByIdea()
init {
setTitle(GradleBundle.message("gradle.build.issue.gradle.deprecated.title", gradleVersion.version))
addDescription(GradleBundle.message(
"gradle.build.issue.gradle.deprecated.description", gradleVersion.version, ideVersionName,
minimumRequiredGradleVersion.version
))
initBuildIssue()
}
}
@ApiStatus.Internal
abstract class AbstractGradleVersionIssue(
private val gradleVersion: GradleVersion?,
private val projectPath: String
) : AbstractGradleBuildIssue() {
protected val ideVersionName: String = ApplicationInfoImpl.getShadowInstance().versionName
protected abstract val minimumRequiredGradleVersion: GradleVersion
protected fun initBuildIssue() {
val wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(projectPath)
if (wrapperPropertiesFile == null || (gradleVersion != null && gradleVersion.baseVersion < minimumRequiredGradleVersion)) {
val gradleVersionFix = GradleVersionQuickFix(projectPath, minimumRequiredGradleVersion, true)
addQuickFixPrompt(GradleBundle.message(
"gradle.build.quick.fix.gradle.version.auto", gradleVersionFix.id,
minimumRequiredGradleVersion.version
))
addQuickFix(gradleVersionFix)
}
else {
val wrapperSettingsOpenQuickFix = GradleWrapperSettingsOpenQuickFix(projectPath, "distributionUrl")
val reimportQuickFix = ReimportQuickFix(projectPath, SYSTEM_ID)
addQuickFixPrompt(GradleBundle.message(
"gradle.build.quick.fix.gradle.version.manual", wrapperSettingsOpenQuickFix.id, reimportQuickFix.id,
minimumRequiredGradleVersion.version
))
addQuickFix(wrapperSettingsOpenQuickFix)
addQuickFix(reimportQuickFix)
}
}
}
| 0 | null | 0 | 0 | 68a9dba2e125a7d8ee96ca86e965a30a8ead7e2c | 7,079 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/myapplication/MainActivity.kt | jakobfridesjo | 636,587,336 | false | null | package com.example.myapplication
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.util.Constants
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Get binding of the main activity
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Setup the mini player here to have it accessible from all fragments
val miniPlayerFragment = MiniPlayerFragment()
supportFragmentManager.beginTransaction()
.add(R.id.container_miniplayer, miniPlayerFragment, "fragment_miniplayer")
.commit()
// Bottom nav bar
val navView: BottomNavigationView = binding.navView
navController = findNavController(R.id.nav_host_fragment_activity_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.navigation_map, R.id.navigation_search, R.id.navigation_favorites, R.id.navigation_recordings))
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
// Get permissions
if (ActivityCompat.checkSelfPermission(
this as Context,
Manifest.permission.RECORD_AUDIO
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this as Activity,
arrayOf(Manifest.permission.RECORD_AUDIO),
Constants.RECORD_AUDIO_PERMISSION_REQUEST_CODE
)
return
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.navigation_settings -> {
navController.navigate(R.id.navigation_settings)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
| 0 | Kotlin | 0 | 0 | a72c92adc8cacb6e2cfbf7f98cee79f49c97855a | 3,110 | Waves | MIT License |
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/roguelike_dungeon/RoguelikeSelectAvatarAndEnterDungeonReq.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 1651536} | package org.anime_game_servers.multi_proto.gi.data.activity.roguelike_dungeon
import org.anime_game_servers.core.base.Version.GI_2_2_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
@AddedIn(GI_2_2_0)
@ProtoCommand(REQUEST)
internal interface RoguelikeSelectAvatarAndEnterDungeonReq {
var backstageAvatarGuidList: List<Long>
var onstageAvatarGuidList: List<Long>
var stageId: Int
}
| 0 | Kotlin | 2 | 6 | 7639afe4f546aa5bbd9b4afc9c06c17f9547c588 | 552 | anime-game-multi-proto | MIT License |
samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt | whaleyu | 118,630,368 | true | {"Kotlin": 4482664, "Java": 224447, "Groovy": 11712, "Shell": 1884, "Batchfile": 106} | package net.corda.notarydemo
import net.corda.cordform.CordformContext
import net.corda.cordform.CordformDefinition
import net.corda.cordform.CordformNode
import net.corda.core.identity.CordaX500Name
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.services.config.BFTSMaRtConfiguration
import net.corda.node.services.config.NotaryConfig
import net.corda.node.services.transactions.minCorrectReplicas
import net.corda.nodeapi.internal.DevIdentityGenerator
import net.corda.testing.node.internal.demorun.*
import net.corda.testing.ALICE_NAME
import net.corda.testing.BOB_NAME
import java.nio.file.Paths
fun main(args: Array<String>) = BFTNotaryCordform().deployNodes()
private val clusterSize = 4 // Minimum size that tolerates a faulty replica.
private val notaryNames = createNotaryNames(clusterSize)
// This is not the intended final design for how to use CordformDefinition, please treat this as experimental and DO
// NOT use this as a design to copy.
class BFTNotaryCordform : CordformDefinition() {
private val clusterName = CordaX500Name("BFT", "Zurich", "CH")
init {
nodesDirectory = Paths.get("build", "nodes", "nodesBFT")
node {
name(ALICE_NAME)
p2pPort(10002)
rpcPort(10003)
rpcUsers(notaryDemoUser)
}
node {
name(BOB_NAME)
p2pPort(10005)
rpcPort(10006)
}
val clusterAddresses = (0 until clusterSize).map { NetworkHostAndPort("localhost", 11000 + it * 10) }
fun notaryNode(replicaId: Int, configure: CordformNode.() -> Unit) = node {
name(notaryNames[replicaId])
notary(NotaryConfig(validating = false, bftSMaRt = BFTSMaRtConfiguration(replicaId, clusterAddresses)))
configure()
}
notaryNode(0) {
p2pPort(10009)
rpcPort(10010)
}
notaryNode(1) {
p2pPort(10013)
rpcPort(10014)
}
notaryNode(2) {
p2pPort(10017)
rpcPort(10018)
}
notaryNode(3) {
p2pPort(10021)
rpcPort(10022)
}
}
override fun setup(context: CordformContext) {
DevIdentityGenerator.generateDistributedNotaryCompositeIdentity(
notaryNames.map { context.baseDirectory(it.toString()) },
clusterName,
minCorrectReplicas(clusterSize)
)
}
}
| 0 | Kotlin | 0 | 0 | d00438b86f6ead59321056d864ea7ad820487dab | 2,465 | corda | Apache License 2.0 |
src/test/kotlin/homework/propositional_logic/Chapter2_7.kt | jpgagnebmc | 625,129,199 | false | null | package homework.propositional_logic
import kotlin.test.Test
class Chapter2_7 {
//Prove that α |= β iff α =⇒ β is valid. This is known as the Deduction Theorem.
@Test
fun homework2_7() {
// Formula("α =⇒ β").apply {
// world.print()
// }
}
}
| 0 | Kotlin | 0 | 0 | 087bcc0f908fb71da2e3f0e03fe8066f44797643 | 290 | homework | Apache License 2.0 |
bgw-gui/src/main/kotlin/tools/aqua/bgw/animation/DiceAnimation.kt | tudo-aqua | 377,420,862 | false | null | /*
* Copyright 2021-2023 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package tools.aqua.bgw.animation
import tools.aqua.bgw.components.gamecomponentviews.DiceView
import tools.aqua.bgw.core.DEFAULT_ANIMATION_DURATION
import tools.aqua.bgw.core.DEFAULT_ANIMATION_SPEED
/**
* A dice roll [Animation].
*
* Shuffles through die visuals for given [duration] and shows [toSide] in the end. Use the [speed]
* parameter to define how many steps the animation should have.
*
* For example:
*
* An animation with [duration] = 1s and [speed] = 50 will change the visual 50 times within the
* [duration] of one second.
*
* @constructor Creates a [DiceAnimation] for the given [DiceView].
*
* @param T Generic [DiceView].
* @param dice [DiceView] to animate.
* @property toSide Resulting side after roll.
* @param duration Duration in milliseconds. Default: [DEFAULT_ANIMATION_DURATION].
* @param speed Count of steps. Default: [DEFAULT_ANIMATION_SPEED].
*/
class DiceAnimation<T : DiceView>(
dice: T,
val toSide: Int,
duration: Int = DEFAULT_ANIMATION_DURATION,
speed: Int = DEFAULT_ANIMATION_SPEED
) : SteppedComponentAnimation<T>(gameComponentView = dice, duration = duration, speed = speed)
| 8 | null | 16 | 24 | 266db439e4443d10bc1ec7eb7d9032f29daf6981 | 1,829 | bgw | Apache License 2.0 |
app/src/main/java/com/coupleblog/singleton/CB_SingleSystemMgr.kt | Yumin2019 | 412,790,011 | false | {"Kotlin": 547883, "Java": 37622} | package com.coupleblog.singleton
import android.annotation.SuppressLint
import android.content.Context
import android.widget.Toast
class CB_SingleSystemMgr
{
// enum class for single system
enum class ACTIVITY_TYPE
{
MAIN,
PHOTO_EDTIOR,
VIDEO_CALL,
DAYS_WIDGET,
ACTIVITY_TYPE_END
}
enum class DIALOG_TYPE
{
DATE_PICKER,
// CUSTOM DIALOG
LOADING_DIALOG,
ITEM_LIST_DIALOG,
COMMENT_EDIT_DIALOG,
EDIT_DIALOG,
CHANGE_DIALOG,
WARN_BEHAVIOR_DIALOG,
IMAGE,
STICKER,
// MATERIAL DIALOG CUSTOM
OK_DIALOG,
CONFIRM_DIALOG,
DIALOG_TYPE_END
}
companion object
{
private var isActivity = BooleanArray(ACTIVITY_TYPE.ACTIVITY_TYPE_END.ordinal)
private var isDialog = BooleanArray(DIALOG_TYPE.DIALOG_TYPE_END.ordinal)
private var toast : Toast? = null
private fun isToastMessage() = (toast != null)
fun isActivity(type : ACTIVITY_TYPE) = isActivity[type.ordinal]
fun isDialog(type : DIALOG_TYPE) = isDialog[type.ordinal]
@SuppressLint("ShowToast")
fun showToast(text : CharSequence)
{
if (isToastMessage())
toast?.cancel()
toast = Toast.makeText(CB_AppFunc.application, text, Toast.LENGTH_SHORT)
toast!!.show()
}
@SuppressLint("ShowToast")
fun showToast(context: Context, text : CharSequence)
{
if (isToastMessage())
toast?.cancel()
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)
toast!!.show()
}
@SuppressLint("ShowToast")
fun showToast(resId : Int)
{
if (isToastMessage())
toast?.cancel()
toast = Toast.makeText(CB_AppFunc.application, resId, Toast.LENGTH_SHORT)
toast!!.show()
}
@SuppressLint("ShowToast")
fun showToast(context: Context, resId : Int)
{
if (isToastMessage())
toast?.cancel()
toast = Toast.makeText(context, resId, Toast.LENGTH_SHORT)
toast!!.show()
}
fun registerActivity(type : ACTIVITY_TYPE)
{
if(type == ACTIVITY_TYPE.ACTIVITY_TYPE_END)
return
/* if(isActivity[type.ordinal])
assert(false)*/
isActivity[type.ordinal] = true
}
fun releaseActivity(type : ACTIVITY_TYPE)
{
if(type == ACTIVITY_TYPE.ACTIVITY_TYPE_END)
return
/* if(!isActivity[type.ordinal])
assert(false)*/
isActivity[type.ordinal] = false
}
fun registerDialog(type : DIALOG_TYPE)
{
/* if(isDialog[type.ordinal])
assert(false)*/
isDialog[type.ordinal] = true
}
fun releaseDialog(type : DIALOG_TYPE)
{
/*if(!isDialog[type.ordinal])
assert(false)*/
isDialog[type.ordinal] = false
}
}
} | 1 | Kotlin | 0 | 1 | e4092ca0149a8cf76d3dcb49b54a7abf76d586db | 3,170 | CoupleBlog | MIT License |
app/src/main/java/com/example/calculator/NumberStorage.kt | kire27 | 574,937,556 | false | {"Kotlin": 23805} | package com.example.calculator
import android.widget.Toast
data class NumberStorage(var equation: String = "", var theResult: String = "")
// var firstNumber: String = "",
// var secondNumber: String = "",
// var calculatedNumber: String = "",
// var strongerSymbol: String = "",
// var weakerSymbol: String = "",
// var symbol: String = ""
//) {
// var calculatedResult = {
// if (secondNumber.isNotEmpty()) {
// val sn = secondNumber.toFloat()
// val pn = firstNumber.toFloat()
// when (symbol) {
// "/" -> sn / pn
// "*" -> sn * pn
// "-" -> sn - pn
// "+" -> sn + pn
// else -> "error"
// }
// } else secondNumber + symbol
// }.toString()
//}
| 0 | Kotlin | 0 | 0 | 159c68cab95babd9fa3729fd8038fdc6977a9411 | 801 | Calculator | The Unlicense |
examples/src/main/kotlin/space/kscience/kmath/operations/complexDemo.kt | SciProgCentre | 129,486,382 | false | {"Kotlin": 2003550, "ANTLR": 887} | /*
* Copyright 2018-2022 KMath contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package space.kscience.kmath.operations
import space.kscience.kmath.complex.Complex
import space.kscience.kmath.complex.algebra
import space.kscience.kmath.complex.ndAlgebra
import space.kscience.kmath.nd.BufferND
import space.kscience.kmath.nd.StructureND
import space.kscience.kmath.nd.structureND
fun main() = Complex.algebra {
val complex = 2 + 2 * i
println(complex * 8 - 5 * i)
//flat buffer
val buffer = with(bufferAlgebra) {
buffer(8) { Complex(it, -it) }.map { Complex(it.im, it.re) }
}
println(buffer)
// 2d element
val element: BufferND<Complex> = ndAlgebra.structureND(2, 2) { (i, j) ->
Complex(i - j, i + j)
}
println(element)
// 1d element operation
val result: StructureND<Complex> = ndAlgebra {
val a = structureND(8) { (it) -> i * it - it.toDouble() }
val b = 3
val c = Complex(1.0, 1.0)
(a pow b) + c
}
println(result)
}
| 91 | Kotlin | 55 | 645 | 6c1a5e62bff541cca8065e4ab4c97d02a29d685a | 1,116 | kmath | Apache License 2.0 |
daggie-sample/src/main/java/com/nextfaze/daggie/Activity.kt | NextFaze | 245,320,888 | false | null | package com.nextfaze.daggie
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
abstract class DaggerActivity<I> : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
inject(injector)
super.onCreate(savedInstanceState)
}
protected abstract val injector: I
protected abstract fun inject(injector: I)
}
| 0 | Kotlin | 0 | 0 | 833ff0cb478a03af60cc004f090e8b90bc1d1744 | 381 | daggie | Apache License 2.0 |
messageview/src/main/java/dev/armoury/android/widget/MessageView.kt | filmnet | 520,485,868 | false | null | package dev.armoury.android.widget
import android.animation.Animator
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.IntDef
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.databinding.DataBindingUtil
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import dev.armoury.android.widget.data.INVALID_VALUE
import dev.armoury.android.widget.data.MessageModel
import dev.armoury.android.widget.databinding.ViewMessageBinding
import dev.armoury.android.widget.utils.SimpleAnimatorListener
// TODO Show loading indicator
class MessageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayoutCompat(context, attrs, defStyleAttr) {
private var binding: ViewMessageBinding
private var externalCallbacks : Callbacks? = null
private var animationRepeatCount : Int = LottieDrawable.INFINITE
private var messageModel: MessageModel? = null
// Images
@DrawableRes
private var normalImageRes: Int = INVALID_VALUE
@DrawableRes
private var loadingImageRes: Int = INVALID_VALUE
@DrawableRes
private var errorImageRes: Int = INVALID_VALUE
// Texts
// Titles
private var titleNormal: CharSequence? = null
private var titleLoading: CharSequence? = null
private var titleError: CharSequence? = null
// Descriptions
private var descNormal: CharSequence? = null
private var descLoading: CharSequence? = null
private var descError: CharSequence? = null
// Lottie File Name
private var lottieFileName: String? = null
// Button Text
private var buttonText: String? = null
// Colors
// Titles
private var titleNormalColor = 0xFF_F0_F0_F0.toInt()
private var titleLoadingColor = titleNormalColor
private var titleErrorColor = titleNormalColor
// Descriptions
private var descNormalColor = 0xFF_E9_E9_E9.toInt()
private var descLoadingColor = descNormalColor
private var descErrorColor = descNormalColor
// Button
private var buttonTextColor = 0xFF_FF_FF_FF.toInt()
init {
orientation = VERTICAL
gravity = Gravity.CENTER
binding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.view_message,
this,
true
)
visibility = View.GONE
setAttributes(attrs)
binding.messageView = this
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
binding.animation.cancelAnimation()
}
fun updateState(messageModel: MessageModel?) {
this.messageModel = messageModel
messageModel?.let {
var visibility = View.VISIBLE
var loadingIndicatorVisibility = View.GONE
when (messageModel.state) {
States.NORMAL -> {
updateTextColors(titleNormalColor, descNormalColor)
updateIcon(messageModel.imageRes, normalImageRes)
}
States.LOADING -> {
updateTextColors(titleLoadingColor, descLoadingColor)
updateIcon(messageModel.imageRes, loadingImageRes)
if (loadingImageRes == INVALID_VALUE && lottieFileName.isNullOrEmpty()){
loadingIndicatorVisibility = View.VISIBLE
}
}
States.ERROR -> {
updateTextColors(titleErrorColor, descErrorColor)
updateIcon(messageModel.imageRes, errorImageRes)
}
States.HIDE -> visibility = View.GONE
}
binding.textTitle.updateState(messageModel.titleText, messageModel.titleTextRes)
binding.textDescription.updateState(
messageModel.descriptionText,
messageModel.descriptionTextRes
)
binding.button.updateState(messageModel.buttonText, messageModel.buttonTextRes)
binding.animation.updateState(messageModel.state, lottieFileName)
this.visibility = visibility
binding.progress.visibility = loadingIndicatorVisibility
}
}
fun setCallbacks(externalCallbacks : Callbacks) {
this.externalCallbacks = externalCallbacks
}
fun onClick(view : View) {
when (view.id) {
R.id.button -> externalCallbacks?.onButtonClicked(messageModel = messageModel)
}
}
private fun updateTextColors(titleColor: Int, descriptionColor: Int) {
binding.textTitle.setTextColor(titleColor)
binding.textDescription.setTextColor(descriptionColor)
}
private fun updateIcon(@DrawableRes imageRes: Int, @DrawableRes defaultRes: Int) {
binding.image.updateState(if (imageRes != INVALID_VALUE) imageRes else defaultRes)
}
private fun LottieAnimationView.updateState(@State state: Int, lottieFileName: String?) {
when {
state == States.LOADING &&
lottieFileName != null -> {
visibility = View.VISIBLE
setAnimation(lottieFileName)
repeatCount = animationRepeatCount
binding.animation.addAnimatorListener(object : SimpleAnimatorListener() {
override fun onAnimationEnd(animation: Animator) {
externalCallbacks?.onAnimationEnd()
}
})
binding.animation.addAnimatorUpdateListener { valueAnimator ->
externalCallbacks?.onAnimationProgress(valueAnimator.animatedValue as? Float)
}
playAnimation()
}
else -> visibility = View.GONE
}
}
private fun AppCompatImageView.updateState(@DrawableRes imageRes: Int) {
when (imageRes) {
INVALID_VALUE -> visibility = View.GONE
else -> {
visibility = View.VISIBLE
setImageResource(imageRes)
}
}
}
private fun TextView.updateState(text: CharSequence? = null, textRes: Int = INVALID_VALUE) {
var visibility = View.VISIBLE
when {
text != null -> this.text = text
textRes != INVALID_VALUE -> setText(textRes)
else -> visibility = View.GONE
}
this.visibility = visibility
}
private fun setAttributes(attrs: AttributeSet?) {
attrs?.let {
val a: TypedArray = context.obtainStyledAttributes(it, R.styleable.MessageView)
val indexCount = a.indexCount
@State var state : Int? = null
for (i in 0 until indexCount) {
when (val attr = a.getIndex(i)) {
R.styleable.MessageView_mv_animation_file -> lottieFileName = a.getString(attr)
// Texts
// Titles
R.styleable.MessageView_mv_title_normal -> titleNormal = a.getString(attr)
R.styleable.MessageView_mv_title_loading -> titleLoading = a.getString(attr)
R.styleable.MessageView_mv_title_error -> titleError = a.getString(attr)
// Descriptions
R.styleable.MessageView_mv_desc_normal -> descNormal = a.getString(attr)
R.styleable.MessageView_mv_desc_loading -> descLoading = a.getString(attr)
R.styleable.MessageView_mv_desc_error -> descError = a.getString(attr)
// Button
R.styleable.MessageView_mv_button_text -> buttonText = a.getString(attr)
// Colors
// Titles' Colors
R.styleable.MessageView_mv_title_color_normal ->
titleNormalColor = a.getColor(attr, titleNormalColor)
R.styleable.MessageView_mv_title_color_loading ->
titleLoadingColor = a.getColor(attr, titleLoadingColor)
R.styleable.MessageView_mv_title_color_error ->
titleErrorColor = a.getColor(attr, titleErrorColor)
// Descriptions' Colors
R.styleable.MessageView_mv_desc_color_normal ->
descNormalColor = a.getColor(attr, descNormalColor)
R.styleable.MessageView_mv_desc_color_loading ->
descLoadingColor = a.getColor(attr, descLoadingColor)
R.styleable.MessageView_mv_desc_color_error ->
descErrorColor = a.getColor(attr, descErrorColor)
// Button Text Color
R.styleable.MessageView_mv_button_text_color ->
buttonTextColor = a.getColor(attr, buttonTextColor)
// Icons
R.styleable.MessageView_mv_image_normal ->
normalImageRes = a.getResourceId(attr,
INVALID_VALUE
)
R.styleable.MessageView_mv_image_loading ->
loadingImageRes = a.getResourceId(attr,
INVALID_VALUE
)
R.styleable.MessageView_mv_image_error ->
errorImageRes = a.getResourceId(attr,
INVALID_VALUE
)
// Background
R.styleable.MessageView_mv_button_background ->
binding.button.setBackgroundResource(a.getResourceId(attr,
INVALID_VALUE
))
// Button Customization
R.styleable.MessageView_mv_button_width ->
binding.button.width = a.getDimensionPixelOffset(attr, 100)
R.styleable.MessageView_mv_button_height ->
binding.button.height = a.getDimensionPixelOffset(attr, 40)
// State
R.styleable.MessageView_mv_state -> state = a.getInt(attr, States.HIDE)
// Repeat
R.styleable.MessageView_mv_repeat_animation -> animationRepeatCount = if (a.getBoolean(attr, true)) LottieDrawable.INFINITE else 0
}
}
binding.button.setTextColor(buttonTextColor)
state?.let { updateState(it) }
a.recycle()
}
}
private fun updateState(@State state: Int) {
var visibility = View.VISIBLE
var loadingIndicatorVisibility = View.GONE
when (state) {
States.NORMAL -> {
updateTextColors(titleNormalColor, descNormalColor)
binding.textTitle.updateState(text = titleNormal)
binding.textDescription.updateState(text = descNormal)
binding.image.updateState(normalImageRes)
}
States.LOADING -> {
updateTextColors(titleLoadingColor, descLoadingColor)
if (loadingImageRes == INVALID_VALUE && lottieFileName.isNullOrEmpty()){
loadingIndicatorVisibility = View.VISIBLE
}
binding.textTitle.updateState(text = titleLoading)
binding.textDescription.updateState(text = descLoading)
binding.image.updateState(loadingImageRes)
}
States.ERROR -> {
updateTextColors(titleErrorColor, descErrorColor)
binding.textTitle.updateState(text = titleError)
binding.textDescription.updateState(text = descError)
binding.image.updateState(errorImageRes)
}
States.HIDE -> visibility = View.GONE
}
binding.animation.updateState(state, lottieFileName)
binding.button.updateState() // TODO
this.visibility = visibility
binding.progress.visibility = loadingIndicatorVisibility
}
interface Callbacks {
fun onButtonClicked(messageModel: MessageModel? = null)
fun onAnimationEnd()
fun onAnimationProgress(progress: Float?)
}
open class SimpleCallbacks : Callbacks {
override fun onButtonClicked(messageModel: MessageModel?) {}
override fun onAnimationEnd() {}
override fun onAnimationProgress(progress: Float?) {}
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(States.NORMAL, States.LOADING, States.ERROR, States.HIDE)
annotation class State
class States {
companion object {
const val NORMAL = 0
const val LOADING = 1
const val ERROR = 2
const val HIDE = 3
}
}
} | 1 | Kotlin | 1 | 0 | e6349313f1ecc98eeefb509bc07297715212c5d1 | 13,088 | MessageView | MIT License |
app/src/main/java/com/github/naz013/tasker/task/AddTaskFragment.kt | Vistaus | 178,057,902 | false | null | package com.github.naz013.tasker.task
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import com.github.naz013.tasker.R
import com.github.naz013.tasker.arch.BaseFragment
import com.github.naz013.tasker.data.TaskGroup
import com.github.naz013.tasker.utils.Prefs
import com.mcxiaoke.koi.ext.onClick
import kotlinx.android.synthetic.main.fragment_add.*
import java.lang.Exception
/**
* Copyright 2018 <NAME>
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class AddTaskFragment : BaseFragment() {
private var mGroupId: Int = 0
private var mGroup: TaskGroup? = null
private lateinit var viewModel: AddViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
val safeArgs = AddTaskFragmentArgs.fromBundle(it)
mGroupId = safeArgs.argId
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_add, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fab.onClick { findNavController().navigateUp() }
initViewModel()
if (!Prefs.getInstance(context!!).isCreateBannerShown()) {
closeButton.onClick { hideBanner() }
bannerView.visibility = View.VISIBLE
} else bannerView.visibility = View.GONE
}
private fun hideBanner() {
Prefs.getInstance(context!!).setCreateBannerShown(true)
bannerView.visibility = View.GONE
}
private fun initViewModel() {
viewModel = ViewModelProviders.of(this, AddViewModel.Factory(activity?.application!!, mGroupId)).get(AddViewModel::class.java)
viewModel.data.observe(this, Observer { group -> if (group != null) showGroup(group) })
}
private fun showGroup(group: TaskGroup) {
mGroup = group
groupTitleView.text = group.name
try {
val drawable = groupTitleView.background as GradientDrawable
drawable.setColor(Color.parseColor(group.color))
} catch (e: Exception) {
}
}
override fun onStop() {
super.onStop()
val summary = summaryView.text.toString().trim()
val group = mGroup
if (!TextUtils.isEmpty(summary) && group != null && isRemoving) {
hideKeyboard(summaryView)
viewModel.saveTask(summary, group, favouriteView.isChecked)
}
}
} | 1 | null | 1 | 1 | 4aa8fedf8bed3244ea87699d0933e5ef052b90a6 | 3,391 | my-day-todo | Apache License 2.0 |
lib/src/main/java/me/ertugrul/lib/OnItemReselectedListener.kt | ertugrulkaragoz | 353,617,181 | false | null | package me.ertugrul.lib
interface OnItemReselectedListener {
fun onItemReselect(pos: Int)
}
| 0 | Kotlin | 4 | 78 | ffc8b7b9e4f157437b8fe39e0d8dccd8c5f6fa12 | 97 | SuperBottomBar | MIT License |
src/main/kotlin/dev/jbang/idea/run/JBangRunScriptAction.kt | jbangdev | 439,798,570 | false | {"Kotlin": 99272, "Java": 3691} | package dev.jbang.intellij.plugins.jbang.run
import com.intellij.execution.Executor
import com.intellij.execution.Location
import com.intellij.execution.PsiLocation
import com.intellij.execution.RunManagerEx
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.psi.PsiElement
class JbangRunScriptAction(private val target: PsiElement) : AnAction() {
override fun actionPerformed(event: AnActionEvent) {
val dataContext = SimpleDataContext.getSimpleContext(Location.DATA_KEY, PsiLocation(target), event.dataContext)
val context = ConfigurationContext.getFromContext(dataContext, event.place)
val producer = JbangRunConfigurationProducer()
val configuration = producer.findOrCreateConfigurationFromContext(context)?.configurationSettings ?: return
(context.runManager as RunManagerEx).setTemporaryConfiguration(configuration)
ExecutionUtil.runConfiguration(configuration, Executor.EXECUTOR_EXTENSION_NAME.extensionList.first())
}
} | 27 | Kotlin | 8 | 20 | 4db3b15f18854a2597c52fdd7639ab76cce38ff9 | 1,234 | jbang-idea | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/cognito/CfnLogDeliveryConfiguration.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.cognito
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* The logging parameters of a user pool.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.cognito.*;
* CfnLogDeliveryConfiguration cfnLogDeliveryConfiguration =
* CfnLogDeliveryConfiguration.Builder.create(this, "MyCfnLogDeliveryConfiguration")
* .userPoolId("userPoolId")
* // the properties below are optional
* .logConfigurations(List.of(LogConfigurationProperty.builder()
* .cloudWatchLogsConfiguration(CloudWatchLogsConfigurationProperty.builder()
* .logGroupArn("logGroupArn")
* .build())
* .eventSource("eventSource")
* .logLevel("logLevel")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html)
*/
public open class CfnLogDeliveryConfiguration(
cdkObject: software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration,
) : CfnResource(cdkObject), IInspectable {
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnLogDeliveryConfigurationProps,
) :
this(software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration(scope.let(CloudshiftdevConstructsConstruct::unwrap),
id, props.let(CfnLogDeliveryConfigurationProps::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnLogDeliveryConfigurationProps.Builder.() -> Unit,
) : this(scope, id, CfnLogDeliveryConfigurationProps(props)
)
/**
* A user pool ID, for example `us-east-1_EXAMPLE` .
*/
public open fun attrId(): String = unwrap(this).getAttrId()
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector::unwrap))
}
/**
* The detailed activity logging destination of a user pool.
*/
public open fun logConfigurations(): Any? = unwrap(this).getLogConfigurations()
/**
* The detailed activity logging destination of a user pool.
*/
public open fun logConfigurations(`value`: IResolvable) {
unwrap(this).setLogConfigurations(`value`.let(IResolvable::unwrap))
}
/**
* The detailed activity logging destination of a user pool.
*/
public open fun logConfigurations(`value`: List<Any>) {
unwrap(this).setLogConfigurations(`value`)
}
/**
* The detailed activity logging destination of a user pool.
*/
public open fun logConfigurations(vararg `value`: Any): Unit = logConfigurations(`value`.toList())
/**
* The ID of the user pool where you configured detailed activity logging.
*/
public open fun userPoolId(): String = unwrap(this).getUserPoolId()
/**
* The ID of the user pool where you configured detailed activity logging.
*/
public open fun userPoolId(`value`: String) {
unwrap(this).setUserPoolId(`value`)
}
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.cognito.CfnLogDeliveryConfiguration].
*/
@CdkDslMarker
public interface Builder {
/**
* The detailed activity logging destination of a user pool.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfigurations)
* @param logConfigurations The detailed activity logging destination of a user pool.
*/
public fun logConfigurations(logConfigurations: IResolvable)
/**
* The detailed activity logging destination of a user pool.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfigurations)
* @param logConfigurations The detailed activity logging destination of a user pool.
*/
public fun logConfigurations(logConfigurations: List<Any>)
/**
* The detailed activity logging destination of a user pool.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfigurations)
* @param logConfigurations The detailed activity logging destination of a user pool.
*/
public fun logConfigurations(vararg logConfigurations: Any)
/**
* The ID of the user pool where you configured detailed activity logging.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-userpoolid)
* @param userPoolId The ID of the user pool where you configured detailed activity logging.
*/
public fun userPoolId(userPoolId: String)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.Builder =
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.Builder.create(scope,
id)
/**
* The detailed activity logging destination of a user pool.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfigurations)
* @param logConfigurations The detailed activity logging destination of a user pool.
*/
override fun logConfigurations(logConfigurations: IResolvable) {
cdkBuilder.logConfigurations(logConfigurations.let(IResolvable::unwrap))
}
/**
* The detailed activity logging destination of a user pool.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfigurations)
* @param logConfigurations The detailed activity logging destination of a user pool.
*/
override fun logConfigurations(logConfigurations: List<Any>) {
cdkBuilder.logConfigurations(logConfigurations)
}
/**
* The detailed activity logging destination of a user pool.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfigurations)
* @param logConfigurations The detailed activity logging destination of a user pool.
*/
override fun logConfigurations(vararg logConfigurations: Any): Unit =
logConfigurations(logConfigurations.toList())
/**
* The ID of the user pool where you configured detailed activity logging.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-logdeliveryconfiguration.html#cfn-cognito-logdeliveryconfiguration-userpoolid)
* @param userPoolId The ID of the user pool where you configured detailed activity logging.
*/
override fun userPoolId(userPoolId: String) {
cdkBuilder.userPoolId(userPoolId)
}
public fun build(): software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration =
cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnLogDeliveryConfiguration {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnLogDeliveryConfiguration(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration):
CfnLogDeliveryConfiguration = CfnLogDeliveryConfiguration(cdkObject)
internal fun unwrap(wrapped: CfnLogDeliveryConfiguration):
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration = wrapped.cdkObject as
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration
}
/**
* The CloudWatch logging destination of a user pool detailed activity logging configuration.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.cognito.*;
* CloudWatchLogsConfigurationProperty cloudWatchLogsConfigurationProperty =
* CloudWatchLogsConfigurationProperty.builder()
* .logGroupArn("logGroupArn")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-cloudwatchlogsconfiguration.html)
*/
public interface CloudWatchLogsConfigurationProperty {
/**
* The Amazon Resource Name (arn) of a CloudWatch Logs log group where your user pool sends
* logs.
*
* The log group must not be encrypted with AWS Key Management Service and must be in the same
* AWS account as your user pool.
*
* To send logs to log groups with a resource policy of a size greater than 5120 characters,
* configure a log group with a path that starts with `/aws/vendedlogs` . For more information, see
* [Enabling logging from certain AWS
* services](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-cloudwatchlogsconfiguration.html#cfn-cognito-logdeliveryconfiguration-cloudwatchlogsconfiguration-loggrouparn)
*/
public fun logGroupArn(): String? = unwrap(this).getLogGroupArn()
/**
* A builder for [CloudWatchLogsConfigurationProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param logGroupArn The Amazon Resource Name (arn) of a CloudWatch Logs log group where your
* user pool sends logs.
* The log group must not be encrypted with AWS Key Management Service and must be in the same
* AWS account as your user pool.
*
* To send logs to log groups with a resource policy of a size greater than 5120 characters,
* configure a log group with a path that starts with `/aws/vendedlogs` . For more information,
* see [Enabling logging from certain AWS
* services](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html)
* .
*/
public fun logGroupArn(logGroupArn: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty.Builder
=
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty.builder()
/**
* @param logGroupArn The Amazon Resource Name (arn) of a CloudWatch Logs log group where your
* user pool sends logs.
* The log group must not be encrypted with AWS Key Management Service and must be in the same
* AWS account as your user pool.
*
* To send logs to log groups with a resource policy of a size greater than 5120 characters,
* configure a log group with a path that starts with `/aws/vendedlogs` . For more information,
* see [Enabling logging from certain AWS
* services](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html)
* .
*/
override fun logGroupArn(logGroupArn: String) {
cdkBuilder.logGroupArn(logGroupArn)
}
public fun build():
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty
= cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty,
) : CdkObject(cdkObject), CloudWatchLogsConfigurationProperty {
/**
* The Amazon Resource Name (arn) of a CloudWatch Logs log group where your user pool sends
* logs.
*
* The log group must not be encrypted with AWS Key Management Service and must be in the same
* AWS account as your user pool.
*
* To send logs to log groups with a resource policy of a size greater than 5120 characters,
* configure a log group with a path that starts with `/aws/vendedlogs` . For more information,
* see [Enabling logging from certain AWS
* services](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-cloudwatchlogsconfiguration.html#cfn-cognito-logdeliveryconfiguration-cloudwatchlogsconfiguration-loggrouparn)
*/
override fun logGroupArn(): String? = unwrap(this).getLogGroupArn()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}):
CloudWatchLogsConfigurationProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty):
CloudWatchLogsConfigurationProperty = CdkObjectWrappers.wrap(cdkObject) as?
CloudWatchLogsConfigurationProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: CloudWatchLogsConfigurationProperty):
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty
= (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationProperty
}
}
/**
* The logging parameters of a user pool.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.cognito.*;
* LogConfigurationProperty logConfigurationProperty = LogConfigurationProperty.builder()
* .cloudWatchLogsConfiguration(CloudWatchLogsConfigurationProperty.builder()
* .logGroupArn("logGroupArn")
* .build())
* .eventSource("eventSource")
* .logLevel("logLevel")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html)
*/
public interface LogConfigurationProperty {
/**
* The CloudWatch logging destination of a user pool detailed activity logging configuration.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfiguration-cloudwatchlogsconfiguration)
*/
public fun cloudWatchLogsConfiguration(): Any? = unwrap(this).getCloudWatchLogsConfiguration()
/**
* The source of events that your user pool sends for detailed activity logging.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfiguration-eventsource)
*/
public fun eventSource(): String? = unwrap(this).getEventSource()
/**
* The `errorlevel` selection of logs that a user pool sends for detailed activity logging.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfiguration-loglevel)
*/
public fun logLevel(): String? = unwrap(this).getLogLevel()
/**
* A builder for [LogConfigurationProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param cloudWatchLogsConfiguration The CloudWatch logging destination of a user pool
* detailed activity logging configuration.
*/
public fun cloudWatchLogsConfiguration(cloudWatchLogsConfiguration: IResolvable)
/**
* @param cloudWatchLogsConfiguration The CloudWatch logging destination of a user pool
* detailed activity logging configuration.
*/
public
fun cloudWatchLogsConfiguration(cloudWatchLogsConfiguration: CloudWatchLogsConfigurationProperty)
/**
* @param cloudWatchLogsConfiguration The CloudWatch logging destination of a user pool
* detailed activity logging configuration.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1c72dbd13231f18ec304bbe35965e946d533d687a2d96901fa93fa1a35c6cc0d")
public
fun cloudWatchLogsConfiguration(cloudWatchLogsConfiguration: CloudWatchLogsConfigurationProperty.Builder.() -> Unit)
/**
* @param eventSource The source of events that your user pool sends for detailed activity
* logging.
*/
public fun eventSource(eventSource: String)
/**
* @param logLevel The `errorlevel` selection of logs that a user pool sends for detailed
* activity logging.
*/
public fun logLevel(logLevel: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty.Builder
=
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty.builder()
/**
* @param cloudWatchLogsConfiguration The CloudWatch logging destination of a user pool
* detailed activity logging configuration.
*/
override fun cloudWatchLogsConfiguration(cloudWatchLogsConfiguration: IResolvable) {
cdkBuilder.cloudWatchLogsConfiguration(cloudWatchLogsConfiguration.let(IResolvable::unwrap))
}
/**
* @param cloudWatchLogsConfiguration The CloudWatch logging destination of a user pool
* detailed activity logging configuration.
*/
override
fun cloudWatchLogsConfiguration(cloudWatchLogsConfiguration: CloudWatchLogsConfigurationProperty) {
cdkBuilder.cloudWatchLogsConfiguration(cloudWatchLogsConfiguration.let(CloudWatchLogsConfigurationProperty::unwrap))
}
/**
* @param cloudWatchLogsConfiguration The CloudWatch logging destination of a user pool
* detailed activity logging configuration.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("1c72dbd13231f18ec304bbe35965e946d533d687a2d96901fa93fa1a35c6cc0d")
override
fun cloudWatchLogsConfiguration(cloudWatchLogsConfiguration: CloudWatchLogsConfigurationProperty.Builder.() -> Unit):
Unit =
cloudWatchLogsConfiguration(CloudWatchLogsConfigurationProperty(cloudWatchLogsConfiguration))
/**
* @param eventSource The source of events that your user pool sends for detailed activity
* logging.
*/
override fun eventSource(eventSource: String) {
cdkBuilder.eventSource(eventSource)
}
/**
* @param logLevel The `errorlevel` selection of logs that a user pool sends for detailed
* activity logging.
*/
override fun logLevel(logLevel: String) {
cdkBuilder.logLevel(logLevel)
}
public fun build():
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty
= cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty,
) : CdkObject(cdkObject), LogConfigurationProperty {
/**
* The CloudWatch logging destination of a user pool detailed activity logging configuration.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfiguration-cloudwatchlogsconfiguration)
*/
override fun cloudWatchLogsConfiguration(): Any? =
unwrap(this).getCloudWatchLogsConfiguration()
/**
* The source of events that your user pool sends for detailed activity logging.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfiguration-eventsource)
*/
override fun eventSource(): String? = unwrap(this).getEventSource()
/**
* The `errorlevel` selection of logs that a user pool sends for detailed activity logging.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-logdeliveryconfiguration-logconfiguration.html#cfn-cognito-logdeliveryconfiguration-logconfiguration-loglevel)
*/
override fun logLevel(): String? = unwrap(this).getLogLevel()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): LogConfigurationProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty):
LogConfigurationProperty = CdkObjectWrappers.wrap(cdkObject) as? LogConfigurationProperty
?: Wrapper(cdkObject)
internal fun unwrap(wrapped: LogConfigurationProperty):
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty
= (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.cognito.CfnLogDeliveryConfiguration.LogConfigurationProperty
}
}
}
| 3 | null | 0 | 4 | 8571d0ceb68f09e0c8ce412281fefeb99866fc87 | 23,354 | kotlin-cdk-wrapper | Apache License 2.0 |
app/src/main/java/com/nohjason/momori/component/button/MomoriImageButton.kt | Team-Nojason | 697,189,752 | false | {"Kotlin": 103550} | package com.nohjason.momori.component.button
import android.util.Log
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.nohjason.momori.R
import com.nohjason.momori.component.modifier.mmrClickable
import com.nohjason.momori.util.TAG
@Composable
fun MomoriImageButton(
modifier: Modifier = Modifier,
@DrawableRes iconId: Int,
contentDescription: String = "",
width: Dp = Dp.Unspecified,
height: Dp = Dp.Unspecified,
scale: Float = 1f,
contentScale: ContentScale = ContentScale.Fit,
flipX: Boolean = false,
flipY: Boolean = false,
onClick: () -> Unit,
) {
Box(
modifier = modifier
) {
Image(
painter = painterResource(id = iconId),
contentDescription = contentDescription,
contentScale = contentScale,
modifier = Modifier
.size(width, height)
.scale(scale)
.graphicsLayer(
scaleY = if (flipY) -1f else 1f,
scaleX = if (flipX) -1f else 1f
)
.mmrClickable(
rippleEnable = false
) {
onClick()
}
)
}
}
@Composable
@Preview
fun ImageButtonPreview() {
Row {
MomoriImageButton(iconId = R.drawable.google) {
Log.d(TAG, "IconButtonPreview: Google Image Button")
}
Spacer(modifier = Modifier.padding(horizontal = 10.dp))
MomoriImageButton(iconId = R.drawable.kakao) {
Log.d(TAG, "ImageButtonPreview: Kakao Image Button")
}
Spacer(modifier = Modifier.padding(horizontal = 10.dp))
MomoriImageButton(iconId = R.drawable.naver) {
Log.d(TAG, "ImageButtonPreview: Kakao Image Button")
}
}
}
| 6 | Kotlin | 0 | 0 | c77d15a81b107a9dc089387fa5bedab0cbdef411 | 2,461 | Momori-Android | MIT License |
projects/pathfinder-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/entity/ReferenceData.kt | ministryofjustice | 500,855,647 | false | null | package uk.gov.justice.digital.hmpps.epf.entity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.hibernate.annotations.Immutable
@Entity
@Immutable
@Table(name = "r_standard_reference_list")
class ReferenceData(
@Id
@Column(name = "standard_reference_list_id", nullable = false)
val id: Long,
@Column(name = "code_value", length = 100, nullable = false)
val code: String,
@Column(name = "code_description", length = 500, nullable = false)
val description: String
)
| 4 | Kotlin | 0 | 2 | da4b4d97531c27c44d2391f39778320d88d18ccd | 590 | hmpps-probation-integration-services | MIT License |
app/src/main/java/io/github/gmathi/novellibrary/network/NovelApi_Recents.kt | TechnoJo4 | 249,806,029 | true | {"Kotlin": 582529, "Java": 16521} | package io.github.gmathi.novellibrary.network
import io.github.gmathi.novellibrary.model.RecenlytUpdatedItem
fun NovelApi.getRecentlyUpdatedNovels(): ArrayList<RecenlytUpdatedItem>? {
var searchResults: ArrayList<RecenlytUpdatedItem>? = null
try {
searchResults = ArrayList()
val document = getDocument("https://www.novelupdates.com/")
val elements = document.body()?.getElementsByTag("td")?.filter { it.className().contains("sid") }
if (elements != null)
for (element in elements) {
val item = RecenlytUpdatedItem()
item.novelUrl = element.selectFirst("a[href]")?.attr("abs:href")
item.novelName = element.selectFirst("a[title]")?.attr("title")
item.chapterName = element.selectFirst("a.chp-release")?.text()
item.publisherName = element.selectFirst("span.mob_group > a")?.attr("title")
searchResults.add(item)
}
} catch (e: Exception) {
e.printStackTrace()
}
return searchResults
} | 1 | Kotlin | 1 | 1 | 4a9e1b66c508430b6024319658bb50eb5a313e64 | 1,069 | NovelLibrary | Apache License 2.0 |
shared/src/main/java/xyz/klinker/messenger/shared/service/ReplyService.kt | zacharee | 295,825,167 | false | null | /*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.klinker.messenger.shared.service
import android.app.IntentService
import android.content.Intent
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.RemoteInput
import android.util.Log
import xyz.klinker.messenger.api.implementation.Account
import xyz.klinker.messenger.api.implementation.ApiUtils
import xyz.klinker.messenger.shared.R
import xyz.klinker.messenger.shared.data.DataSource
import xyz.klinker.messenger.shared.data.MimeType
import xyz.klinker.messenger.shared.data.model.Message
import xyz.klinker.messenger.shared.receiver.ConversationListUpdatedReceiver
import xyz.klinker.messenger.shared.receiver.MessageListUpdatedReceiver
import xyz.klinker.messenger.shared.util.*
import xyz.klinker.messenger.shared.widget.MessengerAppWidgetProvider
/**
* Service for getting back voice replies from Android Wear and sending them out.
*/
class ReplyService : IntentService("Reply Service") {
override fun onHandleIntent(intent: Intent?) {
val remoteInput = RemoteInput.getResultsFromIntent(intent)
var reply: String? = null
if (remoteInput != null) {
reply = remoteInput.getCharSequence(EXTRA_REPLY)!!.toString()
}
if (reply == null) {
Log.e(TAG, "could not find attached reply")
return
}
val conversationId = intent?.getLongExtra(EXTRA_CONVERSATION_ID, -1) ?: return
if (conversationId == -1L) {
Log.e(TAG, "could not find attached conversation id")
return
}
val conversation = DataSource.getConversation(this, conversationId) ?: return
val m = Message()
m.conversationId = conversationId
m.type = Message.TYPE_SENDING
m.data = reply
m.timestamp = TimeUtils.now
m.mimeType = MimeType.TEXT_PLAIN
m.read = true
m.seen = true
m.from = null
m.color = null
m.simPhoneNumber = if (conversation.simSubscriptionId != null)
DualSimUtils
.getPhoneNumberFromSimSubscription(conversation.simSubscriptionId!!)
else
null
m.sentDeviceId = if (Account.exists()) java.lang.Long.parseLong(Account.deviceId!!) else -1L
val messageId = DataSource.insertMessage(this, m, conversationId, true)
DataSource.readConversation(this, conversationId)
Log.v(TAG, "sending message \"" + reply + "\" to \"" + conversation.phoneNumbers + "\"")
SendUtils(conversation.simSubscriptionId)
.send(this, reply, conversation.phoneNumbers!!)
// cancel the notification we just replied to or
// if there are no more notifications, cancel the summary as well
val unseenMessages = DataSource.getUnseenMessages(this)
if (unseenMessages.count <= 0) {
try {
NotificationUtils.cancelAll(this)
} catch (e: SecurityException) {
}
} else {
NotificationManagerCompat.from(this).cancel(conversationId.toInt())
}
// if (Settings.dismissNotificationAfterReply) {
// val conversationIdInt = conversationId.toInt()
// val manager = NotificationManagerCompat.from(this)
//
// Thread {
// try {
// Thread.sleep(1000)
// } catch (e: Exception) {
// }
//
// manager.cancel(conversationIdInt)
// }.start()
// }
ApiUtils.dismissNotification(Account.accountId,
Account.deviceId,
conversationId)
unseenMessages.closeSilent()
ConversationListUpdatedReceiver.sendBroadcast(this, conversationId, getString(R.string.you) + ": " + reply, true)
MessageListUpdatedReceiver.sendBroadcast(this, conversationId)
MessengerAppWidgetProvider.refreshWidget(this)
}
companion object {
private val TAG = "ReplyService"
val EXTRA_REPLY = "reply_text"
val EXTRA_CONVERSATION_ID = "conversation_id"
}
}
| 1 | null | 7 | 4 | f957421823801b617194cd68e31ba31b96e6100b | 4,667 | pulse-sms-android | Apache License 2.0 |
src/main/java/lala/di/module/StartViewModule.kt | miguelslemos | 112,460,912 | false | null | package lala.di.module
import dagger.Module
import dagger.Provides
import lala.Navigator
import lala.data.AppDataManager
import lala.ui.start.StartPresenter
/**
* Created by miguellemos on 18/10/17.
*/
@Module
class StartViewModule {
@Provides
fun providerStartPresenter(appDataManager: AppDataManager, navigator: Navigator): StartPresenter {
return StartPresenter(appDataManager, navigator)
}
}
| 1 | Kotlin | 1 | 2 | 31db387ae4557eb55754c6afa986653c79b7c567 | 421 | brazilian-voting-system | Apache License 2.0 |
tray-gtk/src/main/kotlin/com/hristogochev/tray/gtk/components/TrayIcon.kt | hristogochev | 634,594,951 | false | null | package com.hristogochev.tray.gtk.components
import com.hristogochev.tray.gtk.jna.lib.GObject
import com.hristogochev.tray.gtk.jna.lib.Gtk3
import com.hristogochev.tray.gtk.jna.Gtk3Dispatcher
import com.hristogochev.tray.gtk.jna.structs.GEventCallback
import com.hristogochev.tray.gtk.jna.structs.GdkEventButton
import com.hristogochev.tray.gtk.util.toPixBufPointer
import com.sun.jna.Memory
import com.sun.jna.Pointer
import java.awt.image.BufferedImage
/**
* Native GTK tray icon
*/
class TrayIcon {
private var pointer: Pointer? = null
private var callback: GEventCallback? = null
private var imagePixBuf: Pair<Memory, Pointer>? = null
var title: String? = null
set(value) {
field = value
setGtkTitle(value)
}
var imagePath: String? = null
set(value) {
field = value
setGtkImageFromPath(value)
}
var image: BufferedImage? = null
set(value) {
field = value
setGtkImage(value)
}
var visible: Boolean = false
set(value) {
field = value
setGtkVisible(value)
}
var tooltip: String? = null
set(value) {
field = value
setGtkTooltip(value)
}
var menu: Menu? = null
init {
Gtk3Dispatcher.dispatch {
val pointer = Gtk3.gtk_status_icon_new()
this.pointer = pointer
this.callback = object : GEventCallback {
override fun callback(instance: Pointer?, event: GdkEventButton?) {
if (event?.type == 4) {
Gtk3.gtk_menu_popup(
menu?.menuPointer, null, null, Gtk3.gtk_status_icon_position_menu,
pointer, 0, event.time
)
}
}
}
GObject.g_signal_connect_object(pointer, "button_press_event", callback, null, 0)
}
Gtk3Dispatcher.waitAllDispatches()
}
private fun setGtkTitle(title: String?) {
Gtk3Dispatcher.dispatch {
Gtk3.gtk_status_icon_set_title(pointer, title)
}
}
private fun setGtkImage(image: BufferedImage?) {
Gtk3Dispatcher.dispatch {
imagePixBuf = image?.toPixBufPointer()
Gtk3.gtk_status_icon_set_from_pixbuf(pointer, imagePixBuf?.second)
}
}
private fun setGtkImageFromPath(imagePath: String?) {
Gtk3Dispatcher.dispatch {
Gtk3.gtk_status_icon_set_from_file(pointer, imagePath)
}
}
private fun setGtkVisible(visible: Boolean) {
Gtk3Dispatcher.dispatch {
Gtk3.gtk_status_icon_set_visible(pointer, visible)
}
}
private fun setGtkTooltip(tooltip: String?) {
Gtk3Dispatcher.dispatch {
Gtk3.gtk_status_icon_set_tooltip_text(pointer, tooltip)
}
}
fun destroy() {
menu?.destroy()
callback = null
Gtk3.gtk_status_icon_set_visible(pointer, false)
imagePixBuf = null
GObject.g_object_unref(pointer)
pointer = null
}
}
| 0 | null | 0 | 2 | d79710dd9e74ebfa38679914a5d9f78a1ea28483 | 3,170 | tray-gtk | Apache License 2.0 |
test-case-factory/src/test/java/com/barteklipinski/testcasefactory/CombinationsBuildingFlowTest.kt | blipinsk | 439,698,827 | false | null | package com.barteklipinski.testcasefactory
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import strikt.api.Assertion
import strikt.api.expectThat
import strikt.assertions.any
import strikt.assertions.isEqualTo
import strikt.assertions.isNull
@RunWith(JUnit4::class)
class CombinationsBuildingFlowTest {
@Test
fun `exactly builds a single combination`() {
// given
val input = "string_input"
// when
val combinations = combinationsOf { exactly(input) }
// then
expectThat(combinations.size).isEqualTo(1)
expectThat(combinations).containsInput(input)
}
@Test
fun `exactlyOrNull builds a two combinations, one for null`() {
// given
val input = "string_input"
// when
val combinations = combinationsOf { exactlyOrNull(input) }
// then
expectThat(combinations.size).isEqualTo(2)
expectThat(combinations).containsInput(input)
expectThat(combinations).containsNullInput()
}
@Suppress("deprecation")
@Test
fun `anyOf with a single arg builds a single combination`() {
// given
val input = "string_input"
// when
val combinations = combinationsOf { anyOf(input) }
// then
expectThat(combinations.size).isEqualTo(1)
expectThat(combinations).containsInput(input)
}
@Suppress("deprecation")
@Test
fun `anyOfOrNull with a single arg builds a two combinations, one for null`() {
// given
val input = "string_input"
// when
val combinations = combinationsOf { anyOfOrNull(input) }
// then
expectThat(combinations.size).isEqualTo(2)
expectThat(combinations).containsInput(input)
expectThat(combinations).containsNullInput()
}
@Test
fun `anyOf with two args builds a two combinations`() {
// given
val input1 = "first_input"
val input2 = "second_input"
// when
val combinations = combinationsOf { anyOf(input1, input2) }
// then
expectThat(combinations.size).isEqualTo(2)
expectThat(combinations).containsInput(input1)
expectThat(combinations).containsInput(input2)
}
@Test
fun `anyOfOrNull with two args builds builds a three combinations, one for null`() {
// given
val input1 = "first_input"
val input2 = "second_input"
// when
val combinations = combinationsOf { anyOfOrNull(input1, input2) }
// then
expectThat(combinations.size).isEqualTo(3)
expectThat(combinations).containsInput(input1)
expectThat(combinations).containsInput(input2)
expectThat(combinations).containsNullInput()
}
@Test
fun `anyOf with array builds a correct number of combinations`() {
// given
val input1 = "first_input"
val input2 = "second_input"
val input3 = "third_input"
val inputs = arrayOf(input1, input2, input3)
// when
val combinations = combinationsOf { anyOf(inputs) }
// then
expectThat(combinations.size).isEqualTo(3)
expectThat(combinations).containsInput(input1)
expectThat(combinations).containsInput(input2)
expectThat(combinations).containsInput(input3)
}
@Test
fun `anyOfOrNull with array builds a correct number of combinations, one for null`() {
// given
val input1 = "first_input"
val input2 = "second_input"
val input3 = "third_input"
val inputs = arrayOf(input1, input2, input3)
// when
val combinations = combinationsOf { anyOfOrNull(inputs) }
// then
expectThat(combinations.size).isEqualTo(4)
expectThat(combinations).containsInput(input1)
expectThat(combinations).containsInput(input2)
expectThat(combinations).containsInput(input3)
expectThat(combinations).containsNullInput()
}
@Test
fun `anyOf with iterable builds a correct number of combinations`() {
// given
val input1 = "first_input"
val input2 = "second_input"
val input3 = "third_input"
val inputs = listOf(input1, input2, input3)
// when
val combinations = combinationsOf { anyOf(inputs) }
// then
expectThat(combinations.size).isEqualTo(3)
expectThat(combinations).containsInput(input1)
expectThat(combinations).containsInput(input2)
expectThat(combinations).containsInput(input3)
}
@Test
fun `anyOfOrNull with iterable builds a correct number of combinations, one for null`() {
// given
val input1 = "first_input"
val input2 = "second_input"
val input3 = "third_input"
val inputs = listOf(input1, input2, input3)
// when
val combinations = combinationsOf { anyOfOrNull(inputs) }
// then
expectThat(combinations.size).isEqualTo(4)
expectThat(combinations).containsInput(input1)
expectThat(combinations).containsInput(input2)
expectThat(combinations).containsInput(input3)
expectThat(combinations).containsNullInput()
}
@Test
fun `anyBoolean builds a two combinations`() {
// given -> no additional setup
// when
val combinations = combinationsOf { anyBoolean() }
// then
expectThat(combinations.size).isEqualTo(2)
expectThat(combinations).containsInput(true)
expectThat(combinations).containsInput(false)
}
@Test
fun `anyBooleanOrNull builds a three combinations, one for null`() {
// given -> no additional setup
// when
val combinations = combinationsOf { anyBooleanOrNull() }
// then
expectThat(combinations.size).isEqualTo(3)
expectThat(combinations).containsInput(true)
expectThat(combinations).containsInput(false)
expectThat(combinations).containsNullInput()
}
private fun <T : Combination1<A>, A> Assertion.Builder<Array<T>>.containsInput(expected: A) {
get { toList() }.any { get { first }.isEqualTo(expected) }
}
// bonus: this works only for a Combination1 with a nullable arg
private fun <T : Combination1<A?>, A> Assertion.Builder<Array<T>>.containsNullInput() {
get { toList() }.any { get { first }.isNull() }
}
} | 0 | Kotlin | 0 | 3 | 9820d6ed81cfa9cd595a45cd0c600afe89d2d6e1 | 6,459 | test-case-factory | Apache License 2.0 |
app/src/main/java/com/example/compose_clean_base/presentation/login/LoginScreen.kt | samyoney | 783,208,332 | false | {"Kotlin": 136569} | package com.example.compose_clean_base.presentation.login
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.compose_clean_base.R
import com.example.compose_clean_base.app.component.ErrorDialog
import com.example.compose_clean_base.app.component.ExtraLargeSpacer
import com.example.compose_clean_base.app.component.FullScreenLoading
import com.example.compose_clean_base.app.component.Toolbar
import com.example.compose_clean_base.app.theme.dimen20
import com.example.compose_clean_base.app.theme.dimen38
import com.example.compose_clean_base.presentation.login.view.LoginBirthButton
import com.example.compose_clean_base.presentation.login.view.LoginInputField
import com.example.compose_clean_base.presentation.login.view.LoginButton
import com.example.compose_clean_base.provider.mask.NavigationProvider
import com.example.framework.base.LoadingState
import com.ramcosta.composedestinations.annotation.Destination
import kotlinx.coroutines.flow.asStateFlow
@OptIn(ExperimentalComposeUiApi::class)
@Destination(start = true)
@Composable
fun LoginScreen(
viewModel: LoginViewModel = hiltViewModel(),
navigator: NavigationProvider
) {
val uiState by viewModel.uiState.asStateFlow().collectAsState()
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
Scaffold(
topBar = { Toolbar(if (uiState.isRegisterScreen) R.string.register_nav_tab else R.string.login_nav_tab) },
content = { padding ->
val modifier = Modifier
.fillMaxSize()
.padding(padding)
.clickable(
onClick = {
keyboardController?.hide()
focusManager.clearFocus()
},
indication = null,
interactionSource = remember { MutableInteractionSource() }
)
Column(modifier = modifier) {
LoginInputField(
modifier = Modifier.padding(top = dimen38()),
label = stringResource(R.string.username),
value = uiState.username,
onValueChange = { newValue ->
viewModel.onTriggerEvent(
LoginEvent.InputUsername(newValue)
)
},
placeholder = stringResource(R.string.place_holder),
helperText = stringResource(R.string.description),
)
LoginInputField(
modifier = Modifier.padding(top = dimen20()),
label = stringResource(R.string.password),
value = uiState.password,
onValueChange = { newValue ->
viewModel.onTriggerEvent(
LoginEvent.InputPassword(newValue)
)
},
placeholder = stringResource(R.string.place_holder),
helperText = stringResource(R.string.description),
)
if (uiState.isRegisterScreen) {
LoginInputField(
modifier = Modifier.padding(top = dimen20()),
label = stringResource(R.string.name),
value = uiState.name,
onValueChange = { newValue ->
viewModel.onTriggerEvent(
LoginEvent.InputName(newValue)
)
},
placeholder = stringResource(R.string.place_holder),
helperText = stringResource(R.string.description),
)
LoginBirthButton(uiState) { year, month ->
viewModel.onTriggerEvent(LoginEvent.InputBirth(year, month))
}
ExtraLargeSpacer()
LoginButton(stringResource(R.string.register)) {
viewModel.onTriggerEvent(LoginEvent.Register)
}
ExtraLargeSpacer()
LoginButton(stringResource(R.string.back_to_login)) {
viewModel.onTriggerEvent(LoginEvent.ChangeLoginMode)
}
} else {
ExtraLargeSpacer()
LoginButton(stringResource(R.string.login)) {
viewModel.onTriggerEvent(LoginEvent.Login)
}
ExtraLargeSpacer()
LoginButton(stringResource(R.string.go_to_register)) {
viewModel.onTriggerEvent(LoginEvent.ChangeLoginMode)
}
}
}
when (val stateObserver = uiState.loadingState) {
is LoadingState.Loading -> FullScreenLoading()
is LoadingState.Loaded -> {
navigator.openSam()
}
is LoadingState.Error -> {
ErrorDialog(content = stateObserver.mess) {
viewModel.onTriggerEvent(LoginEvent.IdleReturn)
}
}
else -> {}
}
}
)
} | 0 | Kotlin | 0 | 7 | 38ebae18cd04f7533f151885746f8b90cef0099a | 6,102 | compose_clean_base | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.