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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jvm/core/src/main/kotlin/com/intuit/player/jvm/core/plugins/logging/PlayerLoggingConfig.kt | player-ui | 513,673,239 | false | {"TypeScript": 1109550, "Kotlin": 797722, "Swift": 519759, "Starlark": 95966, "JavaScript": 19037, "Ruby": 17488, "Shell": 10073, "MDX": 2336, "Smarty": 660, "C": 104, "Java": 103, "CSS": 31} | package com.intuit.player.jvm.core.plugins.logging
/** Base configuration for [Logging] */
public abstract class PlayerLoggingConfig {
public abstract var name: String
}
| 65 | TypeScript | 29 | 65 | 9a23beae226afaa628d52f50fdda6147d37fc878 | 175 | player | MIT License |
app/src/main/java/com/example/ader/DummyDtdResolver.kt | chinwobble | 161,988,490 | false | null | package com.example.ader
import java.io.ByteArrayInputStream
import org.xml.sax.EntityResolver
import org.xml.sax.InputSource
import org.xml.sax.SAXException
// The EntityResolver prevents the SAX parser from trying to
// download external entities e.g. xhtml1-strict.dtd from
// the referenced URI. Having our own entity resolver makes
// the tests both faster, as they don't need to visit the web;
// and more reliable, as the w3c site returns a HTTP 503 to
// requests for this file from the SAX parser (it loads OK in
// a web browser).
// Thanks to: http://forums.sun.com/thread.jspa?threadID=413937
// for the following code and fix.
class DummyDtdResolver : EntityResolver {
@Throws(SAXException::class, java.io.IOException::class)
override fun resolveEntity(publicId: String, systemId: String): InputSource? {
return if (systemId.endsWith(".dtd")) {
InputSource(ByteArrayInputStream(
"<?xml version='1.0' encoding='UTF-8'?>".toByteArray()))
} else {
null
}
}
}
| 1 | Kotlin | 4 | 2 | 87e6cfd70f0c2560b9c36484435dedcb013c14f2 | 1,053 | mobile-ebook-player | Apache License 2.0 |
src/i_introduction/_7_Nullable_Types/n07NullableTypes.kt | smandy | 151,222,994 | false | null | package i_introduction._7_Nullable_Types
import util.TODO
import util.doc7
fun test() {
val s: String = "this variable cannot store null references"
val q: String? = null
if (q != null) q.length // you have to check to dereference
val i: Int? = q?.length // null
val j: Int = q?.length ?: 0 // 0
}
fun todoTask7(client: Client?, message: String?, mailer: Mailer): Unit {
val email = client?.personalInfo?.email
if(email!= null && message!= null){
mailer.sendMessage(email, message)
}
}
fun sendMessageToClient(
client: Client?, message: String?, mailer: Mailer
) {
todoTask7(client, message, mailer)
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
| 0 | Kotlin | 0 | 0 | 929450b070c8f57423787cf44257957d2fc4036c | 832 | kotlin-koans | MIT License |
banshee-paper/src/main/kotlin/io/github/aecsocket/banshee/paper/Banshee.kt | aecsocket | 625,929,786 | false | null | package io.github.aecsocket.banshee.paper
import com.github.retrooper.packetevents.PacketEvents
import io.github.aecsocket.alexandria.LoggingList
import io.github.aecsocket.alexandria.extension.registerExact
import io.github.aecsocket.alexandria.paper.AlexandriaPlugin
import io.github.aecsocket.alexandria.paper.fallbackLocale
import io.github.aecsocket.alexandria.paper.render.DisplayRenders
import io.github.aecsocket.alexandria.paper.render.Renders
import io.github.aecsocket.alexandria.paper.seralizer.alexandriaPaperSerializers
import io.github.aecsocket.banshee.bansheeApiSerializers
import io.github.aecsocket.glossa.MessageProxy
import io.github.aecsocket.glossa.configurate.LocaleSerializer
import io.github.aecsocket.glossa.messageProxy
import io.github.aecsocket.klam.configurate.klamSerializers
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder
import net.kyori.adventure.serializer.configurate4.ConfigurateComponentSerializer
import net.kyori.adventure.text.format.TextColor
import org.spongepowered.configurate.ConfigurationNode
import org.spongepowered.configurate.ConfigurationOptions
import org.spongepowered.configurate.kotlin.dataClassFieldDiscoverer
import org.spongepowered.configurate.kotlin.extensions.get
import org.spongepowered.configurate.objectmapping.ConfigSerializable
import org.spongepowered.configurate.objectmapping.ObjectMapper
import java.util.*
private lateinit var instance: Banshee
val BansheeAPI get() = instance
class Banshee : AlexandriaPlugin(Manifest("banshee",
accentColor = TextColor.color(0x543deb),
languageResources = listOf(
"lang/en-US.yml",
),
savedResources = listOf(
"settings.yml",
),
)) {
companion object {
@JvmStatic
fun api() = BansheeAPI
}
@ConfigSerializable
data class Settings(
override val defaultLocale: Locale = fallbackLocale,
) : AlexandriaPlugin.Settings
override lateinit var settings: Settings private set
lateinit var messages: MessageProxy<BansheeMessages> private set
lateinit var renders: Renders private set
override val configOptions: ConfigurationOptions = ConfigurationOptions.defaults().serializers { it
.registerAll(ConfigurateComponentSerializer.configurate().serializers())
.registerExact(LocaleSerializer)
.registerAll(klamSerializers)
.registerAll(alexandriaPaperSerializers)
.registerAll(bansheeApiSerializers)
.registerAnnotatedObjects(ObjectMapper.factoryBuilder()
.addDiscoverer(dataClassFieldDiscoverer())
.build()
)
}
init {
instance = this
}
override fun onLoad() {
PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this))
PacketEvents.getAPI().settings
.checkForUpdates(false)
.bStats(true)
PacketEvents.getAPI().load()
super.onLoad()
renders = DisplayRenders(PacketEvents.getAPI())
}
override fun onEnable() {
PacketEvents.getAPI().init()
BansheeCommand(this)
}
override fun loadSettings(node: ConfigurationNode?) {
settings = node?.get() ?: Settings()
}
override fun load(log: LoggingList) {
messages = glossa.messageProxy()
}
}
| 0 | Kotlin | 0 | 0 | fb5b0f5b6be41b624604d23196da85c113af2ddb | 3,295 | banshee | MIT License |
src/nl/rubensten/texifyidea/highlighting/LatexAnnotator.kt | lflobo | 104,448,886 | false | {"Markdown": 1, "Text": 1, "Ignore List": 1, "Java": 162, "Kotlin": 57, "JFlex": 1, "Python": 1, "XML": 2, "HTML": 22} | package nl.rubensten.texifyidea.highlighting
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import nl.rubensten.texifyidea.lang.Environment
import nl.rubensten.texifyidea.psi.*
import nl.rubensten.texifyidea.util.childrenOfType
import nl.rubensten.texifyidea.util.inDirectEnvironmentContext
/**
* @author <NAME>
*/
open class LatexAnnotator : Annotator {
override fun annotate(psiElement: PsiElement, annotationHolder: AnnotationHolder) {
// Comments
if (psiElement is PsiComment) {
annotateComment(psiElement, annotationHolder)
}
else if (psiElement.inDirectEnvironmentContext(Environment.Context.COMMENT)) {
annotateComment(psiElement, annotationHolder)
}
// Math display
else if (psiElement is LatexInlineMath) {
annotateInlineMath(psiElement, annotationHolder)
}
else if (psiElement is LatexDisplayMath) {
annotateDisplayMath(psiElement, annotationHolder)
}
else if (psiElement.inDirectEnvironmentContext(Environment.Context.MATH)) {
annotateDisplayMath(psiElement, annotationHolder)
}
// Optional parameters
else if (psiElement is LatexOptionalParam) {
annotateOptionalParameters(psiElement, annotationHolder)
}
}
/**
* Annotates an inline math element and its children.
*
* All elements will be coloured accoding to [LatexSyntaxHighlighter.INLINE_MATH] and
* all commands that are contained in the math environment get styled with
* [LatexSyntaxHighlighter.COMMAND_MATH_INLINE].
*/
private fun annotateInlineMath(inlineMathElement: LatexInlineMath,
annotationHolder: AnnotationHolder) {
val annotation = annotationHolder.createInfoAnnotation(inlineMathElement, null)
annotation.textAttributes = LatexSyntaxHighlighter.INLINE_MATH
annotateMathCommands(LatexPsiUtil.getAllChildren(inlineMathElement), annotationHolder,
LatexSyntaxHighlighter.COMMAND_MATH_INLINE)
}
/**
* Annotates a display math element and its children.
*
* All elements will be coloured accoding to [LatexSyntaxHighlighter.DISPLAY_MATH] and
* all commands that are contained in the math environment get styled with
* [LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY].
*/
private fun annotateDisplayMath(displayMathElement: PsiElement,
annotationHolder: AnnotationHolder) {
val annotation = annotationHolder.createInfoAnnotation(displayMathElement, null)
annotation.textAttributes = LatexSyntaxHighlighter.DISPLAY_MATH
annotateMathCommands(displayMathElement.childrenOfType(LatexCommands::class), annotationHolder,
LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY)
}
/**
* Annotates the given comment.
*/
private fun annotateComment(comment: PsiElement, annotationHolder: AnnotationHolder) {
val annotation = annotationHolder.createInfoAnnotation(comment, null)
annotation.textAttributes = LatexSyntaxHighlighter.COMMENT
}
/**
* Annotates all command tokens of the comands that are included in the `elements`.
*
* @param elements
* All elements to handle. Only elements that are [LatexCommands] are considered.
* @param highlighter
* The attributes to apply to all command tokens.
*/
private fun annotateMathCommands(elements: Collection<PsiElement>,
annotationHolder: AnnotationHolder,
highlighter: TextAttributesKey) {
for (element in elements) {
if (element !is LatexCommands) {
continue
}
val token = element.commandToken
val annotation = annotationHolder.createInfoAnnotation(token, null)
annotation.textAttributes = highlighter
}
}
/**
* Annotates the given optional parameters of commands.
*/
private fun annotateOptionalParameters(optionalParamElement: LatexOptionalParam,
annotationHolder: AnnotationHolder) {
for (element in optionalParamElement.openGroup.contentList) {
if (element !is LatexContent) {
continue
}
val noMathContent = element.noMathContent ?: continue
val toStyle = noMathContent.normalText ?: continue
val annotation = annotationHolder.createInfoAnnotation(toStyle, null)
annotation.textAttributes = LatexSyntaxHighlighter.OPTIONAL_PARAM
}
}
}
| 1 | null | 1 | 1 | 3038a144a0a3c0769b7d1816ae7f074375e23804 | 4,912 | TeXiFy-IDEA | MIT License |
mobile/src/main/java/com/example/androidthings/lantern/channels/config/WebConfigActivity.kt | nordprojects | 118,455,585 | false | null | package com.example.androidthings.lantern.channels.config
import android.os.Bundle
import com.example.androidthings.lantern.R
import kotlinx.android.synthetic.main.activity_web_config.*
class WebConfigActivity : ChannelConfigActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web_config)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.setNavigationIcon(R.drawable.back_chevron)
setChannelButton.setOnClickListener { updateConfig() }
}
private fun updateConfig() {
config.settings.put("url", editText.text)
config.settings.put("subtitle", "‘${editText.text}’")
finishWithConfigUpdate()
}
}
| 1 | null | 50 | 464 | fa015faa1c9f4f500bc14074a3485750aecf14e1 | 805 | lantern | Apache License 2.0 |
src/test/kotlin/files/NetcdfFileTest.kt | mdklatt | 374,524,231 | false | null | /**
* Unit tests for the NetcdFile module.
*/
package dev.mdklatt.idea.netcdf.files
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Unit tests for the NetdfFileType class.
*/
internal class NetcdfFileTypeTest {
private var type = NetcdfFileType()
/**
* Test the name attribute.
*/
@Test
fun testName() {
assertEquals("netCDF", type.name)
}
/**
* Test the defaultExtension property.
*/
@Test
fun testDefaultExtenstion() {
assertEquals("nc", type.defaultExtension)
}
/**
* Test the icon property.
*/
@Test
fun testIcon() {
assertNotNull(type.icon)
}
/**
* Test the description property.
*/
@Test
fun testDescription() {
assertTrue(type.description.isNotEmpty())
}
/**
* Test the isBinary property.
*/
@Test
fun testIsBinary() {
assertTrue(type.isBinary)
}
}
| 1 | null | 0 | 1 | b3f4109337c2c7024d9ebc9f8683343a401eef45 | 1,030 | idea-netcdf-plugin | Apache License 2.0 |
src/main/kotlin/fm/force/quiz/configuration/properties/QuestionValidationProperties.kt | night-crawler | 207,094,425 | false | null | package fm.force.quiz.configuration.properties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
@Configuration
@ConfigurationProperties(prefix = "force.quiz.validation.question")
class QuestionValidationProperties {
var minTextLength: Int = 5
var maxAnswers: Int = 16
var maxTags: Int = 20
var maxTopics: Int = 20
val textRange get() = minTextLength..Int.MAX_VALUE
val answersRange get() = 1..maxAnswers
val tagsRange get() = 0..maxTags
val topicsRange get() = 0..maxTopics
val helpRange get() = 0..Int.MAX_VALUE
}
| 1 | null | 1 | 7 | 0e34f5ff4cd85f877e739260a6055ada933364e2 | 640 | quiz | MIT License |
app/src/main/java/give/away/good/deeds/di/AppComponents.kt | hitesh-dhamshaniya | 803,497,316 | false | {"Kotlin": 273575} | package give.away.good.deeds.di
import give.away.good.deeds.sharePref.di.sharedPrefModules
import give.away.good.deeds.ui.screens.main.post.postModule
import give.away.good.deeds.ui.screens.main.setting.settingModule
/**
* @author Hitesh
* @version 1.0
* @since July 2023
*/
val appComponent = listOf(
appViewModules,
sharedPrefModules,
settingModule,
postModule
) | 0 | Kotlin | 0 | 0 | 5da593d493a04319b3d53a537d3893ccde9ab47d | 386 | GiveAwayThings_GoodDeed | MIT License |
app/src/main/java/dev/berwyn/jellybox/ui/screens/album/AlbumScreenModel.kt | berwyn | 586,199,884 | false | {"Kotlin": 125751} | package dev.berwyn.jellybox.ui.screens.album
import app.cash.molecule.RecompositionMode
import app.cash.molecule.launchMolecule
import app.cash.sqldelight.coroutines.asFlow
import app.cash.sqldelight.coroutines.mapToList
import app.cash.sqldelight.coroutines.mapToOne
import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import dev.berwyn.jellybox.data.local.Album
import dev.berwyn.jellybox.data.local.Jellybox
import dev.berwyn.jellybox.data.local.Track
import dev.berwyn.jellybox.data.store.AlbumStore
import dev.berwyn.jellybox.data.store.AlbumTrackStore
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.mobilenativefoundation.store.store5.StoreReadRequest
import java.util.UUID
@OptIn(ExperimentalCoroutinesApi::class)
data class AlbumScreenModel(
private val jellybox: Jellybox,
private val albumStore: AlbumStore,
private val trackStore: AlbumTrackStore
) : ScreenModel {
sealed class State {
data object Loading : State()
data class Ready(
val album: Album,
val tracks: ImmutableList<Track>,
) : State()
}
private val _idFlow = MutableSharedFlow<UUID>(replay = 1)
private val _albumFlow = _idFlow.flatMapLatest { id ->
albumStore.stream(StoreReadRequest.cached(id, refresh = true))
.map { it.dataOrNull() }
}
private val _tracksFlow = _albumFlow
.filterNotNull()
.flatMapLatest { album ->
trackStore.stream(StoreReadRequest.cached(album, refresh = true))
.map { response ->
response.dataOrNull()
.orEmpty()
.toImmutableList()
}
}
val state: StateFlow<State> = screenModelScope.launchMolecule(RecompositionMode.Immediate) {
AlbumScreenPresenter(
albumFlow = _albumFlow,
tracksFlow = _tracksFlow,
)
}
fun updateId(id: UUID) {
screenModelScope.launch {
_idFlow.emit(id)
}
}
}
| 0 | Kotlin | 0 | 0 | bd346b82126c6fc7dc9bb78ec35fb4dc7e54135a | 2,510 | jellybox | Apache License 2.0 |
erpc-registry/src/main/java/io/patamon/erpc/registry/zookeeper/ZookeeperRegistry.kt | IceMimosa | 139,144,504 | false | {"Maven POM": 15, "Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 42, "Java": 5, "Protocol Buffer": 1, "XML": 2} | package io.patamon.erpc.registry.zookeeper
import io.patamon.erpc.registry.Registry
import org.I0Itec.zkclient.ZkClient
/**
* Desc: 注册中心 zookeeper 实现
*
* Mail: <EMAIL>
* Created by IceMimosa
* Date: 2018/6/28
*/
class ZookeeperRegistry(
// zookeeper 地址
zkAddress: String = "127.0.0.1:2181"
) : Registry {
/** zk 根目录 */
private val ROOT = "erpc"
/** 初始化 zkClient */
private val zkClient: ZkClient = ZkClient(zkAddress)
/**
* 向注册中心注册服务
*
* [serviceName]: 服务接口的全名名称
* [serverAddress]: 服务提供者的地址
*/
override fun regist(serviceName: String, serverAddress: String): Boolean {
// 创建服务根节点
create("/$ROOT/$serviceName")
// 创建主机节点
return create("/$ROOT/$serviceName/$serverAddress", false)
}
/**
* 服务发现, 返回服务提供者的地址
*/
override fun discover(serviceName: String): String {
val paths = zkClient.getChildren("/$ROOT/$serviceName")
if (paths.isEmpty()) {
throw RuntimeException("No regist server found !!!")
}
// TODO, 默认返回第一个, 需要做负载均衡
return paths[0]
}
/**
* 关闭服务注册对象
*/
override fun close() {
zkClient.close()
}
/**
* 递归创建 zk path
*/
private fun create(path: String, persist: Boolean = true): Boolean {
if (path.isBlank()) {
return false
}
var pathLine = StringBuilder()
path.split("/").filter { it.isNotBlank() }.forEach {
pathLine = pathLine.append("/$it")
if (!zkClient.exists(pathLine.toString())) {
if (persist) {
zkClient.createPersistent(pathLine.toString())
} else {
zkClient.createEphemeral(pathLine.toString())
}
}
}
return true
}
} | 0 | Kotlin | 0 | 2 | 95cff3fb292c2cea091651f251abb6371a27ef1f | 1,854 | Erpc | MIT License |
kotlin-node/src/jsMain/generated/node/vm/ModuleEvaluateOptions.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package node.vm
sealed external interface ModuleEvaluateOptions {
var timeout: Double?
var breakOnSigint: Boolean?
}
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 180 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackHolder.kt | arkon | 127,645,159 | false | null | package eu.kanade.tachiyomi.ui.manga.track
import android.annotation.SuppressLint
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.databinding.TrackItemBinding
import eu.kanade.tachiyomi.util.view.popupMenu
import uy.kohesive.injekt.injectLazy
import java.text.DateFormat
class TrackHolder(private val binding: TrackItemBinding, adapter: TrackAdapter) : RecyclerView.ViewHolder(binding.root) {
private val preferences: PreferencesHelper by injectLazy()
private val dateFormat: DateFormat by lazy {
preferences.dateFormat()
}
private val listener = adapter.rowClickListener
init {
binding.trackSet.setOnClickListener { listener.onSetClick(bindingAdapterPosition) }
binding.trackTitle.setOnClickListener { listener.onSetClick(bindingAdapterPosition) }
binding.trackTitle.setOnLongClickListener {
listener.onTitleLongClick(bindingAdapterPosition)
true
}
binding.trackStatus.setOnClickListener { listener.onStatusClick(bindingAdapterPosition) }
binding.trackChapters.setOnClickListener { listener.onChaptersClick(bindingAdapterPosition) }
binding.trackScore.setOnClickListener { listener.onScoreClick(bindingAdapterPosition) }
}
@SuppressLint("SetTextI18n")
fun bind(item: TrackItem) {
val track = item.track
binding.trackLogo.setImageResource(item.service.getLogo())
binding.logoContainer.setCardBackgroundColor(item.service.getLogoColor())
binding.trackSet.isVisible = track == null
binding.trackTitle.isVisible = track != null
binding.more.isVisible = track != null
binding.middleRow.isVisible = track != null
binding.bottomDivider.isVisible = track != null
binding.bottomRow.isVisible = track != null
binding.card.isVisible = track != null
if (track != null) {
val ctx = binding.trackTitle.context
binding.trackLogo.setOnClickListener {
listener.onOpenInBrowserClick(bindingAdapterPosition)
}
binding.trackTitle.text = track.title
binding.trackChapters.text = track.last_chapter_read.toString()
if (track.total_chapters > 0) {
binding.trackChapters.text = "${binding.trackChapters.text} / ${track.total_chapters}"
}
binding.trackStatus.text = item.service.getStatus(track.status)
val supportsScoring = item.service.getScoreList().isNotEmpty()
if (supportsScoring) {
if (track.score != 0F) {
item.service.getScoreList()
binding.trackScore.text = item.service.displayScore(track)
binding.trackScore.alpha = SET_STATUS_TEXT_ALPHA
} else {
binding.trackScore.text = ctx.getString(R.string.score)
binding.trackScore.alpha = UNSET_STATUS_TEXT_ALPHA
}
}
binding.trackScore.isVisible = supportsScoring
binding.vertDivider2.isVisible = supportsScoring
val supportsReadingDates = item.service.supportsReadingDates
if (supportsReadingDates) {
if (track.started_reading_date != 0L) {
binding.trackStartDate.text = dateFormat.format(track.started_reading_date)
binding.trackStartDate.alpha = SET_STATUS_TEXT_ALPHA
binding.trackStartDate.setOnClickListener {
it.popupMenu(R.menu.track_item_date) {
when (itemId) {
R.id.action_edit -> listener.onStartDateEditClick(bindingAdapterPosition)
R.id.action_remove -> listener.onStartDateRemoveClick(bindingAdapterPosition)
}
}
}
} else {
binding.trackStartDate.text = ctx.getString(R.string.track_started_reading_date)
binding.trackStartDate.alpha = UNSET_STATUS_TEXT_ALPHA
binding.trackStartDate.setOnClickListener {
listener.onStartDateEditClick(bindingAdapterPosition)
}
}
if (track.finished_reading_date != 0L) {
binding.trackFinishDate.text = dateFormat.format(track.finished_reading_date)
binding.trackFinishDate.alpha = SET_STATUS_TEXT_ALPHA
binding.trackFinishDate.setOnClickListener {
it.popupMenu(R.menu.track_item_date) {
when (itemId) {
R.id.action_edit -> listener.onFinishDateEditClick(bindingAdapterPosition)
R.id.action_remove -> listener.onFinishDateRemoveClick(bindingAdapterPosition)
}
}
}
} else {
binding.trackFinishDate.text = ctx.getString(R.string.track_finished_reading_date)
binding.trackFinishDate.alpha = UNSET_STATUS_TEXT_ALPHA
binding.trackFinishDate.setOnClickListener {
listener.onFinishDateEditClick(bindingAdapterPosition)
}
}
}
binding.bottomDivider.isVisible = supportsReadingDates
binding.bottomRow.isVisible = supportsReadingDates
binding.more.setOnClickListener {
it.popupMenu(R.menu.track_item) {
when (itemId) {
R.id.action_open_in_browser -> {
listener.onOpenInBrowserClick(bindingAdapterPosition)
}
R.id.action_remove -> {
listener.onRemoveItemClick(bindingAdapterPosition)
}
}
}
}
}
}
companion object {
private const val SET_STATUS_TEXT_ALPHA = 1F
private const val UNSET_STATUS_TEXT_ALPHA = 0.5F
}
}
| 92 | null | 58 | 9 | 2f07f226b8182699884262ac67139454d5b7070d | 6,332 | tachiyomi | Apache License 2.0 |
src/main/kotlin/entity/SurgeryBooking.kt | SmartOperatingBlock | 602,429,730 | false | null | /*
* Copyright (c) 2023. Smart Operating Block
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package entity
import java.time.LocalDateTime
/**
* A surgery booking for an elective interventions.
* @param surgeryID the id of the surgery.
* @param surgeryType the type of the surgery.
* @param healthcareUserID the tax code of the patient.
* @param healthProfessionalID the id of the health professional.
* @param surgeryDateTime the date time of the surgery.
* @param patientID the id of the patient.
*/
class SurgeryBooking(
val surgeryID: SurgeryID,
val surgeryType: SurgeryType,
val healthcareUserID: HealthcareUserID,
val healthProfessionalID: HealthProfessionalID,
val surgeryDateTime: SurgeryDateTime,
val patientID: PatientID
)
/**
* The id of the surgery.
* @param id the id.
*/
data class SurgeryID(val id: String) {
init {
require(id.isNotEmpty())
}
}
/**
* The type of the surgery.
* @param type the type of the surgery.
*/
data class SurgeryType(val type: String) {
init {
require(type.isNotEmpty())
}
}
/**
* The id of the healthcare user.
* @param id the healthcare user id.
*/
data class HealthcareUserID(val id: String) {
init {
require(id.isNotEmpty())
}
}
/**
* The id of the health professional assigned for the intervention.
* @param id the id of the health professional.
*/
data class HealthProfessionalID(val id: String) {
init {
require(id.isNotEmpty())
}
}
/**
* The id of the patient of the intervention.
* @param id the id of the patient.
*/
data class PatientID(val id: String) {
init {
require(id.isNotEmpty())
}
}
/**
* The date time of the surgery.
* @param date the id of the health professional.
*/
data class SurgeryDateTime(val date: LocalDateTime) {
init {
require(date.isAfter(LocalDateTime.now()))
}
}
| 2 | Kotlin | 0 | 0 | a38226e725e609db91700ab2f98783f1c252f2b5 | 2,004 | surgery-booking-integration-microservice | MIT License |
workflow-runtime/src/commonMain/kotlin/com/squareup/workflow1/RenderWorkflow.kt | square | 268,864,554 | false | null | package com.squareup.workflow1
import com.squareup.workflow1.internal.WorkflowRunner
import com.squareup.workflow1.internal.chained
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart.ATOMIC
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
/**
* Launches the [workflow] in a new coroutine in [scope] and returns a [StateFlow] of its
* [renderings][RenderingT] and [snapshots][Snapshot]. The workflow tree is seeded with
* [initialSnapshot] and the current value value of [props]. Subsequent values emitted from [props]
* will be used to re-render the workflow.
*
* This is the primary low-level entry point into the workflow runtime. If you are writing an app,
* you should probably be using a higher-level entry point that will also let you define UI bindings
* for your renderings.
*
* ## Initialization
*
* When this function is called, the workflow runtime is started immediately, before the function
* even returns. The current value of the [props] [StateFlow] is used to perform the initial render
* pass. The result of this render pass is used to initialize the [StateFlow] of renderings and
* snapshots that is returned.
*
* Once the initial render pass is complete, the workflow runtime will continue executing in a new
* coroutine launched in [scope].
*
* ## Scoping
*
* The workflow runtime makes use of
* [structured concurrency](https://medium.com/@elizarov/structured-concurrency-722d765aa952).
*
* The runtime is started in [scope], which defines the context for the entire workflow tree – most
* importantly, the [Job] that governs the runtime's lifetime and exception
* reporting path, and the [CoroutineDispatcher][kotlinx.coroutines.CoroutineDispatcher] that
* decides on what thread(s) to run workflow code. Note that if the scope's dispatcher executes
* on threads different than the caller, then the initial render pass will occur on the current
* thread but all subsequent render passes, and actions, will be executed on that dispatcher. This
* shouldn't affect well-written workflows, since the render method should not perform side effects
* anyway.
*
* All workers that are run by this runtime will be collected in coroutines that are children of
* [scope]. When the root workflow emits an output, [onOutput] will be invoked in a child of
* [scope].
*
* To stop the workflow runtime, simply cancel [scope]. Any running workers will be cancelled, and
* if [onOutput] is currently running it will be cancelled as well.
*
* ## Error handling
*
* If the initial render pass throws an exception, that exception will be thrown from this function.
* Any exceptions thrown from the runtime (and any workflows or workers) after that will bubble up
* and be handled by [scope] (usually by cancelling it).
*
* Since the [onOutput] function is executed in [scope], any exceptions it throws will also bubble
* up to [scope]. Any exceptions thrown by subscribers of the returned [StateFlow] will _not_ cancel
* [scope] or cancel the runtime, but will be handled in the [CoroutineScope] of the subscriber.
*
* @param workflow
* The root workflow to render.
*
* @param scope
* The [CoroutineScope] in which to launch the workflow runtime. Any exceptions thrown
* in any workflows, after the initial render pass, will be handled by this scope, and cancelling
* this scope will cancel the workflow runtime and any running workers. Note that any dispatcher
* in this scope will _not_ be used to execute the very first render pass.
*
* @param props
* Specifies the initial [PropsT] to use to render the root workflow, and will cause a re-render
* when new props are emitted. If this flow completes _after_ emitting at least one value, the
* runtime will _not_ fail or stop, it will continue running with the last-emitted input.
* To only pass a single props value, simply create a [MutableStateFlow] with the value.
*
* @param initialSnapshot
* If not null or empty, used to restore the workflow. Should be obtained from a previous runtime's
* [RenderingAndSnapshot].
*
* @param interceptors
* An optional list of [WorkflowInterceptor]s that will wrap every workflow rendered by the runtime.
* Interceptors will be invoked in 0-to-`length` order: the interceptor at index 0 will process the
* workflow first, then the interceptor at index 1, etc.
*
* @param onOutput
* A function that will be called whenever the root workflow emits an [OutputT]. This is a suspend
* function, and is invoked synchronously within the runtime: if it suspends, the workflow runtime
* will effectively be paused until it returns. This means that it will propagate backpressure if
* used to forward outputs to a [Flow] or [Channel][kotlinx.coroutines.channels.Channel], for
* example.
*
* @return
* A [StateFlow] of [RenderingAndSnapshot]s that will emit any time the root workflow creates a new
* rendering.
*/
@OptIn(ExperimentalCoroutinesApi::class)
public fun <PropsT, OutputT, RenderingT> renderWorkflowIn(
workflow: Workflow<PropsT, OutputT, RenderingT>,
scope: CoroutineScope,
props: StateFlow<PropsT>,
initialSnapshot: TreeSnapshot? = null,
interceptors: List<WorkflowInterceptor> = emptyList(),
onOutput: suspend (OutputT) -> Unit
): StateFlow<RenderingAndSnapshot<RenderingT>> {
val chainedInterceptor = interceptors.chained()
val runner = WorkflowRunner(scope, workflow, props, initialSnapshot, chainedInterceptor)
// Rendering is synchronous, so we can run the first render pass before launching the runtime
// coroutine to calculate the initial rendering.
val renderingsAndSnapshots = MutableStateFlow(
try {
runner.nextRendering()
} catch (e: Throwable) {
// If any part of the workflow runtime fails, the scope should be cancelled. We're not in a
// coroutine yet however, so if the first render pass fails it won't cancel the runtime,
// but this is an implementation detail so we must cancel the scope manually to keep the
// contract.
val cancellation =
(e as? CancellationException) ?: CancellationException("Workflow runtime failed", e)
runner.cancelRuntime(cancellation)
throw e
}
)
// Launch atomically so the finally block is run even if the scope is cancelled before the
// coroutine starts executing.
scope.launch(start = ATOMIC) {
while (isActive) {
// It might look weird to start by consuming the output before getting the rendering below,
// but remember the first render pass already occurred above, before this coroutine was even
// launched.
val output = runner.nextOutput()
// After receiving an output, the next render pass must be done before emitting that output,
// so that the workflow states appear consistent to observers of the outputs and renderings.
renderingsAndSnapshots.value = runner.nextRendering()
output?.let { onOutput(it.value) }
}
}
return renderingsAndSnapshots
}
| 149 | null | 85 | 773 | d19ae7acbe5897d0f487d292c63e0fbd05e78ded | 7,281 | workflow-kotlin | Apache License 2.0 |
app/src/main/java/com/thecode/cryptomania/core/usecases/IsOnboardingCompleted.kt | gabriel-TheCode | 375,033,948 | false | {"Kotlin": 89192} | package com.thecode.cryptomania.core.usecases
import com.thecode.cryptomania.core.repositories.OnBoardingRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class IsOnboardingCompleted @Inject constructor(
private val repository: OnBoardingRepository
) {
operator fun invoke(): Flow<Boolean> {
return repository.isOnboardingCompleted()
}
}
| 1 | Kotlin | 6 | 26 | c45130092bd4f73b92b47a3eb57b57ba3978dd82 | 384 | CryptoMania | Apache License 2.0 |
domain/src/main/java/app/tivi/domain/observers/ObserveShowImages.kt | chrisbanes | 100,624,553 | false | null | /*
* Copyright 2020 Google LLC
*
* 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 app.tivi.domain.observers
import app.tivi.data.entities.ShowImages
import app.tivi.data.repositories.showimages.ShowImagesStore
import app.tivi.domain.SubjectInteractor
import app.tivi.util.AppCoroutineDispatchers
import com.dropbox.android.external.store4.StoreRequest
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class ObserveShowImages @Inject constructor(
private val store: ShowImagesStore,
dispatchers: AppCoroutineDispatchers
) : SubjectInteractor<ObserveShowImages.Params, ShowImages>() {
override val dispatcher: CoroutineDispatcher = dispatchers.io
override fun createObservable(params: Params): Flow<ShowImages> {
return store.stream(StoreRequest.cached(params.showId, refresh = false))
.map { ShowImages(it.requireData()) }
}
data class Params(val showId: Long)
}
| 39 | null | 780 | 5,603 | bffa49f7c4a61b168317ea59f135699878960bdc | 1,526 | tivi | Apache License 2.0 |
compiler/fir/analysis-tests/testData/resolve/delegatingConstructorCall.kt | JetBrains | 3,432,266 | false | null | fun <K> materialize(): K = null!!
open class A1(val x: String)
class B1 : A1(materialize())
open class A2(val x: Int)
class B2 : A2(1 + 1)
open class A3(x: String, y: String = "") {
constructor(x: String, b: Boolean = true) : this(x, x)
}
class B3_1 : <!OVERLOAD_RESOLUTION_AMBIGUITY!>A3<!>("")
class B3_2 : A3("", "asas")
class B3_3 : A3("", true)
class B3_4 : <!NONE_APPLICABLE!>A3<!>("", Unit)
open class A4(val x: Byte)
class B4 : A4( <!ARGUMENT_TYPE_MISMATCH!>1 + 1<!>)
open class A5 {
constructor(x: Byte)
constructor(x: Short)
}
class B5_1 : <!NONE_APPLICABLE!>A5<!>(1 + 1)
class B5_2 : <!NONE_APPLICABLE!>A5<!>(100 * 2)
| 151 | null | 5478 | 44,267 | 7545472dd3b67d2ac5eb8024054e3e6ff7795bf6 | 647 | kotlin | Apache License 2.0 |
test-suite-kotlin-ksp/src/test/kotlin/io/micronaut/docs/config/converters/MyConfigurationProperties.kt | micronaut-projects | 124,230,204 | false | null | /*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.docs.config.converters
import io.micronaut.context.annotation.ConfigurationProperties
import java.time.LocalDate
// tag::class[]
@ConfigurationProperties(MyConfigurationProperties.PREFIX)
class MyConfigurationProperties {
var updatedAt: LocalDate? = null
protected set
companion object {
const val PREFIX = "myapp"
}
}
// end::class[]
| 753 | null | 1061 | 6,059 | c9144646b31b23bd3c4150dec8ddd519947e55cf | 989 | micronaut-core | Apache License 2.0 |
reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/view/MenuItemAction.kt | Judrummer | 51,418,404 | true | {"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 6, "XML": 27, "Kotlin": 104, "Java": 1} | package com.github.kittinunf.reactiveandroid.view
import android.view.MenuItem
import com.github.kittinunf.reactiveandroid.Action
import com.github.kittinunf.reactiveandroid.rx.addTo
import com.github.kittinunf.reactiveandroid.rx.bindTo
import rx.Subscription
import rx.subscriptions.CompositeSubscription
fun MenuItem.rx_applyAction(action: Action<Unit, *>): Subscription {
val subscriptions = CompositeSubscription()
rx_enabled.bindTo(action.enabled).addTo(subscriptions)
rx_menuItemClick(true).map { Unit }.bindTo(action, Action<Unit, *>::execute).addTo(subscriptions)
return subscriptions
}
| 0 | Kotlin | 0 | 0 | c9a90e31736f3c3a992e48d8a76c9e40c76f767f | 614 | ReactiveAndroid | MIT License |
vgsshow/src/main/java/com/verygoodsecurity/vgsshow/core/network/model/VGSRequest.kt | verygoodsecurity | 306,635,386 | false | {"Kotlin": 262124} | package com.verygoodsecurity.vgsshow.core.network.model
import com.verygoodsecurity.vgsshow.core.network.client.VGSHttpBodyFormat
import com.verygoodsecurity.vgsshow.core.network.client.VGSHttpMethod
import com.verygoodsecurity.vgsshow.core.network.model.data.request.JsonRequestData
import com.verygoodsecurity.vgsshow.core.network.model.data.request.RequestData
import com.verygoodsecurity.vgsshow.core.network.model.data.request.UrlencodedData
private const val DEFAULT_CONNECTION_TIME_OUT = 60000L
/**
* Request definition class for revealing data.
*/
class VGSRequest private constructor(
val path: String,
val method: VGSHttpMethod,
val headers: Map<String, String>?,
val requestFormat: VGSHttpBodyFormat,
val responseFormat: VGSHttpBodyFormat,
val requestTimeoutInterval: Long,
internal val payload: RequestData?,
) {
/**
* Check if payload is valid
*
* @return true if payload valid
*/
fun isPayloadValid(): Boolean = payload?.isValid() == true
/**
* VGSRequest builder helper.
*
* @param path path for a request.
* @param method HTTP method of request. @see [com.verygoodsecurity.vgsshow.core.network.client.VGSHttpMethod]
*/
data class Builder(
private val path: String,
private val method: VGSHttpMethod
) {
private var headers: Map<String, String>? = null
private var requestFormat: VGSHttpBodyFormat = VGSHttpBodyFormat.JSON
private var responseFormat: VGSHttpBodyFormat = VGSHttpBodyFormat.JSON
private var payload: RequestData? = null
private var requestTimeoutInterval: Long = DEFAULT_CONNECTION_TIME_OUT
/**
* List of headers that will be added to this request.
*
* @param headers key-value headers store, where key - header name and value - header value.
* (ex. key = "Authorization", value = "authorization_token")
*/
fun headers(headers: Map<String, String>) = apply { this.headers = headers }
/**
* Body that will send with this request.
*
*/
fun body(payload: Map<String, Any>?): Builder = apply {
this.payload = if (payload != null) JsonRequestData(payload) else null
}
/**
* Body that will send with this request.
*
*/
fun body(payload: String, format: VGSHttpBodyFormat): Builder = apply {
this.requestFormat = format
this.responseFormat = format
this.payload = when (format) {
VGSHttpBodyFormat.JSON -> JsonRequestData(payload)
VGSHttpBodyFormat.X_WWW_FORM_URLENCODED -> UrlencodedData(payload)
}
}
/**
* Specifies expected response body format.
*
* @param format @see [com.verygoodsecurity.vgsshow.core.network.client.VGSHttpBodyFormat]
*/
fun responseFormat(format: VGSHttpBodyFormat) = apply { this.responseFormat = format }
/**
* Specifies request timeout interval in milliseconds.
*
* @param timeout interval in milliseconds.
*/
fun requestTimeoutInterval(timeout: Long) = apply { this.requestTimeoutInterval = timeout }
/**
* Build VGSRequest object.
*
* @return configured VGSRequest.
*/
fun build() = VGSRequest(
path,
method,
headers,
requestFormat,
responseFormat,
requestTimeoutInterval,
payload
)
}
} | 5 | Kotlin | 8 | 8 | e1496feaf2a6f552fcbd55de947958f1164b15cc | 3,608 | vgs-show-android | MIT License |
core/main/kotlin/me/kgustave/dkt/core/internal/websocket/CloseCancellationException.kt | Shengaero | 151,363,236 | false | null | /*
* Copyright 2018 <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.
*/
@file:Suppress("MemberVisibilityCanBePrivate")
package me.kgustave.dkt.core.internal.websocket
import io.ktor.http.cio.websocket.CloseReason
import kotlinx.coroutines.CancellationException
class CloseCancellationException(val reason: CloseReason): CancellationException() {
override val message: String get() = reason.message
val code get() = reason.code
}
| 1 | Kotlin | 0 | 10 | 745f72c59ed8e331975f0f62057f8f09fb9722fc | 957 | discord.kt | Apache License 2.0 |
screens/location-weather/screen/implementation/src/main/kotlin/aa/weather/screens/weather/kernel/PluginManager.kt | marwinxxii | 608,084,351 | false | null | package aa.weather.screens.weather.kernel
import aa.weather.screens.location.plugin.api.PluginRenderer
import aa.weather.screens.location.plugin.api.PluginUIStateProvider
import aa.weather.screens.location.plugin.api.UIModel
internal interface PluginManager {
val stateProviders: List<Pair<PluginKey, PluginUIStateProvider>>
fun getOrCreateRenderer(pluginKey: PluginKey): PluginRenderer<UIModel>
}
internal typealias PluginKey = Any
| 0 | Kotlin | 0 | 0 | 9d056070987da45ca1bf496f98ca54c8c5cfef97 | 445 | weather-app | Apache License 2.0 |
src/main/kotlin/com/foxentry/foxentrysdk/models/Error400RequestBodyNotJson.kt | Foxentry | 830,077,226 | false | {"Kotlin": 442689} | /**
* Foxentry API reference
*
* The version of the OpenAPI document: 2.0 Contact: <EMAIL>
*
* NOTE: This file is auto generated. Do not edit the file manually.
*/
package com.foxentry.foxentrysdk.models
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.foxentry.foxentrysdk.core.*
@JsonDeserialize(`as` = Error400RequestBodyNotJsonImpl::class)
interface Error400RequestBodyNotJson {
val group: Error400RequestBodyNotJsonGroup?
val type: Error400RequestBodyNotJsonType?
val subtype: Error400RequestBodyNotJsonSubtype?
val severity: Error400RequestBodyNotJsonSeverity?
val relatedTo: List<String?>?
val description: Error400RequestBodyNotJsonDescription?
}
data class Error400RequestBodyNotJsonImpl(
override val group: Error400RequestBodyNotJsonGroup?,
override val type: Error400RequestBodyNotJsonType?,
override val subtype: Error400RequestBodyNotJsonSubtype?,
override val severity: Error400RequestBodyNotJsonSeverity?,
override val relatedTo: List<String?>?,
override val description: Error400RequestBodyNotJsonDescription?,
) : Error400RequestBodyNotJson
/** Group of error. */
enum class Error400RequestBodyNotJsonGroup(@JsonValue val value: String) {
REQUEST("REQUEST"),
}
/** Type of error. */
enum class Error400RequestBodyNotJsonType(@JsonValue val value: String) {
BODY("BODY"),
}
/** Subtype of error. */
enum class Error400RequestBodyNotJsonSubtype(@JsonValue val value: String) {
NOT_JSON("NOT_JSON"),
}
/**
* Severity of error. <b>Info</b> = cosmetic changes that don't change the overall meaning.
* <b>Warning</b> = typos and other errors that could affect the meaning. <b>Critical</b> = critical
* errors.
*/
enum class Error400RequestBodyNotJsonSeverity(@JsonValue val value: String) {
CRITICAL("critical"),
}
/** Description of error. */
enum class Error400RequestBodyNotJsonDescription(@JsonValue val value: String) {
CANNOT_PROCESS_THE_REQUEST_BECAUSE_THE_JSON_IS_NOT_VALID_PLEASE_CHECK_FOXENTRY_DEV_FOR_MORE_INFORMATION_(
"Cannot process the request because the JSON is not valid. Please check Foxentry.dev for more information."),
}
| 0 | Kotlin | 0 | 0 | 8b215f6df68bd39c86ca0d44689e55704cc39457 | 2,197 | kotlin-sdk | MIT License |
src/main/kotlin/viewmodel/MainScreenViewModel.kt | spbu-coding-2023 | 790,907,560 | false | {"Kotlin": 24284} | package viewmodel
import androidx.compose.ui.graphics.Color
import layouts.YifanHuPlacementStrategy
import graphs.primitives.Graph
import viewmodel.graph.GraphViewModel
class MainScreenViewModel<V, E>(var graph: Graph<V, E>) {
private val representationStrategy = YifanHuPlacementStrategy()
var graphViewModel = GraphViewModel(graph)
fun runLayoutAlgorithm(cords: Pair<Int, Int>) {
representationStrategy.place(cords.first.toDouble(), cords.second.toDouble(), graphViewModel)
}
fun updateOnResize(old: Pair<Int, Int>, new: Pair<Int, Int>) {
representationStrategy.move(old, new, graphViewModel.vertices)
}
fun restoreGraphState() {
graphViewModel.edges.forEach { e ->
e.color = Color.Black
e.width = 1f
}
graphViewModel.vertices.forEach { v ->
v.color = Color.Gray
}
graphViewModel.pickedVertices.clear()
}
}
| 6 | Kotlin | 0 | 1 | f05c7c519c736f46d9e16e90487eb445e8d09d90 | 938 | graphs-graph-10 | MIT License |
forge/src/main/kotlin/game/LuckyBlockItem.kt | alexsocha | 181,845,813 | false | {"Kotlin": 432247, "Dockerfile": 861, "JavaScript": 402, "Shell": 114} | package mod.lucky.forge.game
import mod.lucky.forge.*
import mod.lucky.java.game.LuckyItemValues
import net.minecraft.core.NonNullList
import net.minecraft.world.item.BlockItem
import net.minecraft.world.item.CreativeModeTab
import net.minecraft.world.item.TooltipFlag
class LuckyBlockItem(block: MCBlock) : BlockItem(
block,
Properties()
) {
@OnlyInClient
override fun appendHoverText(stack: MCItemStack, world: MCWorld?, tooltip: MutableList<MCChatComponent>, context: TooltipFlag) {
tooltip.addAll(createLuckyTooltip(stack))
}
}
| 23 | Kotlin | 19 | 32 | 173133a6933c6a57aacf6426d148cf133e14a5ac | 562 | luckyblock | FSF All Permissive License |
module_bookshelf/src/main/kotlin/com/crow/module_bookshelf/ui/adapter/BookshelfComicRvAdapter.kt | CrowForKotlin | 610,636,509 | false | null | package com.crow.module_bookshelf.ui.adapter
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import com.bumptech.glide.GenericTransitionOptions
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.request.transition.DrawableCrossFadeTransition
import com.bumptech.glide.request.transition.NoTransition
import com.crow.base.copymanga.appComicCardHeight
import com.crow.base.copymanga.appComicCardWidth
import com.crow.base.copymanga.appDp10
import com.crow.base.copymanga.glide.AppGlideProgressFactory
import com.crow.base.tools.extensions.BASE_ANIM_200L
import com.crow.base.tools.extensions.doOnClickInterval
import com.crow.base.ui.adapter.BaseGlideLoadingViewHolder
import com.crow.module_bookshelf.databinding.BookshelfFragmentRvBinding
import com.crow.module_bookshelf.model.resp.bookshelf_comic.BookshelfComicResults
class BookshelfComicRvAdapter(
inline val doOnTap: (BookshelfComicResults) -> Unit
) : PagingDataAdapter<BookshelfComicResults, BookshelfComicRvAdapter.LoadingViewHolder>(DiffCallback()) {
class DiffCallback: DiffUtil.ItemCallback<BookshelfComicResults>() {
override fun areItemsTheSame(oldItem: BookshelfComicResults, newItem: BookshelfComicResults): Boolean {
return oldItem.mUuid == newItem.mUuid
}
override fun areContentsTheSame(oldItem: BookshelfComicResults, newItem: BookshelfComicResults): Boolean {
return oldItem == newItem
}
}
inner class LoadingViewHolder(binding: BookshelfFragmentRvBinding) : BaseGlideLoadingViewHolder<BookshelfFragmentRvBinding>(binding)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LoadingViewHolder {
return LoadingViewHolder(BookshelfFragmentRvBinding.inflate(LayoutInflater.from(parent.context), parent,false)).also { vh ->
val layoutParams = vh.binding.bookshelfRvImage.layoutParams
layoutParams.width = appComicCardWidth - appDp10
layoutParams.height = appComicCardHeight
vh.binding.bookshelfRvImage.doOnClickInterval {
doOnTap(getItem(vh.absoluteAdapterPosition) ?: return@doOnClickInterval)
}
}
}
override fun onBindViewHolder(vh: LoadingViewHolder, position: Int) {
val item = getItem(position) ?: return
vh.binding.bookshelfRvLoading.isVisible = true
vh.binding.bookshelfRvProgressText.isVisible = true
vh.binding.bookshelfRvProgressText.text = AppGlideProgressFactory.PERCENT_0
vh.mAppGlideProgressFactory?.doRemoveListener()?.doClean()
vh.mAppGlideProgressFactory = AppGlideProgressFactory.createGlideProgressListener(item.mComic.mCover) { _, _, percentage, _, _ ->
vh.binding.bookshelfRvProgressText.text = AppGlideProgressFactory.getProgressString(percentage)
}
Glide.with(vh.itemView.context)
.load(item.mComic.mCover)
.listener(vh.mAppGlideProgressFactory?.getRequestListener())
.transition(GenericTransitionOptions<Drawable>().transition { dataSource, _ ->
if (dataSource == DataSource.REMOTE) {
vh.binding.bookshelfRvLoading.isInvisible = true
vh.binding.bookshelfRvProgressText.isInvisible = true
DrawableCrossFadeTransition(BASE_ANIM_200L.toInt(), true)
} else {
vh.binding.bookshelfRvLoading.isInvisible = true
vh.binding.bookshelfRvProgressText.isInvisible = true
NoTransition()
}
})
.into(vh.binding.bookshelfRvImage)
vh.binding.bookshelfRvName.text = item.mComic.mName
vh.binding.bookshelfRvTime.text = item.mComic.mDatetimeUpdated
}
} | 8 | null | 5 | 76 | 3b64f3bc7ef0f8014e9311f1c69515ecba83ebfc | 4,015 | CopyMangaX | Apache License 2.0 |
src/main/kotlin/ru/yoomoney/tech/grafana/dsl/metrics/MetricsBuilder.kt | yoomoney | 158,901,967 | false | null | package ru.yoomoney.tech.grafana.dsl.metrics
import ru.yoomoney.tech.grafana.dsl.DashboardElement
import ru.yoomoney.tech.grafana.dsl.datasource.Datasource
import ru.yoomoney.tech.grafana.dsl.datasource.ZabbixDatasource
import ru.yoomoney.tech.grafana.dsl.metrics.functions.Alias
import ru.yoomoney.tech.grafana.dsl.metrics.prometheus.PrometheusMetric
import ru.yoomoney.tech.grafana.dsl.panels.graph.display.seriesoverrides.SeriesOverride
import ru.yoomoney.tech.grafana.dsl.panels.graph.display.seriesoverrides.SeriesOverrideBuilder
@DashboardElement
class MetricsBuilder<DatasourceT : Datasource> {
val metrics = mutableListOf<DashboardMetric>()
internal val seriesOverrides: MutableList<SeriesOverride> = mutableListOf()
private val metricIdGenerator by lazy { MetricIdGenerator() }
fun metric(referenceId: String? = null, hidden: Boolean = false, fn: () -> Metric) {
metrics += ReferencedDashboardMetric(fn(), referenceId ?: generateMetricId(), hidden)
}
fun prometheusMetric(
legendFormat: String? = null,
instant: Boolean = false,
referenceId: String? = null,
hidden: Boolean = false,
fn: () -> PrometheusMetric
) {
metrics += PromQlMetric(fn(), legendFormat, instant, referenceId, hidden)
}
private fun generateMetricId(): String {
var generatedId: String
do {
generatedId = metricIdGenerator.nextMetricId()
} while (metrics.map { (it as ReferencedDashboardMetric).id }.contains(generatedId))
return generatedId
}
fun MetricsBuilder<out ZabbixDatasource>.metricsQuery(build: ZabbixMetric.Builder.Metric.() -> Unit = {}) {
val builder = ZabbixMetric.Builder.Metric()
builder.build()
metrics += builder.createMetric()
}
fun MetricsBuilder<out ZabbixDatasource>.textQuery(build: ZabbixMetric.Builder.Text.() -> Unit = {}) {
val builder = ZabbixMetric.Builder.Text()
builder.build()
metrics += builder.createText()
}
infix fun Alias.override(build: SeriesOverrideBuilder.() -> Unit): Alias {
val builder = SeriesOverrideBuilder(this.aliasName)
builder.build()
seriesOverrides += builder.createSeriesOverride()
return this
}
}
| 2 | null | 8 | 53 | 58ab4e2e70e544c4160b97b4dc64e73235a4bd00 | 2,283 | grafana-dashboard-dsl | MIT License |
app/src/main/java/Screen/HomeWorks.kt | LaithAltawil | 832,563,925 | false | {"Kotlin": 88189} | package Screen
import Screen.commons.mainmenuitems
import androidx.compose.foundation.layout.Arrangement
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.example.apptryout.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeWorks(navController: NavController) {
val mainmenuitem = listOf(
mainmenuitems("Maths", painterResource(id = R.drawable.math)) { },
mainmenuitems("Science", painterResource(id = R.drawable.science)) { },
mainmenuitems("English", painterResource(id = R.drawable.english)) { },
mainmenuitems("History", painterResource(id = R.drawable.history)) {},
mainmenuitems("Arabic", painterResource(id = R.drawable.arabic)) {},
mainmenuitems("Geography", painterResource(id = R.drawable.geography)) {}
)
Surface(
modifier = Modifier
.fillMaxWidth()
.fillMaxSize(), color = colorResource(id = R.color.color_secondary)
) {
Scaffold(
containerColor = colorResource(id = R.color.color_secondary),
topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = colorResource(id = R.color.color_secondary),
titleContentColor = colorResource(id = R.color.color_light),
),
title = {
Text("Homeworks")
},
navigationIcon = {
IconButton(onClick = { navController.popBackStack()}) {
Icon(
modifier = Modifier.size(50.dp),
imageVector = Icons.AutoMirrored.Default.ArrowBack,
contentDescription = "Localized description",
tint = colorResource(id = R.color.color_light)
)
}
},
)
},
// Add content padding
) { innerPadding ->
Column(
modifier = Modifier.padding(innerPadding),
horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally
) {
LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 128.dp)) {
items(mainmenuitem) { item ->
Card(
onClick = {}, modifier = Modifier
.padding(16.dp)
.size(200.dp)
.width(100.dp)
) {
Column(
modifier = Modifier
.padding(16.dp)
.wrapContentSize(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(painter = item.ImagePath, contentDescription = "")
Text(
text = item.name,
fontSize = 20.sp,
color = Color.White,
textAlign = TextAlign.Center
)
}
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 1 | fd423ce75ddb40875b231bc1b65e652c1554ef74 | 5,046 | SchoolAppUI | MIT License |
src/main/kotlin/com/github/kory33/kalgebra/structures/instances/monoid/StringMonoid.kt | kory33 | 135,460,140 | false | null | package com.github.kory33.kalgebra.structures.instances.monoid
import com.github.kory33.kalgebra.operations.MonoidOperation
import com.github.kory33.kalgebra.structures.Monoid
import com.github.kory33.kalgebra.structures.ProductComposable
class StringMonoid(value: String): Monoid<String, StringMonoid>(value), ProductComposable<StringMonoid> {
override val operation = StringMonoid
override fun lift(value: String) = StringMonoid(value)
companion object: MonoidOperation<String> {
override fun invoke(p1: String, p2: String) = p1 + p2
override val identity = ""
}
}
| 0 | Kotlin | 0 | 2 | ae2420a27ef848c13fd5728d6c5cfeae3901f905 | 604 | Kalgebra | MIT License |
plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.kt | JetBrains | 2,489,216 | 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 org.jetbrains.plugins.github
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
internal class GithubShareAction : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
e.presentation.isEnabledAndVisible = project != null && !project.isDefault && project.isTrusted()
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
if (project == null || project.isDisposed) {
return
}
GHShareProjectUtil.shareProjectOnGithub(project, file)
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,070 | intellij-community | Apache License 2.0 |
sphinx/application/network/concepts/queries/concept-network-query-lightning/src/main/java/chat/sphinx/concept_network_query_lightning/NetworkQueryLightning.kt | kevkevinpal | 385,406,512 | true | {"Kotlin": 1368824, "Java": 357402, "JavaScript": 4745, "Shell": 2453} | package chat.sphinx.concept_network_query_lightning
import chat.sphinx.concept_network_query_lightning.model.balance.BalanceAllDto
import chat.sphinx.concept_network_query_lightning.model.balance.BalanceDto
import chat.sphinx.concept_network_query_lightning.model.channel.ChannelsDto
import chat.sphinx.concept_network_query_lightning.model.invoice.InvoicesDto
import chat.sphinx.concept_network_query_lightning.model.route.RouteSuccessProbabilityDto
import chat.sphinx.kotlin_response.LoadResponse
import chat.sphinx.kotlin_response.ResponseError
import chat.sphinx.wrapper_common.dashboard.ChatId
import chat.sphinx.wrapper_common.lightning.LightningNodePubKey
import chat.sphinx.wrapper_common.lightning.LightningRouteHint
import chat.sphinx.wrapper_relay.AuthorizationToken
import chat.sphinx.wrapper_relay.RelayUrl
import kotlinx.coroutines.flow.Flow
abstract class NetworkQueryLightning {
///////////
/// GET ///
///////////
abstract fun getInvoices(
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<InvoicesDto, ResponseError>>
abstract fun getChannels(
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<ChannelsDto, ResponseError>>
abstract fun getBalance(
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<BalanceDto, ResponseError>>
abstract fun getBalanceAll(
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<BalanceAllDto, ResponseError>>
abstract fun checkRoute(
publicKey: LightningNodePubKey,
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<RouteSuccessProbabilityDto, ResponseError>>
abstract fun checkRoute(
publicKey: LightningNodePubKey,
routeHint: LightningRouteHint,
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<RouteSuccessProbabilityDto, ResponseError>>
abstract fun checkRoute(
chatId: ChatId,
relayData: Pair<AuthorizationToken, RelayUrl>? = null
): Flow<LoadResponse<RouteSuccessProbabilityDto, ResponseError>>
// app.get('/getinfo', details.getInfo)
// app.get('/logs', details.getLogsSince)
// app.get('/info', details.getNodeInfo)
// app.get('/route', details.checkRoute)
// app.get('/query/onchain_address/:app', queries.queryOnchainAddress)
// app.get('/utxos', queries.listUTXOs)
///////////
/// PUT ///
///////////
// app.put('/invoices', invoices.payInvoice)
////////////
/// POST ///
////////////
// app.post('/invoices', invoices.createInvoice)
// app.post('/invoices/cancel', invoices.cancelInvoice)
//////////////
/// DELETE ///
//////////////
} | 0 | null | 0 | 0 | 5a5f316654ada1171270e28bf4d72d96182afd80 | 2,774 | sphinx-kotlin | MIT License |
app/src/main/java/de/hsaugsburg/teamulster/sohappy/viewmodel/SettingsViewModel.kt | teamulster | 289,924,548 | false | null | package de.hsaugsburg.teamulster.sohappy.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import de.hsaugsburg.teamulster.sohappy.config.ConfigManager
import de.hsaugsburg.teamulster.sohappy.config.SettingsConfig
import kotlin.properties.Delegates.observable
/**
* SettingsViewModel contain information about which settings are enabled / disabled.
*/
class SettingsViewModel(application: Application) : AndroidViewModel(application) {
var notificationsEnabled: Boolean by observable(ConfigManager.settingsConfig.notifications) { _, _, new ->
ConfigManager.storeSettings(
application,
SettingsConfig(
new,
databaseEnabled
)
)
}
var databaseEnabled: Boolean by observable(ConfigManager.settingsConfig.databaseSync) { _, _, new ->
ConfigManager.storeSettings(
application,
SettingsConfig(
notificationsEnabled,
new
)
)
}
init {
notificationsEnabled = ConfigManager.settingsConfig.notifications
databaseEnabled = ConfigManager.settingsConfig.databaseSync
}
}
| 0 | Kotlin | 0 | 9 | 0bceb03f47f0d72320de9080ada19bc7473795c7 | 1,203 | soHappy | MIT License |
android-common/src/main/java/com/caldremch/common/widget/status/IStatusView.kt | android-module | 424,496,469 | false | {"Kotlin": 76902, "Java": 16616, "Shell": 514} | package com.caldremch.common.widget.status
import android.view.View
/**
* @author Caldremch
* @describe
*/
interface IStatusView {
/**
* 初始化ErrorView的实现
*
* @return
*/
fun initErrorViewImpl(): View? {
return null
}
/**
* 初始化LoadingView的实现
*
* @return
*/
fun initLoadingViewImpl(): View? {
return null
}
/**
* 开始加载, 用于重写自己的statusView 的startLoading动作
*/
fun startLoadingImpl() {}
/**
* 停止加载
*/
fun stopLoadingImpl() {}
/**
* 获取错误View
*
* @return
*/
val errorView: View?
get() = null
/**
* 错误页面重试
*/
fun reTry() {}
/**
* 是否使用加载状态也
*/
val isUseLoading: Boolean
get() = false
/**
* 一般是页面使用功能
*/
fun setViewStatus(@ViewState status: Int)
} | 0 | Kotlin | 0 | 0 | 85037eb69d234970cd73cd44e91fb17403fe2700 | 860 | android-common | Apache License 2.0 |
src/main/kotlin/icu/windea/pls/ep/config/CwtOverriddenConfigProvider.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.ep.config
import com.intellij.openapi.extensions.*
import com.intellij.psi.*
import icu.windea.pls.*
import icu.windea.pls.config.config.*
import icu.windea.pls.config.expression.*
import icu.windea.pls.core.*
import icu.windea.pls.lang.*
import icu.windea.pls.core.annotations.*
import icu.windea.pls.core.collections.*
/**
* 用于基于上下文为某些特定的脚本表达式提供重载后的CWT规则。
*
* 这里获取的CWT规则会覆盖原始的CWT规则。
*/
@WithGameTypeEP
interface CwtOverriddenConfigProvider {
/**
* 基于指定的上下文PSI元素[contextElement]和原始的CWT规则[config]获取重载后的CWT规则。
*/
fun <T : CwtMemberConfig<*>> getOverriddenConfigs(contextElement: PsiElement, config: T): List<T>?
fun skipMissingExpressionCheck(configs: List<CwtMemberConfig<*>>, configExpression: CwtDataExpression) = false
fun skipTooManyExpressionCheck(configs: List<CwtMemberConfig<*>>, configExpression: CwtDataExpression) = false
companion object INSTANCE {
val EP_NAME = ExtensionPointName.create<CwtOverriddenConfigProvider>("icu.windea.pls.overriddenConfigProvider")
fun <T : CwtMemberConfig<*>> getOverriddenConfigs(contextElement: PsiElement, config: T): List<T>? {
val gameType = config.configGroup.gameType ?: return null
return EP_NAME.extensionList.firstNotNullOfOrNull f@{ ep ->
if(!gameType.supportsByAnnotation(ep)) return@f null
ep.getOverriddenConfigs(contextElement, config).orNull()
?.onEach {
it.putUserData(CwtMemberConfig.Keys.originalConfig, config)
it.putUserData(CwtMemberConfig.Keys.overriddenProvider, ep)
}
?.also { PlsStatus.overrideConfig.set(true) } //set overrideConfigStatus
}
}
}
}
| 5 | null | 5 | 41 | 99e8660a23f19642c7164c6d6fcafd25b5af40ee | 1,804 | Paradox-Language-Support | MIT License |
app/src/main/java/com/example/ps_raccoon_andre_fortes/ToDoAdapter.kt | andrenfortes | 388,199,833 | false | {"Kotlin": 7089} | package com.example.ps_raccoon_andre_fortes
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.TextView
class ToDoAdapter(context: Context , toDoList:MutableList<ToDoModel>): BaseAdapter() {
private val inflater:LayoutInflater = LayoutInflater.from(context)
private var itemList = toDoList
private var updateAndDelete:UpdateAndDelete = context as UpdateAndDelete
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val UID :String = itemList.get(p0).UID as String
val itemTextData = itemList.get(p0).itemDataText as String
val done: Boolean = itemList.get(p0).done as Boolean
val view: View
val viewHolder: ListViewHolder
if (p1==null){
view=inflater.inflate(R.layout.row_itemslayout,p2,false)
viewHolder=ListViewHolder(view)
view.tag = viewHolder
}
else {
view = p1
viewHolder = view.tag as ListViewHolder
}
viewHolder.textLabel.text = itemTextData
viewHolder.isDone.isChecked = done
viewHolder.isDone.setOnClickListener(){
updateAndDelete.modifyItem(UID, !done)
}
viewHolder.isDeleted.setOnClickListener(){
updateAndDelete.onItemDelete(UID)
}
return view
}
class ListViewHolder(row:View?) {
val textLabel: TextView = row!!.findViewById(R.id.item_textView) as TextView
val isDone: CheckBox=row!!.findViewById(R.id.checkbox) as CheckBox
val isDeleted:ImageButton = row!!.findViewById(R.id.close) as ImageButton
}
override fun getItem(p0: Int): Any {
return itemList.get(p0)
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return itemList.size
}
} | 0 | Kotlin | 0 | 0 | 54ea18b820fdd409a1b1b72532e9649beee51ec2 | 2,022 | to_do_list_app | MIT License |
libraries/stdlib/test/exceptions/ExceptionTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 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 test.exceptions
import test.supportsSuppressedExceptions
import kotlin.test.*
@Suppress("Reformat") // author's formatting
class ExceptionTest {
private val cause = Exception("cause")
@Test fun throwable() = testCreateException(::Throwable, ::Throwable, ::Throwable, ::Throwable)
@Test fun error() = testCreateException(::Error, ::Error, ::Error, ::Error)
@Test fun exception() = testCreateException(::Exception, ::Exception, ::Exception, ::Exception)
@Test fun runtimeException() = testCreateException(::RuntimeException, ::RuntimeException, ::RuntimeException, ::RuntimeException)
@Test fun illegalArgumentException() = testCreateException(::IllegalArgumentException, ::IllegalArgumentException, ::IllegalArgumentException, ::IllegalArgumentException)
@Test fun illegalStateException() = testCreateException(::IllegalStateException, ::IllegalStateException, ::IllegalStateException, ::IllegalStateException)
@Test fun indexOutOfBoundsException() = testCreateException(::IndexOutOfBoundsException, ::IndexOutOfBoundsException)
@Test fun unsupportedOperationException() = testCreateException(::UnsupportedOperationException, ::UnsupportedOperationException, ::UnsupportedOperationException, ::UnsupportedOperationException)
@Test fun numberFormatException() = testCreateException(::NumberFormatException, ::NumberFormatException)
@Test fun nullPointerException() = testCreateException(::NullPointerException, ::NullPointerException)
@Test fun classCastException() = testCreateException(::ClassCastException, ::ClassCastException)
@Test fun noSuchElementException() = testCreateException(::NoSuchElementException, ::NoSuchElementException)
@Test fun concurrentModificationException() = testCreateException(::ConcurrentModificationException, ::ConcurrentModificationException)
@Test fun arithmeticException() = testCreateException(::ArithmeticException, ::ArithmeticException)
@Test fun noWhenBranchMatchedException() = @Suppress("DEPRECATION_ERROR") testCreateException(::NoWhenBranchMatchedException, ::NoWhenBranchMatchedException, ::NoWhenBranchMatchedException, ::NoWhenBranchMatchedException)
@Test fun uninitializedPropertyAccessException() = @Suppress("DEPRECATION_ERROR") testCreateException(::UninitializedPropertyAccessException, ::UninitializedPropertyAccessException, ::UninitializedPropertyAccessException, ::UninitializedPropertyAccessException)
@Test fun assertionError() = testCreateException(::AssertionError, ::AssertionError, ::AssertionError)
private fun <T : Throwable> testCreateException(
noarg: () -> T,
fromMessage: (String?) -> T,
fromCause: ((Throwable?) -> T)? = null,
fromMessageCause: ((String?, Throwable?) -> T)? = null
) {
noarg().let { e ->
assertEquals(null, e.message)
assertEquals(null, e.cause)
}
fromMessage("message").let { e ->
assertEquals("message", e.message)
assertEquals(null, e.cause)
}
fromMessage(null).let { e ->
assertTrue(e.message == null || e.message == "null")
}
fromMessageCause?.run {
invoke("message", cause).let { e ->
assertEquals("message", e.message)
assertSame(cause, e.cause)
}
invoke(null, null).let { e ->
assertEquals(null, e.message)
assertEquals(null, e.cause)
}
}
fromCause?.invoke(cause)?.let { e ->
assertSame(cause, e.cause)
}
}
@Test
fun suppressedExceptions() {
val e1 = Throwable()
val c1 = Exception("Suppressed 1")
val c2 = Exception("Suppressed 2")
assertTrue(e1.suppressedExceptions.isEmpty())
e1.addSuppressed(c1)
e1.addSuppressed(c2)
if (supportsSuppressedExceptions) {
assertEquals(listOf(c1, c2), e1.suppressedExceptions)
} else {
assertTrue(e1.suppressedExceptions.isEmpty())
}
}
@Test
fun exceptionDetailedTrace() {
fun root(): Nothing = throw IllegalStateException("Root cause\nDetails: root")
fun suppressedError(id: Int): Throwable = UnsupportedOperationException("Side error\nId: $id")
fun induced(): Nothing {
try {
root()
} catch (e: Throwable) {
for (id in 0..1)
e.addSuppressed(suppressedError(id))
throw RuntimeException("Induced", e)
}
}
val e = try {
induced()
} catch (e: Throwable) {
e.apply { addSuppressed(suppressedError(2)) }
}
val topLevelTrace = e.stackTraceToString()
fun assertInTrace(value: Any) {
if (value.toString() !in topLevelTrace) {
fail("Expected top level trace: $topLevelTrace\n\nto contain: $value")
}
}
assertInTrace(e)
val cause = assertNotNull(e.cause, "Should have cause")
assertInTrace(cause)
if (supportsSuppressedExceptions) {
val topLevelSuppressed = e.suppressedExceptions.single()
assertInTrace(topLevelSuppressed)
cause.suppressedExceptions.forEach {
assertInTrace(it)
}
}
// fail(topLevelTrace) // to dump the entire trace
}
@Test
fun circularSuppressedDetailedTrace() {
if (!supportsSuppressedExceptions) return
// Testing an exception of the following structure
// e1
// -- suppressed: e0 (same stack as e1)
// -- suppressed: e3
// -- suppressed: e1
// Caused by: e2
// -- suppressed: e1
// Caused by: e3
val e3 = Exception("e3")
val e2 = Error("e2", e3)
val (e1, e0) = listOf("e1", "e0").map { msg -> RuntimeException(msg, e2.takeIf { msg == "e1" }) }
e1.addSuppressed(e0)
e1.addSuppressed(e3)
e3.addSuppressed(e1)
e2.addSuppressed(e1)
val topLevelTrace = e1.stackTraceToString()
fun assertAppearsInTrace(value: Any, count: Int) {
if (Regex.fromLiteral(value.toString()).findAll(topLevelTrace).count() != count) {
fail("Expected to find $value $count times in $topLevelTrace")
}
}
assertAppearsInTrace(e1, 3)
assertAppearsInTrace(e0, 1)
assertAppearsInTrace(e2, 1)
assertAppearsInTrace(e3, 2)
// fail(topLevelTrace) // to dump the entire trace
}
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 6,845 | kotlin | Apache License 2.0 |
akka-benchmark/src/main/kotlin/io/sarl/akka/sample/Printer.kt | alexandrelombard | 158,681,229 | false | null | package io.sarl.akka.sample
import akka.actor.AbstractActor
import akka.actor.Props
import akka.event.Logging
import akka.event.LoggingAdapter
import akka.japi.Creator
//#printer-messages
class Printer : AbstractActor() {
//#printer-messages
private val log = Logging.getLogger(context.system, this)
//#printer-messages
class Greeting(val message: String)
override fun createReceive(): AbstractActor.Receive {
return receiveBuilder()
.match(Greeting::class.java) { greeting -> log.info(greeting.message) }
.build()
}
companion object {
fun props(): Props {
return Props.create<Printer>(Printer::class.java) { Printer() }
}
}
}
//#printer-messages
| 2 | Kotlin | 0 | 0 | d0ba4b1977e020379d91b0ffd5f7e5de798ae072 | 753 | akka-sre | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/stepfunctions/tasks/EmrCreateClusterOnDemandProvisioningSpecificationPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.stepfunctions.tasks
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import software.amazon.awscdk.services.stepfunctions.tasks.EmrCreateCluster
/**
* The launch specification for On-Demand Instances in the instance fleet, which determines the
* allocation strategy.
*
* Example:
* ```
* EmrCreateCluster.Builder.create(this, "OnDemandSpecification")
* .instances(InstancesConfigProperty.builder()
* .instanceFleets(List.of(InstanceFleetConfigProperty.builder()
* .instanceFleetType(EmrCreateCluster.getInstanceRoleType().MASTER)
* .launchSpecifications(InstanceFleetProvisioningSpecificationsProperty.builder()
* .onDemandSpecification(OnDemandProvisioningSpecificationProperty.builder()
* .allocationStrategy(EmrCreateCluster.getOnDemandAllocationStrategy().LOWEST_PRICE)
* .build())
* .build())
* .build()))
* .build())
* .name("OnDemandCluster")
* .integrationPattern(IntegrationPattern.RUN_JOB)
* .build();
* EmrCreateCluster.Builder.create(this, "SpotSpecification")
* .instances(InstancesConfigProperty.builder()
* .instanceFleets(List.of(InstanceFleetConfigProperty.builder()
* .instanceFleetType(EmrCreateCluster.getInstanceRoleType().MASTER)
* .launchSpecifications(InstanceFleetProvisioningSpecificationsProperty.builder()
* .spotSpecification(SpotProvisioningSpecificationProperty.builder()
* .allocationStrategy(EmrCreateCluster.getSpotAllocationStrategy().CAPACITY_OPTIMIZED)
* .timeoutAction(EmrCreateCluster.getSpotTimeoutAction().TERMINATE_CLUSTER)
* .timeout(Duration.minutes(5))
* .build())
* .build())
* .build()))
* .build())
* .name("SpotCluster")
* .integrationPattern(IntegrationPattern.RUN_JOB)
* .build();
* ```
*
* [Documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-instancefleetconfig-ondemandprovisioningspecification.html)
*/
@CdkDslMarker
public class EmrCreateClusterOnDemandProvisioningSpecificationPropertyDsl {
private val cdkBuilder: EmrCreateCluster.OnDemandProvisioningSpecificationProperty.Builder =
EmrCreateCluster.OnDemandProvisioningSpecificationProperty.builder()
/**
* @param allocationStrategy Specifies the strategy to use in launching On-Demand instance
* fleets.
*
* Currently, the only option is lowest-price (the default), which launches the lowest price
* first.
*/
public fun allocationStrategy(allocationStrategy: EmrCreateCluster.OnDemandAllocationStrategy) {
cdkBuilder.allocationStrategy(allocationStrategy)
}
public fun build(): EmrCreateCluster.OnDemandProvisioningSpecificationProperty =
cdkBuilder.build()
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 2,902 | awscdk-dsl-kotlin | Apache License 2.0 |
embrace-android-features/src/main/kotlin/io/embrace/android/embracesdk/internal/anr/ndk/EmbraceNativeThreadSamplerService.kt | embrace-io | 704,537,857 | false | null | package io.embrace.android.embracesdk.internal.anr.ndk
import io.embrace.android.embracesdk.internal.DeviceArchitecture
import io.embrace.android.embracesdk.internal.SharedObjectLoader
import io.embrace.android.embracesdk.internal.anr.mapThreadState
import io.embrace.android.embracesdk.internal.config.ConfigService
import io.embrace.android.embracesdk.internal.config.behavior.AnrBehavior
import io.embrace.android.embracesdk.internal.logging.EmbLogger
import io.embrace.android.embracesdk.internal.payload.NativeThreadAnrInterval
import io.embrace.android.embracesdk.internal.payload.NativeThreadAnrSample
import io.embrace.android.embracesdk.internal.worker.ScheduledWorker
import java.util.Random
import java.util.concurrent.TimeUnit
/**
* Samples the target thread stacktrace when the thread is detected as blocked.
*
* The NDK layer must be enabled in order to use this functionality as this class
* calls native code.
*/
class EmbraceNativeThreadSamplerService @JvmOverloads constructor(
private val configService: ConfigService,
private val symbols: Lazy<Map<String, String>?>,
private val random: Random = Random(),
private val logger: EmbLogger,
private val delegate: NdkDelegate = NativeThreadSamplerNdkDelegate(),
private val scheduledWorker: ScheduledWorker,
private val deviceArchitecture: DeviceArchitecture,
private val sharedObjectLoader: SharedObjectLoader
) : NativeThreadSamplerService {
private companion object {
const val MAX_NATIVE_SAMPLES = 10
}
interface NdkDelegate {
fun setupNativeThreadSampler(is32Bit: Boolean): Boolean
fun monitorCurrentThread(): Boolean
fun startSampling(unwinderOrdinal: Int, intervalMs: Long)
fun finishSampling(): List<NativeThreadAnrSample>?
}
var ignored: Boolean = true
var sampling: Boolean = false
var count: Int = -1
var factor: Int = -1
var intervals: MutableList<NativeThreadAnrInterval> = mutableListOf()
val currentInterval: NativeThreadAnrInterval?
get() = intervals.lastOrNull()
private var targetThread: Thread = Thread.currentThread()
override fun setupNativeSampler(): Boolean {
return if (sharedObjectLoader.loadEmbraceNative()) {
delegate.setupNativeThreadSampler(deviceArchitecture.is32BitDevice)
} else {
logger.logWarning("Embrace native binary load failed. Native thread sampler setup aborted.")
false
}
}
override fun monitorCurrentThread(): Boolean {
targetThread = Thread.currentThread()
return delegate.monitorCurrentThread()
}
override fun onThreadBlocked(thread: Thread, timestamp: Long) {
// use consistent config for the duration of this ANR interval.
val anrBehavior = configService.anrBehavior
ignored = !containsAllowedStackframes(anrBehavior, targetThread.stackTrace)
if (ignored || shouldSkipNewSample(anrBehavior)) {
// we've reached the data capture limit - ignore any thread blocked intervals.
ignored = true
return
}
val unwinder = anrBehavior.getNativeThreadAnrSamplingUnwinder()
factor = anrBehavior.getNativeThreadAnrSamplingFactor()
val offset = random.nextInt(factor)
count = (factor - offset) % factor
intervals.add(
NativeThreadAnrInterval(
targetThread.id,
targetThread.name,
targetThread.priority,
offset * anrBehavior.getSamplingIntervalMs(),
timestamp,
mutableListOf(),
mapThreadState(targetThread.state),
unwinder
)
)
}
override fun onThreadBlockedInterval(thread: Thread, timestamp: Long) {
val limit = configService.anrBehavior.getMaxStacktracesPerInterval()
if (count >= limit) {
logger.logDebug("ANR stacktrace not captured. Maximum allowed ticks per ANR interval reached.")
return
}
if (ignored || !configService.anrBehavior.isUnityAnrCaptureEnabled()) {
return
}
if (count % factor == 0) {
count = 0
if (!sampling) {
sampling = true
// start sampling the native thread
val anrBehavior = configService.anrBehavior
val unwinder = anrBehavior.getNativeThreadAnrSamplingUnwinder()
val intervalMs = anrBehavior.getNativeThreadAnrSamplingIntervalMs()
delegate.startSampling(
unwinder.code,
intervalMs
)
scheduledWorker.schedule<Unit>(::fetchIntervals, intervalMs * MAX_NATIVE_SAMPLES, TimeUnit.MILLISECONDS)
}
}
count++
}
override fun onThreadUnblocked(thread: Thread, timestamp: Long) {
if (sampling) {
scheduledWorker.submit {
fetchIntervals()
}
}
ignored = true
sampling = false
}
private fun fetchIntervals() {
currentInterval?.let { interval ->
delegate.finishSampling()?.let { samples ->
interval.samples?.run {
clear()
addAll(samples)
}
}
}
}
override fun cleanCollections() {
intervals = mutableListOf()
}
private fun shouldSkipNewSample(anrBehavior: AnrBehavior): Boolean {
val sessionLimit = anrBehavior.getMaxAnrIntervalsPerSession()
return !configService.anrBehavior.isUnityAnrCaptureEnabled() || intervals.size >= sessionLimit
}
override fun getNativeSymbols(): Map<String, String>? = symbols.value
override fun getCapturedIntervals(receivedTermination: Boolean?): List<NativeThreadAnrInterval>? {
if (!configService.anrBehavior.isUnityAnrCaptureEnabled()) {
return null
}
// optimization: avoid trying to make a JNI call every 2s due to regular session caching!
if (sampling && receivedTermination == false) {
// fetch JNI samples (blocks main thread, but no way around it if we want
// the information in the session)
fetchIntervals()
}
// the ANR might end before samples with offsets are recorded - avoid
// recording an empty sample in the payload if this is the case.
val usefulSamples = intervals.toList().filter { it.samples?.isNotEmpty() ?: false }
if (usefulSamples.isEmpty()) {
return null
}
return usefulSamples.toList()
}
/**
* Determines whether or not we should sample the target thread based on the thread stacktrace
* and the ANR config.
*/
fun containsAllowedStackframes(
anrBehavior: AnrBehavior,
stacktrace: Array<StackTraceElement>
): Boolean {
if (anrBehavior.isNativeThreadAnrSamplingAllowlistIgnored()) {
return true
}
val allowlist = anrBehavior.getNativeThreadAnrSamplingAllowlist()
return stacktrace.any { frame ->
allowlist.any { allowed ->
frame.methodName == allowed.method && frame.className == allowed.clz
}
}
}
}
fun isUnityMainThread(): Boolean = "UnityMain" == Thread.currentThread().name
| 29 | null | 8 | 134 | 06fb424ba2746c22e8e47e549a9f00ae8f85d72d | 7,430 | embrace-android-sdk | Apache License 2.0 |
app/src/main/java/com/example/demoapp/utils/ErrorUtils.kt | alinbabu2010 | 338,063,365 | false | null | package com.example.demoapp.utils
import com.example.demoapp.api.RetrofitManager
import com.example.demoapp.models.APIError
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Response
import java.io.IOException
/**
* Utility class for parsing error response
*/
class ErrorUtils {
/**
* Method to parse error response
* @param response An instance of class [Response]
* @return An object of class [APIError]
*/
fun parseError(response: Response<*>): APIError? {
val converter: Converter<ResponseBody, APIError> = RetrofitManager.getRetrofit
.responseBodyConverter(APIError::class.java, arrayOfNulls<Annotation>(0))
val error: APIError? = try {
response.errorBody()?.let { converter.convert(it) }
} catch (e: IOException) {
return APIError()
}
return error
}
} | 0 | Kotlin | 1 | 1 | 23766560e733b9ff7d19eb7e2b6764deeb8ce9bb | 893 | BitNews | MIT License |
PixabayApp/app/src/main/java/br/com/pixabayapp/AppApplication.kt | gitdaniellopes | 515,614,285 | false | null | package br.com.pixabayapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class AppApplication : Application() | 0 | Kotlin | 0 | 0 | 2845c1248de836f88b234886cdd183bac68b3281 | 153 | pixabay-app | MIT License |
app/src/main/java/org/fossasia/openevent/general/order/OrderDetailsViewModel.kt | Kapil706 | 172,433,206 | false | null | package org.fossasia.openevent.general.order
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.fossasia.openevent.general.attendees.Attendee
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventService
import timber.log.Timber
class OrderDetailsViewModel(private val eventService: EventService, private val orderService: OrderService) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val message = SingleLiveEvent<String>()
val event = MutableLiveData<Event>()
val attendees = MutableLiveData<List<Attendee>>()
val progress = MutableLiveData<Boolean>()
fun loadEvent(id: Long) {
if (id.equals(-1)) {
throw IllegalStateException("ID should never be -1")
}
compositeDisposable.add(eventService.getEventFromApi(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.value = it
}, {
Timber.e(it, "Error fetching event %d", id)
message.value = "Error fetching event"
}))
}
fun loadAttendeeDetails(id: String) {
if (id.equals(-1)) {
throw IllegalStateException("ID should never be -1")
}
compositeDisposable.add(orderService.attendeesUnderOrder(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
progress.value = true
}.doFinally {
progress.value = false
}.subscribe({
attendees.value = it
}, {
Timber.e(it, "Error fetching attendee details")
message.value = "Error fetching attendee details"
}))
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| 0 | null | 1 | 1 | e3bf6da900f3715759cd5a4d172ed198a4dd207d | 2,274 | open-event-android | Apache License 2.0 |
app/src/main/java/org/fossasia/openevent/general/utils/Utils.kt | G-LOKi | 172,433,206 | true | {"Kotlin": 342899, "Java": 3836, "Shell": 3765} | package org.fossasia.openevent.general.utils
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Context
import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.Uri
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import androidx.annotation.DrawableRes
import androidx.annotation.NonNull
import androidx.appcompat.content.res.AppCompatResources
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.navigation.NavOptions
import com.google.android.material.bottomnavigation.BottomNavigationView
import org.fossasia.openevent.general.R
import timber.log.Timber
object Utils {
fun openUrl(context: Context, link: String) {
var url = link
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "https://$url"
}
CustomTabsIntent.Builder()
.setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
.setCloseButtonIcon(BitmapFactory.decodeResource(context.resources,
R.drawable.ic_arrow_back_white_cct))
.setStartAnimations(context, R.anim.slide_in_right, R.anim.slide_out_left)
.setExitAnimations(context, R.anim.slide_in_left, R.anim.slide_out_right)
.build()
.launchUrl(context, Uri.parse(url))
}
fun showNoInternetDialog(context: Context?) {
AlertDialog.Builder(context)
.setMessage(context?.resources?.getString(R.string.no_internet_message))
.setPositiveButton(context?.resources?.getString(R.string.ok)) { dialog, _ -> dialog.cancel() }
.show()
}
fun isNetworkConnected(context: Context?): Boolean {
val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
return connectivityManager?.activeNetworkInfo != null
}
fun progressDialog(context: Context?): ProgressDialog {
val dialog = ProgressDialog(context)
dialog.setCancelable(false)
dialog.setMessage("Loading...")
return dialog
}
fun ProgressDialog.show(show: Boolean) {
if (show) this.show()
else this.dismiss()
}
fun showSoftKeyboard(context: Context?, view: View) {
view.requestFocus()
val manager = context?.getSystemService(Context.INPUT_METHOD_SERVICE)
if (manager is InputMethodManager) manager.toggleSoftInputFromWindow(view.windowToken,
InputMethodManager.RESULT_UNCHANGED_SHOWN, InputMethodManager.RESULT_UNCHANGED_HIDDEN)
}
fun hideSoftKeyboard(context: Context?, view: View) {
val inputManager: InputMethodManager = context?.getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.SHOW_FORCED)
}
fun checkAndLoadFragment(
fragmentManager: FragmentManager,
fragment: Fragment,
frameLayout: Int,
addToBackStack: Boolean = true
) {
val savedFragment = fragmentManager.findFragmentByTag(fragment::class.java.name)
if (savedFragment != null) {
loadFragment(fragmentManager, savedFragment, frameLayout, addToBackStack)
Timber.d("Loading fragment from stack ${fragment::class.java}")
} else {
loadFragment(fragmentManager, fragment, frameLayout, addToBackStack)
}
}
fun loadFragment(
fragmentManager: FragmentManager,
fragment: Fragment,
frameLayout: Int,
addToBackStack: Boolean = true
) {
val fragmentTransaction = fragmentManager.beginTransaction()
.replace(frameLayout, fragment, fragment::class.java.name)
if (addToBackStack) fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
fun requireDrawable(@NonNull context: Context, @DrawableRes resId: Int) = AppCompatResources
.getDrawable(context, resId) ?: throw IllegalStateException("Drawable should not be null")
fun getAnimFade(): NavOptions {
val builder = NavOptions.Builder()
builder.setEnterAnim(R.anim.fade_in)
builder.setExitAnim(R.anim.fade_out)
builder.setPopEnterAnim(R.anim.fade_in)
builder.setPopExitAnim(R.anim.fade_out)
return builder.build()
}
fun getAnimSlide(): NavOptions {
val builder = NavOptions.Builder()
builder.setEnterAnim(R.anim.slide_in_right)
builder.setExitAnim(R.anim.slide_out_left)
builder.setPopEnterAnim(R.anim.slide_in_left)
builder.setPopExitAnim(R.anim.slide_out_right)
return builder.build()
}
fun navAnimVisible(navigation: BottomNavigationView?, context: Context) {
if (navigation?.visibility == View.GONE) {
navigation.visibility = View.VISIBLE
navigation.animation = AnimationUtils.loadAnimation(context, R.anim.slide_up)
}
}
fun navAnimGone(navigation: BottomNavigationView?, context: Context) {
if (navigation?.visibility == View.VISIBLE) {
navigation.visibility = View.GONE
navigation.animation = AnimationUtils.loadAnimation(context, R.anim.slide_down)
}
}
}
| 0 | Kotlin | 0 | 1 | 18583f39c231a5f7e77417adb0024f4b0cf61aac | 5,511 | open-event-android | Apache License 2.0 |
app/src/main/java/com/strongr/main/MainApp.kt | kryanbeane | 564,696,768 | false | null | package com.strongr.main
import android.app.Application
import android.util.Log
import com.strongr.models.exercise.ExerciseFireStore
import com.strongr.models.trainee.TraineeFireStore
import com.strongr.models.trainee.TraineeModel
import com.strongr.models.workout.WorkoutFireStore
class MainApp: Application() {
private val tag = "MAIN_APP"
lateinit var traineeFS: TraineeFireStore
lateinit var workoutFS: WorkoutFireStore
lateinit var exerciseFS: ExerciseFireStore
override fun onCreate() {
super.onCreate()
traineeFS = TraineeFireStore()
workoutFS = WorkoutFireStore()
exerciseFS = ExerciseFireStore()
}
} | 2 | Kotlin | 0 | 0 | d29d5855ccb406723a45457b6027ca914731ba0c | 667 | strongr | Apache License 2.0 |
mall-service/mall-product/src/main/kotlin/com/github/product/dao/CategoryDao.kt | andochiwa | 409,491,115 | false | {"Kotlin": 5143282, "Java": 228835, "TSQL": 18775, "Dockerfile": 134} | package com.github.product.dao
import com.github.product.entity.Category
import kotlinx.coroutines.flow.Flow
import org.springframework.data.r2dbc.repository.Modifying
import org.springframework.data.r2dbc.repository.Query
import org.springframework.data.repository.kotlin.CoroutineCrudRepository
/**
*
* @author Andochiwa
* @email <EMAIL>
* @date 2021-09-24 00:47:19
*/
interface CategoryDao : CoroutineCrudRepository<Category, Long> {
@Modifying
@Query("update pms_category set show_status = 0 where cat_id = :id")
suspend fun softDelete(id: Long)
@Modifying
@Query("update pms_category set show_status = 0 where cat_id in (:id)")
suspend fun softDeleteAll(id: List<Long>)
fun findAllByShowStatus(showStatus: Int = 1): Flow<Category>
@Query("select name from pms_category where cat_id = :id")
suspend fun findCatelogNameById(id: Long): Category
fun getAllByCatLevel(catLevel: Int): Flow<Category>
fun getAllByParentCid(parentCid: Long): Flow<Category>
}
| 0 | Kotlin | 1 | 2 | 5685d6749a924dddd79d7f06e222b425190c7168 | 1,013 | Webflux-Mall-Back | MIT License |
android/src/main/kotlin/com/javih/add_2_calendar/Add2CalendarPlugin.kt | ja2375 | 155,364,892 | false | null | package com.javih.add_2_calendar
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.provider.CalendarContract
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
/** Add2CalendarPlugin */
class Add2CalendarPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
private var activity: Activity? = null
private var context: Context? = null
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
context = flutterPluginBinding.applicationContext
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "add_2_calendar")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "add2Cal") {
val success = insert(
call.argument("title")!!,
call.argument("desc") as String?,
call.argument("location") as String?,
call.argument("startDate")!!,
call.argument("endDate")!!,
call.argument("timeZone") as String?,
call.argument("allDay")!!,
call.argument("recurrence") as HashMap<String, Any>?,
call.argument("invites") as String?
)
result.success(success)
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivity() {
activity = null
}
private fun insert(
title: String,
desc: String?,
loc: String?,
start: Long,
end: Long,
timeZone: String?,
allDay: Boolean,
recurrence: HashMap<String, Any>?,
invites: String?
): Boolean {
val mContext: Context = if (activity != null) activity!!.applicationContext else context!!
val intent = Intent(Intent.ACTION_INSERT)
intent.data = CalendarContract.Events.CONTENT_URI
intent.putExtra(CalendarContract.Events.TITLE, title)
if (desc != null) {
intent.putExtra(CalendarContract.Events.DESCRIPTION, desc)
}
if (loc != null) {
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, loc)
}
intent.putExtra(CalendarContract.Events.EVENT_TIMEZONE, timeZone)
intent.putExtra(CalendarContract.Events.EVENT_END_TIMEZONE, timeZone)
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start)
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end)
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay)
if (recurrence != null) {
intent.putExtra(CalendarContract.Events.RRULE, buildRRule(recurrence))
}
if (invites != null) {
intent.putExtra(Intent.EXTRA_EMAIL, invites)
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (intent.resolveActivity(mContext.packageManager) != null) {
mContext.startActivity(intent)
return true
}
return false;
}
private fun buildRRule(recurrence: HashMap<String, Any>): String? {
var rRule = recurrence["rRule"] as String?
if (rRule == null) {
rRule = ""
val freqEnum: Int? = recurrence["frequency"] as Int?
if (freqEnum != null) {
rRule += "FREQ="
when (freqEnum) {
0 -> rRule += "DAILY"
1 -> rRule += "WEEKLY"
2 -> rRule += "MONTHLY"
3 -> rRule += "YEARLY"
}
rRule += ";"
}
rRule += "INTERVAL=" + recurrence["interval"] as Int + ";"
val occurrences: Int? = recurrence["ocurrences"] as Int?
if (occurrences != null) {
rRule += "COUNT=" + occurrences.toInt().toString() + ";"
}
val endDateMillis = recurrence["endDate"] as Long?
if (endDateMillis != null) {
val endDate = Date(endDateMillis)
val formatter: DateFormat = SimpleDateFormat("yyyyMMdd'T'HHmmss")
rRule += "UNTIL=" + formatter.format(endDate).toString() + ";"
}
}
return rRule
}
}
| 8 | Dart | 89 | 93 | 314b15d761e87c4a3bb11d9d693a57157e8c71f9 | 5,519 | add_2_calendar | MIT License |
goblin-dao-mongo/src/main/java/org/goblinframework/dao/mongo/module/test/DropDatabaseBeforeTestMethod.kt | xiaohaiz | 206,246,434 | false | null | package org.goblinframework.dao.mongo.module.test
import com.mongodb.reactivestreams.client.Success
import org.goblinframework.api.annotation.Singleton
import org.goblinframework.api.test.TestContext
import org.goblinframework.api.test.TestExecutionListener
import org.goblinframework.core.reactor.BlockingListSubscriber
import org.goblinframework.core.reactor.BlockingMonoSubscriber
import org.goblinframework.dao.exception.GoblinDaoException
import org.goblinframework.dao.mongo.client.MongoClientManager
import org.slf4j.LoggerFactory
@Singleton
class DropDatabaseBeforeTestMethod private constructor() : TestExecutionListener {
companion object {
private val logger = LoggerFactory.getLogger(DropDatabaseBeforeTestMethod::class.java)
@JvmField val INSTANCE = DropDatabaseBeforeTestMethod()
}
override fun beforeTestMethod(testContext: TestContext) {
val annotations = lookupAnnotations(testContext) ?: return
val names = annotations.map { it.connection }.distinct().sorted().toList()
for (name in names) {
val client = MongoClientManager.INSTANCE.getMongoClient(name)
?: throw GoblinDaoException("MongoClient [$name] not found")
val subscriber = BlockingListSubscriber<String>()
client.getNativeClient().listDatabaseNames().subscribe(subscriber)
val databases = subscriber.block().filter { it.startsWith("goblin--ut--") }.toList()
subscriber.dispose()
for (database in databases) {
val db = client.getNativeClient().getDatabase(database)
val s = BlockingMonoSubscriber<Success>()
db.drop().subscribe(s)
s.block()
s.dispose()
logger.debug("Database [$database@$name] dropped")
}
}
}
private fun lookupAnnotations(testContext: TestContext): List<DropDatabase>? {
val annotations = mutableListOf<DropDatabase>()
var s = testContext.getTestMethod().getAnnotation(DropDatabase::class.java)
s?.run { annotations.add(this) }
var m = testContext.getTestMethod().getAnnotation(DropDatabases::class.java)
m?.run { annotations.addAll(this.value) }
s = testContext.getTestClass().getAnnotation(DropDatabase::class.java)
s?.run { annotations.add(this) }
m = testContext.getTestClass().getAnnotation(DropDatabases::class.java)
m?.run { annotations.addAll(this.value) }
return if (annotations.isEmpty()) null else annotations
}
}
| 0 | null | 6 | 9 | b1db234912ceb23bdd81ac66a3bf61933b717d0b | 2,400 | goblinframework | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/sykmelding/service/MottattSykmeldingConsumerService.kt | navikt | 147,519,013 | false | {"Kotlin": 512874, "Dockerfile": 277} | package no.nav.syfo.sykmelding.service
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.coroutines.delay
import no.nav.syfo.Environment
import no.nav.syfo.LoggingMeta
import no.nav.syfo.application.ApplicationState
import no.nav.syfo.model.ReceivedSykmelding
import no.nav.syfo.objectMapper
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.clients.consumer.KafkaConsumer
import java.time.Duration
class MottattSykmeldingConsumerService(
private val applicationState: ApplicationState,
private val env: Environment,
private val kafkaAivenConsumer: KafkaConsumer<String, String>,
private val updateSykmeldingService: UpdateSykmeldingService
) {
suspend fun start() {
kafkaAivenConsumer.subscribe(
listOf(
env.okSykmeldingTopic,
env.manuellSykmeldingTopic,
env.avvistSykmeldingTopic
)
)
while (applicationState.ready) {
kafkaAivenConsumer.poll(Duration.ofMillis(0)).filterNot { it.value() == null }.forEach {
handleMessageSykmelding(it)
}
delay(100)
}
}
private suspend fun handleMessageSykmelding(it: ConsumerRecord<String, String>) {
val receivedSykmelding: ReceivedSykmelding = objectMapper.readValue(it.value())
val loggingMeta = LoggingMeta(
mottakId = receivedSykmelding.navLogId,
orgNr = receivedSykmelding.legekontorOrgNr,
msgId = receivedSykmelding.msgId,
sykmeldingId = receivedSykmelding.sykmelding.id
)
updateSykmeldingService.handleMessageSykmelding(receivedSykmelding, loggingMeta, it.topic())
}
}
| 1 | Kotlin | 2 | 0 | c13ccee6e31a2327bd26ca46c33b66e96e5755a7 | 1,730 | syfosmregister | MIT License |
tests/integration-tests/src/test/kotlin/steps/multitenancy/WalletsSteps.kt | hyperledger | 512,835,706 | false | null | package features.multitenancy
import common.TestConstants
import interactions.Get
import interactions.Post
import io.cucumber.java.en.Given
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import io.iohk.atala.automation.extensions.get
import io.iohk.atala.automation.serenity.ensure.Ensure
import io.iohk.atala.prism.models.CreateWalletRequest
import io.iohk.atala.prism.models.WalletDetail
import io.iohk.atala.prism.models.WalletDetailPage
import net.serenitybdd.rest.SerenityRest
import net.serenitybdd.screenplay.Actor
import org.apache.http.HttpStatus.*
import java.util.*
import kotlin.random.Random
class WalletsSteps {
@OptIn(ExperimentalStdlibApi::class)
fun createNewWallet(
actor: Actor,
name: String = "test-wallet",
seed: String = Random.nextBytes(64).toHexString(),
id: UUID = UUID.randomUUID()
): WalletDetail {
actor.attemptsTo(
Post.to("/wallets")
.with {
it.body(
CreateWalletRequest(
name = name,
seed = seed,
id = id
)
)
}
)
return SerenityRest.lastResponse().get<WalletDetail>()
}
@When("{actor} creates new wallet with name {string}")
fun iCreateNewWalletWithName(acme: Actor, name: String) {
val wallet = createNewWallet(acme, name)
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_CREATED)
)
acme.remember("walletId", wallet.id)
}
@When("{actor} creates new wallet with unique id")
fun acmeCreateNewWalletWithId(acme: Actor) {
val uniqueId = UUID.randomUUID()
acme.remember("uniqueId", uniqueId)
val wallet = createNewWallet(acme, id = uniqueId)
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_CREATED),
Ensure.that(wallet.id).isEqualTo(uniqueId)
.withReportedError("Wallet id is not correct!")
)
}
@When("{actor} creates new wallet with the same unique id")
fun acmeCreateNewWalletWithTheSameId(acme: Actor) {
createNewWallet(acme, id = acme.recall("uniqueId"))
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_BAD_REQUEST)
)
}
@When("{actor} creates new wallet with unique name")
fun acmeCreatesNewWalletWithUniqueName(acme: Actor) {
val name = UUID.randomUUID().toString()
acme.remember("uniqueName", name)
createNewWallet(acme, name = name)
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_CREATED)
)
}
@When("{actor} creates new wallet with the same unique name")
fun acmeCreatesNewWalletWithTheSameUniqueName(acme: Actor) {
createNewWallet(acme, name = acme.recall("uniqueName"))
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_CREATED)
)
}
@Then("{actor} should have a wallet with name {string}")
fun iShouldHaveAWalletWithName(acme: Actor, name: String) {
acme.attemptsTo(
Get.resource("/wallets/${acme.recall<String>("walletId")}")
.with {
it.queryParam("name", name)
}
)
val wallet = SerenityRest.lastResponse().get<WalletDetail>()
acme.attemptsTo(
Ensure.that(wallet.name).isEqualTo(name)
.withReportedError("Wallet name is not correct!"),
Ensure.that(wallet.id).isEqualTo(acme.recall("walletId"))
.withReportedError("Wallet id is not correct!")
)
}
@Then("{actor} should have two wallets with unique name but different ids")
fun acmeShouldHaveTwoWalletsWithNameButDifferentIds(acme: Actor) {
acme.attemptsTo(
Get.resource("/wallets")
)
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_OK)
)
val wallets = SerenityRest.lastResponse().get<WalletDetailPage>().contents!!.filter { it.name == acme.recall("uniqueName") }
acme.attemptsTo(
Ensure.that(wallets.size).isEqualTo(2)
.withReportedError("Two wallets with the same name were not created!")
)
}
@Then("{actor} should have only one wallet and second operation should fail")
fun acmeShouldHaveOnlyOneWalletAndSecondOperationShouldFail(acme: Actor) {
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_BAD_REQUEST)
)
acme.attemptsTo(
Get.resource("/wallets")
)
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_OK)
)
val wallets = SerenityRest.lastResponse().get<WalletDetailPage>().contents!!.filter { it.id == acme.recall("uniqueId") }
acme.attemptsTo(
Ensure.that(wallets.size).isEqualTo(1)
.withReportedError("Only one wallet should be created with the same id!")
)
}
@Given("{actor} creates new wallet with wrong seed")
fun acmeCreatesNewWalletWithWrongSeed(acme: Actor) {
createNewWallet(acme, seed = TestConstants.WRONG_SEED)
}
@Then("{actor} should see the error and wallet should not be created")
fun acmeShouldSeeTheErrorAndWalletShouldNotBeCreated(acme: Actor) {
acme.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(SC_BAD_REQUEST)
)
}
}
| 42 | null | 22 | 80 | c5071d5707e8c79b450f82c0c891f77d2eb26b95 | 5,659 | identus-cloud-agent | Apache License 2.0 |
gradle/gradle-idea/test/org/jetbrains/kotlin/idea/codeInsight/gradle/NativeRunConfigurationTest.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.codeInsight.gradle
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.execution.PsiLocation
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import org.jetbrains.kotlin.gradle.GradleDaemonAnalyzerTestCase
import org.jetbrains.kotlin.test.TagsTestDataUtil
import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.junit.Test
class NativeRunConfigurationTest : MultiplePluginVersionGradleImportingTestCase() {
override fun testDataDirName(): String = "nativeRunConfiguration"
@Test
@TargetVersions("6.0+")
fun multiplatformNativeRunGutter() {
doTest()
}
@Test
@TargetVersions("6.0+")
fun customEntryPointWithoutRunGutter() {
doTest()
}
private fun doTest() {
val files = importProjectFromTestData()
val project = myTestFixture.project
org.jetbrains.kotlin.gradle.checkFiles(
files.filter { it.extension == "kt" },
project,
object : GradleDaemonAnalyzerTestCase(
testLineMarkers = true,
checkWarnings = false,
checkInfos = false,
rootDisposable = testRootDisposable
) {
override fun renderAdditionalAttributeForTag(tag: TagsTestDataUtil.TagInfo<*>): String? {
val lineMarkerInfo = tag.data as? LineMarkerInfo<*> ?: return null
val gradleRunConfigs = lineMarkerInfo.extractConfigurations().filter { it.configuration is GradleRunConfiguration }
val runConfig = gradleRunConfigs.singleOrNull() // can we have more than one?
val settings = (runConfig?.configurationSettings?.configuration as? GradleRunConfiguration)?.settings ?: return null
return "settings=\"${settings}\""
}
}
)
}
private fun LineMarkerInfo<*>.extractConfigurations(): List<ConfigurationFromContext> {
val location = PsiLocation(element)
val emptyContext = ConfigurationContext.createEmptyContextForLocation(location)
return emptyContext.configurationsFromContext.orEmpty()
}
} | 1 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 2,570 | intellij-kotlin | Apache License 2.0 |
LiveDataDataBinding/app/src/main/java/com/keepseung/livedatadatabinding/MainActivity.kt | keepseung | 282,581,869 | false | null | package com.keepseung.livedatadatabinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.keepseung.livedatadatabinding.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
// liveData를 binding에서 사용하기 위해
// 뷰 모델 객체에 실제 lifecycleowner를 현재 activity로 지정해줘야 함
binding.lifecycleOwner = this
// 뷰 모델을 바인딩 변수로 사용함
binding.myViewModel = viewModel
}
}
| 0 | Kotlin | 15 | 12 | 4fee942fcd44ec5816fe6eecfb633421adaa37b3 | 911 | Android-Blog-Source | MIT License |
app/src/main/java/changhwan/experiment/sopthomework/data/remote/model/request/RequestSignUpData.kt | 29th-WE-SOPT-Android-Part | 413,076,866 | false | null | package changhwan.experiment.sopthomework.data.remote.model.request
data class RequestSignUpData(
val email : String,
val name : String,
val password : String
)
| 0 | Kotlin | 0 | 1 | e9929a84a4bd840a013b2e11139d55b6b77475b7 | 174 | Android-Changhwan | Apache License 2.0 |
src/main/kotlin/org/opensearch/replication/task/index/IndexReplicationState.kt | opensearch-project | 323,830,219 | false | null | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.replication.task.index
import org.opensearch.replication.task.ReplicationState
import org.opensearch.replication.task.shard.ShardReplicationParams
import org.opensearch.core.ParseField
import org.opensearch.core.common.io.stream.StreamInput
import org.opensearch.core.common.io.stream.StreamOutput
import org.opensearch.core.xcontent.ObjectParser
import org.opensearch.core.xcontent.ToXContent
import org.opensearch.core.xcontent.XContentBuilder
import org.opensearch.core.xcontent.XContentParser
import org.opensearch.core.index.shard.ShardId
import org.opensearch.persistent.PersistentTaskState
import org.opensearch.persistent.PersistentTasksCustomMetadata.PersistentTask
import java.io.IOException
import java.lang.IllegalArgumentException
sealed class IndexReplicationState : PersistentTaskState {
var state: ReplicationState
companion object {
const val NAME = IndexReplicationExecutor.TASK_NAME
fun reader(inp : StreamInput) : IndexReplicationState {
val state = inp.readEnum(ReplicationState::class.java)!!
return when (state) {
ReplicationState.INIT -> InitialState
ReplicationState.RESTORING -> RestoreState
ReplicationState.INIT_FOLLOW -> InitFollowState
ReplicationState.FOLLOWING -> FollowingState(inp)
ReplicationState.COMPLETED -> CompletedState
ReplicationState.MONITORING -> MonitoringState
ReplicationState.FAILED -> FailedState(inp)
}
}
private val PARSER = ObjectParser<Builder, Void>(NAME, true) { Builder() }
init {
PARSER.declareString(Builder::setIndexTaskState, ParseField("state"))
}
@Throws(IOException::class)
fun fromXContent(parser: XContentParser): IndexReplicationState {
return PARSER.parse(parser, null).build()
}
}
constructor(state: ReplicationState) {
this.state = state
}
override fun writeTo(out: StreamOutput) {
out.writeEnum(state)
}
final override fun getWriteableName(): String = NAME
override fun toXContent(builder: XContentBuilder, params: ToXContent.Params?): XContentBuilder {
return builder.startObject()
.field("state", state)
.endObject()
}
class Builder {
lateinit var state: String
fun setIndexTaskState(state: String) {
this.state = state
}
fun build(): IndexReplicationState {
// Issue details - https://github.com/opensearch-project/cross-cluster-replication/issues/223
state = if(!this::state.isInitialized) {
ReplicationState.MONITORING.name
} else {
state
}
return when (state) {
ReplicationState.INIT.name -> InitialState
ReplicationState.RESTORING.name -> RestoreState
ReplicationState.INIT_FOLLOW.name -> InitFollowState
ReplicationState.FOLLOWING.name -> FollowingState(mapOf())
ReplicationState.COMPLETED.name -> CompletedState
ReplicationState.MONITORING.name -> MonitoringState
ReplicationState.FAILED.name -> FailedState(mapOf(), "")
else -> throw IllegalArgumentException("$state - Not a valid state for index replication task")
}
}
}
}
/**
* Singleton that represent initial state.
*/
object InitialState : IndexReplicationState(ReplicationState.INIT)
/**
* Singleton that represents an in-progress restore.
*/
object RestoreState : IndexReplicationState(ReplicationState.RESTORING)
/**
* Singleton that represents initial follow.
*/
object InitFollowState : IndexReplicationState(ReplicationState.INIT_FOLLOW)
/**
* Singleton that represents completed task state.
*/
object CompletedState : IndexReplicationState(ReplicationState.COMPLETED)
/**
* Singleton that represents monitoring state.
*/
object MonitoringState : IndexReplicationState(ReplicationState.MONITORING)
/**
* State when index task is in failed state.
*/
data class FailedState(val failedShards: Map<ShardId, PersistentTask<ShardReplicationParams>>, val errorMsg: String)
: IndexReplicationState(ReplicationState.FAILED) {
constructor(inp: StreamInput) : this(inp.readMap(::ShardId, ::PersistentTask), "")
override fun writeTo(out: StreamOutput) {
super.writeTo(out)
out.writeMap(failedShards, { o, k -> k.writeTo(o) }, { o, v -> v.writeTo(o) })
}
override fun toXContent(builder: XContentBuilder, params: ToXContent.Params?): XContentBuilder {
return builder.startObject()
.field("error_message", errorMsg)
.field("failed_shard_replication_tasks").map(failedShards.mapKeys { it.key.toString() })
.field("state", state)
.endObject()
}
}
/**
* State when index is being actively replicated.
*/
data class FollowingState(val shardReplicationTasks: Map<ShardId, PersistentTask<ShardReplicationParams>>)
: IndexReplicationState(ReplicationState.FOLLOWING) {
constructor(inp: StreamInput) : this(inp.readMap(::ShardId, ::PersistentTask))
override fun writeTo(out: StreamOutput) {
super.writeTo(out)
out.writeMap(shardReplicationTasks, { o, k -> k.writeTo(o) }, { o, v -> v.writeTo(o) })
}
override fun toXContent(builder: XContentBuilder, params: ToXContent.Params?): XContentBuilder {
return builder.startObject()
.field("shard_replication_tasks").map(shardReplicationTasks.mapKeys { it.key.toString() })
.field("state", state)
.endObject()
}
}
| 87 | null | 58 | 48 | 0cc41c620b96a4798adbe2237e48b67269e3e509 | 6,055 | cross-cluster-replication | Apache License 2.0 |
fabric/1.20.4/src/main/kotlin/com/turikhay/mc/pwam/fabric/platform/EmojiFlag.kt | turikhay | 786,989,595 | false | {"Kotlin": 74167, "Java": 16135} | package com.turikhay.mc.pwam.fabric.platform
const val SUPPORTS_EMOJI = false | 3 | Kotlin | 0 | 0 | a0765da1806def2900f459bfcea94e654f2e5032 | 78 | passwordmanager-for-authme | MIT License |
app/src/main/java/com/br/presentation/ui/views/SelectDropDownMenu.kt | DaniilIgorevich | 505,218,802 | false | null | package com.br.presentation.ui.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
@Composable
fun <T>SelectDropDownMenu(
modifier: Modifier = Modifier,
itemSelected: T,
items: List<T>,
onItemSelected: (item: T) -> Unit
) {
var text by remember { mutableStateOf(itemSelected.toString()) }
var expanded by remember { mutableStateOf(false) }
Box(
modifier = modifier.clickable { expanded = true },
contentAlignment = Alignment.Center
) {
Text(
text = text,
fontSize = 18.sp
)
DropdownMenu(
expanded = expanded,
onDismissRequest = {}
) {
items.forEach { item ->
DropdownMenuItem(
onClick = {
text = item.toString()
expanded = false
onItemSelected(item)
}
) {
Text(text = item.toString())
}
}
}
}
} | 0 | Kotlin | 0 | 0 | f4cddc584c6de46b454eb5b8c7090bb6a69e7283 | 1,362 | Presentation | Apache License 2.0 |
app/src/main/java/com/example/fooddelivery/presentation/intro/IntroActivity.kt | spencer2k19 | 720,201,452 | false | {"Kotlin": 305089} | package com.example.fooddelivery.presentation.intro
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.example.fooddelivery.R
import com.example.fooddelivery.common.PrefSingleton
import com.example.fooddelivery.presentation.home.HomeActivity
import com.example.fooddelivery.presentation.main.MainActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class IntroActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
lifecycleScope.launch {
delay(3000)
if(PrefSingleton.getTokenData() != null) {
val intent = Intent(this@IntroActivity,HomeActivity::class.java)
startActivity(intent)
} else {
val intent = Intent(this@IntroActivity,MainActivity::class.java)
startActivity(intent)
}
finish()
}
}
} | 0 | Kotlin | 0 | 2 | 7be246eba97aa90740952a8bd85dbeb3229c826b | 1,093 | Food-Delivery-Android | MIT License |
src/models/table/Questionnaires.kt | alxgrk | 157,362,886 | false | null | package models.table
import org.jetbrains.exposed.dao.IntIdTable
object Questionnaires : IntIdTable() {
val name = varchar("name", 255)
val state = enumeration("questionnaireState", QuestionnaireState::class)
// wohnflaeche
val breite = decimal("breite", 19, 5).nullable()
val laenge = decimal("laenge", 19, 5).nullable()
val ebenen = integer("ebenen").nullable()
val wohnflaeche = decimal("wohnflaeche", 19, 5).nullable()
// art des hauses
val geschosse = enumeration("geschosse", Geschosse::class).nullable()
val dach = enumeration("dach", Dach::class).nullable()
val art = enumeration("art", Art::class).nullable()
val standardstufe = integer("standardstufe").nullable()
val zwischenergebnisHausaufbau = decimal("zwischenergebnisHausaufbau", 19, 5).nullable()
// herstellungswert
val baupreisindex = decimal("baupreisindex", 19, 5).nullable()
val aussenanlage = decimal("aussenanlage", 19, 5).nullable()
val herstellungswert = decimal("herstellungswert", 19, 5).nullable()
// sachwert
val baujahr = integer("baujahr").nullable()
val sanierungDach = integer("sanierungDach").nullable()
val sanierungAussenwaende = integer("sanierungAussenwaende ").nullable()
val sanierungFensterUndAussentueren = integer("sanierungFensterUndAussentueren").nullable()
val sanierungSonstigeTechnischeAusstattung = integer("sanierungSonstigeTechnischeAusstattung").nullable()
val sanierungFussboden = integer("sanierungFussboden").nullable()
val sanierungHeizung = integer("sanierungHeizung").nullable()
val calculatedBaujahr = integer("calculatedBaujahr").nullable()
val restnutzungsdauer = integer("restnutzungsdauer").nullable()
val vorlaeufigerSachwert = decimal("vorlaeufigerSachwert", 19, 5).nullable()
// besonderes
// referenced in 'BesonderesTable'
val vorlaeufigerSachwertMitBesonderem = decimal("vorlaeufigerSachwertMitBesonderem", 19, 5).nullable()
// marktanpassungsfaktor
val marktanpassungsfaktor = decimal("marktanpassungsfaktor", 19, 5).nullable()
val vorlaeufigerSachwertMitMarktanpassungsfaktor =
decimal("vorlaeufigerSachwertMitMarktanpassungsfaktor", 19, 5).nullable()
// grundstueckswert
val grundstuecksgroesse = decimal("grundstuecksgroesse", 19, 5).nullable()
val grundstueckswert = decimal("grundstueckswert", 19, 5).nullable()
val gesamtwert = decimal("gesamtwert", 19, 5).nullable()
}
object BesonderesTable : IntIdTable() {
val questionnaire = reference("questionnaire", Questionnaires)
val name = varchar("name", 255)
val value = decimal("value", 19, 5)
}
enum class QuestionnaireState {
OPEN,
FINISHED
}
enum class Geschosse {
KG_EG,
KG_EG_OG,
EG,
EG_OG;
}
enum class Dach {
AUSGEBAUT,
NICHT_AUSGEBAUT,
FLACH;
}
enum class Art {
EIN,
DOPPEL,
REIHE,
REIHENEND,
REIHENMITTEL;
} | 1 | Kotlin | 0 | 0 | 19ac9d8cf062b36309233bed46cf34c8d31bcb38 | 2,933 | hausbewerter-server | Apache License 2.0 |
src/main/kotlin/cc/rits/membership/console/paymaster/infrastructure/api/response/ErrorResponse.kt | membership-console | 558,499,219 | false | null | package cc.rits.membership.console.paymaster.infrastructure.api.response
import io.micronaut.core.annotation.Introspected
/**
* エラーレスポンス
*/
@Introspected
data class ErrorResponse(val code: Int, val message: String)
| 5 | Kotlin | 0 | 3 | 612d59a4419e09ff0e20dbdea0aa1114fb12507f | 219 | paymaster | MIT License |
app/src/androidTest/java/net/oleg/fd/room/AppDatabaseTest.kt | olegnet | 495,531,574 | false | {"Kotlin": 169402, "Prolog": 62} | /*
* Copyright 2022-2024 <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 net.oleg.fd.room
import android.content.Context
import android.text.format.DateUtils
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.*
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
import java.util.*
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
class AppDatabaseTest {
private lateinit var foodDao: FoodDao
private lateinit var database: FoodDatabase
private val scope = TestScope()
@Before
fun createDb() {
Dispatchers.setMain(StandardTestDispatcher(scope.testScheduler))
val context: Context = ApplicationProvider.getApplicationContext()
runBlocking {
database = FoodDatabase.getDatabase(context)
foodDao = database.foodDao()
}
}
@After
@Throws(IOException::class)
fun closeDb() {
database.close()
Dispatchers.resetMain()
}
@Test
@Ignore(value = "Run it manually")
@Throws(Exception::class)
fun addDefaultData() = runTest {
val foodItemList = listOf(
FoodItem(null, "quadratisch", "4000417932006", Date(1652262140799), 1.0f, 2.0f, 3.0f, 4.0f, false),
FoodItem(null, "quadratisch 2", "4000417212009", Date(1652270512503), 5.0f, 6.0f, 7.0f, 8.0f, false),
)
val newFoodItemList = mutableListOf<FoodItem>()
foodItemList.forEach {
val id = foodDao.insertFoodItem(it)
newFoodItemList.add(it.replaceId(id))
}
newFoodItemList.forEach { foodItem ->
assertNotNull(foodItem.id)
flow<FoodItem> {
foodDao.getFoodItem(foodItem.id!!)
}.collect {
assertEquals(foodItem, it)
}
}
}
@Test
@Ignore(value = "Run it manually")
@Throws(Exception::class)
fun addGeneratedData() = runTest {
val foodItemList = mutableListOf<FoodItem>()
val foodDiaryItemList = mutableListOf<FoodDiaryItem>()
for (i in 1..49) {
val item = FoodItem(
id = null,
name = "Random food $i",
barcode = (4000417932006 + i).toString(),
date = Date(),
energy = 50.0f + i,
carbs = 100.0f - i,
fat = 30.0f + i * 2,
protein = 180.0f - i * 2,
itemIsDeleted = false
)
val itemId = foodDao.insertFoodItem(item)
foodItemList.add(item.replaceId(itemId))
val foodDiaryItem = FoodDiaryItem(
id = null,
date = if (itemId % 2 == 0L) Date() else Date(Date().time - DateUtils.DAY_IN_MILLIS),
itemId = itemId,
weight = Random().nextFloat()
)
val diaryItemId = foodDao.insertFoodDiaryItem(foodDiaryItem)
foodDiaryItemList.add(foodDiaryItem.replaceId(diaryItemId))
}
val item50 = FoodItem(
id = null,
name = "Very very long line so it should be second line here and then even more text",
barcode = 4000417932006.toString(),
date = Date(),
energy = 10.34f,
carbs = 2.0f,
fat = 3.0f,
protein = 4.0f,
itemIsDeleted = false
)
val id50 = foodDao.insertFoodItem(item50)
foodItemList.add(item50.replaceId(id50))
foodItemList.forEach { foodItem ->
assertNotNull(foodItem.id)
flow<FoodItem> {
foodDao.getFoodItem(foodItem.id!!)
}.collect {
assertEquals(foodItem, it)
}
}
foodDiaryItemList.forEach { foodDiaryItem ->
assertNotNull(foodDiaryItem.id)
flow<FoodItem> {
foodDao.getFoodDiaryItem(foodDiaryItem.id!!)
}.collect {
assertEquals(foodDiaryItem, it)
}
}
}
@Test
@Ignore(value = "Will clear all data in the app")
@Throws(Exception::class)
fun clearAllTables() = runTest {
database.clearAllTables()
}
} | 0 | Kotlin | 0 | 0 | fd429134fb7196bc10b03e8d5442dbde1dcdbaba | 5,172 | food-diary-android | Apache License 2.0 |
app/src/main/java/com/vrudenko/telephonyserver/data/database/AppDatabase.kt | iamworkingasrudenko | 560,806,639 | false | null | package com.vrudenko.telephonyserver.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.vrudenko.telephonyserver.data.database.call.CallDao
import com.vrudenko.telephonyserver.data.database.call.DBCall
import com.vrudenko.telephonyserver.data.database.log.DBLogQuery
import com.vrudenko.telephonyserver.data.database.log.LogQueryDao
@Database(
entities = [
DBCall::class,
DBLogQuery::class
],
version = 1,
exportSchema = false
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun callDao(): CallDao
abstract fun logQueryDao(): LogQueryDao
} | 0 | Kotlin | 0 | 0 | 787d7995e40ecb530794a004000f2624dec35e15 | 701 | telephony-server | Apache License 2.0 |
app/src/main/java/com/razeware/emitron/ui/download/DownloadViewModel.kt | razeware | 192,712,585 | false | null | package com.razeware.emitron.ui.download
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.razeware.emitron.data.download.DownloadRepository
import com.razeware.emitron.model.DownloadProgress
import com.razeware.emitron.ui.content.ContentPagedViewModel
import com.razeware.emitron.ui.login.PermissionActionDelegate
import com.razeware.emitron.ui.login.PermissionsAction
import com.razeware.emitron.ui.onboarding.OnboardingAction
import com.razeware.emitron.ui.onboarding.OnboardingActionDelegate
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* ViewModel for downloads
*/
@HiltViewModel
class DownloadViewModel @Inject constructor(
private val downloadRepository: DownloadRepository,
private val contentPagedViewModel: ContentPagedViewModel,
private val onboardingActionDelegate: OnboardingActionDelegate,
private val permissionActionDelegate: PermissionActionDelegate,
private val downloadActionDelegate: DownloadActionDelegate
) : ViewModel(), OnboardingAction by onboardingActionDelegate,
PermissionsAction by permissionActionDelegate, DownloadAction by downloadActionDelegate {
/**
* Load bookmarks from database
*/
fun loadDownloads() {
val listing = downloadRepository.getDownloads()
contentPagedViewModel.localRepoResult.value = listing
}
/**
* Get pagination helper
*/
fun getPaginationViewModel(): ContentPagedViewModel = contentPagedViewModel
/**
* Update download progress
*
* @param downloadProgress Download progress
*/
fun updateDownload(downloadProgress: DownloadProgress) {
viewModelScope.launch {
downloadActionDelegate.updateDownloadProgress(downloadProgress)
}
}
}
| 30 | Kotlin | 31 | 53 | 4dcb00f09eee2ae1ff0a6c9c2e2dd141227b51c4 | 1,771 | emitron-Android | Apache License 2.0 |
plugin/project-plugin/src/main/kotlin/plugin/RootProjectTasks.kt | top-bettercode | 387,652,015 | false | null | package plugin
import hudson.cli.CLI
import org.gradle.api.Project
import top.bettercode.gradle.generator.GeneratorPlugin
import java.io.File
/**
*
* @author Peter Wu
*/
object RootProjectTasks {
fun config(project: Project) {
project.tasks.apply {
val jenkinsJobs = project.findProperty("jenkins.jobs")?.toString()?.split(",")
?.filter { it.isNotBlank() }
val jenkinsServer = project.findProperty("jenkins.server")?.toString()
val jenkinsAuth = project.findProperty("jenkins.auth")?.toString()
if (!jenkinsJobs.isNullOrEmpty() && !jenkinsAuth.isNullOrBlank() && !jenkinsServer.isNullOrBlank()) {
create("jenkins[All]") {
it.group = "jenkins"
it.doLast {
jenkinsJobs.forEach { jobName ->
CLI._main(
arrayOf(
"-s",
jenkinsServer,
"-auth",
jenkinsAuth,
"build",
jobName,
"-s",
"-v"
)
)
}
}
}
jenkinsJobs.forEach { jobName ->
val jobTaskName = jobName.replace(
"[()\\[\\]{}|/]|\\s*|\t|\r|\n|".toRegex(),
""
)
create("jenkins[$jobTaskName]") {
it.group = "jenkins"
it.doLast {
CLI._main(
arrayOf(
"-s",
jenkinsServer,
"-auth",
jenkinsAuth,
"build",
jobName,
"-s",
"-v"
)
)
}
}
}
}
create("genDbScript") { t ->
t.group = GeneratorPlugin.taskGroup
t.doLast {
val destFile: File = project.rootProject.file("database/init.sql")
val initBuilder = StringBuilder()
initBuilder.appendln("SET NAMES 'utf8';")
// initBuilder.appendln(project.rootProject.file("database/database.sql").readText())
project.rootProject.file("database/ddl").listFiles()?.filter { it.isFile }
?.forEach {
initBuilder.appendln(it.readText())
}
project.rootProject.file("database/init").listFiles()?.filter { it.isFile }
?.forEach {
initBuilder.appendln(it.readText())
}
println(
"${if (destFile.exists()) "覆盖" else "生成"}:${
destFile.absolutePath.substringAfter(
project.rootDir.absolutePath + File.separator
)
}"
)
destFile.writeText(initBuilder.toString())
}
}
create("prettyConfig") { t ->
t.doLast {
ConfigTool.prettyConfig(
project.file("conf"),
project.subprojects.map { it.file("src/main/resources/application.yml") }
.filter { it.exists() })
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 06bc1af2c336a85338f944c969e3be8d55efc387 | 4,010 | summer | Apache License 2.0 |
android/src/main/java/com/haeyum/android/presentation/translation/TranslationScreenState.kt | kisa002 | 584,385,916 | false | {"Kotlin": 178872} | package com.haeyum.android.presentation.translation
sealed class TranslationScreenState {
object Translating : TranslationScreenState()
data class Translated(val originalText: String, val translatedText: String) : TranslationScreenState()
object DisconnectedNetwork : TranslationScreenState()
object FailedTranslate : TranslationScreenState()
} | 1 | Kotlin | 2 | 48 | c57d5e8ca2dadbf35a565726d01cd04e7ede7105 | 361 | Transer | MIT License |
app/src/main/java/com/eatssu/android/ui/mypage/inquire/InquiryActivity.kt | EAT-SSU | 601,871,281 | false | {"Kotlin": 242939} | package com.eatssu.android.ui.mypage.inquire
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.eatssu.android.base.BaseActivity
import com.eatssu.android.databinding.ActivityInquireBinding
import com.eatssu.android.util.MySharedPreferences
import com.eatssu.android.util.extension.showToast
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import timber.log.Timber
@AndroidEntryPoint
class InquiryActivity : BaseActivity<ActivityInquireBinding>(ActivityInquireBinding::inflate) {
private val inquireViewModel: InquireViewModel by viewModels()
private var email = ""
private var comment = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
toolbarTitle.text = "문의하기" // 툴바 제목 설정
bindData()
setOnClickListener()
}
private fun bindData() {
// 카카오 로그인으로 받아온 이메일 정보 가져오기
// Todo 뷰모델에서 하게끔 수정하기
email = MySharedPreferences.getUserEmail(this)
// EditText에 이메일 정보 설정
binding.etEmail.setText(email)
// EditText를 편집 가능하게 만들기
binding.etEmail.isEnabled = true
binding.etEmail.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
// 사용자가 입력한 새로운 이메일 값을 업데이트
email = s.toString()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// 이 메소드는 필요하지 않음
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// 이 메소드는 필요하지 않음
}
})
binding.etReportComment.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
// 사용자가 입력한 새로운 이메일 값을 업데이트
comment = s.toString()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// 이 메소드는 필요하지 않음
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// 이 메소드는 필요하지 않음
}
})//Todo 데이터 바인딩으로 리팩토링
}
private fun setOnClickListener() {
binding.btnSendReport.setOnClickListener {
val currentEmail = binding.etEmail.text.toString()
val reportComment = binding.etReportComment.text.toString()
Timber.d(currentEmail + reportComment)
inquireViewModel.inquireContent(currentEmail, reportComment)
lifecycleScope.launch {
inquireViewModel.uiState.collectLatest {
if (it.done) {
showToast(it.toastMessage)//Todo 토스트 두번 나옴
finish()
} else {
showToast(it.toastMessage)
}
}
}
}
}
} | 26 | Kotlin | 0 | 8 | bf33fd4e0f357a60aa4b0dbad983f7137357d80a | 3,131 | Android | MIT License |
components/src/androidTest/java/emperorfin/android/components/ui/screens/authentication/AuthenticationScreenTest5.kt | emperorfin | 611,222,954 | false | null | /**
* Copyright 2023 Francis Nwokelo (emperorfin)
*
* 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 emperorfin.android.militaryjet.ui.screens.authentication
import android.content.Context
import android.view.KeyEvent.*
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.NativeKeyEvent
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import emperorfin.android.militaryjet.ui.screens.authentication.enums.PasswordRequirement
import emperorfin.android.militaryjet.ui.extensions.waitUntilDoesNotExist
import emperorfin.android.militaryjet.ui.extensions.waitUntilExists
import emperorfin.android.militaryjet.ui.utils.AuthenticationScreenTestUtil
import emperorfin.android.militaryjet.ui.utils.KeyboardHelper
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/**
* @Author: Francis Nwokelo (emperorfin)
* @Date: Thursday 09th March, 2023.
*/
/**
* The following classes are revisions of this class:
* [AuthenticationScreenTest4]
* [AuthenticationScreenTest5]
*
* Important:
*
* - Try not to run all the test cases by running this test class as some tests might fail. If you
* do and some tests fail, try re-running those failed tests one after the other. If a test fails,
* check the test function's KDoc/comment (if any) on possible solution to make the test pass when
* it should.
* - If you try to run a test and it fails, check the test function's KDoc/comment (if any) on
* possible solution to make the test pass when it should.
* - Test cases with "_AnotherApproach" suffixed in their function names might fail. A little
* changes would need to be made for them to pass. Kindly take a look at the function's KDoc/comment
* on how to make the test pass when it should.
*
* Useful Docs:
*
* - Compose [ComposeContentTestRule.waitUntil] test API as an alternative to Espresso's Idling
* Resources ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* - [Compose testing, matchers and more!]( https://developer.android.com/jetpack/compose/testing ).
*
* - [Compose testing cheatsheet]( https://developer.android.com/jetpack/compose/testing-cheatsheet )
*
* Notes:
*
* - If you ever need to pass a resource (e.g. a string resource) into a composable during testing,
* be sure to use the one from the main source set and the R must be the one from
* [emperorfin.android.militaryjet.R] and not
* [emperorfin.android.militaryjet.test.R].
* - Every other thing during testing that involves the use of a resource (e.g. a string resource)
* such as performing matches or assertions, be sure to use the resource from the androidTest source
* set (which you should've provided a copy and always in sync with the one from the main source set).
* And the R must be the one from [emperorfin.android.militaryjet.test.R] instead of
* [emperorfin.android.militaryjet.R].
*
* Be sure to have configured res srcDirs for androidTest sourceSet in app/build.gradle file.
* See the following:
* - https://stackoverflow.com/questions/36955608/espresso-how-to-use-r-string-resources-of-androidtest-folder
* - https://stackoverflow.com/questions/26663539/configuring-res-srcdirs-for-androidtest-sourceset
*/
class AuthenticationScreenTest3 {
private companion object {
private const val TRUE: Boolean = true
private const val FALSE: Boolean = false
private const val INPUT_CONTENT_EMAIL: String = "[email protected]"
private const val INPUT_CONTENT_PASSWORD: String = "passworD1"
private const val INPUT_CONTENT_PASSWORD_PASSWORD: String = "password"
private const val INPUT_CONTENT_PASSWORD_PASS: String = "Pass"
private const val INPUT_CONTENT_PASSWORD_1PASS: String = "1pass"
/**
* Since the delay time millis in the authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt
* is 2000L, the [ComposeContentTestRule.waitUntil] test API timeoutMillis should be
* something greater than 2_000L such as 2_010L or 2_500L instead of the default 1_000L
* value.
*
* For scenarios where the amount of time an operation such as network call is unknown, you
* should keep increasing the timeoutMillis of the [ComposeContentTestRule.waitUntil] until
* the test doesn't throw any error or exception related to timeout exception.
*/
private const val TIMEOUT_MILLIS_2500L: Long = 2_500L
}
/**
* Use this when resources are coming from the main source set, whether directly
* (e.g. R.string.sample_text) or indirectly (e.g. [PasswordRequirement.EIGHT_CHARACTERS.label]
* which is directly using a string resource).
*
* To actually reference the resource, you use
* [emperorfin.android.militaryjet.R] and not
* [emperorfin.android.militaryjet.test.R]
*
* So let's say if you want to reference a string resource, that string resource should come
* from app/src/main/res/values/strings.xml XML resource file which must be, as you may have
* noticed, from the main source set.
*/
private lateinit var mTargetContext: Context
/**
* Use this when resources are coming from the androidTest or test source set. In this case, the
* resources should come from androidTest (not test) source set.
*
* To actually reference the resource, you use
* [emperorfin.android.militaryjet.test.R] and not
* [emperorfin.android.militaryjet.R]
*
* So let's say if you want to reference a string resource, that string resource should come
* from app/src/androidTest/res/values/strings.xml XML resource file which must be, as you may
* have noticed, from the androidTest source set. And always update this file with the changes
* made to the app/src/main/res/values/strings.xml XML resource file from the main source set.
* And of course, you may/should re-run existing test(s) to be sure they don't fail as a result
* of the synchronization.
*
* Be sure to have Configured res srcDirs for androidTest sourceSet in app/build.gradle file.
* See the following:
* - https://stackoverflow.com/questions/36955608/espresso-how-to-use-r-string-resources-of-androidtest-folder
* - https://stackoverflow.com/questions/26663539/configuring-res-srcdirs-for-androidtest-sourceset
*/
private lateinit var mContext: Context
@get:Rule
val composeTestRule: ComposeContentTestRule = createComposeRule()
private val keyboardHelper = KeyboardHelper(composeRule = composeTestRule)
private lateinit var authenticationScreenTestUtil: AuthenticationScreenTestUtil
@Before
fun setUpContexts() {
// See field's KDoc for more info.
mTargetContext = InstrumentationRegistry.getInstrumentation().targetContext
// mTargetContext = ApplicationProvider.getApplicationContext<Context>() // Haven't tested but might work.
// See field's KDoc for more info.
mContext = InstrumentationRegistry.getInstrumentation().context
authenticationScreenTestUtil = AuthenticationScreenTestUtil(
mContext = mContext,
mTargetContext = mTargetContext,
composeTestRule = composeTestRule
)
}
@Test
fun sign_In_Mode_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertSignInModeIsDisplayed(composeTestRule)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed(composeTestRule)
}
@Test
fun sign_Up_Mode_Displayed_After_Toggled() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertSignUpModeIsDisplayed(composeTestRule)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
}
@Test
fun sign_In_Title_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed(composeTestRule)
}
@Test
fun sign_Up_Title_Displayed_After_Toggled() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
}
@Test
fun sign_In_Button_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.assertIsDisplayed()
}
@Test
fun sign_Up_Button_Displayed_After_Toggle() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.assertIsDisplayed()
}
@Test
fun need_Account_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithAuthenticationToggleModeAndTextExactlyNeedAnAccount()
.assertIsDisplayed()
}
@Test
fun already_Have_Account_Displayed_After_Toggle() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithAuthenticationToggleModeAndTextExactlyAlreadyHaveAnAccount()
.assertIsDisplayed()
}
@Test
fun sign_In_Button_Disabled_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.assertIsNotEnabled()
}
@Test
fun sign_Up_Button_Disabled_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.assertIsNotEnabled()
}
@Test
fun sign_In_Button_Enabled_With_Valid_Form_Content() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.assertIsDisplayed()
.assertIsEnabled()
}
@Test
fun sign_In_Button_Disabled_When_Email_Input_Has_No_Content() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.assertIsDisplayed()
.assertIsNotEnabled()
}
@Test
fun sign_In_Button_Disabled_When_Password_Input_Has_No_Content() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.assertIsDisplayed()
.assertIsNotEnabled()
}
@Test
fun sign_Up_Button_Enabled_With_Valid_Form_Content() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.assertIsDisplayed()
.assertIsEnabled()
}
@Test
fun sign_Up_Button_Disabled_When_Email_Input_Has_No_Content() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.assertIsDisplayed()
.assertIsNotEnabled()
}
@Test
fun sign_Up_Button_Disabled_When_Password_Input_Has_No_Content() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.assertIsDisplayed()
.assertIsNotEnabled()
}
@Test
fun sign_In_Error_Alert_Dialog_Not_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithAuthenticationErrorDialogAndAlertDialogTitleWhoops()
.assertDoesNotExist()
}
@Test
fun sign_Up_Error_Alert_Dialog_Not_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithAuthenticationErrorDialogAndAlertDialogTitleWhoops()
.assertDoesNotExist()
}
/**
* NOTE:
*
* For this test case to pass when it should, whatever time delay that's used in the
* authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt,
* the time delay used in this test case should be more than it.
*
* E.g., if 2000L milliseconds is used in the ViewModel, its recommended to wait for at least
* 2500L milliseconds in the test case.
*
* Compose waitUntil test API as an alternative to Espresso's Idling Resources
* ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* Since a Repository (which a ViewModel would depend on for network or disk I/O call) or a
* ViewModel (for time consuming task) takes some amount of time to fetch data or compute an
* operation, the Compose waitUntil() test API shouldn't be used for this kind of scenario. Use
* test doubles ( https://developer.android.com/training/testing/fundamentals/test-doubles )
* instead.
*
* Assuming you want to test a part of the app the involves a network operation, the Repository
* should be injectable in the ViewModel so that a fake Repository can be injected into the
* ViewModel during testing in order to simulate the network operation.
*
* If you load data in a background thread, the test framework might execute the next operation
* too soon, making your test fail. The worst situation is when this happens only a small
* percentage of the time, making the test flaky.
*
* So this is where test doubles is really necessary as loading data is usually fast, especially
* when using fake data, so why waste time with idling resources. If you don’t want to modify
* your code under test to expose when it’s busy, one option is to waitUntil() a certain
* condition is met, instead of waiting for an arbitrary amount of time.
*
* But this should be used as a last resort when installing an Idling Resource is not practical
* or you don’t want to modify your production code. Using it before every test statement should
* be considered a smell, as it pollutes the test code unnecessarily, making it harder to
* maintain.
*
* But wait..., when you have hundreds or thousands of UI tests, you want tests to be as fast as
* possible. Also, sometimes emulators or devices misbehave and jank, making that operation take
* a bit longer than than the operation, breaking your build. When you have hundreds of tests
* this becomes a huge issue.
*
* When should you use waitUntil() then? A good use case for it is loading data from an
* observable (with LiveData, Kotlin Flow or RxJava). When your UI needs to receive multiple
* updates before you consider it idle, you might want to simplify synchronization using
* waitUntil().
*
* There is an open issue ( https://issuetracker.google.com/226934294 ) to introduce a more
* sophisticated version of this helper in the future but for now, happy… wait for it… testing!
*
* For more info, see https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473
*/
@Test
fun sign_In_Error_Alert_Dialog_Displayed_After_Error() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.performClick()
composeTestRule.waitUntilExists(
matcher = authenticationScreenTestUtil.hasTestTagAuthenticationErrorDialogAndHasAlertDialogTitleWhoops(),
timeoutMillis = TIMEOUT_MILLIS_2500L,
useUnmergedTree = TRUE // Optional.
)
authenticationScreenTestUtil
.onNodeWithAuthenticationErrorDialogAndAlertDialogTitleWhoops(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
/**
* NOTE:
*
* For this test case to pass when it should, whatever time delay that's used in the
* authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt,
* the time delay used in this test case should be more than it.
*
* E.g., if 2000L milliseconds is used in the ViewModel, its recommended to wait for at least
* 2500L milliseconds in the test case.
*
* Compose waitUntil test API as an alternative to Espresso's Idling Resources
* ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* Since a Repository (which a ViewModel would depend on for network or disk I/O call) or a
* ViewModel (for time consuming task) takes some amount of time to fetch data or compute an
* operation, the Compose waitUntil() test API shouldn't be used for this kind of scenario. Use
* test doubles ( https://developer.android.com/training/testing/fundamentals/test-doubles )
* instead.
*
* Assuming you want to test a part of the app the involves a network operation, the Repository
* should be injectable in the ViewModel so that a fake Repository can be injected into the
* ViewModel during testing in order to simulate the network operation.
*
* If you load data in a background thread, the test framework might execute the next operation
* too soon, making your test fail. The worst situation is when this happens only a small
* percentage of the time, making the test flaky.
*
* So this is where test doubles is really necessary as loading data is usually fast, especially
* when using fake data, so why waste time with idling resources. If you don’t want to modify
* your code under test to expose when it’s busy, one option is to waitUntil() a certain
* condition is met, instead of waiting for an arbitrary amount of time.
*
* But this should be used as a last resort when installing an Idling Resource is not practical
* or you don’t want to modify your production code. Using it before every test statement should
* be considered a smell, as it pollutes the test code unnecessarily, making it harder to
* maintain.
*
* But wait..., when you have hundreds or thousands of UI tests, you want tests to be as fast as
* possible. Also, sometimes emulators or devices misbehave and jank, making that operation take
* a bit longer than than the operation, breaking your build. When you have hundreds of tests
* this becomes a huge issue.
*
* When should you use waitUntil() then? A good use case for it is loading data from an
* observable (with LiveData, Kotlin Flow or RxJava). When your UI needs to receive multiple
* updates before you consider it idle, you might want to simplify synchronization using
* waitUntil().
*
* There is an open issue ( https://issuetracker.google.com/226934294 ) to introduce a more
* sophisticated version of this helper in the future but for now, happy… wait for it… testing!
*
* For more info, see https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473
*/
@Test
fun sign_Up_Error_Alert_Dialog_Displayed_After_Error() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.performClick()
composeTestRule.waitUntilExists(
matcher = authenticationScreenTestUtil.hasTestTagAuthenticationErrorDialogAndHasAlertDialogTitleWhoops(),
timeoutMillis = TIMEOUT_MILLIS_2500L,
useUnmergedTree = TRUE // Optional.
)
authenticationScreenTestUtil
.onNodeWithAuthenticationErrorDialogAndAlertDialogTitleWhoops(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
@Test
fun sign_In_Progress_Indicator_Not_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor()
.assertDoesNotExist()
}
@Test
fun sign_Up_Progress_Indicator_Not_Displayed_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor()
.assertDoesNotExist()
}
/**
* NOTE:
*
* Reducing the time delay to, e.g., 1 millisecond in the authenticate() function in
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt
* will cause the test to fail with the following message:
*
* "java.lang.AssertionError: Failed to perform isDisplayed check. Reason: Expected exactly '1'
* node but could not find any node that satisfies: (TestTag = 'ui.screens.authentication.uicomponents.authentication-progress')"
*
* This is because the length of time for the CircularProgressIndicator with the testTag
* "ui.screens.authentication.uicomponents.authentication-progress" to remain on the screen
* before it disappears is 1ms. 1 millisecond 0.001 second which is an ultra-short time.
*
* For a production app, if the time delay is so short for the CircularProgressIndicator to be
* noticeable then a simulated delay would have to be injected for the test to pass.
*/
@Test
fun sign_In_Progress_Indicator_Displayed_While_Loading() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.performClick()
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor()
.assertIsDisplayed()
}
/**
* NOTE:
*
* Reducing the time delay to, e.g., 1 millisecond in the authenticate() function in
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt
* will cause the test to fail with the following message:
*
* "java.lang.AssertionError: Failed to perform isDisplayed check. Reason: Expected exactly '1'
* node but could not find any node that satisfies: (TestTag = 'ui.screens.authentication.uicomponents.authentication-progress')"
*
* This is because the length of time for the CircularProgressIndicator with the testTag
* "ui.screens.authentication.uicomponents.authentication-progress" to remain on the screen
* before it disappears is 1ms. 1 millisecond 0.001 second which is an ultra-short time.
*
* For a production app, if the time delay is so short for the CircularProgressIndicator to be
* noticeable then a simulated delay would have to be injected for the test to pass.
*/
@Test
fun sign_Up_Progress_Indicator_Displayed_While_Loading() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.performClick()
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor()
.assertIsDisplayed()
}
/**
* NOTE:
*
* For this test case to pass when it should, whatever time delay that's used in the
* authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt,
* the time delay used in this test case should be more than it.
*
* E.g., if 2000L milliseconds is used in the ViewModel, its recommended to wait for at least
* 2500L milliseconds in the test case.
*
* Compose waitUntil test API as an alternative to Espresso's Idling Resources
* ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* Since a Repository (which a ViewModel would depend on for network or disk I/O call) or a
* ViewModel (for time consuming task) takes some amount of time to fetch data or compute an
* operation, the Compose waitUntil() test API shouldn't be used for this kind of scenario. Use
* test doubles ( https://developer.android.com/training/testing/fundamentals/test-doubles )
* instead.
*
* Assuming you want to test a part of the app the involves a network operation, the Repository
* should be injectable in the ViewModel so that a fake Repository can be injected into the
* ViewModel during testing in order to simulate the network operation.
*
* If you load data in a background thread, the test framework might execute the next operation
* too soon, making your test fail. The worst situation is when this happens only a small
* percentage of the time, making the test flaky.
*
* So this is where test doubles is really necessary as loading data is usually fast, especially
* when using fake data, so why waste time with idling resources. If you don’t want to modify
* your code under test to expose when it’s busy, one option is to waitUntil() a certain
* condition is met, instead of waiting for an arbitrary amount of time.
*
* But this should be used as a last resort when installing an Idling Resource is not practical
* or you don’t want to modify your production code. Using it before every test statement should
* be considered a smell, as it pollutes the test code unnecessarily, making it harder to
* maintain.
*
* But wait..., when you have hundreds or thousands of UI tests, you want tests to be as fast as
* possible. Also, sometimes emulators or devices misbehave and jank, making that operation take
* a bit longer than than the operation, breaking your build. When you have hundreds of tests
* this becomes a huge issue.
*
* When should you use waitUntil() then? A good use case for it is loading data from an
* observable (with LiveData, Kotlin Flow or RxJava). When your UI needs to receive multiple
* updates before you consider it idle, you might want to simplify synchronization using
* waitUntil().
*
* There is an open issue ( https://issuetracker.google.com/226934294 ) to introduce a more
* sophisticated version of this helper in the future but for now, happy… wait for it… testing!
*
* For more info, see https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473
*/
@Test
fun sign_In_Progress_Indicator_Not_Displayed_After_Loading() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.performClick()
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
composeTestRule.waitUntilDoesNotExist(
matcher = authenticationScreenTestUtil.hasTestTagCircularProgressIndicatorAndHasCircularProgressIndicatorColorArgbPresetColor(),
timeoutMillis = TIMEOUT_MILLIS_2500L,
useUnmergedTree = TRUE // Optional.
)
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor(
useUnmergedTree = TRUE // Optional
)
.assertDoesNotExist()
}
/**
* NOTE:
*
* For this test case to pass when it should, whatever time delay that's used in the
* authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt,
* the time delay used in this test case should be more than it.
*
* E.g., if 2000L milliseconds is used in the ViewModel, its recommended to wait for at least
* 2500L milliseconds in the test case.
*
* Compose waitUntil test API as an alternative to Espresso's Idling Resources
* ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* Since a Repository (which a ViewModel would depend on for network or disk I/O call) or a
* ViewModel (for time consuming task) takes some amount of time to fetch data or compute an
* operation, the Compose waitUntil() test API shouldn't be used for this kind of scenario. Use
* test doubles ( https://developer.android.com/training/testing/fundamentals/test-doubles )
* instead.
*
* Assuming you want to test a part of the app the involves a network operation, the Repository
* should be injectable in the ViewModel so that a fake Repository can be injected into the
* ViewModel during testing in order to simulate the network operation.
*
* If you load data in a background thread, the test framework might execute the next operation
* too soon, making your test fail. The worst situation is when this happens only a small
* percentage of the time, making the test flaky.
*
* So this is where test doubles is really necessary as loading data is usually fast, especially
* when using fake data, so why waste time with idling resources. If you don’t want to modify
* your code under test to expose when it’s busy, one option is to waitUntil() a certain
* condition is met, instead of waiting for an arbitrary amount of time.
*
* But this should be used as a last resort when installing an Idling Resource is not practical
* or you don’t want to modify your production code. Using it before every test statement should
* be considered a smell, as it pollutes the test code unnecessarily, making it harder to
* maintain.
*
* But wait..., when you have hundreds or thousands of UI tests, you want tests to be as fast as
* possible. Also, sometimes emulators or devices misbehave and jank, making that operation take
* a bit longer than than the operation, breaking your build. When you have hundreds of tests
* this becomes a huge issue.
*
* When should you use waitUntil() then? A good use case for it is loading data from an
* observable (with LiveData, Kotlin Flow or RxJava). When your UI needs to receive multiple
* updates before you consider it idle, you might want to simplify synchronization using
* waitUntil().
*
* There is an open issue ( https://issuetracker.google.com/226934294 ) to introduce a more
* sophisticated version of this helper in the future but for now, happy… wait for it… testing!
*
* For more info, see https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473
*/
@Test
fun sign_Up_Progress_Indicator_Not_Displayed_After_Loading() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.performClick()
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
composeTestRule.waitUntilDoesNotExist(
matcher = authenticationScreenTestUtil.hasTestTagCircularProgressIndicatorAndHasCircularProgressIndicatorColorArgbPresetColor(),
timeoutMillis = TIMEOUT_MILLIS_2500L,
useUnmergedTree = TRUE // Optional.
)
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor(
useUnmergedTree = TRUE // Optional
)
.assertDoesNotExist()
}
/**
* NOTE:
*
* For this test case to pass when it should, whatever time delay that's used in the
* authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt,
* the time delay used in this test case should be more than it.
*
* E.g., if 2000L milliseconds is used in the ViewModel, its recommended to wait for at least
* 2500L milliseconds in the test case.
*
* Compose waitUntil test API as an alternative to Espresso's Idling Resources
* ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* Since a Repository (which a ViewModel would depend on for network or disk I/O call) or a
* ViewModel (for time consuming task) takes some amount of time to fetch data or compute an
* operation, the Compose waitUntil() test API shouldn't be used for this kind of scenario. Use
* test doubles ( https://developer.android.com/training/testing/fundamentals/test-doubles )
* instead.
*
* Assuming you want to test a part of the app the involves a network operation, the Repository
* should be injectable in the ViewModel so that a fake Repository can be injected into the
* ViewModel during testing in order to simulate the network operation.
*
* If you load data in a background thread, the test framework might execute the next operation
* too soon, making your test fail. The worst situation is when this happens only a small
* percentage of the time, making the test flaky.
*
* So this is where test doubles is really necessary as loading data is usually fast, especially
* when using fake data, so why waste time with idling resources. If you don’t want to modify
* your code under test to expose when it’s busy, one option is to waitUntil() a certain
* condition is met, instead of waiting for an arbitrary amount of time.
*
* But this should be used as a last resort when installing an Idling Resource is not practical
* or you don’t want to modify your production code. Using it before every test statement should
* be considered a smell, as it pollutes the test code unnecessarily, making it harder to
* maintain.
*
* But wait..., when you have hundreds or thousands of UI tests, you want tests to be as fast as
* possible. Also, sometimes emulators or devices misbehave and jank, making that operation take
* a bit longer than than the operation, breaking your build. When you have hundreds of tests
* this becomes a huge issue.
*
* When should you use waitUntil() then? A good use case for it is loading data from an
* observable (with LiveData, Kotlin Flow or RxJava). When your UI needs to receive multiple
* updates before you consider it idle, you might want to simplify synchronization using
* waitUntil().
*
* There is an open issue ( https://issuetracker.google.com/226934294 ) to introduce a more
* sophisticated version of this helper in the future but for now, happy… wait for it… testing!
*
* For more info, see https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473
*/
@Test
fun sign_In_Ui_Components_Displayed_After_Loading() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignIn()
.performClick()
composeTestRule.waitUntilExists(
matcher = authenticationScreenTestUtil.hasTestTagAuthenticationTitleAndHasTextExactlySignInToYourAccount(), // authenticationScreenTestUtil.hasTestTagAuthenticationScreen()
timeoutMillis = TIMEOUT_MILLIS_2500L
)
authenticationScreenTestUtil
.onNodeWithAuthenticationScreen()
.assertExists()
/**
* This would fail the test if [AuthenticationScreenTestUtil.hasTestTagAuthenticationScreen] is used in the above
* [ComposeContentTestRule.waitUntilExists] function (NB: this is an extension function).
*/
authenticationScreenTestUtil
.onNodeWithAuthenticationTitleAndTextExactlySignInToYourAccount()
.assertExists()
}
/**
* NOTE:
*
* For this test case to pass when it should, whatever time delay that's used in the
* authenticate() function in app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/stateholders/AuthenticationViewModel.kt,
* the time delay used in this test case should be more than it.
*
* E.g., if 2000L milliseconds is used in the ViewModel, its recommended to wait for at least
* 2500L milliseconds in the test case.
*
* Compose waitUntil test API as an alternative to Espresso's Idling Resources
* ( https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473 ).
*
* Since a Repository (which a ViewModel would depend on for network or disk I/O call) or a
* ViewModel (for time consuming task) takes some amount of time to fetch data or compute an
* operation, the Compose waitUntil() test API shouldn't be used for this kind of scenario. Use
* test doubles ( https://developer.android.com/training/testing/fundamentals/test-doubles )
* instead.
*
* Assuming you want to test a part of the app the involves a network operation, the Repository
* should be injectable in the ViewModel so that a fake Repository can be injected into the
* ViewModel during testing in order to simulate the network operation.
*
* If you load data in a background thread, the test framework might execute the next operation
* too soon, making your test fail. The worst situation is when this happens only a small
* percentage of the time, making the test flaky.
*
* So this is where test doubles is really necessary as loading data is usually fast, especially
* when using fake data, so why waste time with idling resources. If you don’t want to modify
* your code under test to expose when it’s busy, one option is to waitUntil() a certain
* condition is met, instead of waiting for an arbitrary amount of time.
*
* But this should be used as a last resort when installing an Idling Resource is not practical
* or you don’t want to modify your production code. Using it before every test statement should
* be considered a smell, as it pollutes the test code unnecessarily, making it harder to
* maintain.
*
* But wait..., when you have hundreds or thousands of UI tests, you want tests to be as fast as
* possible. Also, sometimes emulators or devices misbehave and jank, making that operation take
* a bit longer than than the operation, breaking your build. When you have hundreds of tests
* this becomes a huge issue.
*
* When should you use waitUntil() then? A good use case for it is loading data from an
* observable (with LiveData, Kotlin Flow or RxJava). When your UI needs to receive multiple
* updates before you consider it idle, you might want to simplify synchronization using
* waitUntil().
*
* There is an open issue ( https://issuetracker.google.com/226934294 ) to introduce a more
* sophisticated version of this helper in the future but for now, happy… wait for it… testing!
*
* For more info, see https://medium.com/androiddevelopers/alternatives-to-idling-resources-in-compose-tests-8ae71f9fc473
*/
@Test
fun sign_Up_Ui_Components_Displayed_After_Loading() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performTextInput(text = INPUT_CONTENT_EMAIL)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(text = INPUT_CONTENT_PASSWORD)
authenticationScreenTestUtil
.onNodeWithAuthenticationButtonAndTextExactlySignUp()
.performClick()
composeTestRule
.waitUntilExists(
matcher = authenticationScreenTestUtil.hasTestTagAuthenticationTitleAndHasTextExactlySignUpForAnAccount(), // authenticationScreenTestUtil.hasTestTagAuthenticationScreen()
timeoutMillis = TIMEOUT_MILLIS_2500L
)
authenticationScreenTestUtil
.onNodeWithAuthenticationScreen()
.assertExists()
/**
* This would fail the test if [AuthenticationScreenTestUtil.hasTestTagAuthenticationScreen] is used in the above
* [ComposeContentTestRule.waitUntilExists] function (NB: this is an extension function).
*/
authenticationScreenTestUtil
.onNodeWithAuthenticationTitleAndTextExactlySignUpForAnAccount()
.assertExists()
}
//....|
@Test
fun sign_In_Email_Text_Field_Is_Focused_When_Clicked() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
performClick()
assertIsFocused()
}
}
@Test
fun sign_In_Password_Text_Field_Is_Focused_When_Clicked() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.apply {
performClick()
assertIsFocused()
}
}
@Test
fun sign_Up_Email_Text_Field_Is_Focused_When_Clicked() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
performClick()
assertIsFocused()
}
}
@Test
fun sign_Up_Password_Text_Field_Is_Focused_When_Clicked() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.apply {
performClick()
assertIsFocused()
}
}
//....|
@Test
fun sign_In_Password_Text_Field_Is_Focused_When_Next_Ime_Action_Clicked_From_Email_Text_Field() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
// Optional
performTextInput(
text = INPUT_CONTENT_EMAIL
)
performImeAction()
}
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsFocused()
}
@Test
fun sign_Up_Password_Text_Field_Is_Focused_When_Next_Ime_Action_Clicked_From_Email_Text_Field() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
// Optional
performTextInput(
text = INPUT_CONTENT_EMAIL
)
performImeAction()
}
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsFocused()
}
@Test
fun sign_In_Progress_Indicator_Displays_When_Done_Ime_Action_Clicked_From_Password_Text_Field() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
// Optional
performTextInput(
text = INPUT_CONTENT_EMAIL
)
performImeAction()
}
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.apply {
// Optional
performTextInput(
text = INPUT_CONTENT_PASSWORD
)
performImeAction()
}
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor()
.assertIsDisplayed()
}
@Test
fun sign_Up_Progress_Indicator_Displays_When_Done_Ime_Action_Clicked_From_Password_Text_Field() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
// Optional
performTextInput(
text = INPUT_CONTENT_EMAIL
)
performImeAction()
}
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.apply {
// Optional
performTextInput(
text = INPUT_CONTENT_PASSWORD
)
performImeAction()
}
authenticationScreenTestUtil
.onNodeWithCircularProgressIndicatorAndCircularProgressIndicatorColorArgbPresetColor()
.assertIsDisplayed()
}
@Test
fun sign_Up_No_Password_Requirement_Satisfied_By_Default() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersAndTextExactlyAtLeastEightCharactersNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterAndTextExactlyAtLeastOneUppercaseLetterNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitAndTextExactlyAtLeastOneDigitNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
}
/**
* For this test case to pass when it should, the code in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt
* would need to be changed to be like the one in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt.another_approach
*/
@Test
fun sign_Up_No_Password_Requirement_Satisfied_By_Default_AnotherApproach() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersNeededAndTextExactlyAtLeastEightCharacters(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterNeededAndTextExactlyAtLeastOneUppercaseLetter(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitNeededAndTextExactlyAtLeastOneDigit(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
@Test
fun sign_Up_Only_At_Least_Eight_Characters_Satisfied() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD_PASSWORD
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersAndTextExactlyAtLeastEightCharactersSatisfied(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterAndTextExactlyAtLeastOneUppercaseLetterNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitAndTextExactlyAtLeastOneDigitNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
}
/**
* For this test case to pass when it should, the code in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt
* would need to be changed to be like the one in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt.another_approach
*/
@Test
fun sign_Up_Only_At_Least_Eight_Characters_Satisfied_AnotherApproach() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD_PASSWORD
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersSatisfiedAndTextExactlyAtLeastEightCharacters(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterNeededAndTextExactlyAtLeastOneUppercaseLetter(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitNeededAndTextExactlyAtLeastOneDigit(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
@Test
fun sign_Up_Only_At_Least_One_Uppercase_Letter_Satisfied() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD_PASS
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersAndTextExactlyAtLeastEightCharactersNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterAndTextExactlyAtLeastOneUppercaseLetterSatisfied(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitAndTextExactlyAtLeastOneDigitNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
}
/**
* For this test case to pass when it should, the code in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt
* would need to be changed to be like the one in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt.another_approach
*/
@Test
fun sign_Up_Only_At_Least_One_Uppercase_Letter_Satisfied_AnotherApproach() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD_PASS
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersNeededAndTextExactlyAtLeastEightCharacters(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterSatisfiedAndTextExactlyAtLeastOneUppercaseLetter(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitNeededAndTextExactlyAtLeastOneDigit(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
@Test
fun sign_Up_Only_At_Least_One_Digit_Satisfied() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD_1PASS
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersAndTextExactlyAtLeastEightCharactersNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterAndTextExactlyAtLeastOneUppercaseLetterNeeded(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitAndTextExactlyAtLeastOneDigitSatisfied(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
}
/**
* For this test case to pass when it should, the code in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt
* would need to be changed to be like the one in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt.another_approach
*/
@Test
fun sign_Up_Only_At_Least_One_Digit_Satisfied_AnotherApproach() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD_1PASS
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersNeededAndTextExactlyAtLeastEightCharacters(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterNeededAndTextExactlyAtLeastOneUppercaseLetter(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitSatisfiedAndTextExactlyAtLeastOneDigit(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
@Test
fun sign_Up_All_Password_Requirements_Satisfied() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersAndTextExactlyAtLeastEightCharactersSatisfied(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterAndTextExactlyAtLeastOneUppercaseLetterSatisfied(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitAndTextExactlyAtLeastOneDigitSatisfied(
useUnmergedTree = TRUE // Optional.
)
.assertIsDisplayed()
}
/**
* For this test case to pass when it should, the code in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt
* would need to be changed to be like the one in the file
* app/src/main/java/emperorfin/android/militaryjet/ui/screens/authentication/uicomponents/Requirement.kt.another_approach
*/
@Test
fun sign_Up_All_Password_Requirements_Satisfied_AnotherApproach() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performTextInput(
text = INPUT_CONTENT_PASSWORD
)
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastEightCharactersSatisfiedAndTextExactlyAtLeastEightCharacters(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneUppercaseLetterSatisfiedAndTextExactlyAtLeastOneUppercaseLetter(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordRequirementAtLeastOneDigitSatisfiedAndTextExactlyAtLeastOneDigit(
useUnmergedTree = TRUE // Optional
)
.assertIsDisplayed()
}
@Test
fun sign_In_Perform_Key_Press_On_Text_Fields() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = TRUE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
performClick()
// performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_SHIFT_LEFT)))
// performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_SHIFT_RIGHT)))
// performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_CAPS_LOCK)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_C)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_O)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_N)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_T)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_A)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_C)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_T)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_AT)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_E)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_M)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_A)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_I)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_L)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_PERIOD)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_C)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_O)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_M)))
assertTextContains(value = INPUT_CONTENT_EMAIL)
}
// Just to change the VisualTransformation of the PasswordInput so the test could pass when
// it should.
authenticationScreenTestUtil
.onNodeWithPasswordInputTrailingIcon()
.performClick()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.apply {
performClick()
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_P)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_A)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_S)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_S)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_W)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_O)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_R)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_D)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_1)))
assertTextContains(value = INPUT_CONTENT_PASSWORD.lowercase())
}
}
// If this test case fails, try to re-run it for a second time (which should pass).
@Test
fun sign_Up_Perform_Key_Press_On_Text_Fields() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.apply {
performClick()
// performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_SHIFT_LEFT)))
// performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_SHIFT_RIGHT)))
// performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_CAPS_LOCK)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_C)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_O)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_N)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_T)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_A)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_C)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_T)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_AT)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_E)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_M)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_A)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_I)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_L)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_PERIOD)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_C)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_O)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_M)))
assertTextContains(value = INPUT_CONTENT_EMAIL)
}
// Just to change the VisualTransformation of the PasswordInput so the test could pass when
// it should.
authenticationScreenTestUtil
.onNodeWithPasswordInputTrailingIcon()
.performClick()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.apply {
performClick()
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_P)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_A)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_S)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_S)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_W)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_O)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_R)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_D)))
performKeyPress(KeyEvent(NativeKeyEvent(ACTION_DOWN, KEYCODE_1)))
assertTextContains(value = INPUT_CONTENT_PASSWORD.lowercase())
}
}
@Test
fun sign_In_To_Sign_Up_And_Back_To_Sign_In() {
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(isSignInMode = FALSE)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
// This should have been used but navigation has been between modes (SignIn and SignUp) but
// inside of a single AuthenticationScreen screen (i.e. route/destination).
// Espresso.pressBack()
authenticationScreenTestUtil
.onNodeWithAuthenticationToggleModeAndTextExactlyAlreadyHaveAnAccount()
.performClick()
authenticationScreenTestUtil
.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
}
@Test
fun sign_In_No_Text_Field_Showing_Soft_Keyboard_By_Default() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_In_Email_Input_Shows_Soft_Keyboard_When_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
}
@Test
fun sign_In_Password_Input_Shows_Soft_Keyboard_When_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
}
@Test
fun sign_In_Email_Input_Soft_Keyboard_Manually_Closes_After_Shown() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
// Before this point of trying to close the soft keyboard, the keyboard must have been shown
// since a click was performed on the TextField which automatically shows the keyboard.
// It suffices to say that hideKeyboard() rather than hideKeyboardIfShown() (even though
// with it the test would pass when it should but it doesn't properly test that the keyboard
// was actually shown before trying to close it) should be called on the KeyboardHelper
// object.
keyboardHelper.hideKeyboard()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_In_Password_Input_Soft_Keyboard_Manually_Closes_After_Shown() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
// Before this point of trying to close the soft keyboard, the keyboard must have been shown
// since a click was performed on the TextField which automatically shows the keyboard.
// It suffices to say that hideKeyboard() rather than hideKeyboardIfShown() (even though
// with it the test would pass when it should but it doesn't properly test that the keyboard
// was actually shown before trying to close it) should be called on the KeyboardHelper
// object.
keyboardHelper.hideKeyboard()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_In_Email_Input_Soft_Keyboard_Closes_When_Next_Ime_Action_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performImeAction()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_In_Password_Input_Soft_Keyboard_Closes_When_Done_Ime_Action_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performImeAction()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
// If this test fails, try a re-run (may be more than once - it should pass).
@Test
fun sign_In_Password_Input_Soft_Keyboard_Shown_When_Next_Ime_Action_Clicked_From_Email_Input() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = TRUE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.assertAuthenticationTitleAndTextExactlySignInToYourAccountIsDisplayed()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performImeAction()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsFocused()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
}
@Test
fun sign_Up_No_Text_Field_Showing_Soft_Keyboard_By_Default() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_Up_Email_Input_Shows_Soft_Keyboard_When_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
}
@Test
fun sign_Up_Password_Input_Shows_Soft_Keyboard_When_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
}
@Test
fun sign_Up_Email_Input_Soft_Keyboard_Manually_Closes_After_Shown() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
// Before this point of trying to close the soft keyboard, the keyboard must have been shown
// since a click was performed on the TextField which automatically shows the keyboard.
// It suffices to say that hideKeyboard() rather than hideKeyboardIfShown() (even though
// with it the test would pass when it should but it doesn't properly test that the keyboard
// was actually shown before trying to close it) should be called on the KeyboardHelper
// object.
keyboardHelper.hideKeyboard()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_Up_Password_Input_Soft_Keyboard_Manually_Closes_After_Shown() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
// Before this point of trying to close the soft keyboard, the keyboard must have been shown
// since a click was performed on the TextField which automatically shows the keyboard.
// It suffices to say that hideKeyboard() rather than hideKeyboardIfShown() (even though
// with it the test would pass when it should but it doesn't properly test that the keyboard
// was actually shown before trying to close it) should be called on the KeyboardHelper
// object.
keyboardHelper.hideKeyboard()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_Up_Email_Input_Soft_Keyboard_Closes_When_Next_Ime_Action_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performImeAction()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_Up_Password_Input_Soft_Keyboard_Closes_When_Done_Ime_Action_Clicked() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.performImeAction()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
}
@Test
fun sign_Up_Password_Input_Soft_Keyboard_Shown_When_Next_Ime_Action_Clicked_From_Email_Input() {
// Since this has been replaced, it should be removed.
// authenticationScreenTestUtil.setContentAsAuthenticationScreenWithKeyboardHelperInitAndAssertItIsDisplayed(
// composeTestRule= composeTestRule, keyboardHelper = keyboardHelper
// )
authenticationScreenTestUtil
.setContentAsAuthenticationScreenAndAssertItIsDisplayed(
keyboardHelper = keyboardHelper, isSignInMode = FALSE
)
// This is no longer necessary and should be removed.
// authenticationScreenTestUtil.navigateFromSignInToSignUpModesAndConfirmTitles(composeTestRule)
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performClick()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.performImeAction()
keyboardHelper.waitForKeyboardVisibility(visible = FALSE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isFalse()
authenticationScreenTestUtil
.onNodeWithEmailInputAndTextExactlyEmailAddress()
.assertIsNotFocused()
authenticationScreenTestUtil
.onNodeWithPasswordInputAndTextExactlyPassword()
.assertIsFocused()
keyboardHelper.waitForKeyboardVisibility(visible = TRUE)
assertThat(keyboardHelper.isSoftwareKeyboardShown()).isTrue()
}
} | 0 | Kotlin | 0 | 28 | e0d9ad8b2b0fc13087d602b88b0c64cf6dddb3c2 | 106,132 | MilitaryJet | Apache License 2.0 |
app/src/main/java/com/example/composedemo/ui/activity/bottombar/BottombarDemActivity.kt | keyur-n | 565,866,258 | false | null | package com.example.composedemo.ui.activity.bottombar
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.navigation.compose.rememberNavController
import com.example.composedemo.ui.theme.ComposeDemoTheme
class BottombarDemActivity:ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// BottomNavigation(navController = nav)
ComposeDemoTheme() {
MainScreenView()
}
}
}
companion object{
fun newIntent(context: Context){
context.startActivity(Intent(context,BottombarDemActivity::class.java))
}
}
}
@Composable
fun MainScreenView(){
val navController = rememberNavController()
Scaffold(
bottomBar = { BottomNavigation(navController = navController) },
) {
it.calculateTopPadding()
NavigationGraph(navController = navController)
}
} | 0 | Kotlin | 0 | 0 | d3e749e8ffb1daf9e2378736ae5411208b4e9458 | 1,185 | compose-demo | Apache License 2.0 |
noria-jvm/src/main/kotlin/noria/utils/Queue.kt | y2k | 136,721,211 | true | {"Kotlin": 104868, "Java": 1211, "HTML": 423} | package noria.utils
import java.util.concurrent.*
import java.util.concurrent.atomic.*
private val callback : AtomicReference<(() -> Unit)?> = AtomicReference(null)
private val pool = Executors.newSingleThreadExecutor() {
Executors.defaultThreadFactory().newThread(it).apply {
name = "Noria-Reconciler"
isDaemon = true
}
}
actual fun scheduleOnce(f: () -> Unit) {
if (callback.compareAndSet(null, f)) {
pool.submit {
val c = callback.getAndSet(null)
c?.invoke()
}
}
}
| 0 | Kotlin | 0 | 2 | ef6d146126aa301d8828e61c0eab544770ed80ad | 543 | noria-kt | Apache License 2.0 |
increase-java-core/src/main/kotlin/com/increase/api/services/async/simulations/RealTimePaymentsTransferServiceAsync.kt | Increase | 614,596,462 | false | null | @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102
package com.increase.api.services.async.simulations
import com.increase.api.core.RequestOptions
import com.increase.api.models.InboundRealTimePaymentsTransferSimulationResult
import com.increase.api.models.RealTimePaymentsTransfer
import com.increase.api.models.SimulationRealTimePaymentsTransferCompleteParams
import com.increase.api.models.SimulationRealTimePaymentsTransferCreateInboundParams
import java.util.concurrent.CompletableFuture
interface RealTimePaymentsTransferServiceAsync {
/**
* Simulates submission of a Real Time Payments transfer and handling the response from the
* destination financial institution. This transfer must first have a `status` of
* `pending_submission`.
*/
@JvmOverloads
fun complete(
params: SimulationRealTimePaymentsTransferCompleteParams,
requestOptions: RequestOptions = RequestOptions.none()
): CompletableFuture<RealTimePaymentsTransfer>
/**
* Simulates an inbound Real Time Payments transfer to your account. Real Time Payments are a
* beta feature.
*/
@JvmOverloads
fun createInbound(
params: SimulationRealTimePaymentsTransferCreateInboundParams,
requestOptions: RequestOptions = RequestOptions.none()
): CompletableFuture<InboundRealTimePaymentsTransferSimulationResult>
}
| 1 | null | 0 | 2 | ee89d5acc6e3b3f5b5a0c9750000c1f8d2b717eb | 1,416 | increase-java | Apache License 2.0 |
smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/integration/httpResponse/HttpResponseBindingErrorNarrowGenerator.kt | awslabs | 242,852,561 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.smithy.swift.codegen.integration.httpResponse
import software.amazon.smithy.aws.traits.protocols.AwsQueryErrorTrait
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.model.shapes.StructureShape
import software.amazon.smithy.swift.codegen.ClientRuntimeTypes
import software.amazon.smithy.swift.codegen.SwiftDependency
import software.amazon.smithy.swift.codegen.SwiftTypes
import software.amazon.smithy.swift.codegen.declareSection
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
import software.amazon.smithy.swift.codegen.integration.SectionId
import software.amazon.smithy.swift.codegen.integration.middlewares.handlers.MiddlewareShapeUtils
import software.amazon.smithy.swift.codegen.model.getTrait
class HttpResponseBindingErrorNarrowGenerator(
val ctx: ProtocolGenerator.GenerationContext,
val op: OperationShape,
val unknownServiceErrorSymbol: Symbol
) {
object HttpResponseBindingErrorNarrowGeneratorSectionId : SectionId
fun render() {
val errorShapes = op.errors.map { ctx.model.expectShape(it) as StructureShape }.toSet().sorted()
val operationErrorName = MiddlewareShapeUtils.outputErrorSymbolName(op)
val rootNamespace = ctx.settings.moduleName
val httpBindingSymbol = Symbol.builder()
.definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseBinding.swift")
.name(operationErrorName)
.build()
ctx.delegator.useShapeWriter(httpBindingSymbol) { writer ->
writer.addImport(SwiftDependency.CLIENT_RUNTIME.target)
writer.addImport(unknownServiceErrorSymbol)
val unknownServiceErrorType = unknownServiceErrorSymbol.name
val context = mapOf(
"ctx" to ctx,
"unknownServiceErrorType" to unknownServiceErrorType,
"operationErrorName" to operationErrorName,
"errorShapes" to errorShapes
)
writer.declareSection(HttpResponseBindingErrorNarrowGeneratorSectionId, context) {
writer.openBlock("extension \$L {", "}", operationErrorName) {
writer.openBlock(
"public init(errorType: \$T, httpResponse: \$N, decoder: \$D, message: \$D, requestID: \$D) throws {", "}",
SwiftTypes.String, ClientRuntimeTypes.Http.HttpResponse, ClientRuntimeTypes.Serde.ResponseDecoder, SwiftTypes.String, SwiftTypes.String
) {
writer.write("switch errorType {")
for (errorShape in errorShapes) {
var errorShapeName = resolveErrorShapeName(errorShape)
var errorShapeType = ctx.symbolProvider.toSymbol(errorShape).name
var errorShapeEnumCase = errorShapeType.decapitalize()
writer.write("case \$S : self = .\$L(try \$L(httpResponse: httpResponse, decoder: decoder, message: message, requestID: requestID))", errorShapeName, errorShapeEnumCase, errorShapeType)
}
writer.write("default : self = .unknown($unknownServiceErrorType(httpResponse: httpResponse, message: message, requestID: requestID, errorType: errorType))")
writer.write("}")
}
}
}
}
}
// TODO: Move to be called from a protocol
private fun resolveErrorShapeName(errorShape: StructureShape): String {
errorShape.getTrait<AwsQueryErrorTrait>()?.let {
return it.code
} ?: run {
return ctx.symbolProvider.toSymbol(errorShape).name
}
}
}
| 16 | Kotlin | 16 | 20 | 7b28da158d92cd06a3549140d43b8fbcf64a94a6 | 3,936 | smithy-swift | Apache License 2.0 |
Chapter12/Activity12.01/app/src/main/java/com/packt/android/storage/repository/Result.kt | PacktPublishing | 810,886,298 | false | {"Kotlin": 1028530} | package com.packt.android.storage.repository
sealed class Result<T> {
class Loading<T> : Result<T>()
data class Success<T>(val data: T) : Result<T>()
class Error<T> : Result<T>()
} | 0 | Kotlin | 3 | 2 | 7200427e273b8d0ef7c27991370f7541ae0f6a86 | 194 | How-to-Build-Android-Apps-with-Kotlin-Third-Edition | MIT License |
Chapter12/Activity12.01/app/src/main/java/com/packt/android/storage/repository/Result.kt | PacktPublishing | 810,886,298 | false | {"Kotlin": 1028530} | package com.packt.android.storage.repository
sealed class Result<T> {
class Loading<T> : Result<T>()
data class Success<T>(val data: T) : Result<T>()
class Error<T> : Result<T>()
} | 0 | Kotlin | 3 | 2 | 7200427e273b8d0ef7c27991370f7541ae0f6a86 | 194 | How-to-Build-Android-Apps-with-Kotlin-Third-Edition | MIT License |
app/src/main/java/com/guru/composecookbook/ui/learnwidgets/UICards.kt | Gurupreet | 293,227,683 | false | {"Kotlin": 528795} | package com.guru.composecookbook.ui.learnwidgets
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material3.Icon
import androidx.compose.material.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.guru.composecookbook.R
import com.guru.composecookbook.data.DemoDataProvider
import com.guru.composecookbook.theme.components.Material3Card
import com.guru.composecookbook.theme.typography
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun UICards() {
Text(
text = "UI Cards, Boxes and Lists",
style = typography.h6,
modifier = Modifier.padding(8.dp)
)
val item = remember { DemoDataProvider.item }
Text(
text = "Inbuilt box as container for any Clipping/Alignment controls",
style = typography.subtitle1,
modifier = Modifier.padding(8.dp)
)
Material3Card(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
backgroundColor = MaterialTheme.colorScheme.primary,
shape = RoundedCornerShape(topStart = 16.dp, bottomEnd = 16.dp)
) {
Column {
Text(
text = item.title,
modifier = Modifier.padding(8.dp),
color = MaterialTheme.colorScheme.onPrimary
)
Text(
text = item.subtitle,
modifier = Modifier.padding(8.dp),
color = MaterialTheme.colorScheme.onPrimary
)
}
}
Divider()
Text(text = "Inbuilt Card", style = typography.subtitle1, modifier = Modifier.padding(8.dp))
Material3Card(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(4.dp),
elevation = 4.dp
) {
Row {
Image(
painter = painterResource(id = R.drawable.p3),
contentDescription = null,
modifier = Modifier.size(60.dp)
)
Text(text = item.title, modifier = Modifier.padding(16.dp))
}
}
Divider()
Text(
text = "In-built ListItems",
style = typography.subtitle1,
modifier = Modifier.padding(8.dp)
)
ListItem(text = { Text(item.title) }, secondaryText = { Text(item.subtitle) })
Divider(modifier = Modifier.padding(4.dp))
ListItem(
text = { Text(item.title) },
secondaryText = { Text(item.subtitle) },
singleLineSecondaryText = false
)
Divider(modifier = Modifier.padding(4.dp))
ListItem(text = { Text(item.title) }, secondaryText = { Text(item.subtitle) }, icon = {
Image(
painter = painterResource(R.drawable.p3),
contentDescription = null,
)
})
Divider(modifier = Modifier.padding(4.dp))
//I am not sure why this is not going multiline for secondaryText...
ListItem(
text = { Text(item.title) },
secondaryText = { Text(item.subtitle) },
icon = { Image(painter = painterResource(id = R.drawable.p1), contentDescription = null) },
overlineText = { Text("Overline text") },
singleLineSecondaryText = false
)
Divider()
ListItem(
text = { Text(item.title) },
secondaryText = { Text(item.subtitle) },
icon = { Image(painter = painterResource(id = R.drawable.p2), contentDescription = null) },
trailing = { Icon(Icons.Default.ShoppingCart, contentDescription = null) },
singleLineSecondaryText = false
)
Divider()
} | 13 | Kotlin | 774 | 6,057 | 1b82b0b990648b2ece5c890fef622d9bdb00e4d8 | 4,278 | ComposeCookBook | MIT License |
server/src/main/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/server/impl/players/GetPlayersRouter.kt | Vauhtijuoksu | 394,707,727 | false | {"Kotlin": 389348, "Smarty": 2566, "Dockerfile": 172, "Shell": 106} | package fi.vauhtijuoksu.vauhtijuoksuapi.server.impl.players
import fi.vauhtijuoksu.vauhtijuoksuapi.database.api.VauhtijuoksuDatabase
import fi.vauhtijuoksu.vauhtijuoksuapi.models.Participant
import fi.vauhtijuoksu.vauhtijuoksuapi.server.DependencyInjectionConstants
import fi.vauhtijuoksu.vauhtijuoksuapi.server.impl.base.GetRouter
import io.vertx.ext.web.handler.CorsHandler
import jakarta.inject.Inject
import jakarta.inject.Named
class GetPlayersRouter
@Inject constructor(
@Named(DependencyInjectionConstants.PUBLIC_CORS)
publicEndpointCorsHandler: CorsHandler,
participantDatabase: VauhtijuoksuDatabase<Participant>,
) : GetRouter<Participant>(
publicEndpointCorsHandler,
participantDatabase,
{ participant: Participant -> PlayerResponse.fromParticipant(participant).toJson() },
)
| 11 | Kotlin | 0 | 3 | 99b374a55d914f1ef7b01add4a3dbaaa93f26fdd | 812 | vauhtijuoksu-api | MIT License |
src/main/java/com/micabytes/util/FontHandler.kt | micabytes | 8,377,248 | false | {"Gradle Kotlin DSL": 1, "Proguard": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "XML": 12, "Kotlin": 35, "Java": 1} | package com.micabytes.util
import android.graphics.Typeface
import com.micabytes.Game
import java.util.*
object FontHandler {
private const val FONT_DIR = "fonts"
private val CACHE = HashMap<String, Typeface>()
operator fun get(fontName: String): Typeface? {
return if (CACHE.containsKey(fontName)) {
CACHE[fontName]
} else {
val typeface = Typeface.createFromAsset(Game.instance.assets, FONT_DIR + StringHandler.SLASH + fontName + ".ttf")
CACHE[fontName] = typeface
typeface
}
}
/*
@BindingAdapter("app:font")
@JvmStatic
fun setFont(view: TextView, fontName: String) {
view.typeface = FontHandler[fontName]
}
@BindingAdapter("app:font")
fun setFont(view: Button, fontName: String) {
view.typeface = FontHandler[fontName]
}
*/
}
| 0 | Kotlin | 11 | 21 | b6db6995555b93af0f8d4e955b55dfa285efd606 | 806 | mica-android | Apache License 2.0 |
KotlinMVP/app/src/main/java/com/emedinaa/mvp/presenter/LogInPresenter.kt | emedinaa | 178,754,256 | false | null | package com.emedinaa.mvp.presenter
import com.emedinaa.mvp.data.LogInRepository
import com.emedinaa.mvp.data.OperationCallback
import com.emedinaa.mvp.model.User
import com.emedinaa.mvp.view.LogInContract
class LogInPresenter(val view:LogInContract.View,val repository:LogInRepository):LogInContract.Presenter{
init {
view.presenter=this
}
override fun logIn() {
if (view.validateForm()) {
view.showLoadingView()
repository.logIn(view.usernameField(), view.passwordField(), object : OperationCallback {
override fun onError(obj: Any?) {
view.hideLoadingView()
obj?.let {
if(it is String){
view.showError(it)
}
}?:kotlin.run {
view.showError("Ocurrío un error")
}
}
override fun onSuccess(obj: Any?) {
view.hideLoadingView()
obj?.let {
if(it is User){
view.goToMainView(it)
}
}
}
})
} else {
}
}
} | 0 | Kotlin | 3 | 8 | cdeb2880a1d5f2b481fb3687bf917b1555e020af | 1,266 | kotlin-mvp-volley | Apache License 2.0 |
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/repository/behandling/PostgresBehandlingRepo.kt | navikt | 487,246,438 | false | {"Kotlin": 944586, "Dockerfile": 495, "Shell": 150, "HTML": 45} | package no.nav.tiltakspenger.vedtak.repository.behandling
import kotliquery.Row
import kotliquery.TransactionalSession
import kotliquery.queryOf
import kotliquery.sessionOf
import mu.KotlinLogging
import no.nav.tiltakspenger.domene.behandling.BehandlingIverksatt
import no.nav.tiltakspenger.domene.behandling.BehandlingTilBeslutter
import no.nav.tiltakspenger.domene.behandling.BehandlingVilkårsvurdert
import no.nav.tiltakspenger.domene.behandling.Søknadsbehandling
import no.nav.tiltakspenger.felles.BehandlingId
import no.nav.tiltakspenger.felles.Periode
import no.nav.tiltakspenger.felles.SakId
import no.nav.tiltakspenger.felles.nå
import no.nav.tiltakspenger.vedtak.db.DataSource
import no.nav.tiltakspenger.vedtak.repository.søknad.SøknadDAO
import org.intellij.lang.annotations.Language
import java.time.LocalDateTime
private val LOG = KotlinLogging.logger {}
private val SECURELOG = KotlinLogging.logger("tjenestekall")
// todo Må enten endres til å kunne hente og lagre alle typer behandlinger og ikke bare Søknadsbehandlinger
// eller så må vi lage egne Repo for de andre type behandlingene
internal class PostgresBehandlingRepo(
private val saksopplysningRepo: SaksopplysningRepo = SaksopplysningRepo(),
private val vurderingRepo: VurderingRepo = VurderingRepo(),
private val søknadDAO: SøknadDAO = SøknadDAO(),
private val tiltakDAO: TiltakDAO = TiltakDAO(),
) : BehandlingRepo {
override fun hent(behandlingId: BehandlingId): Søknadsbehandling? {
return sessionOf(DataSource.hikariDataSource).use {
it.transaction { txSession ->
txSession.run(
queryOf(
SqlHentBehandling,
mapOf(
"id" to behandlingId.toString(),
),
).map { row ->
row.toBehandling(txSession)
}.asSingle,
)
}
}
}
override fun hentAlle(): List<Søknadsbehandling> {
return sessionOf(DataSource.hikariDataSource).use {
it.transaction { txSession ->
txSession.run(
queryOf(
SqlHentAlleBehandlinger,
).map { row ->
row.toBehandling(txSession)
}.asList,
)
}
}
}
override fun hentForSak(sakId: SakId): List<Søknadsbehandling> {
return sessionOf(DataSource.hikariDataSource).use {
it.transaction { txSession ->
txSession.run(
queryOf(
SqlHentBehandlingForSak,
mapOf(
"sakId" to sakId.toString(),
),
).map { row ->
row.toBehandling(txSession)
}.asList,
)
}
}
}
override fun hentForJournalpostId(journalpostId: String): Søknadsbehandling? {
return sessionOf(DataSource.hikariDataSource).use {
it.transaction { txSession ->
txSession.run(
queryOf(
SqlHentBehandlingForJournalpostId,
mapOf(
"journalpostId" to journalpostId,
),
).map { row ->
row.toBehandling(txSession)
}.asSingle,
)
}
}
}
override fun lagre(behandling: Søknadsbehandling): Søknadsbehandling {
sessionOf(DataSource.hikariDataSource).use {
it.transaction { txSession ->
val sistEndret = hentSistEndret(behandling.id, txSession)
if (sistEndret == null) {
opprettBehandling(behandling, txSession)
} else {
oppdaterBehandling(sistEndret, behandling, txSession)
}.also {
saksopplysningRepo.lagre(behandling.id, behandling.saksopplysninger, txSession)
søknadDAO.oppdaterBehandlingId(behandling.id, behandling.søknader, txSession)
tiltakDAO.lagre(behandling.id, behandling.tiltak, txSession)
when (behandling) {
is BehandlingIverksatt -> {
vurderingRepo.lagre(behandling.id, behandling.vilkårsvurderinger, txSession)
}
is BehandlingVilkårsvurdert -> {
vurderingRepo.lagre(behandling.id, behandling.vilkårsvurderinger, txSession)
}
is BehandlingTilBeslutter -> {
vurderingRepo.lagre(behandling.id, behandling.vilkårsvurderinger, txSession)
}
is Søknadsbehandling.Opprettet -> {}
}
}
}
}
return behandling
}
private fun oppdaterBehandling(
sistEndret: LocalDateTime,
behandling: Søknadsbehandling,
txSession: TransactionalSession,
): Søknadsbehandling {
SECURELOG.info { "Oppdaterer behandling ${behandling.id}" }
val antRaderOppdatert = txSession.run(
queryOf(
SqlOppdaterBehandling,
mapOf(
"id" to behandling.id.toString(),
"sakId" to behandling.sakId.toString(),
"fom" to behandling.vurderingsperiode.fra,
"tom" to behandling.vurderingsperiode.til,
"tilstand" to finnTilstand(behandling),
"status" to finnStatus(behandling),
"sistEndretOld" to sistEndret,
"sistEndret" to nå(),
"saksbehandler" to if (behandling is BehandlingTilBeslutter) behandling.saksbehandler else null,
),
).asUpdate,
)
if (antRaderOppdatert == 0) {
throw IllegalStateException("Noen andre har endret denne behandlingen ${behandling.id}")
}
return behandling
}
private fun opprettBehandling(behandling: Søknadsbehandling, txSession: TransactionalSession): Søknadsbehandling {
SECURELOG.info { "Oppretter behandling ${behandling.id}" }
val nå = nå()
txSession.run(
queryOf(
sqlOpprettBehandling,
mapOf(
"id" to behandling.id.toString(),
"sakId" to behandling.sakId.toString(),
"fom" to behandling.vurderingsperiode.fra,
"tom" to behandling.vurderingsperiode.til,
"tilstand" to finnTilstand(behandling),
"status" to finnStatus(behandling),
"sistEndret" to nå,
"opprettet" to nå,
),
).asUpdate,
)
return behandling
}
private fun hentSistEndret(behandlingId: BehandlingId, txSession: TransactionalSession): LocalDateTime? =
txSession.run(
queryOf(
sqlHentSistEndret,
mapOf(
"id" to behandlingId.toString(),
),
).map { row -> row.localDateTime("sist_endret") }.asSingle,
)
private fun Row.toBehandling(txSession: TransactionalSession): Søknadsbehandling {
val id = BehandlingId.fromDb(string("id"))
val sakId = SakId.fromDb(string("sakId"))
val fom = localDate("fom")
val tom = localDate("tom")
val status = string("status")
return when (val type = string("tilstand")) {
"søknadsbehandling" -> Søknadsbehandling.Opprettet.fromDb(
id = id,
sakId = sakId,
søknader = søknadDAO.hentMedBehandlingId(id, txSession),
vurderingsperiode = Periode(fom, tom),
saksopplysninger = saksopplysningRepo.hent(id, txSession),
tiltak = tiltakDAO.hent(id, txSession),
)
"Vilkårsvurdert" -> BehandlingVilkårsvurdert.fromDb(
id = id,
sakId = sakId,
søknader = søknadDAO.hentMedBehandlingId(id, txSession),
vurderingsperiode = Periode(fom, tom),
saksopplysninger = saksopplysningRepo.hent(id, txSession),
tiltak = tiltakDAO.hent(id, txSession),
vilkårsvurderinger = vurderingRepo.hent(id, txSession),
status = status,
)
"TilBeslutting" -> BehandlingTilBeslutter.fromDb(
id = id,
sakId = sakId,
søknader = søknadDAO.hentMedBehandlingId(id, txSession),
vurderingsperiode = Periode(fom, tom),
saksopplysninger = saksopplysningRepo.hent(id, txSession),
tiltak = tiltakDAO.hent(id, txSession),
vilkårsvurderinger = vurderingRepo.hent(id, txSession),
status = status,
saksbehandler = string("saksbehandler"),
)
"Iverksatt" -> BehandlingIverksatt.fromDb(
id = id,
sakId = sakId,
søknader = søknadDAO.hentMedBehandlingId(id, txSession),
vurderingsperiode = Periode(fom, tom),
saksopplysninger = saksopplysningRepo.hent(id, txSession),
tiltak = tiltakDAO.hent(id, txSession),
vilkårsvurderinger = vurderingRepo.hent(id, txSession),
status = status,
saksbehandler = string("saksbehandler"),
beslutter = string("attestant"),
)
else -> throw IllegalStateException("Hentet en Behandling $id med ukjent status : $type")
}
}
private fun finnTilstand(behandling: Søknadsbehandling) =
when (behandling) {
is Søknadsbehandling.Opprettet -> "søknadsbehandling"
is BehandlingVilkårsvurdert -> "Vilkårsvurdert"
is BehandlingTilBeslutter -> "TilBeslutting"
is BehandlingIverksatt -> "Iverksatt"
}
private fun finnStatus(behandling: Søknadsbehandling) =
when (behandling) {
is Søknadsbehandling.Opprettet -> "Opprettet"
is BehandlingVilkårsvurdert.Avslag -> "Avslag"
is BehandlingVilkårsvurdert.Innvilget -> "Innvilget"
is BehandlingVilkårsvurdert.Manuell -> "Manuell"
is BehandlingIverksatt.Avslag -> "Avslag"
is BehandlingIverksatt.Innvilget -> "Innvilget"
is BehandlingTilBeslutter.Avslag -> "Avslag"
is BehandlingTilBeslutter.Innvilget -> "Innvilget"
}
private val sqlHentSistEndret = """
select sist_endret from behandling where id = :id
""".trimIndent()
@Language("SQL")
private val sqlOpprettBehandling = """
insert into behandling (
id,
sakId,
fom,
tom,
tilstand,
status,
sist_endret,
opprettet
) values (
:id,
:sakId,
:fom,
:tom,
:tilstand,
:status,
:sistEndret,
:opprettet
)
""".trimIndent()
@Language("SQL")
private val SqlOppdaterBehandling = """
update behandling set
fom = :fom,
tom = :tom,
sakId = :sakId,
tilstand = :tilstand,
status = :status,
sist_endret = :sistEndret,
saksbehandler = :saksbehandler
where id = :id
and sist_endret = :sistEndretOld
""".trimIndent()
@Language("SQL")
private val SqlHentBehandling = """
select * from behandling where id = :id
""".trimIndent()
@Language("SQL")
private val SqlHentBehandlingForSak = """
select * from behandling where sakId = :sakId
""".trimIndent()
@Language("SQL")
private val SqlHentBehandlingForJournalpostId = """
select * from behandling
where id =
(select behandling_id
from søknad
where journalpost_id = :journalpostId)
""".trimIndent()
@Language("SQL")
private val SqlHentAlleBehandlinger = """
select * from behandling
""".trimIndent()
}
| 7 | Kotlin | 0 | 2 | dde1b0532caed17b6bad77e1de4917f829adea1c | 12,546 | tiltakspenger-vedtak | MIT License |
compiler/testData/codegen/boxInline/smap/defaultLambda/kt21827.kt | JakeWharton | 99,388,807 | false | null | // FILE: 1.kt
// SKIP_INLINE_CHECK_IN: lParams$default
package test
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
//A lot of blank lines [Don't delete]
inline fun lParams(initParams: () -> String = {
"OK"
}): String {
val z = "body"
return initParams()
}
// FILE: 2.kt
import test.*
fun box(): String {
return run {
lParams()
}
}
// FILE: 1.smap
SMAP
1.kt
Kotlin
*S Kotlin
*F
+ 1 1.kt
test/_1Kt
*L
1#1,37:1
33#1,2:38
*E
SMAP
1.kt
Kotlin
*S Kotlin
*F
+ 1 1.kt
test/_1Kt$lParams$1
*L
1#1,37:1
*E
// FILE: 2.smap
SMAP
2.kt
Kotlin
*S Kotlin
*F
+ 1 2.kt
_2Kt
+ 2 Standard.kt
kotlin/StandardKt__StandardKt
+ 3 ContractBuilder.kt
kotlin/internal/contracts/ContractBuilderKt
+ 4 1.kt
test/_1Kt
+ 5 1.kt
test/_1Kt$lParams$1
*L
1#1,10:1
34#2:11
37#2:13
43#3:12
30#4,5:14
31#5:19
*E
*S KotlinDebug
*F
+ 1 2.kt
_2Kt
*L
5#1:11
5#1:13
5#1:12
5#1,5:14
5#1:19
*E | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,673 | kotlin | Apache License 2.0 |
feature_tests/kotlin/somelib/src/main/kotlin/dev/diplomattest/somelib/BorrowedFieldsWithBounds.kt | rust-diplomat | 377,296,713 | false | null | package dev.diplomattest.somelib
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
internal interface BorrowedFieldsWithBoundsLib: Library {
fun BorrowedFieldsWithBounds_from_foo_and_strings(foo: Pointer, dstr16X: Slice, utf8StrZ: Slice): BorrowedFieldsWithBoundsNative
}
class BorrowedFieldsWithBoundsNative: Structure(), Structure.ByValue {
@JvmField
var fieldA: Slice = Slice();
@JvmField
var fieldB: Slice = Slice();
@JvmField
var fieldC: Slice = Slice();
// Define the fields of the struct
override fun getFieldOrder(): List<String> {
return listOf("fieldA", "fieldB", "fieldC")
}
}
class BorrowedFieldsWithBounds internal constructor (
internal val nativeStruct: BorrowedFieldsWithBoundsNative,
internal val aEdges: List<Any>,
internal val bEdges: List<Any>,
internal val cEdges: List<Any>
) {
val fieldA: String = PrimitiveArrayTools.getUtf16(nativeStruct.fieldA)
val fieldB: String = PrimitiveArrayTools.getUtf8(nativeStruct.fieldB)
val fieldC: String = PrimitiveArrayTools.getUtf8(nativeStruct.fieldC)
companion object {
internal val libClass: Class<BorrowedFieldsWithBoundsLib> = BorrowedFieldsWithBoundsLib::class.java
internal val lib: BorrowedFieldsWithBoundsLib = Native.load("somelib", libClass)
val NATIVESIZE: Long = Native.getNativeSize(BorrowedFieldsWithBoundsNative::class.java).toLong()
fun fromFooAndStrings(foo: Foo, dstr16X: String, utf8StrZ: String): BorrowedFieldsWithBounds {
val (dstr16XMem, dstr16XSlice) = PrimitiveArrayTools.readUtf16(dstr16X)
val (utf8StrZMem, utf8StrZSlice) = PrimitiveArrayTools.readUtf8(utf8StrZ)
val returnVal = lib.BorrowedFieldsWithBounds_from_foo_and_strings(foo.handle, dstr16XSlice, utf8StrZSlice);
val xEdges: List<Any> = listOf(foo) + listOf(dstr16XMem) + listOf(utf8StrZMem)
val yEdges: List<Any> = listOf(foo) + listOf(utf8StrZMem)
val zEdges: List<Any> = listOf(utf8StrZMem)
val returnStruct = BorrowedFieldsWithBounds(returnVal, xEdges, yEdges, zEdges)
return returnStruct
}
}
}
| 99 | null | 48 | 526 | 808d18ae8a1e687e0ccaa41c74ea626157f88826 | 2,267 | diplomat | Apache License 2.0 |
app/src/main/java/com/example/rental_mobil/Pelanggan/AboutActivity.kt | mrAldirs | 691,938,449 | false | {"Kotlin": 333860} | package com.example.rental_mobil.Pelanggan
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.rental_mobil.R
import com.example.rental_mobil.databinding.ActivityAboutBinding
class AboutActivity : AppCompatActivity() {
private lateinit var b: ActivityAboutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
b = ActivityAboutBinding.inflate(layoutInflater)
setContentView(b.root)
supportActionBar?.setTitle("About")
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
overridePendingTransition(R.anim.slide_in_left, android.R.anim.slide_out_right)
return true
}
override fun onBackPressed() {
super.onBackPressed()
overridePendingTransition(R.anim.slide_in_left, android.R.anim.slide_out_right)
}
} | 1 | Kotlin | 0 | 2 | 624e82b43797c514a0f424ef025d66c4eab53ee8 | 958 | kotlin-rent-car-app | Apache License 2.0 |
core/src/main/java/com/pouyaheydari/android/core/domain/Album.kt | SirLordPouya | 197,946,685 | false | null | package com.pouyaheydari.android.core.domain
data class AlbumResponse(val albums: List<Album>, val totalResults: Int)
data class Album(
val id: Int?,
val albumName: String,
val artistName: String,
var image: String,
)
| 0 | Kotlin | 5 | 23 | ecb4e7627492ba0eedb5a811e9b753a52a8d110c | 236 | MusicManager | Apache License 2.0 |
app/src/androidTest/java/org/calamarfederal/messyink/feature_counter/presentation/create_counter/CreateCounterScreenTest.kt | John-Tuesday | 632,184,075 | false | null | package org.calamarfederal.messyink.feature_counter.presentation.create_counter
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.assertTextContains
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* # Create Counter Screen
* ## Unit Tests
*/
@RunWith(AndroidJUnit4::class)
class CreateCounterScreenTest {
@get:Rule
val composeRule = createComposeRule()
private var counterNameTextState: MutableState<TextFieldValue> = mutableStateOf(TextFieldValue())
private var counterNameText by counterNameTextState
private var counterNameErrorState: MutableState<Boolean> = mutableStateOf(false)
private var counterNameError by counterNameErrorState
private var counterNameHelpState: MutableState<String?> = mutableStateOf(null)
private var counterNameHelp by counterNameHelpState
private lateinit var onCancel: MutableStateFlow<() -> Unit>
private lateinit var onDone: MutableStateFlow<() -> Unit>
private val submitButtonNode get() = composeRule.onNodeWithTag(CreateCounterTestTags.SubmitButton)
private val closeButtonNode get() = composeRule.onNodeWithTag(CreateCounterTestTags.CloseButton)
private val titleFieldNode get() = composeRule.onNodeWithTag(CreateCounterTestTags.TitleTextField)
@Before
fun setUp() {
counterNameTextState = mutableStateOf(TextFieldValue(text = "Test"))
counterNameErrorState = mutableStateOf(false)
counterNameHelpState = mutableStateOf(null)
onCancel = MutableStateFlow({})
onDone = MutableStateFlow({})
composeRule.setContent {
val cancel by onCancel.collectAsState()
val done by onDone.collectAsState()
CreateCounterScreen(
counterName = counterNameText,
counterNameError = counterNameError,
counterNameHelp = counterNameHelp,
isEditCounter = false,
onNameChange = {},
onCancel = cancel,
onDone = done,
)
}
}
@Test
fun `Disable submit button when error`() {
counterNameError = true
submitButtonNode.assertIsNotEnabled()
}
@Test
fun `Enable submit button when no error`() {
counterNameError = false
submitButtonNode.assertIsEnabled()
counterNameError = false
counterNameHelp = "help text"
submitButtonNode.assertIsEnabled()
}
@Test
fun `Close button enabled`() {
closeButtonNode.assertIsEnabled()
}
@Test
fun `Title field shows error message when error`() {
val helpMessage = "help message"
counterNameHelp = helpMessage
counterNameError = true
val semantics = titleFieldNode.fetchSemanticsNode().config
assert(semantics.contains(SemanticsProperties.Error))
titleFieldNode.assertTextContains(helpMessage)
assert(semantics[SemanticsProperties.Error] == helpMessage)
}
@Test
fun `Title field not marked error when no error`() {
counterNameError = false
assert(
!titleFieldNode.fetchSemanticsNode().config.contains(SemanticsProperties.Error)
)
val helpMessage = "help message"
counterNameHelp = helpMessage
counterNameError = false
assert(
!titleFieldNode.fetchSemanticsNode().config.contains(SemanticsProperties.Error)
)
}
@Test
fun `On start the first field is focused`() {
titleFieldNode.assertIsFocused()
}
@Test
fun `Title field Ime action is submit when valid`() {
var hasSubmitted = false
onDone.value = { hasSubmitted = true }
counterNameError = false
assert(
!titleFieldNode.fetchSemanticsNode().config.contains(SemanticsProperties.Error)
)
titleFieldNode.performImeAction()
assert(hasSubmitted)
}
@Test
fun `Title field ime action will not submit when invalid`() {
var hasSubmitted = false
onDone.value = { hasSubmitted = true }
counterNameError = true
assert(
titleFieldNode.fetchSemanticsNode().config.contains(SemanticsProperties.Error)
)
titleFieldNode.performImeAction()
assert(!hasSubmitted)
}
}
| 0 | Kotlin | 0 | 0 | a3091a59f627a677e2a6254991af15e17c40f7db | 5,054 | messy-ink | MIT License |
educational-core/src/com/jetbrains/edu/learning/taskDescription/ui/check/CheckResultLabel.kt | telezhnaya | 264,863,128 | true | {"Kotlin": 2477547, "Java": 634238, "HTML": 131915, "CSS": 12844, "Python": 3994, "JavaScript": 315} | package com.jetbrains.edu.learning.taskDescription.ui.check
import com.intellij.icons.AllIcons
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.jetbrains.edu.learning.checker.CheckResult
import com.jetbrains.edu.learning.courseFormat.CheckStatus
import com.jetbrains.edu.learning.courseFormat.tasks.IdeTask
import com.jetbrains.edu.learning.courseFormat.tasks.Task
import com.jetbrains.edu.learning.courseFormat.tasks.TheoryTask
import icons.EducationalCoreIcons
class CheckResultLabel(task: Task, checkResult: CheckResult) : JBLabel() {
init {
val status = checkResult.status
iconTextGap = JBUI.scale(4)
icon = when (status) {
CheckStatus.Failed -> AllIcons.General.BalloonError
CheckStatus.Solved -> EducationalCoreIcons.ResultCorrect
else -> null
}
foreground = when (status) {
CheckStatus.Failed -> JBColor(0xC7222D, 0xFF5261)
CheckStatus.Solved -> JBColor(0x368746, 0x499C54)
else -> foreground
}
text = when (status) {
CheckStatus.Failed -> "Incorrect"
CheckStatus.Solved -> when (task) {
is IdeTask, is TheoryTask -> "Done"
else -> "Correct"
}
else -> ""
}
border = JBUI.Borders.empty(8, 16, 0, 0)
}
} | 0 | null | 0 | 0 | 9f9492f7505fb86df37c9d582814c075aa3a611d | 1,295 | educational-plugin | Apache License 2.0 |
kMapper-core/src/commonMain/kotlin/de/kotlinBerlin/kMapper/extensions/ReadWritePathConversionExtensions.kt | KotlinBerlin | 287,190,313 | false | null | @file:Suppress("unused")
@file:JvmName("ReadWritePathConversionUtil")
package de.kotlinBerlin.kMapper.extensions
import de.kotlinBerlin.kMapper.ReadWritePath
import de.kotlinBerlin.kMapper.toReadWritePath
import kotlin.jvm.JvmName
import kotlin.reflect.KMutableProperty1
//Not Null
//Path
fun <S, V : Any, V1 : Any> ReadWritePath<S, V?, V1>.notNull(): ReadWritePath<S, V, V1?> = readNotNull().writeNotNull()
fun <S, V : Any, V1 : Any> ReadWritePath<S, V?, V1>.notNull(exceptionBlock: () -> Nothing): ReadWritePath<S, V, V1?> =
readNotNull(exceptionBlock).writeNotNull(exceptionBlock)
//Property
fun <S, V : Any> KMutableProperty1<S, V?>.notNull(): ReadWritePath<S, V, V?> = toReadWritePath().notNull()
fun <S, V : Any> KMutableProperty1<S, V?>.notNull(exceptionBlock: () -> Nothing): ReadWritePath<S, V, V?> = toReadWritePath().notNull(exceptionBlock)
//Map when not null
//Path
fun <S, V : Any, V1 : Any> ReadWritePath<S, V?, V1>.ifPresent(): ReadWritePath<S, V, V1?> = readIfPresent().writeIfPresent()
//Property
fun <S, V : Any> KMutableProperty1<S, V?>.ifPresent(): ReadWritePath<S, V, V?> = toReadWritePath().ifPresent()
//Default value
//Path
fun <S, V : Any, V1 : Any> ReadWritePath<S, V?, V1>.withDefault(readDefault: V, writeDefault: V1): ReadWritePath<S, V, V1?> =
readWithDefault(readDefault).writeWithDefault(writeDefault)
fun <S, V : Any> ReadWritePath<S, V?, V>.withDefault(default: V): ReadWritePath<S, V, V?> =
readWithDefault(default).writeWithDefault(default)
fun <S, V : Any, V1 : Any> ReadWritePath<S, V?, V1>.withDefault(readDefaultBlock: () -> V, writeDefaultBlock: () -> V1): ReadWritePath<S, V, V1?> =
readWithDefault(readDefaultBlock).writeWithDefault(writeDefaultBlock)
fun <S, V : Any> ReadWritePath<S, V?, V>.withDefault(defaultBlock: () -> V): ReadWritePath<S, V, V?> =
readWithDefault(defaultBlock).writeWithDefault(defaultBlock)
//Property
fun <S, V : Any> KMutableProperty1<S, V?>.withDefault(default: V): ReadWritePath<S, V, V?> =
toReadWritePath().withDefault(default)
fun <S, V : Any> KMutableProperty1<S, V?>.withDefault(defaultBlock: () -> V): ReadWritePath<S, V, V?> =
toReadWritePath().withDefault(defaultBlock)
//Double
//Path
@JvmName("doubleAsString")
fun <S> ReadWritePath<S, Double, Double>.asString(): ReadWritePath<S, String, String> =
readAsString().writeFromStr()
fun <S> ReadWritePath<S, String, String>.asDouble(): ReadWritePath<S, Double, Double> =
readAsDouble().writeFromAny()
@JvmName("doubleAsStringOrNull")
fun <S> ReadWritePath<S, Double, Double?>.asStringOrNull(): ReadWritePath<S, String, String> =
readAsString().writeFromStrOrNull()
fun <S> ReadWritePath<S, String, String>.asDoubleOrNull(): ReadWritePath<S, Double?, Double> =
readAsDoubleOrNull().writeFromAny()
@JvmName("doubleAsNullableString")
fun <S> ReadWritePath<S, Double?, Double?>.asString(): ReadWritePath<S, String?, String?> =
readAsString().writeFromStr()
@JvmName("asNullableDouble")
fun <S> ReadWritePath<S, String?, String?>.asDouble(): ReadWritePath<S, Double?, Double?> =
readAsDouble().writeFromAny()
@JvmName("doubleAsNullableStringOrNull")
fun <S> ReadWritePath<S, Double?, Double?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
readAsString().writeFromNullableStrOrNull()
@JvmName("asNullableDoubleOrNull")
fun <S> ReadWritePath<S, String?, String?>.asDoubleOrNull(): ReadWritePath<S, Double?, Double?> =
readAsDoubleOrNull().writeFromAny()
//Property
@JvmName("doubleAsString")
fun <S> KMutableProperty1<S, Double>.asString(): ReadWritePath<S, String, String> =
toReadWritePath().asString()
fun <S> KMutableProperty1<S, String>.asDouble(): ReadWritePath<S, Double, Double> =
toReadWritePath().asDouble()
@JvmName("doubleAsNullableString")
fun <S> KMutableProperty1<S, Double?>.asString(): ReadWritePath<S, String?, String?> =
toReadWritePath().asString()
@JvmName("asNullableDouble")
fun <S> KMutableProperty1<S, String?>.asDouble(): ReadWritePath<S, Double?, Double?> =
toReadWritePath().asDouble()
@JvmName("doubleAsNullableStringOrNull")
fun <S> KMutableProperty1<S, Double?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
toReadWritePath().asStringOrNull()
fun <S> KMutableProperty1<S, String?>.asDoubleOrNull(): ReadWritePath<S, Double?, Double?> =
toReadWritePath().asDoubleOrNull()
//Float
//Path
@JvmName("floatAsString")
fun <S> ReadWritePath<S, Float, Float>.asString(): ReadWritePath<S, String, String> =
readAsString().writeFromStr()
fun <S> ReadWritePath<S, String, String>.asFloat(): ReadWritePath<S, Float, Float> =
readAsFloat().writeFromAny()
@JvmName("floatAsStringOrNull")
fun <S> ReadWritePath<S, Float, Float?>.asStringOrNull(): ReadWritePath<S, String, String> =
readAsString().writeFromStrOrNull()
fun <S> ReadWritePath<S, String, String>.asFloatOrNull(): ReadWritePath<S, Float?, Float> =
readAsFloatOrNull().writeFromAny()
@JvmName("floatAsNullableString")
fun <S> ReadWritePath<S, Float?, Float?>.asString(): ReadWritePath<S, String?, String?> =
readAsString().writeFromStr()
@JvmName("asNullableFloat")
fun <S> ReadWritePath<S, String?, String?>.asFloat(): ReadWritePath<S, Float?, Float?> =
readAsFloat().writeFromAny()
@JvmName("floatAsNullableStringOrNull")
fun <S> ReadWritePath<S, Float?, Float?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
readAsString().writeFromNullableStrOrNull()
@JvmName("asNullableFloatOrNull")
fun <S> ReadWritePath<S, String?, String?>.asFloatOrNull(): ReadWritePath<S, Float?, Float?> =
readAsFloatOrNull().writeFromAny()
//Property
@JvmName("floatAsString")
fun <S> KMutableProperty1<S, Float>.asString(): ReadWritePath<S, String, String> =
toReadWritePath().asString()
fun <S> KMutableProperty1<S, String>.asFloat(): ReadWritePath<S, Float, Float> =
toReadWritePath().asFloat()
@JvmName("floatAsNullableString")
fun <S> KMutableProperty1<S, Float?>.asString(): ReadWritePath<S, String?, String?> =
toReadWritePath().asString()
@JvmName("asNullableFloat")
fun <S> KMutableProperty1<S, String?>.asFloat(): ReadWritePath<S, Float?, Float?> =
toReadWritePath().asFloat()
@JvmName("floatAsNullableStringOrNull")
fun <S> KMutableProperty1<S, Float?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
toReadWritePath().asStringOrNull()
fun <S> KMutableProperty1<S, String?>.asFloatOrNull(): ReadWritePath<S, Float?, Float?> =
toReadWritePath().asFloatOrNull()
//Long
//Path
@JvmName("longAsString")
fun <S> ReadWritePath<S, Long, Long>.asString(): ReadWritePath<S, String, String> =
readAsString().writeFromStr()
fun <S> ReadWritePath<S, String, String>.asLong(): ReadWritePath<S, Long, Long> =
readAsLong().writeFromAny()
@JvmName("longAsStringOrNull")
fun <S> ReadWritePath<S, Long, Long?>.asStringOrNull(): ReadWritePath<S, String, String> =
readAsString().writeFromStrOrNull()
fun <S> ReadWritePath<S, String, String>.asLongOrNull(): ReadWritePath<S, Long?, Long> =
readAsLongOrNull().writeFromAny()
@JvmName("longAsNullableString")
fun <S> ReadWritePath<S, Long?, Long?>.asString(): ReadWritePath<S, String?, String?> =
readAsString().writeFromStr()
@JvmName("asNullableLong")
fun <S> ReadWritePath<S, String?, String?>.asLong(): ReadWritePath<S, Long?, Long?> =
readAsLong().writeFromAny()
@JvmName("longAsNullableStringOrNull")
fun <S> ReadWritePath<S, Long?, Long?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
readAsString().writeFromNullableStrOrNull()
@JvmName("asNullableLongOrNull")
fun <S> ReadWritePath<S, String?, String?>.asLongOrNull(): ReadWritePath<S, Long?, Long?> =
readAsLongOrNull().writeFromAny()
//Property
@JvmName("longAsString")
fun <S> KMutableProperty1<S, Long>.asString(): ReadWritePath<S, String, String> =
toReadWritePath().asString()
fun <S> KMutableProperty1<S, String>.asLong(): ReadWritePath<S, Long, Long> =
toReadWritePath().asLong()
@JvmName("longAsNullableString")
fun <S> KMutableProperty1<S, Long?>.asString(): ReadWritePath<S, String?, String?> =
toReadWritePath().asString()
@JvmName("asNullableLong")
fun <S> KMutableProperty1<S, String?>.asLong(): ReadWritePath<S, Long?, Long?> =
toReadWritePath().asLong()
@JvmName("longAsNullableStringOrNull")
fun <S> KMutableProperty1<S, Long?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
toReadWritePath().asStringOrNull()
fun <S> KMutableProperty1<S, String?>.asLongOrNull(): ReadWritePath<S, Long?, Long?> =
toReadWritePath().asLongOrNull()
//Int
//Path
@JvmName("intAsString")
fun <S> ReadWritePath<S, Int, Int>.asString(): ReadWritePath<S, String, String> =
readAsString().writeFromStr()
fun <S> ReadWritePath<S, String, String>.asInt(): ReadWritePath<S, Int, Int> =
readAsInt().writeFromAny()
@JvmName("intAsStringOrNull")
fun <S> ReadWritePath<S, Int, Int?>.asStringOrNull(): ReadWritePath<S, String, String> =
readAsString().writeFromStrOrNull()
fun <S> ReadWritePath<S, String, String>.asIntOrNull(): ReadWritePath<S, Int?, Int> =
readAsIntOrNull().writeFromAny()
@JvmName("intAsNullableString")
fun <S> ReadWritePath<S, Int?, Int?>.asString(): ReadWritePath<S, String?, String?> =
readAsString().writeFromStr()
@JvmName("asNullableInt")
fun <S> ReadWritePath<S, String?, String?>.asInt(): ReadWritePath<S, Int?, Int?> =
readAsInt().writeFromAny()
@JvmName("intAsNullableStringOrNull")
fun <S> ReadWritePath<S, Int?, Int?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
readAsString().writeFromNullableStrOrNull()
@JvmName("asNullableIntOrNull")
fun <S> ReadWritePath<S, String?, String?>.asIntOrNull(): ReadWritePath<S, Int?, Int?> =
readAsIntOrNull().writeFromAny()
//Property
@JvmName("intAsString")
fun <S> KMutableProperty1<S, Int>.asString(): ReadWritePath<S, String, String> =
toReadWritePath().asString()
fun <S> KMutableProperty1<S, String>.asInt(): ReadWritePath<S, Int, Int> =
toReadWritePath().asInt()
@JvmName("intAsNullableString")
fun <S> KMutableProperty1<S, Int?>.asString(): ReadWritePath<S, String?, String?> =
toReadWritePath().asString()
@JvmName("asNullableInt")
fun <S> KMutableProperty1<S, String?>.asInt(): ReadWritePath<S, Int?, Int?> =
toReadWritePath().asInt()
@JvmName("intAsNullableStringOrNull")
fun <S> KMutableProperty1<S, Int?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
toReadWritePath().asStringOrNull()
fun <S> KMutableProperty1<S, String?>.asIntOrNull(): ReadWritePath<S, Int?, Int?> =
toReadWritePath().asIntOrNull()
//Short
//Path
@JvmName("shortAsString")
fun <S> ReadWritePath<S, Short, Short>.asString(): ReadWritePath<S, String, String> =
readAsString().writeFromStr()
fun <S> ReadWritePath<S, String, String>.asShort(): ReadWritePath<S, Short, Short> =
readAsShort().writeFromAny()
@JvmName("shortAsStringOrNull")
fun <S> ReadWritePath<S, Short, Short?>.asStringOrNull(): ReadWritePath<S, String, String> =
readAsString().writeFromStrOrNull()
fun <S> ReadWritePath<S, String, String>.asShortOrNull(): ReadWritePath<S, Short?, Short> =
readAsShortOrNull().writeFromAny()
@JvmName("shortAsNullableString")
fun <S> ReadWritePath<S, Short?, Short?>.asString(): ReadWritePath<S, String?, String?> =
readAsString().writeFromStr()
@JvmName("asNullableShort")
fun <S> ReadWritePath<S, String?, String?>.asShort(): ReadWritePath<S, Short?, Short?> =
readAsShort().writeFromAny()
@JvmName("shortAsNullableStringOrNull")
fun <S> ReadWritePath<S, Short?, Short?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
readAsString().writeFromNullableStrOrNull()
@JvmName("asNullableShortOrNull")
fun <S> ReadWritePath<S, String?, String?>.asShortOrNull(): ReadWritePath<S, Short?, Short?> =
readAsShortOrNull().writeFromAny()
//Property
@JvmName("shortAsString")
fun <S> KMutableProperty1<S, Short>.asString(): ReadWritePath<S, String, String> =
toReadWritePath().asString()
fun <S> KMutableProperty1<S, String>.asShort(): ReadWritePath<S, Short, Short> =
toReadWritePath().asShort()
@JvmName("shortAsNullableString")
fun <S> KMutableProperty1<S, Short?>.asString(): ReadWritePath<S, String?, String?> =
toReadWritePath().asString()
@JvmName("asNullableShort")
fun <S> KMutableProperty1<S, String?>.asShort(): ReadWritePath<S, Short?, Short?> =
toReadWritePath().asShort()
@JvmName("shortAsNullableStringOrNull")
fun <S> KMutableProperty1<S, Short?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
toReadWritePath().asStringOrNull()
fun <S> KMutableProperty1<S, String?>.asShortOrNull(): ReadWritePath<S, Short?, Short?> =
toReadWritePath().asShortOrNull()
//Byte
//Path
@JvmName("byteAsString")
fun <S> ReadWritePath<S, Byte, Byte>.asString(): ReadWritePath<S, String, String> =
readAsString().writeFromStr()
fun <S> ReadWritePath<S, String, String>.asByte(): ReadWritePath<S, Byte, Byte> =
readAsByte().writeFromAny()
@JvmName("byteAsStringOrNull")
fun <S> ReadWritePath<S, Byte, Byte?>.asStringOrNull(): ReadWritePath<S, String, String> =
readAsString().writeFromStrOrNull()
fun <S> ReadWritePath<S, String, String>.asByteOrNull(): ReadWritePath<S, Byte?, Byte> =
readAsByteOrNull().writeFromAny()
@JvmName("byteAsNullableString")
fun <S> ReadWritePath<S, Byte?, Byte?>.asString(): ReadWritePath<S, String?, String?> =
readAsString().writeFromStr()
@JvmName("asNullableByte")
fun <S> ReadWritePath<S, String?, String?>.asByte(): ReadWritePath<S, Byte?, Byte?> =
readAsByte().writeFromAny()
@JvmName("byteAsNullableStringOrNull")
fun <S> ReadWritePath<S, Byte?, Byte?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
readAsString().writeFromNullableStrOrNull()
@JvmName("asNullableByteOrNull")
fun <S> ReadWritePath<S, String?, String?>.asByteOrNull(): ReadWritePath<S, Byte?, Byte?> =
readAsByteOrNull().writeFromAny()
//Property
@JvmName("byteAsString")
fun <S> KMutableProperty1<S, Byte>.asString(): ReadWritePath<S, String, String> =
toReadWritePath().asString()
fun <S> KMutableProperty1<S, String>.asByte(): ReadWritePath<S, Byte, Byte> =
toReadWritePath().asByte()
@JvmName("byteAsNullableString")
fun <S> KMutableProperty1<S, Byte?>.asString(): ReadWritePath<S, String?, String?> =
toReadWritePath().asString()
@JvmName("asNullableByte")
fun <S> KMutableProperty1<S, String?>.asByte(): ReadWritePath<S, Byte?, Byte?> =
toReadWritePath().asByte()
@JvmName("byteAsNullableStringOrNull")
fun <S> KMutableProperty1<S, Byte?>.asStringOrNull(): ReadWritePath<S, String?, String?> =
toReadWritePath().asStringOrNull()
fun <S> KMutableProperty1<S, String?>.asByteOrNull(): ReadWritePath<S, Byte?, Byte?> =
toReadWritePath().asByteOrNull() | 1 | null | 1 | 1 | 65d68719bff59f3316fe378f5585445bf22aa2bc | 14,735 | kMapper | Apache License 2.0 |
app/src/main/java/com/programmer2704/stoxxwatch/data/DatabaseManager.kt | prgrm274 | 378,989,070 | false | null | package com.programmer2704.stoxxwatch.data
import io.objectbox.BoxStore
interface DatabaseManager {
fun setupCompanyList()
fun boxStore(): BoxStore
} | 0 | Kotlin | 0 | 0 | 29b9e5a325eed42f34e6ac27d2b1a007c060ab07 | 160 | stoxxwatch | MIT License |
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/functions.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-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 file.
package org.jetbrains.plugins.groovy.util
import java.util.function.Consumer
import com.intellij.util.Consumer as JBConsumer
fun <T> JBConsumer<T>.consumeAll(items: Iterable<T>) {
items.forEach(this::consume)
}
operator fun <T> Consumer<in T>.plusAssign(elements: Iterable<T>) {
elements.forEach(this::plusAssign)
}
operator fun <T> Consumer<in T>.plusAssign(element: T) {
accept(element)
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 542 | intellij-community | Apache License 2.0 |
app/src/main/java/tool/xfy9326/milink/nfc/ui/screen/NdefReaderScreen.kt | XFY9326 | 724,531,401 | false | {"Kotlin": 317072} | package tool.xfy9326.milink.nfc.ui.screen
import androidx.annotation.StringRes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.displayCutoutPadding
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Nfc
import androidx.compose.material.icons.outlined.FileOpen
import androidx.compose.material.icons.outlined.Save
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.collectLatest
import lib.xfy9326.xiaomi.nfc.XiaomiNdefType
import tool.xfy9326.milink.nfc.R
import tool.xfy9326.milink.nfc.data.nfc.NdefData
import tool.xfy9326.milink.nfc.data.nfc.NfcTag
import tool.xfy9326.milink.nfc.data.nfc.RawNdefData
import tool.xfy9326.milink.nfc.data.nfc.SmartPosterNdefData
import tool.xfy9326.milink.nfc.data.nfc.XiaomiNdefData
import tool.xfy9326.milink.nfc.ui.common.InfoContent
import tool.xfy9326.milink.nfc.ui.theme.AppTheme
import tool.xfy9326.milink.nfc.ui.theme.LocalAppThemeTypography
import tool.xfy9326.milink.nfc.ui.vm.NdefReaderViewModel
import tool.xfy9326.milink.nfc.utils.showToast
@Preview(showBackground = true)
@Composable
private fun Preview() {
AppTheme {
NdefReaderScreen(
onNavBack = {},
onRequestImportNdefBin = {}
)
}
}
private const val ANIMATION_LABEL_CONTENT = "Content"
@Composable
fun NdefReaderScreen(
viewModel: NdefReaderViewModel = viewModel(),
onNavBack: () -> Unit,
onRequestImportNdefBin: () -> Unit
) {
val uiState = viewModel.uiState.collectAsStateWithLifecycle()
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopBar(
canExportNdefBin = uiState.value.canExportNdefBin,
onNavBack = onNavBack,
onRequestExportNdefBin = viewModel::requestExportNdefBin,
onRequestImportNdefBin = onRequestImportNdefBin
)
}
) { innerPadding ->
Crossfade(targetState = uiState.value.hasData, label = ANIMATION_LABEL_CONTENT) {
if (it) {
NfcContent(innerPadding = innerPadding, uiState = uiState.value)
} else {
Box(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.consumeWindowInsets(innerPadding)
.displayCutoutPadding(),
contentAlignment = Alignment.Center
) {
NfcWaitScan()
}
}
}
}
EventHandler(
viewModel = viewModel
)
}
@Composable
private fun TopBar(
canExportNdefBin: Boolean,
onNavBack: () -> Unit,
onRequestExportNdefBin: () -> Unit,
onRequestImportNdefBin: () -> Unit
) {
TopAppBar(
title = { Text(text = stringResource(id = R.string.nfc_read_ndef)) },
navigationIcon = {
IconButton(onClick = onNavBack) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowBack,
contentDescription = stringResource(id = R.string.nav_back)
)
}
},
actions = {
IconButton(onClick = onRequestImportNdefBin) {
Icon(
imageVector = Icons.Outlined.FileOpen,
contentDescription = stringResource(id = R.string.import_text)
)
}
AnimatedVisibility(visible = canExportNdefBin) {
IconButton(onClick = onRequestExportNdefBin) {
Icon(
imageVector = Icons.Outlined.Save,
contentDescription = stringResource(id = R.string.save)
)
}
}
}
)
}
@Composable
private fun EventHandler(viewModel: NdefReaderViewModel) {
val context = LocalContext.current
LaunchedEffect(Unit) {
viewModel.instantMsg.collectLatest {
context.showToast(it.resId)
}
}
}
@Composable
private fun NfcContent(
innerPadding: PaddingValues,
uiState: NdefReaderViewModel.UiState,
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.consumeWindowInsets(innerPadding)
.displayCutoutPadding()
.padding(horizontal = 8.dp, vertical = 6.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
uiState.nfcTag?.let { tag ->
item {
NfcTagInfoCard(modifier = Modifier.padding(horizontal = 8.dp), data = tag)
}
}
itemsIndexed(uiState.ndefRecords) { index, item ->
NdefDataCard(
modifier = Modifier.padding(horizontal = 8.dp),
index = index,
data = item
)
}
}
}
@Composable
private fun NdefDataCard(
modifier: Modifier = Modifier,
index: Int,
data: NdefData
) {
when (data) {
is RawNdefData -> RawNdefCard(
modifier = modifier,
index = index,
data = data
)
is SmartPosterNdefData -> SmartPosterNdefCard(
modifier = modifier,
index = index,
data = data
)
is XiaomiNdefData -> XiaomiNdefCard(
modifier = modifier,
index = index,
data = data
)
else -> {}
}
}
@Composable
private fun NfcWaitScan() {
val typography = LocalAppThemeTypography.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
modifier = Modifier.size(62.dp),
imageVector = Icons.Default.Nfc,
contentDescription = stringResource(id = R.string.tap_and_read_nfc_tag),
)
Spacer(modifier = Modifier.height(30.dp))
Text(
text = stringResource(id = R.string.tap_and_read_nfc_tag),
textAlign = TextAlign.Center,
style = typography.bodyLarge
)
}
}
@StringRes
private fun Boolean.stringResId(): Int =
if (this) R.string.content_true else R.string.content_false
@Composable
private fun NfcTagInfoCard(modifier: Modifier = Modifier, data: NfcTag) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_nfc_tag),
data = listOf(
stringResource(id = R.string.nfc_field_tech) to data.techList.joinToString(),
stringResource(id = R.string.nfc_field_type) to data.type,
stringResource(id = R.string.nfc_field_size) to stringResource(
id = R.string.current_and_total_bytes,
data.currentSize,
data.maxSize
),
stringResource(id = R.string.nfc_field_writeable) to stringResource(id = data.writeable.stringResId()),
stringResource(id = R.string.nfc_field_can_make_read_only) to stringResource(id = data.canMakeReadOnly.stringResId())
)
)
}
}
@Composable
private fun RawNdefCard(
modifier: Modifier = Modifier,
index: Int,
data: RawNdefData
) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_ndef, index + 1),
data = buildList {
data.id?.let {
add(stringResource(id = R.string.ndef_field_id) to it)
}
add(stringResource(id = R.string.ndef_field_tnf) to data.tnf.name)
data.type?.let {
add(stringResource(id = R.string.ndef_field_type) to it)
}
data.payloadLanguage?.let {
add(stringResource(id = R.string.ndef_field_language) to it)
}
data.payload?.let {
add(stringResource(id = R.string.ndef_field_payload) to it)
}
}
)
}
}
@Composable
private fun SmartPosterNdefCard(
modifier: Modifier = Modifier,
index: Int,
data: SmartPosterNdefData
) {
OutlinedCard(modifier = modifier) {
Column(
modifier = Modifier.padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_sp_ndef, index + 1),
data = listOf(
stringResource(id = R.string.ndef_sp_field_uri) to data.uri.toString()
)
)
data.items.filterIsInstance<SmartPosterNdefData.MetaData>().takeIf {
it.isNotEmpty()
}?.let {
SmartPosterMetaRecordCard(
modifier = Modifier.padding(horizontal = 8.dp),
data = it
)
}
data.items.filter {
it !is SmartPosterNdefData.MetaData
}.forEachIndexed { index, item ->
NdefDataCard(
modifier = Modifier.padding(horizontal = 8.dp),
index = index,
data = item
)
}
}
}
}
@Composable
private fun SmartPosterMetaRecordCard(
modifier: Modifier = Modifier,
data: List<SmartPosterNdefData.MetaData>
) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_sp_field_ndef),
data = SmartPosterNdefData.sortFields(data).map {
when (it) {
is SmartPosterNdefData.Title ->
stringResource(id = R.string.ndef_sp_field_title) to stringResource(
id = R.string.ndef_sp_field_language,
it.languageCode
) + "\n" + it.text
is SmartPosterNdefData.Uri ->
stringResource(id = R.string.ndef_sp_field_uri) to it.uri.toString()
is SmartPosterNdefData.Action ->
stringResource(id = R.string.ndef_sp_field_action) to stringResource(id = it.actionType.resId)
is SmartPosterNdefData.Icon ->
stringResource(id = R.string.ndef_sp_field_icon) to it.payloadHex
is SmartPosterNdefData.Size ->
stringResource(id = R.string.ndef_sp_field_size) to
stringResource(id = R.string.ndef_sp_field_size_value, it.value)
is SmartPosterNdefData.Type ->
stringResource(id = R.string.ndef_sp_field_type) to it.mimeType
}
}
)
}
}
@Composable
private fun XiaomiNdefCard(
modifier: Modifier = Modifier,
index: Int,
data: XiaomiNdefData
) {
OutlinedCard(modifier = modifier) {
Column(
modifier = Modifier.padding(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
XiaomiNdefTypeCard(
modifier = Modifier.padding(horizontal = 8.dp),
index = index,
ndefType = data.ndefType
)
XiaomiNfcPayloadCard(
modifier = Modifier.padding(horizontal = 8.dp),
data = data.payload
)
when (data.appData) {
is XiaomiNdefData.App.Handoff -> HandoffAppDataCard(
modifier = Modifier.padding(horizontal = 8.dp),
data = data.appData
)
is XiaomiNdefData.App.NfcTag -> NfcTagAppDataCard(
modifier = Modifier.padding(horizontal = 8.dp),
data = data.appData
)
}
}
}
}
@Composable
private fun XiaomiNdefTypeCard(
modifier: Modifier = Modifier,
index: Int,
ndefType: XiaomiNdefType
) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_xiaomi_ndef, index + 1),
data = listOf(
stringResource(id = R.string.nfc_field_type) to stringResource(
id = when (ndefType) {
XiaomiNdefType.UNKNOWN -> R.string.unknown
XiaomiNdefType.SMART_HOME -> R.string.ndef_payload_type_smart_home
XiaomiNdefType.MI_CONNECT_SERVICE -> R.string.ndef_payload_type_mi_connect_service
}
)
)
)
}
}
@Composable
private fun XiaomiNfcPayloadCard(modifier: Modifier = Modifier, data: XiaomiNdefData.Payload) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_xiaomi_payload),
data = buildList {
add(stringResource(id = R.string.nfc_field_version) to "${data.majorVersion} ${data.minorVersion}")
add(stringResource(id = R.string.nfc_field_protocol) to stringResource(id = data.protocol.resId))
data.idHash?.let {
add(stringResource(id = R.string.nfc_field_id_hash) to it)
}
}
)
}
}
@Composable
private fun HandoffAppDataCard(modifier: Modifier = Modifier, data: XiaomiNdefData.App.Handoff) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_app_data),
data = buildList {
add(stringResource(id = R.string.nfc_field_version) to "${data.majorVersion} ${data.minorVersion}")
add(stringResource(id = R.string.nfc_field_device_type) to data.deviceType)
if (data.attributesMap.isNotEmpty()) {
add(
stringResource(id = R.string.nfc_field_attributes) to data.attributesMap.map { entry ->
"${entry.key}: ${entry.value}"
}.joinToString("\n")
)
}
add(stringResource(id = R.string.nfc_field_action) to data.action)
if (data.payloadsMap.isNotEmpty()) {
add(
stringResource(id = R.string.nfc_field_properties) to data.payloadsMap.map { entry ->
"${entry.key}: ${entry.value}"
}.joinToString("\n")
)
}
}
)
}
}
@Composable
private fun NfcTagAppDataCard(modifier: Modifier = Modifier, data: XiaomiNdefData.App.NfcTag) {
OutlinedCard(modifier = modifier) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_app_data),
data = listOf(
stringResource(id = R.string.nfc_field_version) to "${data.majorVersion} ${data.minorVersion}",
stringResource(id = R.string.nfc_field_write_time) to data.writeTime,
stringResource(id = R.string.nfc_field_flags) to data.flags,
)
)
data.actionRecord?.let { record ->
OutlinedCard(modifier = Modifier.padding(10.dp)) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_app_data_nfc_tag_action_record),
data = buildList {
add(stringResource(id = R.string.nfc_field_action) to record.action)
add(stringResource(id = R.string.nfc_field_condition) to record.condition)
add(stringResource(id = R.string.nfc_field_device_number) to record.deviceNumber)
add(stringResource(id = R.string.nfc_field_flags) to record.flags)
if (!record.conditionParameters.isNullOrEmpty()) {
add(stringResource(id = R.string.nfc_field_condition_parameters) to record.conditionParameters)
}
}
)
}
}
data.deviceRecord?.let { record ->
OutlinedCard(modifier = Modifier.padding(10.dp)) {
InfoContent(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
title = stringResource(id = R.string.info_app_data_nfc_tag_device_record),
data = buildList {
add(stringResource(id = R.string.nfc_field_device_type) to record.deviceType)
add(stringResource(id = R.string.nfc_field_flags) to record.flags)
add(stringResource(id = R.string.nfc_field_device_number) to record.deviceNumber)
if (record.attributesMap.isNotEmpty()) {
add(
stringResource(id = R.string.nfc_field_attributes) to record.attributesMap.map { entry ->
"${entry.key}: ${entry.value}"
}.joinToString("\n")
)
}
}
)
}
}
}
} | 0 | Kotlin | 7 | 161 | d1b8a8b0d95a6a56ca5d427a3f1614fa3e1b34fb | 19,739 | MiLinkNFC | MIT License |
kotlin/app/src/main/java/com/huawei/hms/site/sample/TextSearchActivity.kt | HMS-Core | 239,805,215 | false | null | /*
* Copyright 2020. Huawei Technologies 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.huawei.hms.site.sample
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.huawei.hms.site.api.SearchResultListener
import com.huawei.hms.site.api.SearchService
import com.huawei.hms.site.api.SearchServiceFactory
import com.huawei.hms.site.api.model.*
import com.huawei.hms.site.sample.Utils.apiKey
import com.huawei.hms.site.sample.Utils.parseDouble
import com.huawei.hms.site.sample.Utils.parseInt
import java.util.*
/**
* Keyword Search Example Code
*/
class TextSearchActivity : AppCompatActivity() {
companion object {
private const val TAG = "TextSearchActivity"
}
private lateinit var queryInput: EditText
private lateinit var latInput: EditText
private lateinit var lngInput: EditText
private lateinit var radiusInput: EditText
private lateinit var poiTypeSpinner: Spinner
private lateinit var countryInput: EditText
private lateinit var languageInput: EditText
private lateinit var politicalViewInput: EditText
private lateinit var pageIndexInput: EditText
private lateinit var pageSizeInput: EditText
private lateinit var resultTextView: TextView
// Declare a SearchService object.
private var searchService: SearchService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_text_search)
// Instantiate the SearchService object.
searchService = SearchServiceFactory.create(this, apiKey)
queryInput = findViewById(R.id.edit_text_text_search_query)
latInput = findViewById(R.id.edit_text_text_search_location_lat)
lngInput = findViewById(R.id.edit_text_text_search_location_lng)
radiusInput = findViewById(R.id.edit_text_text_search_radius)
poiTypeSpinner = findViewById(R.id.spinner_text_search_poitype)
poiTypeSpinner.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, listOf(*LocationType.values()))
val usePOITypeSwitch = findViewById<Switch>(R.id.switch_text_search_poitype)
usePOITypeSwitch.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean -> poiTypeSpinner.isEnabled = isChecked }
countryInput = findViewById(R.id.edit_text_text_search_country)
languageInput = findViewById(R.id.edit_text_text_search_language)
politicalViewInput = findViewById(R.id.edit_text_text_search_politicalview)
pageIndexInput = findViewById(R.id.edit_text_text_search_pageindex)
pageSizeInput = findViewById(R.id.edit_text_text_search_pagesize)
resultTextView = findViewById(R.id.response_text_search)
findViewById<View>(R.id.button_text_search).setOnClickListener {execTextSearch() }
poiTypeSpinner.isEnabled = false
}
private fun execTextSearch() {
Log.d(TAG, "execTextSearch: $this")
Log.d(TAG, "execTextSearch: $applicationContext")
Log.d(TAG, "execTextSearch: "
+ if (applicationContext == null) "" else applicationContext.applicationContext)
val query = queryInput.text.toString()
if (TextUtils.isEmpty(query)) {
resultTextView.text = "Error : Query is empty!"
return
}
// Create a request body.
val request = TextSearchRequest()
request.setQuery(query)
val lat: Double?
val lng: Double?
val latStr = latInput.text.toString()
val lngStr = lngInput.text.toString()
if (latStr.isNotEmpty() || lngStr.isNotEmpty()) {
lat = parseDouble(latStr)
lng = parseDouble(lngStr)
if (lat == null || lng == null) {
resultTextView.text = "Error : Location is invalid!"
return
}
request.setLocation(Coordinate(lat, lng))
}
val radiusInt: Int? = parseInt(radiusInput.text.toString())
if (radiusInt == null || radiusInt <= 0) {
resultTextView.text = "Error : Radius Must be greater than 0 !"
return
}
request.setRadius(radiusInt)
val poiType = if (poiTypeSpinner.isEnabled) poiTypeSpinner.selectedItem as LocationType else null
if (poiType != null) {
request.setPoiType(poiType)
}
val countryCode = countryInput.text.toString()
if (!TextUtils.isEmpty(countryCode)) {
request.setCountryCode(countryCode)
}
val language = languageInput.text.toString()
if (!TextUtils.isEmpty(language)) {
request.setLanguage(language)
}
val politicalView = politicalViewInput.text.toString()
if (!TextUtils.isEmpty(politicalView)) {
request.setPoliticalView(politicalView)
}
val pageIndexInt: Int? = parseInt(pageIndexInput.text.toString())
if (pageIndexInt == null || pageIndexInt < 1 || pageIndexInt > 60) {
resultTextView.text = "Error : PageIndex Must be between 1 and 60!"
return
}
request.setPageIndex(pageIndexInt)
val pageSizeInt: Int? = parseInt(pageSizeInput.text.toString())
if (pageSizeInt == null || pageSizeInt < 1 || pageSizeInt > 20) {
resultTextView.text = "Error : PageSize Must be between 1 and 20!"
return
}
request.setPageSize(pageSizeInt)
// Create a search result listener.
val resultListener: SearchResultListener<TextSearchResponse> = object : SearchResultListener<TextSearchResponse> {
// Return search results upon a successful search.
override fun onSearchResult(results: TextSearchResponse?) {
val siteList: List<Site>? = results?.getSites()
if (results == null || results.getTotalCount() <= 0 || siteList.isNullOrEmpty()) {
resultTextView.text = "Result is Empty!"
return
}
val response = StringBuilder("\n")
response.append("success\n")
var count = 1
var addressDetail: AddressDetail
var location: Coordinate
var poi: Poi
var viewport: CoordinateBounds
for (site in siteList) {
addressDetail = site.getAddress()
location = site.getLocation()
poi = site.getPoi()
viewport = site.getViewport()
response.append(String.format(
"[%s] siteId: '%s', name: %s, formatAddress: %s, country: %s, countryCode: %s, location: %s, poiTypes: %s, viewport is %s \n\n",
"" + count++, site.getSiteId(), site.getName(), site.getFormatAddress(),
if (addressDetail == null) "" else addressDetail.getCountry(),
if (addressDetail == null) "" else addressDetail.getCountryCode(),
if (location == null) "" else location.getLat().toString() + "," + location.getLng(),
if (poi == null) "" else Arrays.toString(poi.getPoiTypes()),
if (viewport == null) "" else viewport.getNortheast().toString() + "," + viewport.getSouthwest()))
}
resultTextView.text = response.toString()
Log.d(TAG, "onTextSearchResult: $response")
}
// Return the result code and description upon a search exception.
override fun onSearchError(status: SearchStatus) {
resultTextView.text = "Error : ${status.getErrorCode()} ${status.getErrorMessage()}"
}
}
// Call the place search API.
searchService?.textSearch(request, resultListener)
}
override fun onDestroy() {
super.onDestroy()
searchService = null
}
} | 1 | null | 13 | 40 | cfba1105c13ec9668e76f5a3fc8dd9085319097c | 8,667 | hms-sitekit-demo | Apache License 2.0 |
plugins/kotlin/project-tests/project-tests-fir/test/org/jetbrains/kotlin/idea/project/tests/fir/perf/FirRustPerformanceTest.kt | JetBrains | 2,489,216 | 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 org.jetbrains.kotlin.idea.project.tests.fir.perf
import org.jetbrains.kotlin.idea.project.test.base.AbstractProjectBasedTest
import org.jetbrains.kotlin.idea.project.test.base.ActionOnError
import org.jetbrains.kotlin.idea.project.test.base.ProjectBasedTestPreferences
import org.jetbrains.kotlin.idea.project.test.base.projects.RustProject
import org.jetbrains.kotlin.idea.project.tests.fir.FirFrontedConfiguration
class FirRustPerformanceTest : AbstractProjectBasedTest() {
fun testRustPlugin() {
val profile = ProjectBasedTestPreferences(
warmUpIterations = 5,
iterations = 10,
checkForValidity = true,
frontendConfiguration = FirFrontedConfiguration,
uploadResultsToEs = true,
actionOnError = ActionOnError.THROW,
)
test(RustProject.project, RustProject.actions, profile)
}
} | 236 | null | 4946 | 15,650 | 32f33d7b7126014b860912a5b6088ffc50fc241d | 1,015 | intellij-community | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/js/nodejs/NodeJsRootExtension.kt | JetBrains | 3,432,266 | 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.gradle.targets.js.nodejs
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.Directory
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.TaskProvider
import org.jetbrains.kotlin.gradle.logging.kotlinInfo
import org.jetbrains.kotlin.gradle.plugin.PropertiesProvider
import org.jetbrains.kotlin.gradle.targets.js.NpmVersions
import org.jetbrains.kotlin.gradle.targets.js.npm.resolver.KotlinRootNpmResolver
import org.jetbrains.kotlin.gradle.targets.js.npm.resolver.PACKAGE_JSON_UMBRELLA_TASK_NAME
import org.jetbrains.kotlin.gradle.targets.js.npm.tasks.KotlinNpmCachesSetup
import org.jetbrains.kotlin.gradle.targets.js.npm.tasks.KotlinNpmInstallTask
import org.jetbrains.kotlin.gradle.targets.js.npm.tasks.RootPackageJsonTask
import org.jetbrains.kotlin.gradle.utils.property
import java.io.File
open class NodeJsRootExtension(
val project: Project,
private val nodeJs: () -> NodeJsEnvSpec,
) {
init {
check(project.rootProject == project)
val projectProperties = PropertiesProvider(project)
if (projectProperties.errorJsGenerateExternals != null) {
project.logger.warn(
"""
|
|==========
|Please note, Dukat integration in Gradle plugin does not work now, it was removed.
|We rethink how we can integrate properly.
|==========
|
""".trimMargin()
)
}
}
private val gradleHome = project.gradle.gradleUserHomeDir.also {
project.logger.kotlinInfo("Storing cached files in $it")
}
@Deprecated(
"Use installationDir from NodeJsExtension (not NodeJsRootExtension) instead." +
"You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
)
var installationDir: File = gradleHome.resolve("nodejs")
@Deprecated(
"Use download from NodeJsExtension (not NodeJsRootExtension) instead" +
"You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
)
var download = true
@Deprecated(
"Use downloadBaseUrl from NodeJsExtension (not NodeJsRootExtension) instead" +
"You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
)
var nodeDownloadBaseUrl by ::downloadBaseUrl
// To prevent Kotlin build from failing (due to `-Werror`), only deprecate after upgrade of bootstrap version
// @Deprecated(
// "Use downloadBaseUrl from NodeJsExtension (not NodeJsRootExtension) instead" +
// "You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
// )
var downloadBaseUrl: String? = "https://nodejs.org/dist"
@Deprecated(
"Use version from NodeJsExtension (not NodeJsRootExtension) instead" +
"You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
)
var nodeVersion by ::version
// To prevent Kotlin build from failing (due to `-Werror`), only deprecate after upgrade of bootstrap version
// @Deprecated(
// "Use downloadBaseUrl from NodeJsExtension (not NodeJsRootExtension) instead" +
// "You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
// )
var version = "22.0.0"
@Deprecated(
"Use command from NodeJsExtension (not NodeJsRootExtension) instead" +
"You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
)
var command = "node"
@Suppress("DEPRECATION")
@Deprecated(
"Use command from NodeJsExtension (not NodeJsRootExtension) instead" +
"You can find this extension after applying NodeJsPlugin. This will be removed in 2.2"
)
var nodeCommand by ::command
val rootProjectDir
get() = project.rootDir
val packageManagerExtension: org.gradle.api.provider.Property<NpmApiExt> = project.objects.property()
val taskRequirements: TasksRequirements
get() = resolver.tasksRequirements
lateinit var resolver: KotlinRootNpmResolver
val rootPackageDirectory: Provider<Directory> = project.layout.buildDirectory.dir("js")
val projectPackagesDirectory: Provider<Directory>
get() = rootPackageDirectory.map { it.dir("packages") }
val nodeModulesGradleCacheDirectory: Provider<Directory>
get() = rootPackageDirectory.map { it.dir("packages_imported") }
val versions = NpmVersions()
val npmInstallTaskProvider: TaskProvider<out KotlinNpmInstallTask>
get() = project.tasks.withType(KotlinNpmInstallTask::class.java).named(KotlinNpmInstallTask.NAME)
val rootPackageJsonTaskProvider: TaskProvider<RootPackageJsonTask>
get() = project.tasks.withType(RootPackageJsonTask::class.java).named(RootPackageJsonTask.NAME)
val packageJsonUmbrellaTaskProvider: TaskProvider<Task>
get() = project.tasks.named(PACKAGE_JSON_UMBRELLA_TASK_NAME)
val npmCachesSetupTaskProvider: TaskProvider<out KotlinNpmCachesSetup>
get() = project.tasks.withType(KotlinNpmCachesSetup::class.java).named(KotlinNpmCachesSetup.NAME)
@Deprecated(
"Use nodeJsSetupTaskProvider from NodeJsExtension (not NodeJsRootExtension) instead" +
"You can find this extension after applying NodeJsPlugin"
)
val nodeJsSetupTaskProvider: TaskProvider<out NodeJsSetupTask>
get() = with(nodeJs()) {
project.nodeJsSetupTaskProvider
}
@Deprecated("Use NodeJsExtension instead. This will be removed in 2.2")
fun requireConfigured(): NodeJsEnv {
return nodeJs().produceEnv(project.providers).get()
}
companion object {
const val EXTENSION_NAME: String = "kotlinNodeJs"
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 6,124 | kotlin | Apache License 2.0 |
src/test/kotlin/dev/shtanko/algorithms/hackerrank/SubarrayDivisionTest.kt | ashtanko | 203,993,092 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.hackerrank
import org.assertj.core.api.Assertions.assertThat
class SubarrayDivisionTest {
// TODO
fun `test`() {
assertThat(listOf<Int>()).containsExactlyInAnyOrder()
}
}
| 4 | null | 0 | 19 | c3eeb85a0de638ec76f4f18f99224c1569661568 | 815 | kotlab | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/clients/KafkaConsumers.kt | navikt | 208,218,158 | false | {"Kotlin": 320509, "Dockerfile": 277} | package no.nav.syfo.clients
import no.nav.syfo.Environment
import no.nav.syfo.kafka.aiven.KafkaUtils
import no.nav.syfo.kafka.toConsumerConfig
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.serialization.StringDeserializer
class KafkaConsumers(env: Environment) {
val kafkaAivenConsumerManuellOppgave =
KafkaConsumer<String, String>(
KafkaUtils.getAivenKafkaConfig("manuell-oppgave-consumer")
.also {
it.let {
it[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = "1"
it[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = "none"
}
}
.toConsumerConfig(
"${env.applicationName}-consumer",
valueDeserializer = StringDeserializer::class,
),
)
}
| 0 | Kotlin | 0 | 0 | cd6eb5e18e9ed116f16c86b8f4ed88820db55f5a | 945 | syfosmmanuell-backend | MIT License |
src/main/kotlin/com/cognifide/gradle/aem/common/instance/check/UnavailableCheck.kt | wttech | 90,353,060 | false | null | package com.cognifide.gradle.aem.common.instance.check
import com.cognifide.gradle.aem.common.instance.LocalInstance
import com.cognifide.gradle.aem.common.instance.local.Status
import java.util.concurrent.TimeUnit
class UnavailableCheck(group: CheckGroup) : DefaultCheck(group) {
/**
* Status of remote instances cannot be checked easily. Because of that, check will work just a little bit longer.
*/
var utilisationTime = TimeUnit.SECONDS.toMillis(15)
override fun check() {
val bundleState = state(sync.osgiFramework.determineBundleState())
if (!bundleState.unknown) {
statusLogger.error(
"Bundles stable (${bundleState.stablePercent})",
"Bundles stable (${bundleState.stablePercent}). HTTP server still responding on $instance"
)
return
}
if (instance is LocalInstance) {
val status = state(instance.checkStatus())
if (!STATUS_EXPECTED.contains(status)) {
statusLogger.error(
"Awaiting not running",
"Unexpected instance status '$status'. Waiting for status '$STATUS_EXPECTED' of $instance"
)
}
} else {
if (utilisationTime !in 0..progress.stateTime) {
statusLogger.error(
"Awaiting utilized",
"HTTP server not responding. Waiting for utilization (port releasing) of $instance"
)
}
}
}
companion object {
val STATUS_EXPECTED = listOf(Status.NOT_RUNNING, Status.UNKNOWN)
}
} | 67 | null | 35 | 158 | 18d6cab33481f8f883c6139267fb059f7f6047ae | 1,669 | gradle-aem-plugin | Apache License 2.0 |
app/src/main/java/com/canopas/yourspace/domain/receiver/BootCompleteReceiver.kt | canopas | 739,382,039 | false | {"Kotlin": 747084, "JavaScript": 11006, "Ruby": 908} | package com.canopas.yourspace.domain.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.canopas.yourspace.data.repository.GeofenceRepository
import com.canopas.yourspace.data.service.auth.AuthService
import com.canopas.yourspace.data.service.location.LocationManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class BootCompleteReceiver : BroadcastReceiver() {
@Inject
lateinit var locationManager: LocationManager
@Inject
lateinit var authService: AuthService
@Inject
lateinit var geofenceRepository: GeofenceRepository
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
override fun onReceive(context: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action && authService.currentUser != null) {
locationManager.startService()
scope.launch { geofenceRepository.registerAllPlaces() }
}
}
}
| 2 | Kotlin | 1 | 5 | b6f41483e0f8b6f0ce1cf5c5ef3a205ea89759ba | 1,184 | your-space | Apache License 2.0 |
socialcats-google/feature-flags/src/androidMain/kotlin/FirebaseFeatureFlagProvider.kt | Couchsurfing | 194,353,465 | false | null | package com.nicolasmilliard.socialcats.featureflags
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings
import kotlinx.coroutines.tasks.await
class FirebaseFeatureFlagProvider(priority: Int, isDevModeEnabled: Boolean) :
FeatureFlagProvider,
RemoteFeatureFlagProvider {
private val remoteConfig: FirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
init {
val configSettings = FirebaseRemoteConfigSettings.Builder()
if (isDevModeEnabled) {
configSettings.minimumFetchIntervalInSeconds = 60
}
remoteConfig.setConfigSettingsAsync(configSettings.build())
}
override val priority: Int = priority
override fun isFeatureEnabled(feature: Feature): Boolean =
remoteConfig.getBoolean(feature.key)
override fun hasFeature(feature: Feature): Boolean {
return false
// return when (feature) {
// FeatureFlag.DARK_MODE -> true
// else -> false
// }
}
override suspend fun fetch(forceRefresh: Boolean) {
if (forceRefresh) {
remoteConfig.fetch(0).await()
} else {
remoteConfig.fetch().await()
}
}
override suspend fun activate() {
remoteConfig.activate().await()
}
}
| 4 | Kotlin | 1 | 3 | ebc38cc10a392d0a5ff0247c15230edc420e3be9 | 1,346 | social-cats-playground | Apache License 2.0 |
src/main/kotlin/gamelogic/Bullet.kt | dutta-anirban | 668,511,859 | false | null | package gamelogic
import com.sun.javafx.geom.Vec2d
private fun getBulletImage(owner: GameObject): String = when (owner) {
is Player -> "images/player_bullet.png"
is Enemy -> {
when(owner.enemyTier) {
0 -> "images/bullet1.png"
1 -> "images/bullet2.png"
2 -> "images/bullet3.png"
else -> TODO()
}
}
else -> TODO()
}
class Bullet(val owner: GameObject) : GameObject(getBulletImage(owner)) {
init {
posX = owner.posX + owner.width/2 - width/2
when (owner) {
is Player -> {
posY = owner.posY
velocity = Vec2d(0.0, -Resources.PLAYERBULLETSPEED)
}
is Enemy -> {
posY = owner.posY + owner.height/2 - height/2
velocity = Vec2d(0.0, Resources.ENEMYBULLETSPEED)
}
else -> {
TODO()
}
}
}
}
| 0 | Kotlin | 0 | 0 | ea4693820dc4db639b15a222ec838ff19ce5fb92 | 945 | space-invaders | Apache License 2.0 |
purlog/src/commonMain/kotlin/core/SdkLogger.kt | metashark-io | 871,823,301 | false | {"Kotlin": 103133} | package com.metashark.purlog.core
import com.metashark.purlog.enums.PurLogEnv
import com.metashark.purlog.enums.PurLogLevel
import com.metashark.purlog.models.PurLogConfig
import com.metashark.purlog.utils.currentTimestamp
import com.metashark.purlog.utils.shouldLog
internal class SdkLogger private constructor() {
private var env: PurLogEnv = PurLogEnv.DEV
private var configLevel: PurLogLevel = PurLogLevel.VERBOSE
companion object {
val shared = SdkLogger()
}
fun initialize(config: PurLogConfig) {
this.env = config.env
this.configLevel = config.level
}
fun log(level: PurLogLevel, message: String, metadata: Map<String, String> = emptyMap()) {
if (env != PurLogEnv.DEV) return
if (!shouldLog(level, configLevel)) return
consoleLog(env, level, message, metadata, isInternal = true)
}
internal fun consoleLog(env: PurLogEnv, logLevel: PurLogLevel, message: String, metadata: Map<String, String>, isInternal: Boolean) {
if (env != PurLogEnv.DEV) return
val formattedMessage = "[${currentTimestamp}] [${logLevel.name}]${if (isInternal) " [PurLog] " else " "}$message"
val formattedMessageWithMetaData = if (metadata.isNotEmpty()) "$formattedMessage\n\nmetadata: $metadata" else formattedMessage
when (logLevel) {
PurLogLevel.VERBOSE -> com.metashark.purlog.utils.logMessage(logLevel, "⚪️ $formattedMessageWithMetaData")
PurLogLevel.DEBUG -> com.metashark.purlog.utils.logMessage(logLevel, "🔵 $formattedMessageWithMetaData")
PurLogLevel.INFO -> com.metashark.purlog.utils.logMessage(logLevel, "🟢 $formattedMessageWithMetaData")
PurLogLevel.WARN -> com.metashark.purlog.utils.logMessage(logLevel, "🟡 $formattedMessageWithMetaData")
PurLogLevel.ERROR -> com.metashark.purlog.utils.logMessage(logLevel, "🔴 $formattedMessageWithMetaData")
PurLogLevel.FATAL -> com.metashark.purlog.utils.logMessage(logLevel, "🔴 $formattedMessageWithMetaData")
}
}
} | 0 | Kotlin | 0 | 1 | eafa233e04fd31bc255d89662007f89acf4ff426 | 2,053 | purlog-kotlin-sdk | MIT License |
core/src/main/kotlin/net/corda/core/messaging/flows/FlowManagerRPCOps.kt | corda | 70,137,417 | false | null | package net.corda.core.internal.messaging
import net.corda.core.messaging.RPCOps
/**
* RPC operations to perform operations related to flows including management of associated persistent states like checkpoints.
*/
interface FlowManagerRPCOps : RPCOps {
/**
* Dump all the current flow checkpoints as JSON into a zip file in the node's log directory.
*/
fun dumpCheckpoints()
/** Dump all the current flow checkpoints, alongside with the node's main jar, all CorDapps and driver jars
* into a zip file in the node's log directory. */
fun debugCheckpoints()
} | 62 | null | 1077 | 3,989 | d27aa0e6850d3804d0982024054376d452e7073a | 594 | corda | Apache License 2.0 |
app/src/main/java/com/se7en/screentrack/viewmodels/HomeViewModel.kt | ashar-7 | 279,871,209 | false | null | package com.se7en.screentrack.viewmodels
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.*
import com.se7en.screentrack.data.AppUsageManager
import com.se7en.screentrack.models.UsageData
import com.se7en.screentrack.repository.HomeRepository
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class HomeViewModel @ViewModelInject constructor(
private val repository: HomeRepository
): ViewModel() {
private val todayUsageData = MutableLiveData<UsageData>()
private val last7DaysUsageData = MutableLiveData<UsageData>()
fun getUsageLiveData(filter: AppUsageManager.FILTER) =
when(filter) {
AppUsageManager.FILTER.TODAY -> todayUsageData
AppUsageManager.FILTER.THIS_WEEK -> last7DaysUsageData
}
init {
viewModelScope.launch {
repository.getTodayUsageData().collect {
todayUsageData.value = it
}
}
viewModelScope.launch {
repository.getWeekUsageData().collect {
last7DaysUsageData.value = it
}
}
viewModelScope.launch { repository.updateData() }
}
}
| 0 | Kotlin | 0 | 12 | 3910707acac6f4e53f32ee086377d27a7a54c8dd | 1,183 | ScreenTrack-Android | The Unlicense |
model/src/main/kotlin/hu/bme/mit/theta/interchange/jani/model/json/JaniJsonMultiOp.kt | ftsrg | 151,930,212 | false | null | /*
* Copyright 2018 Contributors to the Theta project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hu.bme.mit.theta.interchange.jani.model.json
import com.fasterxml.jackson.annotation.JacksonAnnotation
import kotlin.reflect.KClass
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@JacksonAnnotation
annotation class JaniJsonMultiOp(val predicate: KClass<out ConversionPredicate> = ConversionPredicate.None::class)
| 1 | Kotlin | 0 | 0 | 03b302e905396cd300b7c06d2a214d4dd8f9d0bc | 965 | theta-jani-interchange | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.