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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sdk/src/test/java/io/hellgate/android/sdk/client/hellgate/SessionResponseTest.kt
|
starfish-codes
| 785,230,334 | false |
{"Kotlin": 194583, "Shell": 1323}
|
package io.hellgate.android.sdk.client.hellgate
import io.hellgate.android.sdk.TestFactory.JWK
import io.hellgate.android.sdk.TestFactory.TOKENIZE_CARD_RESPONSE
import io.hellgate.android.sdk.util.jsonDeserialize
import io.hellgate.android.sdk.util.toObject
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
private const val TOKEN_COMPLETE = """{"data": {"token_id": "<KEY>"},"status": "success"}"""
class SessionResponseTest {
@Test
fun `SessionResponse, Check if data is correctly parsed`() {
val sessionResponse = TOKEN_COMPLETE.toObject<SessionResponse>().getOrNull()!!
println(sessionResponse)
assertThat(sessionResponse.data).isNotNull()
assertThat(sessionResponse.data).isInstanceOf(SessionResponse.Data.TokenId::class.java)
assertThat(sessionResponse.data).isEqualTo(SessionResponse.Data.TokenId("<KEY>"))
}
@Test
fun `SessionResponse with Guardian_Session, data is correctly parsed`() {
val sessionResponse = TOKENIZE_CARD_RESPONSE.toObject<SessionResponse>().getOrNull()!!
println(sessionResponse)
assertThat(sessionResponse.data).isNotNull()
assertThat(sessionResponse.data).isInstanceOf(SessionResponse.Data.TokenizationParam::class.java)
assertThat(sessionResponse.data).isEqualTo(SessionResponse.Data.TokenizationParam(JWK.jsonDeserialize()))
}
}
| 2 |
Kotlin
|
0
| 0 |
7bbf8a9ad17e3d2c7e50a7985685b896ce9b6746
| 1,394 |
hgate2-headless-android-sdk
|
Apache License 2.0
|
williamchart/src/main/java/ScreenHelper.kt
|
Pirokar
| 314,584,731 | false | null |
import android.content.Context
import android.graphics.Point
import android.view.Display
import android.view.WindowManager
object ScreenHelper {
fun convertDpToPx(context: Context, dp: Float): Float {
return dp * context.resources.displayMetrics.density
}
fun getScreenWidth(context: Context): Int {
val wm: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display: Display = wm.defaultDisplay
val size = Point()
display.getSize(size)
return size.x
}
}
| 0 |
Kotlin
|
0
| 0 |
af748ad449041092e138f77c5232d54b8279bcaf
| 555 |
williamchart-pirokaredition
|
Apache License 2.0
|
workflows/src/main/kotlin/com/r3/corda/lib/tokens/workflows/internal/flows/distribution/UpdateDistributionListRequestFlow.kt
|
christiand09
| 193,019,678 | true |
{"Kotlin": 423626}
|
package com.r3.corda.lib.tokens.workflows.internal.flows.distribution
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.tokens.contracts.states.EvolvableTokenType
import com.r3.corda.lib.tokens.contracts.types.TokenPointer
import net.corda.core.flows.FlowLogic
import net.corda.core.identity.Party
class UpdateDistributionListRequestFlow<T : EvolvableTokenType>(
val tokenPointer: TokenPointer<T>,
val sender: Party,
val receiver: Party
) : FlowLogic<Unit>() {
@Suspendable
override fun call() {
val evolvableToken = tokenPointer.pointer.resolve(serviceHub).state.data
val distributionListUpdate = DistributionListUpdate(sender, receiver, evolvableToken.linearId)
val maintainers = evolvableToken.maintainers
val maintainersSessions = maintainers.map(::initiateFlow)
maintainersSessions.forEach {
it.send(distributionListUpdate)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
4d0c64570572125b22ba96d846e9e61bd476834d
| 952 |
token-sdk
|
Apache License 2.0
|
ktor-swagger-ui/src/main/kotlin/io/github/smiley4/ktorswaggerui/dsl/routes/OpenApiMultipartPart.kt
|
SMILEY4
| 526,907,299 | false | null |
package io.github.smiley4.ktorswaggerui.dsl.routes
import io.github.smiley4.ktorswaggerui.data.KTypeDescriptor
import io.github.smiley4.ktorswaggerui.data.OpenApiMultipartPartData
import io.github.smiley4.ktorswaggerui.data.SwaggerTypeDescriptor
import io.github.smiley4.ktorswaggerui.data.TypeDescriptor
import io.github.smiley4.ktorswaggerui.dsl.OpenApiDslMarker
import io.ktor.http.ContentType
import io.swagger.v3.oas.models.media.Schema
import kotlin.reflect.KType
import kotlin.reflect.typeOf
/**
* Describes one section of a multipart-body.
* See https://swagger.io/docs/specification/describing-request-body/multipart-requests/ for more info
*/
@OpenApiDslMarker
class OpenApiMultipartPart(
/**
* The name of this part
*/
val name: String,
val type: TypeDescriptor
) {
/**
* Set a specific content types for this part
*/
var mediaTypes: Collection<ContentType> = setOf()
/**
* List of headers of this part
*/
val headers = mutableMapOf<String, OpenApiHeader>()
/**
* Possible headers for this part
*/
fun header(name: String, type: TypeDescriptor, block: OpenApiHeader.() -> Unit = {}) {
headers[name] = OpenApiHeader().apply(block).apply {
this.type = type
}
}
/**
* Possible headers for this part
*/
fun header(name: String, type: Schema<*>, block: OpenApiHeader.() -> Unit = {}) = header(name, SwaggerTypeDescriptor(type), block)
/**
* Possible headers for this part
*/
fun header(name: String, type: KType, block: OpenApiHeader.() -> Unit = {}) = header(name, KTypeDescriptor(type), block)
/**
* Possible headers for this part
*/
inline fun <reified T> header(name: String, noinline block: OpenApiHeader.() -> Unit = {}) =
header(name, KTypeDescriptor(typeOf<T>()), block)
fun build() = OpenApiMultipartPartData(
name = name,
type = type,
mediaTypes = mediaTypes.toSet(),
headers = headers.mapValues { it.value.build() }
)
}
| 7 | null |
33
| 172 |
d040a9738c3dbbf3008a776bf38e8fa68386a83d
| 2,067 |
ktor-swagger-ui
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/example/moveeapp_compose_kmm/App.kt
|
adessoTurkey
| 673,248,729 | false |
{"Kotlin": 334470, "Swift": 3538, "Ruby": 101}
|
package com.example.moveeapp_compose_kmm
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import cafe.adriel.voyager.navigator.CurrentScreen
import cafe.adriel.voyager.navigator.Navigator
import com.example.moveeapp_compose_kmm.nav.LocalMainNavigator
import com.example.moveeapp_compose_kmm.nav.SplashScreen
import com.example.moveeapp_compose_kmm.ui.theme.AppTheme
@Composable
fun App() {
AppTheme {
Navigator(SplashScreen()) {
CompositionLocalProvider(LocalMainNavigator provides it) {
CurrentScreen()
}
}
LaunchedEffect(Unit) {
log { "App started." }
}
}
}
| 6 |
Kotlin
|
3
| 78 |
2dbbd48654ee482258c37f0e51e52eb6af15ec3c
| 753 |
compose-multiplatform-sampleapp
|
Apache License 2.0
|
src/main/kotlin/Throwables.kt
|
a-sit-plus
| 629,574,777 | false | null |
package at.asitplus.attestation
//not very idiomatic, but
enum class Platform {
IOS,
ANDROID
}
sealed class AttestationException(val platform: Platform, message: String? = null, cause: Throwable? = null) :
Throwable(message, cause) {
open class Content(platform: Platform, message: String? = null, cause: Throwable? = null) :
AttestationException(platform, message = message, cause = cause)
class Certificate(platform: Platform, message: String? = null, cause: Throwable? = null) :
AttestationException(platform, message = message, cause = cause)
}
| 1 |
Kotlin
|
0
| 3 |
32b1b3f43c1aac23a915dfa28336161a43cd5d9b
| 590 |
attestation-service
|
Apache License 2.0
|
src/main/kotlin/org/ktorm/support/kingbase/KingbaseFormatter.kt
|
isyscore
| 851,513,726 | false |
{"Kotlin": 10343, "Java": 191}
|
package org.ktorm.support.kingbase
import org.ktorm.database.Database
import org.ktorm.expression.*
import org.ktorm.schema.IntSqlType
/**
* [SqlFormatter] implementation for Kingbase, formatting SQL expressions as strings with their execution arguments.
*/
open class KingbaseFormatter(database: Database, beautifySql: Boolean, indentSize: Int) : SqlFormatter(database, beautifySql, indentSize), KingbaseExpressionVisitor {
override fun visit(expr: SqlExpression): SqlExpression {
val result = super<KingbaseExpressionVisitor>.visit(expr)
check(result === expr) { "SqlFormatter cannot modify the expression tree." }
return result
}
override fun shouldQuote(identifier: String): Boolean = identifier.startsWith('_') || super.shouldQuote(identifier)
override fun visitQuerySource(expr: QuerySourceExpression): QuerySourceExpression = super<SqlFormatter>.visitQuerySource(expr)
override fun visitSelect(expr: SelectExpression): SelectExpression {
super<SqlFormatter>.visitSelect(expr)
return expr
}
override fun visitQuery(expr: QueryExpression): QueryExpression {
return super<SqlFormatter>.visitQuery(expr)
// if (expr.offset == null && expr.limit == null) {
// return super<SqlFormatter>.visitQuery(expr)
// }
//
// val offset = expr.offset ?: 0
// val minRowNum = offset + 1
// val maxRowNum = expr.limit?.let { offset + it } ?: Int.MAX_VALUE
//
// val tempTableName = "_t"
//
// writeKeyword("select * ")
// newLine(Indentation.SAME)
// writeKeyword("from (")
// newLine(Indentation.INNER)
// writeKeyword("select ")
// write("${tempTableName.quoted}.*, ")
// writeKeyword("rownum ")
// write("${"_rn".quoted} ")
// newLine(Indentation.SAME)
// writeKeyword("from ")
//
// visitQuerySource(
// when (expr) {
// is SelectExpression -> expr.copy(tableAlias = tempTableName, offset = null, limit = null)
// is UnionExpression -> expr.copy(tableAlias = tempTableName, offset = null, limit = null)
// }
// )
//
// newLine(Indentation.SAME)
// writeKeyword("where rownum <= ?")
// newLine(Indentation.OUTER)
// write(") ")
// newLine(Indentation.SAME)
// writeKeyword("where ")
// write("${"_rn".quoted} >= ? ")
//
// _parameters += ArgumentExpression(maxRowNum, IntSqlType)
// _parameters += ArgumentExpression(minRowNum, IntSqlType)
//
// return expr
}
override fun writePagination(expr: QueryExpression) {
newLine(Indentation.SAME)
writeKeyword("limit ?, ? ")
_parameters += ArgumentExpression(expr.offset ?: 0, IntSqlType)
_parameters += ArgumentExpression(expr.limit ?: Int.MAX_VALUE, IntSqlType)
}
override fun visitBulkInsert(expr: BulkInsertExpression): BulkInsertExpression {
writeKeyword("insert into ")
visitTable(expr.table)
writeInsertColumnNames(expr.assignments[0].map { it.column })
writeKeyword("values ")
for ((i, assignments) in expr.assignments.withIndex()) {
if (i > 0) {
removeLastBlank()
write(", ")
}
writeInsertValues(assignments)
}
if (expr.updateAssignments.isNotEmpty()) {
writeKeyword("on duplicate key update ")
writeColumnAssignments(expr.updateAssignments)
}
return expr
}
override fun visitUnion(expr: UnionExpression): UnionExpression {
if (expr.orderBy.isEmpty()) {
return super<SqlFormatter>.visitUnion(expr)
}
writeKeyword("select * ")
newLine(Indentation.SAME)
writeKeyword("from ")
visitQuerySource(expr.copy(orderBy = emptyList(), tableAlias = null))
newLine(Indentation.SAME)
writeKeyword("order by ")
visitExpressionList(expr.orderBy)
return expr
}
}
| 0 |
Kotlin
|
0
| 0 |
655a8ad7990019c1692b827fb69166e5a657c66e
| 4,057 |
ktorm-support-kingbase
|
Apache License 2.0
|
mineme-craft/src/main/kotlin/me/ddevil/mineme/craft/ui/UIResources.kt
|
BrunoSilvaFreire
| 89,026,535 | false | null |
package me.ddevil.mineme.craft.ui
import me.ddevil.mineme.api.MineMeConstants.MATERIAL_TYPE_IDENTIFIER
import me.ddevil.mineme.craft.config.MineMeConfigSource
import me.ddevil.mineme.craft.config.MineMeConfigValue
import me.ddevil.shiroi.craft.config.YAMLFileConfigManager
import me.ddevil.shiroi.craft.message.MessageManager
import me.ddevil.shiroi.craft.util.createConfig
import me.ddevil.shiroi.craft.util.parseConfig
import me.ddevil.shiroi.util.DEFAULT_SHIROI_ITEM_DATA_IDENTIFIER
import me.ddevil.shiroi.util.DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER
import me.ddevil.util.DEFAULT_NAME_IDENTIFIER
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
object UIResources {
lateinit var PRIMARY_BACKGROUND: ItemStack
private set
lateinit var SECONDARY_BACKGROUND: ItemStack
private set
lateinit var TELEPORT_BUTTON: ItemStack
private set
lateinit var RESET_BUTTON: ItemStack
private set
lateinit var CLEAR_BUTTON: ItemStack
private set
lateinit var BACK_BUTTON: ItemStack
private set
lateinit var CLOSE_BUTTON: ItemStack
private set
lateinit var DISABLE_BUTTON: ItemStack
private set
lateinit var DELETE_BUTTON: ItemStack
private set
lateinit var PAUSE_COUNTDOWN_BUTTON: ItemStack
private set
lateinit var RESUME_COUNTDOWN_BUTTON: ItemStack
private set
lateinit var CHANGE_COMPOSITION_BUTTON: ItemStack
private set
lateinit var INVALID_CONFIG_ICON: ItemStack
private set
lateinit var DEFAULT_MATERIAL_ICON: ItemStack
private set
fun loadItems(configManager: YAMLFileConfigManager<MineMeConfigSource>, messageManager: MessageManager) {
this.PRIMARY_BACKGROUND = parseConfig(configManager.getValue(Keys.PRIMARY_BACKGROUND), messageManager)
this.SECONDARY_BACKGROUND = parseConfig(configManager.getValue(Keys.SECONDARY_BACKGROUND), messageManager)
this.TELEPORT_BUTTON = parseConfig(configManager.getValue(Keys.TELEPORT_BUTTON), messageManager)
this.RESET_BUTTON = parseConfig(configManager.getValue(Keys.RESET_BUTTON), messageManager)
this.CLEAR_BUTTON = parseConfig(configManager.getValue(Keys.CLEAR_BUTTON), messageManager)
this.BACK_BUTTON = parseConfig(configManager.getValue(Keys.BACK_BUTTON), messageManager)
this.CLOSE_BUTTON = parseConfig(configManager.getValue(Keys.CLOSE_BUTTON), messageManager)
this.DISABLE_BUTTON = parseConfig(configManager.getValue(Keys.DISABLE_BUTTON), messageManager)
this.DELETE_BUTTON = parseConfig(configManager.getValue(Keys.DELETE_BUTTON), messageManager)
this.PAUSE_COUNTDOWN_BUTTON = parseConfig(configManager.getValue(Keys.PAUSE_COUNTDOWN_BUTTON), messageManager)
this.RESUME_COUNTDOWN_BUTTON = parseConfig(configManager.getValue(Keys.RESUME_COUNTDOWN_BUTTON), messageManager)
this.CHANGE_COMPOSITION_BUTTON = parseConfig(configManager.getValue(Keys.CHANGE_COMPOSITION_BUTTON),
messageManager)
this.INVALID_CONFIG_ICON = parseConfig(configManager.getValue(Keys.INVALID_CONFIG_ICON), messageManager)
this.DEFAULT_MATERIAL_ICON = parseConfig(configManager.getValue(Keys.DEFAULT_MATERIAL_ICON), messageManager)
}
object Keys {
val PRIMARY_BACKGROUND = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.IRON_FENCE.name
this[DEFAULT_NAME_IDENTIFIER] = "&r"
},
MineMeConfigSource.GUI,
"resources.primaryBackground"
)
val SECONDARY_BACKGROUND = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.STAINED_GLASS_PANE.name
this[DEFAULT_SHIROI_ITEM_DATA_IDENTIFIER] = 15
this[DEFAULT_NAME_IDENTIFIER] = "&r"
}, MineMeConfigSource.GUI,
"resources.secondaryBackground"
)
val TELEPORT_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.ENDER_PEARL.name
this[DEFAULT_NAME_IDENTIFIER] = "$2Teleport to mine location!"
},
MineMeConfigSource.GUI,
"resources.teleportButton"
)
val RESET_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.IRON_PICKAXE.name
this[DEFAULT_NAME_IDENTIFIER] = "$2Resets the mine!"
this[DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER] = listOf(
"$3Uses the default mine repopulator",
"$3and executor to reset the mine."
)
},
MineMeConfigSource.GUI,
"resources.resetButton"
)
val CLEAR_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.IRON_PICKAXE.name
this[DEFAULT_NAME_IDENTIFIER] = "$2Clears the mine!"
},
MineMeConfigSource.GUI,
"resources.clearButton"
)
val BACK_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.EMERALD.name
this[DEFAULT_NAME_IDENTIFIER] = "$5Back"
},
MineMeConfigSource.GUI,
"resources.backButton"
)
val CLOSE_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.BARRIER.name
this[DEFAULT_NAME_IDENTIFIER] = "$4Close"
},
MineMeConfigSource.GUI,
"resources.closeButton"
)
val DISABLE_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.REDSTONE_TORCH_ON.name
this[DEFAULT_NAME_IDENTIFIER] = "$4Disable Mine"
this[DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER] = listOf(
"$4This unloads the mine and prevents ",
"$4it from being loaded in the next start-ups.",
"$4The mine can be re-enabled through it's config"
)
},
MineMeConfigSource.GUI,
"resources.disableButton"
)
val DELETE_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.TNT.name
this[DEFAULT_NAME_IDENTIFIER] = "$4Delete Mine"
this[DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER] = listOf(
"$4This deletes the mine permanently.",
"$4This is not reversible."
)
},
MineMeConfigSource.GUI,
"resources.deleteButton"
)
val PAUSE_COUNTDOWN_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.INK_SACK.name
this[DEFAULT_SHIROI_ITEM_DATA_IDENTIFIER] = 1
this[DEFAULT_NAME_IDENTIFIER] = "$4Pause Mine Countdown"
this[DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER] = listOf(
"$3This pauses the mine's reset countdown.",
"$3The countdown can be resumed again by",
"$3pressing this button again."
)
},
MineMeConfigSource.GUI,
"resources.pauseCountdown"
)
val RESUME_COUNTDOWN_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.INK_SACK.name
this[DEFAULT_SHIROI_ITEM_DATA_IDENTIFIER] = 10
this[DEFAULT_NAME_IDENTIFIER] = "$5Resume Mine Countdown"
this[DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER] = listOf(
"$3This resumes the mine's reset countdown.",
"$3The countdown can be again by",
"$3pressing this button again."
)
},
MineMeConfigSource.GUI,
"resources.resumeCountdown"
)
val CHANGE_COMPOSITION_BUTTON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.DIAMOND_BLOCK.name
this[DEFAULT_NAME_IDENTIFIER] = "$1Change Composition"
this[DEFAULT_SHIROI_ITEM_LORE_IDENTIFIER] = listOf(
"$3Opens a menu to change this mine's composition"
)
},
MineMeConfigSource.GUI,
"resources.changeComposition"
)
val INVALID_CONFIG_ICON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.BARRIER.name
this[DEFAULT_NAME_IDENTIFIER] = "$4Invalid config"
},
MineMeConfigSource.GUI,
"resources.invalidConfig"
)
val DEFAULT_MATERIAL_ICON = MineMeConfigValue(
createConfig {
this[MATERIAL_TYPE_IDENTIFIER] = Material.STONE.name
this[DEFAULT_NAME_IDENTIFIER] = "$4Default Material, YAY"
},
MineMeConfigSource.GUI,
"resources.defaultMaterialIcon"
)
}
}
| 0 |
Kotlin
|
0
| 0 |
6cdfb74a10a5b78d929df9e8bd36b0da626378f4
| 9,790 |
MineMe2
|
Do What The F*ck You Want To Public License
|
gradle-plugins/compose/src/main/kotlin/org/jetbrains/compose/internal/utils/fileUtils.kt
|
JetBrains
| 293,498,508 | false | null |
/*
* Copyright 2020-2023 JetBrains s.r.o. and respective authors and developers.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.compose.internal.utils
import org.gradle.api.Project
import org.gradle.api.file.Directory
import org.gradle.api.file.FileSystemLocation
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.file.RegularFile
import org.gradle.api.provider.Provider
import java.io.File
internal fun Provider<String>.toDir(project: Project): Provider<Directory> =
project.layout.dir(map { File(it) })
internal fun Provider<File>.fileToDir(project: Project): Provider<Directory> =
project.layout.dir(this)
internal fun Provider<Directory>.file(relativePath: String): Provider<RegularFile> =
map { it.file(relativePath) }
internal fun Provider<Directory>.dir(relativePath: String): Provider<Directory> =
map { it.dir(relativePath) }
internal val <T : FileSystemLocation> Provider<T>.ioFile: File
get() = get().asFile
internal val <T : FileSystemLocation> Provider<T>.ioFileOrNull: File?
get() = orNull?.asFile
internal fun FileSystemOperations.delete(vararg files: Any) {
delete { it.delete(*files) }
}
internal fun FileSystemOperations.mkdirs(vararg dirs: File) {
for (dir in dirs) {
dir.mkdirs()
}
}
internal fun FileSystemOperations.mkdirs(vararg dirs: Provider<out FileSystemLocation>) {
mkdirs(*dirs.ioFiles())
}
internal fun FileSystemOperations.clearDirs(vararg dirs: File) {
delete(*dirs)
mkdirs(*dirs)
}
internal fun FileSystemOperations.clearDirs(vararg dirs: Provider<out FileSystemLocation>) {
clearDirs(*dirs.ioFiles())
}
private fun Array<out Provider<out FileSystemLocation>>.ioFiles(): Array<File> =
let { providers -> Array(size) { i -> providers[i].ioFile } }
| 1,055 |
Kotlin
|
953
| 12,717 |
1dc5839ed781a7d7893814b701c18b88c8097046
| 1,865 |
compose-multiplatform
|
Apache License 2.0
|
LibDownloadAndInstall/src/main/java/com/bihe0832/android/lib/download/DownloadUtils.kt
|
carythh
| 341,799,051 | true |
{"Shell": 2, "Gradle": 69, "Proguard": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 179, "Kotlin": 101, "Java": 336, "AIDL": 5, "Groovy": 3, "Java Properties": 1, "HTML": 1, "JavaScript": 1}
|
package com.bihe0832.android.lib.download
import android.content.Context
import com.bihe0832.android.lib.download.manager.DownloadByDownloadManager
import com.bihe0832.android.lib.download.manager.DownloadByHttp
/**
*
* @author zixie <EMAIL>
* Created on 2020-01-10.
* Description: Description
*
*/
const val DOWNLOAD_TYPE_HTTP = 1
const val DOWNLOAD_TYPE_DOWNLOADMANAGER = 2
const val NO_DOWNLOAD = 0
const val IS_DOWNLOADING = 1
const val HAS_DOWNLOAD = 2
const val IS_DOWNLOADING_HTTP = 3
const val IS_DOWNLOADING_DM = 4
object DownloadUtils {
private val httpDownload by lazy {
DownloadByHttp()
}
private val downloadManagerDownload by lazy {
DownloadByDownloadManager()
}
fun hasDownload(type: Int, context: Context, url: String, fileName: String, fileMD5: String, forceDownloadNew: Boolean): Int {
return when (type) {
DOWNLOAD_TYPE_HTTP -> httpDownload.hasDownload(context, url, fileName, fileMD5, forceDownloadNew)
else -> downloadManagerDownload.hasDownload(context, url, fileName, fileMD5, forceDownloadNew)
}
}
fun hasDownload(context: Context, url: String, fileName: String, fileMD5: String, forceDownloadNew: Boolean): Int {
when (downloadManagerDownload.hasDownload(context, url, fileName, fileMD5, forceDownloadNew)) {
NO_DOWNLOAD -> {
when (httpDownload.hasDownload(context, url, fileName, fileMD5, forceDownloadNew)) {
NO_DOWNLOAD -> {
return NO_DOWNLOAD
}
IS_DOWNLOADING -> {
return IS_DOWNLOADING_HTTP
}
}
}
IS_DOWNLOADING -> {
return IS_DOWNLOADING_DM
}
HAS_DOWNLOAD -> {
return HAS_DOWNLOAD
}
}
return NO_DOWNLOAD
}
fun startDownload(type: Int, context: Context, info: DownloadItem, downloadListener: DownloadListener?) {
when (type) {
DOWNLOAD_TYPE_HTTP -> httpDownload.startDownload(context, info, downloadListener)
else -> downloadManagerDownload.startDownload(context, info, downloadListener)
}
}
fun startDownload(context: Context, info: DownloadItem, downloadListener: DownloadListener?) {
downloadManagerDownload.startDownload(context, info, downloadListener)
}
fun cancleDownload(url: String) {
downloadManagerDownload.cancleDownload(url)
httpDownload.cancleDownload(url)
}
fun cancleDownload(type: Int, url: String) {
when (type) {
DOWNLOAD_TYPE_HTTP -> httpDownload.cancleDownload(url)
else -> downloadManagerDownload.cancleDownload(url)
}
}
}
| 0 | null |
0
| 1 |
0f047cf92f4fab30d285460a863e9ef488a0cff3
| 2,805 |
AndroidAppFactory
|
Apache License 2.0
|
odinmain/src/main/kotlin/me/odinmain/features/impl/dungeon/SecretChime.kt
|
odtheking
| 657,580,559 | false |
{"Kotlin": 824053, "Java": 92422, "GLSL": 7311}
|
package me.odinmain.features.impl.dungeon
import me.odinmain.events.impl.EntityLeaveWorldEvent
import me.odinmain.features.Category
import me.odinmain.features.Module
import me.odinmain.features.settings.Setting.Companion.withDependency
import me.odinmain.features.settings.impl.ActionSetting
import me.odinmain.features.settings.impl.NumberSetting
import me.odinmain.features.settings.impl.SelectorSetting
import me.odinmain.features.settings.impl.StringSetting
import me.odinmain.utils.distanceSquaredTo
import me.odinmain.utils.skyblock.PlayerUtils
import me.odinmain.utils.skyblock.dungeon.DungeonUtils
import net.minecraft.entity.item.EntityItem
import net.minecraftforge.client.event.sound.PlaySoundSourceEvent
import net.minecraftforge.event.entity.player.PlayerInteractEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
/**
* Plays a sound whenever you get a secret. Do not use the bat death sound or your game will freeze!
* @author Aton
*/
object SecretChime : Module(
name = "Secret Chime",
category = Category.DUNGEON,
description = "Plays a sound whenever you get a secret. Do not use the bat death sound or your game will freeze!"
){
private val defaultSounds = arrayListOf("mob.blaze.hit", "fire.ignite", "random.orb", "random.break", "mob.guardian.land.hit", "note.pling", "Custom")
private val sound: Int by SelectorSetting("Sound", "mob.blaze.hit", defaultSounds, description = "Which sound to play when you get a secret.")
private val customSound: String by StringSetting("Custom Sound", "mob.blaze.hit",
description = "Name of a custom sound to play. This is used when Custom is selected in the Sound setting."
).withDependency { sound == defaultSounds.size - 1 }
private val volume: Float by NumberSetting("Volume", 1f, 0, 1, .01f, description = "Volume of the sound.")
private val pitch: Float by NumberSetting("Pitch", 2f, 0, 2, .01f, description = "Pitch of the sound.")
val reset: () -> Unit by ActionSetting("Play sound") {
playSecretSound()
}
private var lastPlayed = System.currentTimeMillis()
private val drops = listOf(
"Health Potion VIII Splash Potion", "Healing Potion 8 Splash Potion", "Healing Potion VIII Splash Potion",
"Decoy", "Inflatable Jerry", "Spirit Leap", "Trap", "Training Weights", "Defuse Kit", "Dungeon Chest Key", "Treasure Talisman", "Revive Stone",
)
@SubscribeEvent
fun onInteract(event: PlayerInteractEvent) {
if (!DungeonUtils.inDungeons || event.pos == null || !DungeonUtils.isSecret(mc.theWorld?.getBlockState(event.pos) ?: return, event.pos)) return
playSecretSound()
}
/**
* For item pickup detection. The forge event for item pickups cant be used, because item pickups are handled server side.
*/
@SubscribeEvent
fun onRemoveEntity(event: EntityLeaveWorldEvent) {
if (!DungeonUtils.inDungeons || mc.thePlayer.distanceSquaredTo(event.entity) > 36) return
if (event.entity is EntityItem && drops.any { event.entity.entityItem.displayName.contains(it) })
playSecretSound()
}
/**
* For bat death detection
*/
@SubscribeEvent
fun onSoundPlay(event: PlaySoundSourceEvent) {
if (!DungeonUtils.inDungeons || event.name != "mob.bat.death") return
playSecretSound()
}
private fun playSecretSound() {
if (System.currentTimeMillis() - lastPlayed <= 10) return
val sound = if (sound == defaultSounds.size - 1) customSound else defaultSounds[sound]
PlayerUtils.playLoudSound(sound, volume, pitch)
lastPlayed = System.currentTimeMillis()
}
}
| 0 |
Kotlin
|
9
| 28 |
e0fb5e69dbb31e4f36351d6448a819b13c48240c
| 3,670 |
OdinClient
|
MIT License
|
lib/src/androidTest/java/com/irurueta/android/navigation/inertial/test/collectors/AttitudeSensorCollector2Test.kt
|
albertoirurueta
| 440,663,799 | false | null |
/*
* Copyright (C) 2023 <NAME> (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irurueta.android.navigation.inertial.test.collectors
import android.hardware.Sensor
import android.hardware.SensorDirectChannel
import android.util.Log
import androidx.test.filters.RequiresDevice
import androidx.test.platform.app.InstrumentationRegistry
import com.irurueta.android.navigation.inertial.ThreadSyncHelper
import com.irurueta.android.navigation.inertial.collectors.AttitudeSensorCollector2
import com.irurueta.android.navigation.inertial.collectors.AttitudeSensorType
import com.irurueta.android.navigation.inertial.collectors.SensorDelay
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@RequiresDevice
class AttitudeSensorCollector2Test {
private val syncHelper = ThreadSyncHelper()
@Volatile
private var measured = 0
@Before
fun setUp() {
measured = 0
}
@Test
fun sensor_whenAbsoluteAttitudeSensorType_returnsSensor() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val collector = AttitudeSensorCollector2(
context,
AttitudeSensorType.ABSOLUTE_ATTITUDE
)
val sensor = collector.sensor
requireNotNull(sensor)
logSensor(sensor)
}
@Test
fun sensor_whenRelativeAttitudeSensorType_returnsSensor() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val collector = AttitudeSensorCollector2(
context,
AttitudeSensorType.RELATIVE_ATTITUDE
)
val sensor = collector.sensor
requireNotNull(sensor)
logSensor(sensor)
}
@Test
fun sensorAvailable_whenAbsoluteAttitudeSensorType_returnsTrue() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val collector = AttitudeSensorCollector2(
context,
AttitudeSensorType.ABSOLUTE_ATTITUDE
)
assertTrue(collector.sensorAvailable)
}
@Test
fun sensorAvailable_whenRelativeAttitudeSensorType_returnsTrue() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val collector = AttitudeSensorCollector2(
context,
AttitudeSensorType.RELATIVE_ATTITUDE
)
assertTrue(collector.sensorAvailable)
}
@Test
fun startAndStop_whenAbsoluteAttitudeSensorType_collectsMeasurements() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val collector = AttitudeSensorCollector2(
context,
AttitudeSensorType.ABSOLUTE_ATTITUDE,
SensorDelay.FASTEST,
accuracyChangedListener = { _, accuracy ->
Log.d(
"AttitudeSensorCollector2Test",
"onAccuracyChanged - accuracy: $accuracy"
)
},
measurementListener = { _, measurement ->
val attitude = measurement.attitude
val timestamp = measurement.timestamp
val accuracy = measurement.accuracy
val sensorType = measurement.sensorType
assertEquals(AttitudeSensorType.ABSOLUTE_ATTITUDE, sensorType)
Log.d(
"AttitudeSensorCollector2Test",
"onMeasurement - attitude.a: ${attitude.a}, attitude.b: ${attitude.b}"
+ ", attitude.c: ${attitude.c}, attitude.d: ${attitude.d}"
+ ", timestamp: $timestamp, accuracy: $accuracy"
+ ", sensorType: $sensorType"
)
syncHelper.notifyAll { measured++ }
}
)
collector.start()
syncHelper.waitOnCondition({ measured < 1 })
collector.stop()
assertTrue(measured > 0)
}
@Test
fun startAndStop_whenRelativeAttitudeSensorType_collectsMeasurements() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val collector = AttitudeSensorCollector2(
context,
AttitudeSensorType.RELATIVE_ATTITUDE,
SensorDelay.FASTEST,
accuracyChangedListener = { _, accuracy ->
Log.d(
"AttitudeSensorCollector2Test",
"onAccuracyChanged - accuracy: $accuracy"
)
},
measurementListener = { _, measurement ->
val attitude = measurement.attitude
val timestamp = measurement.timestamp
val accuracy = measurement.accuracy
val sensorType = measurement.sensorType
assertEquals(AttitudeSensorType.RELATIVE_ATTITUDE, sensorType)
Log.d(
"AttitudeSensorCollector2Test",
"onMeasurement - attitude.a: ${attitude.a}, attitude.b: ${attitude.b}"
+ ", attitude.c: ${attitude.c}, attitude.d: ${attitude.d}"
+ ", timestamp: $timestamp, accuracy: $accuracy"
+ ", sensorType: $sensorType"
)
syncHelper.notifyAll { measured++ }
}
)
collector.start()
syncHelper.waitOnCondition({ measured < 1 })
collector.stop()
assertTrue(measured > 0)
}
private fun logSensor(sensor: Sensor) {
val fifoMaxEventCount = sensor.fifoMaxEventCount
val fifoReservedEventCount = sensor.fifoReservedEventCount
val highestDirectReportRateLevel = sensor.highestDirectReportRateLevel
val highestDirectReportRateLevelName = when (highestDirectReportRateLevel) {
SensorDirectChannel.RATE_STOP -> "RATE_STOP"
SensorDirectChannel.RATE_NORMAL -> "RATE_NORMAL"
SensorDirectChannel.RATE_FAST -> "RATE_FAST"
SensorDirectChannel.RATE_VERY_FAST -> "RATE_VERY_FAST"
else -> ""
}
val id = sensor.id
val maxDelay = sensor.maxDelay // microseconds (µs)
val maximumRange = sensor.maximumRange // unitless
val minDelay = sensor.minDelay // microseconds (µs)
val name = sensor.name
val power = sensor.power // milli-amperes (mA)
val reportingMode = sensor.reportingMode
val reportingModeName = when (reportingMode) {
Sensor.REPORTING_MODE_CONTINUOUS -> "REPORTING_MODE_CONTINUOUS"
Sensor.REPORTING_MODE_ON_CHANGE -> "REPORTING_MODE_ON_CHANGE"
Sensor.REPORTING_MODE_ONE_SHOT -> "REPORTING_MODE_ONE_SHOT"
Sensor.REPORTING_MODE_SPECIAL_TRIGGER -> "REPORTING_MODE_SPECIAL_TRIGGER"
else -> ""
}
val resolution = sensor.resolution // unitless
val stringType = sensor.stringType
val type = sensor.type
val vendor = sensor.vendor
val version = sensor.version
val additionInfoSupported = sensor.isAdditionalInfoSupported
val dynamicSensor = sensor.isDynamicSensor
val wakeUpSensor = sensor.isWakeUpSensor
Log.d(
"AttitudeSensorCollector2Test", "Sensor - fifoMaxEventCount: $fifoMaxEventCount, "
+ "fifoReservedEventCount: $fifoReservedEventCount, "
+ "highestDirectReportRateLevel: $highestDirectReportRateLevel, "
+ "highestDirectReportRateLevelName: $highestDirectReportRateLevelName, "
+ "id: $id, "
+ "maxDelay: $maxDelay µs, "
+ "maximumRange: $maximumRange unitless, "
+ "minDelay: $minDelay µs, "
+ "name: $name, "
+ "power: $power mA, "
+ "reportingMode: $reportingMode, "
+ "reportingModeName: $reportingModeName, "
+ "resolution: $resolution unitless, "
+ "stringType: $stringType, "
+ "type: $type, "
+ "vendor: $vendor, "
+ "version: $version, "
+ "additionInfoSupported: $additionInfoSupported, "
+ "dynamicSensor: $dynamicSensor, "
+ "wakeUpSensor: $wakeUpSensor"
)
}
}
| 0 |
Kotlin
|
0
| 0 |
02ee04164a36bc0238fa3b78e8842a799475fcf5
| 8,924 |
irurueta-android-navigation-inertial
|
Apache License 2.0
|
adaptive-core/src/jvmTest/kotlin/fun/adaptive/service/BasicServiceTest.kt
|
spxbhuhb
| 788,711,010 | false |
{"Kotlin": 2104845, "Java": 23090, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
|
/*
* Copyright © 2020-2024, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package `fun`.adaptive.service
import `fun`.adaptive.service.testing.TestServiceTransport
import `fun`.adaptive.wireformat.WireFormatProvider
import `fun`.adaptive.wireformat.json.JsonWireFormatProvider
import `fun`.adaptive.wireformat.protobuf.ProtoWireFormatProvider
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
class BasicServiceTest {
@Test
fun basic() {
suspend fun test(provider: WireFormatProvider): String {
val c = TestApi1.Consumer()
c.serviceCallTransport = TestServiceTransport(TestService1(ServiceContext()), wireFormatProvider = provider)
return c.testFun(1, "hello")
}
runBlocking {
assertTrue(test(ProtoWireFormatProvider()).startsWith("i:1 s:hello ServiceContext("))
assertTrue(test(JsonWireFormatProvider()).startsWith("i:1 s:hello ServiceContext("))
}
}
}
| 21 |
Kotlin
|
0
| 3 |
a423e127a406395002bbc663bb2fea6fcad749f1
| 1,066 |
adaptive
|
Apache License 2.0
|
core/src/main/java/com/wassim/showcase/core/data/local/TagsDao.kt
|
WassimBenltaief
| 275,135,668 | false | null |
package com.wassim.showcase.core.data.local
import androidx.room.Dao
import androidx.room.Query
import com.wassim.showcase.core.data.local.model.TagEntity
@Dao
abstract class TagsDao : BaseDao<TagEntity> {
@Query("SELECT * FROM tagEntity where ref_album_id=:albumId")
abstract suspend fun findTagsForAlbum(albumId: Long): List<TagEntity>
open fun insertTagsForAlbum(tags: List<TagEntity>, insertedAlbumId: Long) = tags
.map { it.copy(refAlbumId = insertedAlbumId) }
.apply { insert(this) }
}
| 0 |
Kotlin
|
0
| 0 |
91a8a266bdc8578e56d7514a70270bd1ad02836a
| 524 |
albums
|
Apache License 2.0
|
src/main/kotlin/edu/frc/technomancers/VisionServer/Camera.kt
|
technomancers
| 102,238,896 | false | null |
/*
* Copyright 2017 Technomancers
*
* 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 edu.frc.technomancers.VisionServer
import edu.wpi.cscore.*
import org.opencv.core.Mat
class Camera(id:Int = 0, rawPort:Int = 1185, procPort:Int = 1186, width:Int = 640, height:Int = 480, fps:Int = 30) {
private val sink:CvSink
private val source:CvSource
private val inputImage = Mat()
init {
val camera = setupCamera(id, rawPort)
camera.setResolution(width, height)
sink = setupCvSink(camera)
source = setupCvSource(width, height, fps, procPort)
}
fun process(processor:(Mat) -> Mat){
val frameTime = sink.grabFrame(inputImage)
if (frameTime == 0.toLong()) return
val outputImage = processor(inputImage)
source.putFrame(outputImage)
}
//Create a new camera with device ID and have a server on port
private fun setupCamera(id:Int, port:Int): UsbCamera {
val inputStream = MjpegServer("MJPEG Server", port)
val camera = UsbCamera("CoprocessorCamera", id)
inputStream.source = camera
return camera
}
//Get a way to grab the image from the camera
private fun setupCvSink(camera: UsbCamera): CvSink {
val imageSink = CvSink("CV Image Grabber")
imageSink.source = camera
return imageSink
}
//Get a way to put processed images to a server on port
private fun setupCvSource(width:Int, height:Int, fps:Int, port:Int): CvSource {
val imageSource = CvSource("CV Image Source", VideoMode.PixelFormat.kMJPEG, width, height, fps)
val cvStream = MjpegServer("CV Image Stream", port)
cvStream.source = imageSource
return imageSource
}
}
| 0 |
Kotlin
|
0
| 0 |
098a65ec0426ecd05a64d643e2cc281592f43012
| 2,249 |
VisionServer
|
Apache License 2.0
|
app/src/main/java/com/comjeong/nomadworker/ui/splash/SplashActivity.kt
|
HUFSummer-Hackathon
| 512,365,622 | false | null |
package com.comjeong.nomadworker.ui.splash
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.comjeong.nomadworker.R
import com.comjeong.nomadworker.data.datasource.local.NomadSharedPreferences
import com.comjeong.nomadworker.ui.MainActivity
import com.comjeong.nomadworker.ui.signin.SignInActivity
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
initSplash()
}
private fun initSplash() {
Handler(Looper.getMainLooper()).postDelayed({
Log.e("Splash", "TEST")
handleUser()
finish()
}, 1000L)
}
private fun handleUser() {
val isLogin = NomadSharedPreferences.getUserIsLogin()
if (isLogin) startActivity(Intent(this, MainActivity::class.java))
else startActivity(Intent(this, SignInActivity::class.java))
}
}
| 2 |
Kotlin
|
0
| 0 |
5857dbe020888785367e0e4596a7b342aa1ec4a7
| 1,099 |
NomadWorker-Android
|
MIT License
|
tools/lint/src/main/java/com/grab/lint/LintReportCommand.kt
|
grab
| 379,151,712 | false |
{"Kotlin": 372586, "Starlark": 172838, "Java": 2517, "Smarty": 2052}
|
package com.grab.lint
import com.github.ajalt.clikt.parameters.options.convert
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import java.io.File
import java.nio.file.Path
import kotlin.io.path.pathString
import kotlin.system.measureTimeMillis
import com.android.tools.lint.Main as LintCli
class LintReportCommand : LintBaseCommand() {
private val updatedBaseline by option(
"-ub",
"--updated-baseline",
help = "The lint baseline file"
).convert { File(it) }.required()
private val lintResultXml by option(
"-o",
"--output-xml",
help = "Lint output xml"
).convert { File(it) }.required()
private val outputJunitXml by option(
"-oj",
"--output-junit-xml",
help = "Lint output in Junit format"
).convert { File(it) }.required()
private val resultCode by option(
"-rc",
"--result-code",
help = "File containing result status of running Lint"
).convert { File(it) }.required()
private val failOnWarnings by option(
"-fow",
"--fail-on-warning",
help = "exit code 1 if it find Lint issues with severity of Warning"
).convert { it.toBoolean() }.default(true)
private val failOnInformation by option(
"-foi",
"--fail-on-information",
help = "exit code 1 if it find Lint issues with severity of Information"
).convert { it.toBoolean() }.default(true)
override fun run(
workingDir: Path,
projectXml: File,
tmpBaseline: File,
) {
val elapsed = measureTimeMillis {
runLint(workingDir, projectXml, tmpBaseline, lintResultXml)
}
tmpBaseline.copyTo(updatedBaseline)
LintResults(
name = name,
lintResultsFile = lintResultXml,
elapsed = elapsed,
resultCodeFile = resultCode,
outputJunitXml = outputJunitXml,
failOnInformation = failOnInformation,
failOnWarnings = failOnWarnings,
).process()
}
override fun preRun() {
// No-op
}
private fun runLint(workingDir: Path, projectXml: File, tmpBaseline: File, lintResultXml: File) {
val cliArgs = (defaultLintOptions + listOf(
"--project", projectXml.toString(),
"--xml", lintResultXml.toString(),
"--baseline", tmpBaseline.absolutePath,
"--path-variables", pathVariables,
"--cache-dir", workingDir.resolve("cache").pathString,
"--update-baseline", // Always update the baseline, so we can copy later if needed
"--report-only" // Only do reporting
)).toTypedArray()
LintCli().run(cliArgs)
}
}
| 13 |
Kotlin
|
14
| 38 |
0540712597f4346f7573bbd01dfe1bd93a7060bb
| 2,850 |
grab-bazel-common
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Excavator.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.Excavator: ImageVector
get() {
if (_excavator != null) {
return _excavator!!
}
_excavator = Builder(name = "Excavator", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(22.396f, 3.242f)
curveToRelative(-0.976f, -0.421f, -2.104f, -0.221f, -2.875f, 0.508f)
lineToRelative(-5.2f, 4.912f)
lineToRelative(-2.235f, -4.999f)
curveToRelative(-0.723f, -1.618f, -2.335f, -2.663f, -4.108f, -2.663f)
horizontalLineToRelative(-0.478f)
curveToRelative(-1.93f, 0.0f, -3.5f, 1.57f, -3.5f, 3.5f)
verticalLineToRelative(4.5f)
curveToRelative(-2.206f, 0.0f, -4.0f, 1.794f, -4.0f, 4.0f)
curveToRelative(0.0f, 1.025f, 0.399f, 1.952f, 1.035f, 2.661f)
curveToRelative(-0.637f, 0.776f, -1.035f, 1.757f, -1.035f, 2.839f)
curveToRelative(0.0f, 2.485f, 2.015f, 4.5f, 4.5f, 4.5f)
horizontalLineToRelative(6.0f)
curveToRelative(2.485f, 0.0f, 4.5f, -2.015f, 4.5f, -4.5f)
curveToRelative(0.0f, -1.083f, -0.398f, -2.063f, -1.035f, -2.839f)
curveToRelative(0.637f, -0.709f, 1.035f, -1.635f, 1.035f, -2.661f)
verticalLineToRelative(-0.854f)
lineToRelative(6.0f, -5.666f)
verticalLineToRelative(4.899f)
lineToRelative(-3.407f, 3.407f)
curveToRelative(-0.541f, 0.54f, -0.701f, 1.346f, -0.408f, 2.052f)
reflectiveCurveToRelative(0.975f, 1.162f, 1.739f, 1.162f)
horizontalLineToRelative(1.576f)
curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f)
lineTo(24.0f, 5.68f)
curveToRelative(0.0f, -1.061f, -0.63f, -2.018f, -1.604f, -2.438f)
close()
moveTo(7.0f, 4.5f)
curveToRelative(0.0f, -0.276f, 0.224f, -0.5f, 0.5f, -0.5f)
horizontalLineToRelative(0.478f)
curveToRelative(0.591f, 0.0f, 1.128f, 0.349f, 1.37f, 0.888f)
lineToRelative(1.838f, 4.112f)
horizontalLineToRelative(-4.186f)
verticalLineToRelative(-4.5f)
close()
moveTo(4.0f, 12.0f)
horizontalLineToRelative(8.0f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f)
horizontalLineToRelative(-7.0f)
curveToRelative(-0.551f, 0.0f, -1.0f, -0.449f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.449f, -1.0f, 1.0f, -1.0f)
close()
moveTo(4.5f, 20.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
close()
moveTo(10.5f, 20.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
close()
}
}
.build()
return _excavator!!
}
private var _excavator: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,410 |
icons
|
MIT License
|
src/main/kotlin/no/nav/tilleggsstonader/sak/behandling/barn/BarnService.kt
|
navikt
| 685,490,225 | false |
{"Kotlin": 2149188, "Gherkin": 54372, "HTML": 39535, "Shell": 924, "Dockerfile": 164}
|
package no.nav.tilleggsstonader.sak.behandling.barn
import no.nav.tilleggsstonader.sak.felles.domain.BarnId
import no.nav.tilleggsstonader.sak.felles.domain.BehandlingId
import no.nav.tilleggsstonader.sak.infrastruktur.database.Sporbar
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class BarnService(
private val barnRepository: BarnRepository,
) {
@Transactional
fun opprettBarn(barn: List<BehandlingBarn>): List<BehandlingBarn> =
barnRepository.insertAll(barn)
fun finnBarnPåBehandling(behandlingId: BehandlingId): List<BehandlingBarn> =
barnRepository.findByBehandlingId(behandlingId)
@Transactional
fun gjenbrukBarn(
forrigeBehandlingId: BehandlingId,
nyBehandlingId: BehandlingId,
): Map<TidligereBarnId, NyttBarnId> {
val nyeBarnPåGammelId = barnRepository.findByBehandlingId(forrigeBehandlingId)
.associate { it.id to it.copy(id = BarnId.random(), behandlingId = nyBehandlingId, sporbar = Sporbar()) }
barnRepository.insertAll(nyeBarnPåGammelId.values.toList())
return nyeBarnPåGammelId.map { it.key to it.value.id }.toMap()
}
}
/**
* Typer for å få litt tydeligere grensesnitt på [gjenbrukBarn]
*/
typealias TidligereBarnId = BarnId
typealias NyttBarnId = BarnId
/**
* Her skal vi opprette barn
* Gjelder for [BARNETILSYN]
* * Skal opprette barn som kommer inn fra søknaden
* * Burde kunne opprette barn som blir lagt in manuellt via journalføringen?
* * Oppdatere personopplysninger -> oppdatere barn
* * Kopiere barn ved revurdering
*
* * Ved revurdering burde vi appende barn, sånn at man fortsatt får med vilkår for tidligere barn?
*/
| 3 |
Kotlin
|
1
| 0 |
7520818c5a146efeb6ad3c690bc6155bf08a09ae
| 1,743 |
tilleggsstonader-sak
|
MIT License
|
src/main/kotlin/com/github/shiraji/namesticker/enums/ValidHorizontalAlignments.kt
|
shiraji
| 796,725,188 | false |
{"Kotlin": 17562}
|
package com.github.shiraji.namesticker.enums
import javax.swing.SwingConstants
enum class ValidHorizontalAlignments(val value: Int) {
LEFT(SwingConstants.LEFT),
CENTER(SwingConstants.CENTER),
RIGHT(SwingConstants.RIGHT),
}
| 1 |
Kotlin
|
1
| 1 |
adea24c03e00ea7830fbe7145865dd953c985b40
| 236 |
name-sticker-plugin
|
Apache License 2.0
|
core-network/src/main/java/com/zavaitar/core/network/model/UserX.kt
|
hybrid-developer
| 240,302,035 | false | null |
package com.zavaitar.core.network.model
import com.google.gson.annotations.SerializedName
import androidx.annotation.Keep
@Keep
data class User(
@SerializedName("contributors_enabled") val contributorsEnabled: Boolean,
@SerializedName("created_at") val createdAt: String,
@SerializedName("default_profile") val defaultProfile: Boolean,
@SerializedName("default_profile_image") val defaultProfileImage: Boolean,
@SerializedName("description") val description: String,
@SerializedName("entities") val entities: EntitiesXX,
@SerializedName("favourites_count") val favouritesCount: Int,
@SerializedName("follow_request_sent") val followRequestSent: Any?,
@SerializedName("followers_count") val followersCount: Int,
@SerializedName("following") val following: Any?,
@SerializedName("friends_count") val friendsCount: Int,
@SerializedName("geo_enabled") val geoEnabled: Boolean,
@SerializedName("has_extended_profile") val hasExtendedProfile: Boolean,
@SerializedName("id") val id: Long,
@SerializedName("id_str") val idStr: String,
@SerializedName("is_translation_enabled") val isTranslationEnabled: Boolean,
@SerializedName("is_translator") val isTranslator: Boolean,
@SerializedName("lang") val lang: Any?,
@SerializedName("listed_count") val listedCount: Int,
@SerializedName("location") val location: String,
@SerializedName("name") val name: String,
@SerializedName("notifications") val notifications: Any?,
@SerializedName("profile_background_color") val profileBackgroundColor: String,
@SerializedName("profile_background_image_url") val profileBackgroundImageUrl: String,
@SerializedName("profile_background_image_url_https") val profileBackgroundImageUrlHttps: String,
@SerializedName("profile_background_tile") val profileBackgroundTile: Boolean,
@SerializedName("profile_banner_url") val profileBannerUrl: String,
@SerializedName("profile_image_url") val profileImageUrl: String,
@SerializedName("profile_image_url_https") val profileImageUrlHttps: String,
@SerializedName("profile_link_color") val profileLinkColor: String,
@SerializedName("profile_sidebar_border_color") val profileSidebarBorderColor: String,
@SerializedName("profile_sidebar_fill_color") val profileSidebarFillColor: String,
@SerializedName("profile_text_color") val profileTextColor: String,
@SerializedName("profile_use_background_image") val profileUseBackgroundImage: Boolean,
@SerializedName("protected") val `protected`: Boolean,
@SerializedName("screen_name") val screenName: String,
@SerializedName("statuses_count") val statusesCount: Int,
@SerializedName("time_zone") val timeZone: Any?,
@SerializedName("translator_type") val translatorType: String,
@SerializedName("url") val url: String,
@SerializedName("utc_offset") val utcOffset: Any?,
@SerializedName("verified") val verified: Boolean
)
| 0 |
Kotlin
|
0
| 0 |
98d454977cc2db035f7e1567448de8977d054b50
| 2,950 |
TwitterFeed
|
Apache License 2.0
|
Oxygen/bukkit/src/main/kotlin/cc/fyre/stark/rank/command/RankHiddenCommand.kt
|
AndyReckt
| 364,514,997 | false |
{"Java": 12055418, "Kotlin": 766337, "Shell": 5518}
|
/*
* Copyright (c) 2020.
* Created by YoloSanta
* Created On 10/22/20, 1:23 AM
*/
package cc.fyre.stark.rank.command
import cc.fyre.stark.core.StarkCore
import cc.fyre.stark.core.rank.Rank
import cc.fyre.stark.engine.command.Command
import cc.fyre.stark.engine.command.data.parameter.Param
import org.bukkit.ChatColor
import org.bukkit.entity.Player
/**
* Created by DaddyDombo <EMAIL> on 5/20/2020.
*/
object RankHiddenCommand {
@Command(["rank sethidden"], "op")
@JvmStatic
fun rankHidden(sender: Player, @Param("rank") rank: Rank, @Param("hidden") hidden: Boolean) {
StarkCore.instance.rankHandler.getByName(rank.displayName)!!.hidden = hidden
StarkCore.instance.rankHandler.saveRank(rank)
sender.sendMessage("${ChatColor.YELLOW}The rank ${ChatColor.GOLD}${rank.displayName} ${ChatColor.YELLOW}hidden has been updated to ${ChatColor.GOLD}$hidden${ChatColor.YELLOW}.")
}
}
| 1 | null |
1
| 1 |
200501c7eb4aaf5709b4adceb053fee6707173fa
| 925 |
Old-Code
|
Apache License 2.0
|
app/src/main/java/dev/enesky/minify/features/home/HomeViewModel.kt
|
enesky
| 814,556,108 | false |
{"Kotlin": 309366}
|
package dev.enesky.minify.features.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.enesky.minify.common.delegate.Event
import dev.enesky.minify.common.delegate.EventDelegate
import dev.enesky.minify.common.delegate.UiState
import dev.enesky.minify.common.delegate.UiStateDelegate
import dev.enesky.minify.common.utils.AppUtils
import dev.enesky.minify.data.database.DataStoreManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.launch
/**
* Created by Enes Kamil YILMAZ on 15/06/2024
*/
class HomeViewModel(
private val appUtils: AppUtils,
dataStoreManager: DataStoreManager
) : ViewModel(),
UiState<HomeUiState> by UiStateDelegate(initialState = { HomeUiState() }),
Event<HomeEvents> by EventDelegate() {
init {
getDefaults()
combine(
dataStoreManager.appearanceSettingsFlow,
dataStoreManager.featureSettingsFlow
) { appearanceSettings, featureSettings ->
updateUiState {
copy(
appearanceSettings = appearanceSettings,
featureSettings = featureSettings
)
}
}.launchIn(viewModelScope)
}
private fun getDefaults() {
viewModelScope.launch(Dispatchers.IO) {
updateUiState {
copy(
clockAppPackageName = appUtils.getClockApp(),
calendarAppPackageName = appUtils.getCalendarApp(),
phoneAppPackageName = appUtils.getPhoneApp(),
cameraAppPackageName = appUtils.getCameraApp(),
contactsAppPackageName = appUtils.getContactsApp(),
messagesAppPackageName = appUtils.getMessagesApp()
)
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
9881bbd59fc17a16bacf83e5308a178e05c372ae
| 1,907 |
minify
|
MIT License
|
app/src/main/java/de/droidcon/berlin2018/ui/speakerdetail/SpeakerDetailsSessionDelegate.kt
|
OpenConference
| 100,889,869 | false | null |
package de.droidcon.berlin2018.ui.speakerdetail
import android.support.annotation.DrawableRes
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.hannesdorfmann.adapterdelegates3.AbsListItemAdapterDelegate
import de.droidcon.berlin2018.R
import de.droidcon.berlin2018.model.Session
/**
*
*
* @author <NAME>
*/
class SpeakerDetailsSessionDelegate(val inflater: LayoutInflater,
val clickListener: (Session) -> Unit) : AbsListItemAdapterDelegate<SpeakerSessionItem, SpeakerDetailsItem, SpeakerDetailsSessionDelegate.SessionViewHolder>() {
override fun isForViewType(item: SpeakerDetailsItem, items: MutableList<SpeakerDetailsItem>,
position: Int): Boolean = item is SpeakerSessionItem
override fun onBindViewHolder(item: SpeakerSessionItem, viewHolder: SessionViewHolder,
payloads: MutableList<Any>) {
viewHolder.session = item.session
viewHolder.bind(if (item.showIcon) R.drawable.ic_sessions_details else null,
item.session.title()!!)
}
override fun onCreateViewHolder(parent: ViewGroup): SessionViewHolder =
SessionViewHolder(inflater.inflate(R.layout.item_details_icon_text, parent, false),
clickListener)
class SessionViewHolder(v: View, val clickListener: (Session) -> Unit) : RecyclerView.ViewHolder(
v) {
lateinit var session: Session
init {
v.setOnClickListener { clickListener(session) }
}
val icon = v.findViewById<ImageView>(R.id.icon)
val text = v.findViewById<TextView>(R.id.text)
inline fun bind(@DrawableRes iconRes: Int?, t: String) {
if (iconRes == null) {
icon.visibility = View.INVISIBLE
} else {
icon.setImageDrawable(itemView.resources.getDrawable(iconRes))
}
text.text = t
}
}
}
| 1 | null |
1
| 27 |
142effaf4eb04abb12d5b812e797a89922b649a5
| 1,913 |
DroidconBerlin2017
|
Apache License 2.0
|
backend/src/main/java/com/paligot/confily/backend/third/parties/billetweb/BilletWebRouting.kt
|
GerardPaligot
| 444,230,272 | false |
{"Kotlin": 887764, "Swift": 125581, "Shell": 1148, "Dockerfile": 542, "HTML": 338, "CSS": 102}
|
package com.paligot.confily.backend.third.parties.billetweb
import com.paligot.confily.backend.events.EventDao
import io.ktor.http.HttpStatusCode
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
fun Routing.registerBilletWebRoutes(
eventDao: EventDao
) {
get("billet-web/{barcode}") {
val eventId = call.parameters["eventId"]!!
val barcode = call.parameters["barcode"]!!
val api = BilletWebApi.Factory.create(enableNetworkLogs = true)
val repository = BilletWebRepository(api, eventDao)
call.respond(HttpStatusCode.OK, repository.get(eventId, barcode))
}
}
| 9 |
Kotlin
|
5
| 141 |
465cf6c21bf28010a01af8095ad9dcca068c5035
| 673 |
Confily
|
Apache License 2.0
|
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/brands/Safari.kt
|
DevSrSouza
| 311,134,756 | false |
{"Kotlin": 36719092}
|
package compose.icons.fontawesomeicons.brands
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.fontawesomeicons.BrandsGroup
public val BrandsGroup.Safari: ImageVector
get() {
if (_safari != null) {
return _safari!!
}
_safari = Builder(name = "Safari", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 512.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(274.69f, 274.69f)
lineToRelative(-37.38f, -37.38f)
lineTo(166.0f, 346.0f)
close()
moveTo(256.0f, 8.0f)
curveTo(119.0f, 8.0f, 8.0f, 119.0f, 8.0f, 256.0f)
reflectiveCurveTo(119.0f, 504.0f, 256.0f, 504.0f)
reflectiveCurveTo(504.0f, 393.0f, 504.0f, 256.0f)
reflectiveCurveTo(393.0f, 8.0f, 256.0f, 8.0f)
close()
moveTo(411.85f, 182.79f)
lineToRelative(14.78f, -6.13f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 437.08f, 181.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -4.33f, 10.46f)
lineTo(418.0f, 197.57f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -10.45f, -4.33f)
horizontalLineToRelative(0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 411.85f, 182.79f)
close()
moveTo(314.43f, 94.0f)
lineToRelative(6.12f, -14.78f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 331.0f, 74.92f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 4.33f, 10.45f)
lineToRelative(-6.13f, 14.78f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -10.45f, 4.33f)
horizontalLineToRelative(0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 314.43f, 94.0f)
close()
moveTo(256.0f, 60.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, 8.0f)
lineTo(264.0f, 84.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -8.0f, 8.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -8.0f, -8.0f)
lineTo(248.0f, 68.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 256.0f, 60.0f)
close()
moveTo(181.0f, 74.92f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 10.46f, 4.33f)
lineTo(197.57f, 94.0f)
arcToRelative(8.0f, 8.0f, 0.0f, true, true, -14.78f, 6.12f)
lineToRelative(-6.13f, -14.78f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 181.0f, 74.92f)
close()
moveTo(117.42f, 117.41f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 11.31f, 0.0f)
lineTo(140.0f, 128.72f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 140.0f, 140.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -11.31f, 0.0f)
lineToRelative(-11.31f, -11.31f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 117.41f, 117.41f)
close()
moveTo(60.0f, 256.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, -8.0f)
lineTo(84.0f, 248.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, 8.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -8.0f, 8.0f)
lineTo(68.0f, 264.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 60.0f, 256.0f)
close()
moveTo(100.15f, 329.21f)
lineTo(85.37f, 335.34f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 74.92f, 331.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 4.33f, -10.46f)
lineTo(94.0f, 314.43f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 10.45f, 4.33f)
horizontalLineToRelative(0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 100.15f, 329.21f)
close()
moveTo(104.48f, 193.21f)
horizontalLineToRelative(0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 94.0f, 197.57f)
lineToRelative(-14.78f, -6.12f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 74.92f, 181.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 10.45f, -4.33f)
lineToRelative(14.78f, 6.13f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 104.48f, 193.24f)
close()
moveTo(197.57f, 418.0f)
lineToRelative(-6.12f, 14.78f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -14.79f, -6.12f)
lineToRelative(6.13f, -14.78f)
arcTo(8.0f, 8.0f, 0.0f, true, true, 197.57f, 418.0f)
close()
moveTo(264.0f, 444.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -8.0f, 8.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -8.0f, -8.0f)
lineTo(248.0f, 428.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, -8.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, 8.0f)
close()
moveTo(331.0f, 437.08f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -10.46f, -4.33f)
lineTo(314.43f, 418.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 4.33f, -10.45f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 10.45f, 4.33f)
lineToRelative(6.13f, 14.78f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 331.0f, 437.08f)
close()
moveTo(394.58f, 394.59f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -11.31f, 0.0f)
lineTo(372.0f, 383.28f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 372.0f, 372.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 11.31f, 0.0f)
lineToRelative(11.31f, 11.31f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 394.59f, 394.59f)
close()
moveTo(286.25f, 286.25f)
lineTo(110.34f, 401.66f)
lineTo(225.75f, 225.75f)
lineTo(401.66f, 110.34f)
close()
moveTo(437.08f, 331.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -10.45f, 4.33f)
lineToRelative(-14.78f, -6.13f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -4.33f, -10.45f)
horizontalLineToRelative(0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 418.0f, 314.43f)
lineToRelative(14.78f, 6.12f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 437.08f, 331.0f)
close()
moveTo(444.0f, 264.0f)
lineTo(428.0f, 264.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, -8.0f, -8.0f)
horizontalLineToRelative(0.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, -8.0f)
horizontalLineToRelative(16.0f)
arcToRelative(8.0f, 8.0f, 0.0f, false, true, 8.0f, 8.0f)
horizontalLineToRelative(0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 444.0f, 264.0f)
close()
}
}
.build()
return _safari!!
}
private var _safari: ImageVector? = null
| 17 |
Kotlin
|
25
| 571 |
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 8,915 |
compose-icons
|
MIT License
|
plugins/kotlin/idea/tests/testData/intentions/convertTrimMarginToTrimIndent/simple.kt
|
ingokegel
| 72,937,917 | true | null |
// AFTER-WARNING: Variable 'x' is never used
// INTENTION_TEXT: "Convert to 'trimIndent()' call"
// WITH_STDLIB
fun test() {
val x =
"""
|a
|b
""".<caret>trimMargin()
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 224 |
intellij-community
|
Apache License 2.0
|
app/src/main/java/fr/julocorp/onbackpressed/StuffRecyclerViewAdapter.kt
|
shinmen
| 342,653,880 | false | null |
package fr.julocorp.onbackpressed
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class StuffRecyclerViewAdapter(
private val bunchOfStuff: List<String>
) : RecyclerView.Adapter<StuffRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.stuff_item, parent, false)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.idView.text = bunchOfStuff[position]
}
override fun getItemCount(): Int = bunchOfStuff.size
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val idView: TextView = view.findViewById(R.id.stuffItem)
}
}
| 0 |
Kotlin
|
0
| 0 |
823272a5adf7f9509e323b4b747dd6df1a64cfb3
| 872 |
onbackpressed
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/ui/screens/dogDetails/DogDetailsScreen.kt
|
PhilipDukhov
| 342,783,324 | false | null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.screens.dogDetails
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.R
import com.example.androiddevchallenge.model.DogInfo
@Composable
fun DogDetailsScreen(dogInfo: DogInfo) {
Box(
modifier = Modifier
.fillMaxSize()
) {
var showDialog by rememberSaveable { mutableStateOf(false) }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
) {
Image(
painterResource(dogInfo.image),
contentDescription = "${dogInfo.name} image",
modifier = Modifier
.fillMaxWidth()
)
Text(
dogInfo.name,
style = MaterialTheme.typography.h4,
modifier = Modifier
.align(Alignment.CenterHorizontally)
)
Text(
dogInfo.description,
style = MaterialTheme.typography.body1,
modifier = Modifier
.padding(horizontal = 10.dp)
)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(20.dp)
.size(44.dp)
.clickable(
role = Role.Button
) {
showDialog = true
}
.background(Color.Green, shape = CircleShape)
) {
Image(
painterResource(R.drawable.ic_round_call_24),
contentDescription = "Call the curator",
)
}
if (showDialog) {
CallingDialog { showDialog = false }
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ada88d1ba317208d9cb77d6b4ea98ca01acf97fa
| 3,543 |
android-dev-challenge-compose-puppy
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/ui/screens/dogDetails/DogDetailsScreen.kt
|
PhilipDukhov
| 342,783,324 | false | null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.screens.dogDetails
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.R
import com.example.androiddevchallenge.model.DogInfo
@Composable
fun DogDetailsScreen(dogInfo: DogInfo) {
Box(
modifier = Modifier
.fillMaxSize()
) {
var showDialog by rememberSaveable { mutableStateOf(false) }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
) {
Image(
painterResource(dogInfo.image),
contentDescription = "${dogInfo.name} image",
modifier = Modifier
.fillMaxWidth()
)
Text(
dogInfo.name,
style = MaterialTheme.typography.h4,
modifier = Modifier
.align(Alignment.CenterHorizontally)
)
Text(
dogInfo.description,
style = MaterialTheme.typography.body1,
modifier = Modifier
.padding(horizontal = 10.dp)
)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(20.dp)
.size(44.dp)
.clickable(
role = Role.Button
) {
showDialog = true
}
.background(Color.Green, shape = CircleShape)
) {
Image(
painterResource(R.drawable.ic_round_call_24),
contentDescription = "Call the curator",
)
}
if (showDialog) {
CallingDialog { showDialog = false }
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ada88d1ba317208d9cb77d6b4ea98ca01acf97fa
| 3,543 |
android-dev-challenge-compose-puppy
|
Apache License 2.0
|
app/src/main/java/com/vinzaceto/augmentedvideo/ArVideoFragment.kt
|
vinzaceto
| 266,373,912 | false | null |
package com.vinzaceto.augmentedvideo
/**
* NTT Data Italia S.p.A.
* File created on 23/05/2020.
*
* @author Vincenzo Aceto - [email protected]
* @version 1.0
*/
import android.animation.ValueAnimator
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.RectF
import android.media.MediaMetadataRetriever
import android.media.MediaMetadataRetriever.*
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.Toast
import androidx.core.animation.doOnStart
import androidx.core.graphics.rotationMatrix
import androidx.core.graphics.transform
import com.google.ar.core.AugmentedImage
import com.google.ar.core.AugmentedImageDatabase
import com.google.ar.core.Config
import com.google.ar.core.Session
import com.google.ar.sceneform.FrameTime
import com.google.ar.sceneform.rendering.ExternalTexture
import com.google.ar.sceneform.rendering.ModelRenderable
import com.google.ar.sceneform.ux.ArFragment
import java.io.IOException
open class ArVideoFragment : ArFragment() {
private lateinit var mediaPlayer: MediaPlayer
private lateinit var externalTexture: ExternalTexture
private lateinit var videoRenderable: ModelRenderable
private lateinit var videoAnchorNode: VideoAnchorNode
private var activeAugmentedImage: AugmentedImage? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mediaPlayer = MediaPlayer()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
planeDiscoveryController.hide()
planeDiscoveryController.setInstructionView(null)
arSceneView.planeRenderer.isEnabled = false
arSceneView.isLightEstimationEnabled = false
initializeSession()
createArScene()
return view
}
override fun getSessionConfiguration(session: Session): Config {
fun loadAugmentedImageBitmap(imageName: String): Bitmap =
requireContext().assets.open(imageName).use { return BitmapFactory.decodeStream(it) }
fun setupAugmentedImageDatabase(config: Config, session: Session): Boolean {
try {
config.augmentedImageDatabase = AugmentedImageDatabase(session).also { db ->
db.addImage("rigori.mp4", loadAugmentedImageBitmap("coppa.jpg"))
}
return true
} catch (e: IllegalArgumentException) {
Log.e(TAG, "Could not add bitmap to augmented image database", e)
} catch (e: IOException) {
Log.e(TAG, "IO exception loading augmented image bitmap.", e)
}
return false
}
return super.getSessionConfiguration(session).also {
it.lightEstimationMode = Config.LightEstimationMode.DISABLED
it.focusMode = Config.FocusMode.AUTO
if (!setupAugmentedImageDatabase(it, session)) {
Toast.makeText(requireContext(), "Could not setup augmented image database", Toast.LENGTH_LONG).show()
}
}
}
private fun createArScene() {
// Create an ExternalTexture for displaying the contents of the video.
externalTexture = ExternalTexture().also {
mediaPlayer.setSurface(it.surface)
}
// Create a renderable with a material that has a parameter of type 'samplerExternal' so that
// it can display an ExternalTexture.
ModelRenderable.builder()
.setSource(requireContext(), R.raw.augmented_video_model)
.build()
.thenAccept { renderable ->
videoRenderable = renderable
renderable.isShadowCaster = false
renderable.isShadowReceiver = false
renderable.material.setExternalTexture("videoTexture", externalTexture)
}
.exceptionally { throwable ->
Log.e(TAG, "Could not create ModelRenderable", throwable)
return@exceptionally null
}
videoAnchorNode = VideoAnchorNode().apply {
setParent(arSceneView.scene)
}
}
/**
* In this case, we want to support the playback of one video at a time.
* Therefore, if ARCore loses current active image FULL_TRACKING we will pause the video.
* If the same image gets FULL_TRACKING back, the video will resume.
* If a new image will become active, then the corresponding video will start from scratch.
*/
override fun onUpdate(frameTime: FrameTime) {
val frame = arSceneView.arFrame ?: return
val updatedAugmentedImages = frame.getUpdatedTrackables(AugmentedImage::class.java)
// If current active augmented image isn't tracked anymore and video playback is started - pause video playback
val nonFullTrackingImages = updatedAugmentedImages.filter { it.trackingMethod != AugmentedImage.TrackingMethod.FULL_TRACKING }
activeAugmentedImage?.let { activeAugmentedImage ->
if (isArVideoPlaying() && nonFullTrackingImages.any { it.index == activeAugmentedImage.index }) {
pauseArVideo()
}
}
val fullTrackingImages = updatedAugmentedImages.filter { it.trackingMethod == AugmentedImage.TrackingMethod.FULL_TRACKING }
if (fullTrackingImages.isEmpty()) return
// If current active augmented image is tracked but video playback is paused - resume video playback
activeAugmentedImage?.let { activeAugmentedImage ->
if (fullTrackingImages.any { it.index == activeAugmentedImage.index }) {
if (!isArVideoPlaying()) {
resumeArVideo()
}
return
}
}
// Otherwise - make the first tracked image active and start video playback
fullTrackingImages.firstOrNull()?.let { augmentedImage ->
try {
playbackArVideo(augmentedImage)
} catch (e: Exception) {
Log.e(TAG, "Could not play video [${augmentedImage.name}]", e)
}
}
}
private fun isArVideoPlaying() = mediaPlayer.isPlaying
private fun pauseArVideo() {
videoAnchorNode.renderable = null
mediaPlayer.pause()
}
private fun resumeArVideo() {
mediaPlayer.start()
fadeInVideo()
}
private fun dismissArVideo() {
videoAnchorNode.anchor?.detach()
videoAnchorNode.renderable = null
activeAugmentedImage = null
mediaPlayer.reset()
}
private fun playbackArVideo(augmentedImage: AugmentedImage) {
Log.d(TAG, "playbackVideo = ${augmentedImage.name}")
requireContext().assets.openFd(augmentedImage.name)
.use { descriptor ->
val metadataRetriever = MediaMetadataRetriever()
metadataRetriever.setDataSource(
descriptor.fileDescriptor,
descriptor.startOffset,
descriptor.length
)
val videoWidth = metadataRetriever.extractMetadata(METADATA_KEY_VIDEO_WIDTH).toFloatOrNull() ?: 0f
val videoHeight = metadataRetriever.extractMetadata(METADATA_KEY_VIDEO_HEIGHT).toFloatOrNull() ?: 0f
val videoRotation = metadataRetriever.extractMetadata(METADATA_KEY_VIDEO_ROTATION).toFloatOrNull() ?: 0f
// Account for video rotation, so that scale logic math works properly
val imageSize = RectF(0f, 0f, augmentedImage.extentX, augmentedImage.extentZ)
.transform(rotationMatrix(videoRotation))
val videoScaleType = VideoScaleType.CenterCrop
videoAnchorNode.setVideoProperties(
videoWidth = videoWidth, videoHeight = videoHeight, videoRotation = videoRotation,
imageWidth = imageSize.width(), imageHeight = imageSize.height(),
videoScaleType = videoScaleType
)
// Update the material parameters
videoRenderable.material.setFloat2(MATERIAL_IMAGE_SIZE, imageSize.width(), imageSize.height())
videoRenderable.material.setFloat2(MATERIAL_VIDEO_SIZE, videoWidth, videoHeight)
videoRenderable.material.setBoolean(MATERIAL_VIDEO_CROP, VIDEO_CROP_ENABLED)
mediaPlayer.reset()
mediaPlayer.setDataSource(descriptor)
}.also {
mediaPlayer.isLooping = true
mediaPlayer.prepare()
mediaPlayer.start()
}
videoAnchorNode.anchor?.detach()
videoAnchorNode.anchor = augmentedImage.createAnchor(augmentedImage.centerPose)
activeAugmentedImage = augmentedImage
externalTexture.surfaceTexture.setOnFrameAvailableListener {
it.setOnFrameAvailableListener(null)
fadeInVideo()
}
}
private fun fadeInVideo() {
ValueAnimator.ofFloat(0f, 1f).apply {
duration = 400L
interpolator = LinearInterpolator()
addUpdateListener { v ->
videoRenderable.material.setFloat(MATERIAL_VIDEO_ALPHA, v.animatedValue as Float)
}
doOnStart { videoAnchorNode.renderable = videoRenderable }
start()
}
}
override fun onPause() {
super.onPause()
dismissArVideo()
}
override fun onDestroy() {
super.onDestroy()
mediaPlayer.release()
}
companion object {
private const val TAG = "ArVideoFragment"
private const val VIDEO_CROP_ENABLED = true
private const val MATERIAL_IMAGE_SIZE = "imageSize"
private const val MATERIAL_VIDEO_SIZE = "videoSize"
private const val MATERIAL_VIDEO_CROP = "videoCropEnabled"
private const val MATERIAL_VIDEO_ALPHA = "videoAlpha"
}
}
| 0 |
Kotlin
|
3
| 3 |
a9863bbecb0dcd9405ca5278d300e67cb8a9f933
| 10,238 |
AugmentedVideo
|
Apache License 2.0
|
rule/src/test/kotlin/retect/rule/SuspendFunctionRuleTest.kt
|
MobileAct
| 202,090,133 | false | null |
package retect.rule
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class SuspendFunctionRuleTest {
@Test
fun testNoWarning_withIgnorePrivateFunction() {
val config = TestConfig(mapOf("ignorePrivateFunction" to "true"))
val findings = SuspendFunctionRule(config).compileAndLint(
"""
class Test {
suspend fun a(){}
private fun b(){}
}
""".trimIndent()
)
assertEquals(0, findings.size)
}
@Test
fun testWarning_withIgnorePrivateFunction() {
val config = TestConfig(mapOf("ignorePrivateFunction" to "true"))
val findings = SuspendFunctionRule(config).compileAndLint(
"""
class Test {
fun a(){}
private fun b(){}
}
""".trimIndent()
)
assertEquals(1, findings.size)
}
@Test
fun testNoWarning_withoutIgnorePrivateFunction() {
val config = TestConfig(mapOf("ignorePrivateFunction" to "false"))
val findings = SuspendFunctionRule(config).compileAndLint(
"""
class Test {
suspend fun a(){}
private suspend fun b(){}
}
""".trimIndent()
)
assertEquals(0, findings.size)
}
@Test
fun testWarning_withoutIgnorePrivateFunction() {
val config = TestConfig(mapOf("ignorePrivateFunction" to "false"))
val findings = SuspendFunctionRule(config).compileAndLint(
"""
class Test {
fun a(){}
private fun b(){}
}
""".trimIndent()
)
assertEquals(2, findings.size)
}
}
| 0 |
Kotlin
|
0
| 0 |
9bc59c19055023fdfd403be76742958f827b5caa
| 1,952 |
RetektRule
|
MIT License
|
core/designsystem/src/main/java/earth/core/designsystem/components/dialog/HomeScreenFailedResponseDialog.kt
|
darkwhite220
| 733,589,658 | false |
{"Kotlin": 422132}
|
package earth.core.designsystem.components.dialog
import earth.core.designsystem.utils.Constants
import earth.core.designsystem.R
enum class HomeScreenFailedResponseDialog(
val dialogData: DialogData
) {
FAILED_WRONG_USERNAME(
dialogData = DialogData(
lottieFileName = Constants.FAILED_LOTTIE_FILE,
titleId = R.string.sync_failed,
textId = R.string.sync_failed_sync_wrong_username_desc,
buttonTextId = R.string.dismiss,
)
),
FAILED_WRONG_PASSWORD(
dialogData = DialogData(
lottieFileName = Constants.FAILED_LOTTIE_FILE,
titleId = R.string.sync_failed,
textId = R.string.sync_failed_sync_wrong_password_desc,
buttonTextId = R.string.dismiss,
)
),
TEMPORARILY_LOCKED_ACCOUNT(
dialogData = DialogData(
lottieFileName = Constants.FAILED_LOTTIE_FILE,
titleId = R.string.sync_failed,
textId = R.string.sync_failed_sync_temporary_lock_desc,
buttonTextId = R.string.dismiss,
)
),
PDF_TEXT_EXTRACTOR(
dialogData = DialogData(
lottieFileName = Constants.FAILED_LOTTIE_FILE,
titleId = R.string.sync_failed,
textId = R.string.sync_failed_sync_pdf_extractor_desc,
buttonTextId = R.string.dismiss,
)
),
FAILED(
dialogData = DialogData(
lottieFileName = Constants.FAILED_LOTTIE_FILE,
titleId = R.string.sync_failed,
textId = R.string.sync_failed_desc,
buttonTextId = R.string.dismiss,
)
),
}
| 0 |
Kotlin
|
0
| 1 |
77d7bd5af138079eb25e2c8f6a728546dbab4cab
| 1,642 |
AlgeriaBillsOnline
|
The Unlicense
|
app/src/main/java/slak/fanfictionstories/utility/JobSchedulerExtensions.kt
|
slak44
| 129,609,523 | false | null |
package slak.fanfictionstories.utility
import android.app.job.JobInfo
import android.app.job.JobScheduler
import androidx.annotation.RequiresApi
/** Wraps some ints in [JobScheduler]. */
enum class ScheduleResult {
SUCCESS, FAILURE;
companion object {
fun from(intResult: Int): ScheduleResult = when (intResult) {
JobScheduler.RESULT_SUCCESS -> SUCCESS
JobScheduler.RESULT_FAILURE -> FAILURE
else -> throw IllegalArgumentException("No such JobScheduler result type")
}
}
}
/** Wraps NETWORK_TYPE_* ints from [JobInfo]. */
enum class NetworkType(val jobInfoVal: Int) {
ANY(JobInfo.NETWORK_TYPE_ANY),
@RequiresApi(28)
CELLULAR(JobInfo.NETWORK_TYPE_CELLULAR),
NONE(JobInfo.NETWORK_TYPE_NONE),
NOT_ROAMING(JobInfo.NETWORK_TYPE_NOT_ROAMING),
UNMETERED(JobInfo.NETWORK_TYPE_UNMETERED);
}
/** Convenience extension to use the [NetworkType] enum instead of named ints. */
fun JobInfo.Builder.setRequiredNetworkType(type: NetworkType): JobInfo.Builder {
return this.setRequiredNetworkType(type.jobInfoVal)
}
/** Wraps BACKOFF_POLICY_* ints from [JobInfo]. */
enum class BackoffPolicy(val jobInfoVal: Int) {
LINEAR(JobInfo.BACKOFF_POLICY_LINEAR), EXPONENTIAL(JobInfo.BACKOFF_POLICY_EXPONENTIAL)
}
/** Convenience extension to use the [BackoffPolicy] enum instead of named ints. */
fun JobInfo.Builder.setBackoffCriteria(initialBackoffMillis: Long,
policy: BackoffPolicy): JobInfo.Builder {
return this.setBackoffCriteria(initialBackoffMillis, policy.jobInfoVal)
}
| 0 |
Kotlin
|
0
| 2 |
25c70cbccd31c4bba01fbb3969013406460eaf44
| 1,550 |
fanfiction-stories
|
MIT License
|
app/src/main/java/ar/edu/utn/frba/mobile/tpdesarrolloappsdispmov/screens/Login.kt
|
UTN-FRBA-Mobile
| 697,568,484 | false |
{"Kotlin": 184161}
|
package ar.edu.utn.frba.mobile.tpdesarrolloappsdispmov.screens
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.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.sharp.ArrowForward
import androidx.compose.material3.Button
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import ar.edu.utn.frba.mobile.tpdesarrolloappsdispmov.stateData.UserViewModel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import ar.edu.utn.frba.mobile.tpdesarrolloappsdispmov.components.TopBar
@Composable
fun Login (usuarioViewModel:UserViewModel){
var nombre by remember { mutableStateOf("") }
var waiting:Boolean = (usuarioViewModel.estadoUser.idDevice=="")
Scaffold (
topBar = { TopBar(userViewModel = usuarioViewModel)},
content = { innerPadding ->
Column (modifier = Modifier
.fillMaxSize()
.padding(innerPadding)){
Text(
text = "Elige un nombre de usuario para identificarte en la mesa",
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Justify,
style = MaterialTheme.typography.titleLarge
)
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp) ,
value = nombre,
onValueChange ={nombre=it},
label={Text("Ingresa tu nombre")} )
ExtendedFloatingActionButton(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize()
.padding(vertical = 8.dp),
onClick = {usuarioViewModel.log(nombre)},
icon = { Icon(Icons.Sharp.ArrowForward, contentDescription ="volver") },
text = { Text(
text = "Ingresar",
style = MaterialTheme.typography.titleSmall
) },
)
}
}
)
}
| 0 |
Kotlin
|
0
| 0 |
dd8d2b5a2a39f56b4d19e01ff0917e78c083eb09
| 2,889 |
OrderEasy
|
MIT License
|
src/main/kotlin/me/chill/infraction/UserStrike.kt
|
ianagbip1oti
| 149,568,021 | true |
{"Kotlin": 110969, "Python": 1773}
|
package me.chill.infraction
import org.joda.time.DateTime
data class UserStrike(val strikeId: Int,
val strikeWeight: Int,
val strikeReason: String,
val strikeDate: DateTime,
val actingModeratorId: String,
val expiryDate: DateTime)
| 0 |
Kotlin
|
0
| 0 |
3ec23923783893250de286071b4fff447a6e718d
| 267 |
Taiga
|
MIT License
|
presentation/viewmodel/src/test/kotlin/org/a_cyb/sayitalarm/presentation/viewmodel/ListViewModelSpec.kt
|
a-cyborg
| 751,578,623 | false |
{"Kotlin": 719375}
|
/*
* Copyright (c) 2024 <NAME> / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package org.a_cyb.sayitalarm.presentation.viewmodel
import app.cash.turbine.test
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.a_cyb.sayitalarm.domain.alarm_service.AlarmServiceContract
import org.a_cyb.sayitalarm.entity.Alarm
import org.a_cyb.sayitalarm.presentation.contracts.ListContract
import org.a_cyb.sayitalarm.presentation.contracts.ListContract.AlarmInfo
import org.a_cyb.sayitalarm.presentation.contracts.ListContract.ListState.Initial
import org.a_cyb.sayitalarm.presentation.contracts.ListContract.ListState.InitialError
import org.a_cyb.sayitalarm.presentation.contracts.ListContract.ListState.Success
import org.a_cyb.sayitalarm.presentation.contracts.command.CommandContract
import org.a_cyb.sayitalarm.presentation.viewmodel.fake.FakeAlarmData
import org.a_cyb.sayitalarm.presentation.viewmodel.fake.ListInteractorFake
import org.a_cyb.sayitalarm.presentation.viewmodel.fake.ListInteractorFake.InvokedType
import org.a_cyb.sayitalarm.presentation.viewmodel.fake.TimeFormatterFake
import org.a_cyb.sayitalarm.presentation.viewmodel.fake.WeekdayFormatterFake
import org.a_cyb.sayitalarm.util.formatter.time.TimeFormatterContract
import org.a_cyb.sayitalarm.util.formatter.weekday.WeekdayFormatterContract
import org.a_cyb.sayitalarm.util.test_utils.fulfils
import org.a_cyb.sayitalarm.util.test_utils.mustBe
import org.junit.Test
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
@OptIn(ExperimentalCoroutinesApi::class)
class ListViewModelSpec {
private val timeFormatter: TimeFormatterContract = TimeFormatterFake()
private val weekdayFormatter: WeekdayFormatterContract = WeekdayFormatterFake()
private val recognizerOfflineHelper: AlarmServiceContract.SttRecognizerOnDeviceHelper = mockk(relaxed = true)
@BeforeTest
fun setup() {
Dispatchers.setMain(StandardTestDispatcher())
every { recognizerOfflineHelper.isOfflineAvailable } answers { MutableStateFlow(true) }
}
@AfterTest
fun tearDown() {
Dispatchers.resetMain()
clearAllMocks()
}
@Test
fun `It is in the Initial State`() {
val viewModel = ListViewModel(ListInteractorFake(), timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel.state.value mustBe Initial
}
@Test
fun `When interactor initialization fails, it sets the state to InitialError`() = runTest {
// Given & When
val results = listOf(Result.failure<List<Alarm>>(IllegalStateException()))
val interactor = ListInteractorFake(results)
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel.state.test {
skipItems(1) // Initial
// Then
awaitItem() mustBe InitialError
}
}
@Test
fun `When interactor initialization success, it sets the state to Success`() = runTest {
// Given & When
val result = listOf(Result.success(alarms))
val interactor = ListInteractorFake(result)
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel.state.test {
skipItems(1)
// Then
awaitItem() mustBe Success(alarmInfo)
}
}
@Test
fun `When setEnabled is called, it calls interactor set enabled and propagates the success state`() = runTest {
// Given
val updatedAlarms = alarms.toMutableList().apply {
set(2, alarms[2].copy(enabled = true))
}
val results = listOf(Result.success(alarms), Result.success(updatedAlarms))
val interactor = ListInteractorFake(results)
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel.state.test {
skipItems(2)
// When
viewModel.setEnabled(3, false)
val expected = alarmInfo.toMutableList().apply {
set(2, alarmInfo[2].copy(enabled = true))
}
// Then
awaitItem() mustBe Success(expected)
interactor.invokedType mustBe InvokedType.SET_ENABLED
}
}
@Test
fun `When interactor setEnabled fails, it sets the state to the Error`() = runTest {
// Given
val results = listOf(Result.success(alarms), Result.failure(IllegalStateException()))
val interactor = ListInteractorFake(results)
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel.state.test {
skipItems(2)
// When
viewModel.setEnabled(3, false)
// Then
awaitItem() mustBe ListContract.ListState.Error(alarmInfo)
interactor.invokedType mustBe InvokedType.SET_ENABLED
}
}
@Test
fun `When deleteAlarm is called, it calls interactor delete and propagates the success state`() = runTest {
// Given
val updatedAlarms = alarms.toMutableList().apply { removeLast() }
val results = listOf(Result.success(alarms), Result.success(updatedAlarms))
val interactor = ListInteractorFake(results)
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel.state.test {
skipItems(2)
// When
viewModel.deleteAlarm(2)
val expected = alarmInfo.toMutableList().apply { removeLast() }
// Then
awaitItem() mustBe Success(expected)
interactor.invokedType mustBe InvokedType.DELETE_ALARM
}
}
@Test
fun `Given runCommand is called it executes the given command`() {
// Given
val interactor = ListInteractorFake()
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
val command: CommandContract.Command<ListViewModel> = mockk(relaxed = true)
// When
viewModel.runCommand(command)
// Then
verify(exactly = 1) { command.execute(any()) }
}
@Test
fun `It fulfills ListViewModel`() {
val interactor = ListInteractorFake()
val viewModel = ListViewModel(interactor, timeFormatter, weekdayFormatter, recognizerOfflineHelper)
viewModel fulfils ListContract.ListViewModel::class
}
private val alarms = FakeAlarmData.alarms
private val alarmInfo = listOf(
AlarmInfo(
id = 1,
time = "6:00 AM",
labelAndWeeklyRepeat = "Wake Up, every weekday",
enabled = true,
),
AlarmInfo(
id = 2,
time = "8:30 PM",
labelAndWeeklyRepeat = "Workout, Mon, Wed, and Fri",
enabled = true,
),
AlarmInfo(
id = 3,
time = "9:00 AM",
labelAndWeeklyRepeat = "Passion Hour, every weekend",
enabled = false,
),
)
}
| 0 |
Kotlin
|
0
| 0 |
f61242b7b7d96160168abc1f19736be04d774ad7
| 7,496 |
SayItAlarm
|
Apache License 2.0
|
client/src/main/kotlin/pt/marmelo/ets2atsjobsync/client/SaveFormat.kt
|
dmarmelo
| 174,200,174 | false | null |
package pt.marmelo.ets2atsjobsync.client
enum class SaveFormat(val value: Int) {
BINARY(0),
TEXT(2),
BOTH(3),
INVALID(-1),
NOT_FOUND(-2)
}
| 26 |
Kotlin
|
0
| 2 |
b714367919945bc76a0c4f7dbb252195271fe608
| 160 |
ets2-ats-job-sync
|
MIT License
|
packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/exception/ExceptionDecorator.kt
|
expo
| 65,750,241 | false | null |
package expo.modules.kotlin.exception
@Throws(CodedException::class)
internal inline fun <T> exceptionDecorator(decoratorBlock: (e: CodedException) -> Throwable, block: () -> T): T {
return try {
block()
} catch (e: Throwable) {
throw decoratorBlock(e.toCodedException())
}
}
| 668 | null |
5226
| 32,824 |
e62f80228dece98d5afaa4f5c5e4fb195f3daa15
| 291 |
expo
|
Apache License 2.0
|
komga/src/main/kotlin/org/gotson/komga/infrastructure/jooq/ThumbnailSeriesDao.kt
|
gotson
| 201,228,816 | false | null |
package org.gotson.komga.infrastructure.jooq
import org.gotson.komga.domain.model.ThumbnailSeries
import org.gotson.komga.domain.persistence.ThumbnailSeriesRepository
import org.gotson.komga.jooq.Tables
import org.gotson.komga.jooq.tables.records.ThumbnailSeriesRecord
import org.jooq.DSLContext
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.net.URL
@Component
class ThumbnailSeriesDao(
private val dsl: DSLContext,
@Value("#{@komgaProperties.database.batchChunkSize}") private val batchSize: Int,
) : ThumbnailSeriesRepository {
private val ts = Tables.THUMBNAIL_SERIES
override fun findByIdOrNull(thumbnailId: String): ThumbnailSeries? =
dsl.selectFrom(ts)
.where(ts.ID.eq(thumbnailId))
.fetchOneInto(ts)
?.toDomain()
override fun findAllBySeriesId(seriesId: String): Collection<ThumbnailSeries> =
dsl.selectFrom(ts)
.where(ts.SERIES_ID.eq(seriesId))
.fetchInto(ts)
.map { it.toDomain() }
override fun findSelectedBySeriesIdOrNull(seriesId: String): ThumbnailSeries? =
dsl.selectFrom(ts)
.where(ts.SERIES_ID.eq(seriesId))
.and(ts.SELECTED.isTrue)
.limit(1)
.fetchInto(ts)
.map { it.toDomain() }
.firstOrNull()
override fun insert(thumbnail: ThumbnailSeries) {
dsl.insertInto(ts)
.set(ts.ID, thumbnail.id)
.set(ts.SERIES_ID, thumbnail.seriesId)
.set(ts.URL, thumbnail.url?.toString())
.set(ts.THUMBNAIL, thumbnail.thumbnail)
.set(ts.TYPE, thumbnail.type.toString())
.set(ts.SELECTED, thumbnail.selected)
.execute()
}
@Transactional
override fun markSelected(thumbnail: ThumbnailSeries) {
dsl.update(ts)
.set(ts.SELECTED, false)
.where(ts.SERIES_ID.eq(thumbnail.seriesId))
.and(ts.ID.ne(thumbnail.id))
.execute()
dsl.update(ts)
.set(ts.SELECTED, true)
.where(ts.SERIES_ID.eq(thumbnail.seriesId))
.and(ts.ID.eq(thumbnail.id))
.execute()
}
override fun delete(thumbnailSeriesId: String) {
dsl.deleteFrom(ts).where(ts.ID.eq(thumbnailSeriesId)).execute()
}
override fun deleteBySeriesId(seriesId: String) {
dsl.deleteFrom(ts).where(ts.SERIES_ID.eq(seriesId)).execute()
}
@Transactional
override fun deleteBySeriesIds(seriesIds: Collection<String>) {
dsl.insertTempStrings(batchSize, seriesIds)
dsl.deleteFrom(ts).where(ts.SERIES_ID.`in`(dsl.selectTempStrings())).execute()
}
private fun ThumbnailSeriesRecord.toDomain() =
ThumbnailSeries(
thumbnail = thumbnail,
url = url?.let { URL(it) },
selected = selected,
type = ThumbnailSeries.Type.valueOf(type),
id = id,
seriesId = seriesId,
createdDate = createdDate,
lastModifiedDate = lastModifiedDate
)
}
| 89 | null |
79
| 2,733 |
4b435be21c6069ffd56ae6a9fba82056c16f2181
| 2,892 |
komga
|
MIT License
|
src/main/kotlin/com/shop/products/application/NegativeSortingWeightException.kt
|
ortzit
| 588,314,011 | false | null |
package com.shop.products.application
class NegativeSortingWeightException(message: String) : IllegalArgumentException(message)
| 0 |
Kotlin
|
0
| 0 |
0f62268b3a698bcfd5b31ecf180cbf972fb10ad8
| 128 |
shop-products-sorting
|
MIT License
|
emtehanak/src/main/java/ir/mahdighanbarpour/emtehanak/model/repositories/FrequentlyQuestionsRepository.kt
|
MahdiGhanbarpour
| 735,064,418 | false |
{"Kotlin": 708590}
|
package ir.mahdighanbarpour.emtehanak.model.repositories
import io.reactivex.rxjava3.core.Single
import ir.mahdighanbarpour.emtehanak.model.data.FrequentlyQuestion
import ir.mahdighanbarpour.emtehanak.model.data.FrequentlyQuestionsMainResult
import ir.mahdighanbarpour.emtehanak.model.dataBase.FrequentlyQuestionsDao
import ir.mahdighanbarpour.emtehanak.model.net.ApiService
class FrequentlyQuestionsRepository(
private val frequentlyQuestionsDao: FrequentlyQuestionsDao, private val apiService: ApiService
) {
// Getting the data of the frequently asked questions of the posted page from the local database
fun getFrequentlyQuestionsLocal(page: String): Single<List<FrequentlyQuestion>> {
return frequentlyQuestionsDao.getFrequentlyQuestions(page)
}
// Getting the data of the frequently asked questions of the posted page from server
fun getFrequentlyQuestionsOnline(page: String): Single<FrequentlyQuestionsMainResult> {
return apiService.getFrequentlyQuestions(page)
}
// Inserting the data of frequently asked questions of the posted page in the local database
fun insertAllFrequentlyQuestions(frequentlyQuestions: List<FrequentlyQuestion>) {
frequentlyQuestionsDao.insertAllFrequentlyQuestions(frequentlyQuestions)
}
}
| 0 |
Kotlin
|
0
| 0 |
6fd6104330e500b9afee6f7f09fa1f80890e3c63
| 1,293 |
Emtehanak
|
MIT License
|
src/mainKotlin/kotlin/me/sizableshrimp/adventofcode2023/days/Day24.kt
|
SizableShrimp
| 723,954,033 | false |
{"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "TOML": 1, "INI": 1, "Java": 38, "Kotlin": 32}
|
/*
* AdventOfCode2023
* Copyright (C) 2023 SizableShrimp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.sizableshrimp.adventofcode2023.days
import com.microsoft.z3.Context
import com.microsoft.z3.Status
import me.sizableshrimp.adventofcode2023.helper.Itertools
import me.sizableshrimp.adventofcode2023.templates.SeparatedDay
class Day24 : SeparatedDay() {
private lateinit var stones: List<Pair<List<Long>, List<Int>>>
override fun part1() = Itertools.combinations(this.stones, 2).count { (a, b) ->
// We have 2 equations for the individual axes: y = velY * t + y_1 and x = velX * t + x_1
// Solving for the classic point-slope form of a line equation, we have:
// y = velY * t + y_1 => t = (y - y_1) / velY and x = velX * t + x_1 => t = (x - x_1) / velX
// Then, setting the 2 equal to each other, we have:
// (y - y_1) / velY = (x - x_1) / velX => y - y_1 = (velY / velX) * (x - x_1)
// m = rise / run = velY / velX
// So, we have y - y_1 = m * (x - x_1) in the form we expect.
// Find the slopes of the 2 lines
val m1 = a.second[1].toDouble() / a.second[0]
val m2 = b.second[1].toDouble() / b.second[0]
val (x1, y1) = a.first
val (x2, y2) = b.first
// y - y_1 = m * (x - x_1) => y = m * (x - x_1) + y_1 => y = m*x - m*x_1 + y_1
// We want to solve for when the 2 line equations equal each other.
// In this case, x is actually like our time variable.
// Solving for x, we have x = (-m_2*x_2 + y_2 + m_1*x_1 - y_1) / (m_1 - m_2).
// Note that for Part 1, the (x,y) intersection point can have decimal values.
val intersectionX = (-m2 * x2 + y2 + m1 * x1 - y1) / (m1 - m2)
if (!ALLOWED_RANGE.contains(intersectionX)) return@count false
// x = velX * t + x_1 => t = (x - x_1) / velX, for either stone
// We have to ensure that the time is greater or equal to 0 for both stones.
val time1 = (intersectionX - x1) / a.second[0]
val time2 = (intersectionX - x2) / b.second[0]
if (time1 < 0 || time2 < 0) return@count false
// y = velY * t + y_1, for either stone
val intersectionY = a.second[1] * time1 + y1
ALLOWED_RANGE.contains(intersectionY)
}
override fun part2() =
Context().use { context ->
val x = context.mkIntConst("x")
val y = context.mkIntConst("y")
val z = context.mkIntConst("z")
val velX = context.mkIntConst("velX")
val velY = context.mkIntConst("velY")
val velZ = context.mkIntConst("velZ")
// Solve the equation for an (x,y,z) + t*(velX,velY,velZ) that satisfies the equation for all stones
// We can uniquely find the (x,y,z) and (velX,velY,velZ) with only 3 stones.
// Why? No idea, but people better at math than me said so.
val solver = context.mkSolver()
for ((i, stone) in this.stones.take(3).withIndex()) {
val (stoneX, stoneY, stoneZ) = stone.first
val (stoneVelX, stoneVelY, stoneVelZ) = stone.second
val hitTime = context.mkIntConst("hitTime_$i")
solver.add(context.mkGe(hitTime, context.mkInt(0)))
solver.add(
context.mkEq(
context.mkAdd(context.mkInt(stoneX), context.mkMul(context.mkInt(stoneVelX), hitTime)),
context.mkAdd(x, context.mkMul(velX, hitTime))
)
)
solver.add(
context.mkEq(
context.mkAdd(context.mkInt(stoneY), context.mkMul(context.mkInt(stoneVelY), hitTime)),
context.mkAdd(y, context.mkMul(velY, hitTime))
)
)
solver.add(
context.mkEq(
context.mkAdd(context.mkInt(stoneZ), context.mkMul(context.mkInt(stoneVelZ), hitTime)),
context.mkAdd(z, context.mkMul(velZ, hitTime))
)
)
}
// Find the first time when the equation is satisfied
val result = solver.check()
if (result != Status.SATISFIABLE) error("No solution found")
// Get the solution
val model = solver.model
listOf(x, y, z).sumOf { model.getConstInterp(it).toString().toLong() }
}
override fun parse() {
this.stones = this.lines.map { l -> l.replace(" ", "") }.map { l ->
l.split('@').map { it.split(',') }.let { (a, b) -> a.map { it.toLong() } to b.map { it.toInt() } }
}
}
companion object {
private val ALLOWED_RANGE = 200_000_000_000_000.0..400_000_000_000_000.0
@JvmStatic
fun main(args: Array<String>) {
Day24().run()
}
}
}
| 0 |
Java
|
0
| 0 |
7741ddd697b7d774695fc6e4ef9eac3d3d70a1a7
| 5,971 |
AdventOfCode2023
|
MIT License
|
src/main/kotlin/top.starp.util/ElmGen.kt
|
starplatinum3
| 713,770,699 | false |
{"Java": 1680703, "Vue": 114617, "Kotlin": 65451, "TypeScript": 54480, "JavaScript": 27991, "HTML": 20966, "Python": 8227}
|
package top.starp.util
import com.example.demo.common.MysqlDataType
import com.example.demo.util.codeGen.ColumnInfo
//fun gen_form_item(columnInfos: List<ColumnInfo>) {
//// 一个列表 把form_item 这些放进去,最后 join成一个字符串
// val formItems = columnInfos.forEach { columnInfo ->
// val javaFieldName = columnInfo.javaFieldName;
// val columnCommentShow = columnInfo.columnCommentShow;
//// val form_item = """
//// <el-form-item
//// prop="$javaFieldName"
//// :rules="rules.$javaFieldName"
//// label="$columnCommentShow"
//// class="check-in__item"
//// >
//// """
////// return
//// form_item
//
// """
// <el-form-item
// prop="$javaFieldName"
// :rules="rules.$javaFieldName"
// label="$columnCommentShow"
// class="check-in__item"
// >
// """
//
//// println(form_item)
//// .trimIndent()
//
// }
//
//}
//public
val haveRules = false
fun genElTableColumnRow(columnInfo: ColumnInfo): String {
val commentShow = columnInfo.columnCommentShow
val column_name = columnInfo.columN_NAME
// val java字段类型 = columnInfo.获取java字段类型()
val javaFieldName = columnInfo.javaFieldName
// Name todo
if (checkIfShouldTypeUrl(javaFieldName)) {
return """
<el-table-column
label="$commentShow"
sortable
align="center"
prop="$javaFieldName"
>
<template v-slot="{ row }">
<el-image
:src="row.$javaFieldName"
fit="cover"
style="width: 50px; height: 50px"
></el-image>
</template>
</el-table-column>
""".trimIndent()
}
val checkIfShouldTypeFormmaterYes = checkIfShouldTypeFormmater(javaFieldName)
val formatter = if (checkIfShouldTypeFormmaterYes) {
"""
:formatter="${javaFieldName}Formatter"
""".trimIndent()
} else {
""
}
if ("id" != column_name) {
return """
<el-table-column label="$commentShow"
sortable
$formatter
align="center" prop="$javaFieldName" >
</el-table-column>
""".trimIndent()
}
return ""
}
//fun genByFunc(columnInfos: List<ColumnInfo>,function: Function<out String>): String{
// val res = StringBuilder()
// for (columnInfo in columnInfos) {
//// val row = genToTableButton(columnInfo)
// val row = function(columnInfo)
// res.append(row)
// }
// return res.toString()
//}
fun genByFunc(columnInfos: List<ColumnInfo>, function: (ColumnInfo) -> String): String {
val res = StringBuilder()
for (columnInfo in columnInfos) {
val row = function(columnInfo)
res.append(row)
}
return res.toString()
}
fun genElTableToTableButton(columnInfos: List<ColumnInfo>): String{
val res = StringBuilder()
for (columnInfo in columnInfos) {
val row = genToTableButton(columnInfo)
res.append(row)
}
return res.toString()
}
fun genElTableColumnRows(columnInfos: List<ColumnInfo>): String? {
val res = StringBuilder()
for (columnInfo in columnInfos) {
val row = genElTableColumnRow(columnInfo)
//// val java字段名 = columnInfo.java字段名
// val commentShow = columnInfo.columnCommentShow
// val column_name = columnInfo.columN_NAME
//// val java字段类型 = columnInfo.获取java字段类型()
// val javaFieldName = columnInfo.javaFieldName
// // Name todo
//
// {
// """
// <el-table-column
// label="房型照片的 URL"
// sortable
// align="center"
// prop="photoUrl"
// >
// <template v-slot="{ row }">
// <el-image
// :src="row.photoUrl"
// fit="cover"
// style="width: 50px; height: 50px"
// ></el-image>
// </template>
// </el-table-column>
// """.trimIndent()
// }
// val checkIfShouldTypeFormmaterYes= checkIfShouldTypeFormmater(javaFieldName)
// val formatter= if(checkIfShouldTypeFormmaterYes){
// """
// :formatter="${javaFieldName}Formatter"
// """.trimIndent()
// }else{
// ""
// }
//
// if ("id" != column_name) {
// val row = """
// <el-table-column label="$commentShow"
// sortable
// $formatter
// align="center" prop="$javaFieldName" >
// </el-table-column>
//
// """.trimIndent()
// var row = "<el-table-column label=\"{commentShow}\" align=\"center\" prop=\"{javaFieldName}\" />"
// row = row
// .replace("{commentShow}", commentShow)
// .replace("{javaFieldName}", javaFieldName)
res.append(row)
}
return res.toString()
}
//fun ddd(){
//// bed_type
// """
// <template>
// <el-select v-model="selectedValue" @change="handleChange">
// <el-option
// v-for="(option, index) in options"
// :key="index"
// :label="option.text"
// :value="option.value"
// />
// </el-select>
//</template>
//
// <script>
//export default {
// props: {
// value: {
// type: Number,
// default: 0,
// },
// },
// data() {
// return {
// options: [
//
// {
// text: '大床间',
// value: 0,
// },
// {
// text: '单人间',
// value: 1,
// },
// {
// text: '双人间',
// value: 2,
// },
//
//
//
// ],
// selectedValue: this.value,
// };
// },
// computed: {
// selectedText() {
// const option = this.options.find(
// (opt) => opt.value === this.selectedValue
// );
// return option ? option.text : '';
// },
// },
// methods: {
// handleChange() {
// this.$emit('input', this.selectedValue);
// },
// },
//};
//</script>
//
// """.trimIndent()
//}
//Level
fun checkIfShouldTypeFormmater(javaFieldName: String): Boolean {
return checkIfShouldType(javaFieldName, listOf("level", "sex", "status", "type", "time", "date"));
}
fun checkIfShouldTypeTime(javaFieldName: String): Boolean {
return checkIfShouldType(javaFieldName, listOf("date", "time"));
}
fun checkIfShouldUploadType(javaFieldName: String): Boolean {
// val shouldUploadTypeList= listOf<String>("url","pic")
// for ( type in shouldUploadTypeList){
// val should=
// StringUtils.containsIgnoreCase(javaFieldName, type)
// if(should){
// return true
// }
// }
// return false
val shouldUploadTypeList = listOf<String>("url", "pic")
return checkIfShouldType(javaFieldName, shouldUploadTypeList)
}
fun checkIfShouldTypeUrl(javaFieldName: String): Boolean {
val shouldUploadTypeList = listOf("url")
return checkIfShouldType(javaFieldName, shouldUploadTypeList)
}
fun checkIfShouldType(javaFieldName: String, shouldUploadTypeList: List<String>): Boolean {
// val shouldUploadTypeList= listOf<String>("url","pic")
for (type in shouldUploadTypeList) {
val should =
StringUtils.containsIgnoreCase(javaFieldName, type)
if (should) {
return true
}
}
return false
}
fun checkIfShouldTextAreaType(javaFieldName: String): Boolean {
// val shouldUploadTypeList= listOf<String>("url","pic")
// return checkIfShouldType(javaFieldName,shouldUploadTypeList)
return checkIfShouldType(javaFieldName, listOf("intro", "extra"))
// for ( type in shouldUploadTypeList){
// val should=
// StringUtils.containsIgnoreCase(javaFieldName, type)
// if(should){
// return true
// }
// }
// return false
}
fun checkIfShouldTypePassword(javaFieldName: String): Boolean {
return checkIfShouldType(javaFieldName, listOf("password", "<PASSWORD>"))
}
fun checkIfShouldTypeSelect(javaFieldName: String): Boolean {
return checkIfShouldType(javaFieldName, listOf("status"))
}
fun gen_form_item_vue3_wrap_col_search(columnInfo: ColumnInfo): String {
val form_item_vue3 = gen_form_item_vue3_search(columnInfo)
if (columnInfo.isNumberType
|| columnInfo.isDateType) {
return form_item_vue3
}
return """
<el-col
:xs="{ span: 24 }"
:sm="{ span: 12 }"
:md="{ span: 12 }"
:lg="{ span: 8 }"
:xl="{ span: 8 }"
>
$form_item_vue3
</el-col>
""".trimIndent()
}
fun gen_form_item_vue3_wrap_col(columnInfo: ColumnInfo): String {
val form_item_vue3 = gen_form_item_vue3(columnInfo)
return """
<el-col
:xs="{ span: 24 }"
:sm="{ span: 12 }"
:md="{ span: 12 }"
:lg="{ span: 8 }"
:xl="{ span: 8 }"
>
$form_item_vue3
</el-col>
""".trimIndent()
}
fun gen_form_item_vue3_search(columnInfo: ColumnInfo): String {
val javaFieldName = columnInfo.javaFieldName
// columnInfo.datA_TYPE
// javaFieldName.contais("url")
val columnCommentShow = columnInfo.columnCommentShow
// 图片 是不用搜索的 吧 但是 上传是要的
val containsUrlIgnoreCase = checkIfShouldUploadType(javaFieldName)
// val containsUrlIgnoreCase = StringUtils.containsIgnoreCase(javaFieldName, "url");
// upload
if (containsUrlIgnoreCase) {
return """
<el-form-item>
$columnCommentShow
<el-upload
ref="uploadElem"
class="l-flex"
action="http://localhost:9092/uploadIntroImg"
:http-request="uploadImg"
list-type="picture-card"
:file-list="upload.list"
:auto-upload="false"
:limit="1"
:on-preview="imgPreview"
:on-change="verifyFileType"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog v-model="dialogVisible">
<div style="text-align: center">
<img :src="form.$javaFieldName" style="width: 100%" />
</div>
</el-dialog>
<p class="hotel-intro__tip">只能上传一张图片</p>
</el-form-item>
""".trimIndent()
}
if (
checkIfShouldTypeSelect(javaFieldName)
) {
return """
<el-form-item label="$columnCommentShow">
<el-select v-model="form.${javaFieldName}" style="width: 35%">
<el-option
v-for="item in ${javaFieldName}Options"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
<span class="add-admin__detail">{{ detail }}</span>
</el-form-item>
<el-select v-model="selectedValue" filterable
:remote-method="handleSearch" :loading="loading" :remote="true">
<el-option v-for="option in options" :key="option.value"
:label="option.label" :value="option.value" />
</el-select>
""".trimIndent()
}
if (
checkIfShouldTypeTime(javaFieldName)
) {
return """
<el-form-item
label="$columnCommentShow"
class="search-filter__item"
v-if="date"
>
<el-date-picker
v-model="form.$javaFieldName"
type="daterange"
start-placeholder="开始日期"
end-placeholder="结束日期"
:disabledDate="disabledDate"
size="small"
>
</el-date-picker>
</el-form-item>
""".trimIndent()
}
if (
checkIfShouldTextAreaType(javaFieldName)
) {
return """
<el-form-item prop="$javaFieldName" label="$columnCommentShow">
<el-input
type="textarea"
v-model="form.$javaFieldName"
placeholder="输入其他内容"
maxlength="254"
rows="5"
show-word-limit
>
<template #prefix>
<i class="el-icon-lock form__icon"></i>
</template>
</el-input>
</el-form-item>
""".trimIndent()
}
if (
checkIfShouldTypePassword(javaFieldName)
) {
// label="密码"
return """
<el-form-item prop="$javaFieldName" >
$columnCommentShow
<el-input
v-model="form.$javaFieldName"
style="width: 200px"
placeholder="请输入密码(长度4-20的数字或字母或下划线)"
show-password
>
<template #prefix>
<i class="el-icon-lock form__icon"></i>
</template>
</el-input>
</el-form-item>
""".trimIndent()
}
// columnInfo.isDateType
// if (columnInfo.isNumberType) {
// return """
// <el-form-item prop="$javaFieldName" label="密码">
// <el-input
// v-model="form.$javaFieldName"
// placeholder="请输入密码(长度4-20的数字或字母或下划线)"
// show-password
// >
// <template #prefix>
// <i class="el-icon-lock form__icon"></i>
// </template>
// </el-input>
// </el-form-item>
// """.trimIndent()
// }
// if(
// checkIfShouldTypePassword(javaFieldName)
// )
if (columnInfo.isNumberType) {
// label="${columnCommentShow} 数字范围"
return """
<el-form-item >
${columnCommentShow}范围
<el-input-number
v-model="form.${javaFieldName}Min"
:min="0"
:max="form.${javaFieldName}Max"
:step="1"
controls-position="right"
placeholder="${columnCommentShow}最小值"
size="small"
></el-input-number>
~
<el-input-number
size="small"
v-model="form.${javaFieldName}Max"
:min="form.${javaFieldName}Min"
:step="1"
controls-position="right"
placeholder="${columnCommentShow}最大值"
></el-input-number>
</el-form-item>
""".trimIndent()
}
// v-model
val v_model = if (columnInfo.isNumberType) {
"""
v-model.number
"""
} else {
"v-model"
}
val el_input_conf_type = if (columnInfo.isNumberType) {
"""
v-number-range="{ min: 0, max: 20 }"
type="number"
"""
} else {
"""
"""
}
val rules = if (haveRules) {
"""
:rules="rules.$javaFieldName"
"""
} else {
""
}
// v-number-range="{ min: 0, max: 20 }"
return """
<el-form-item
prop="$javaFieldName"
$rules
class="check-in__item"
>
$columnCommentShow
<el-input
placeholder="请输入$columnCommentShow"
:maxlength="10"
size="small"
clearable
style="width: 200px"
$v_model="form.$javaFieldName"
$el_input_conf_type
></el-input>
</el-form-item>
""".trimIndent()
}
fun gen_form_item_vue3(columnInfo: ColumnInfo): String {
val javaFieldName = columnInfo.javaFieldName
// columnInfo.datA_TYPE
// javaFieldName.contais("url")
val columnCommentShow = columnInfo.columnCommentShow
// 图片 是不用搜索的 吧 但是 上传是要的
val containsUrlIgnoreCase = checkIfShouldUploadType(javaFieldName)
// val containsUrlIgnoreCase = StringUtils.containsIgnoreCase(javaFieldName, "url");
// upload
if (containsUrlIgnoreCase) {
return """
<el-form-item>
$columnCommentShow
<el-upload
ref="uploadElem"
class="l-flex"
action="http://localhost:9092/uploadIntroImg"
:http-request="uploadImg"
list-type="picture-card"
:file-list="upload.list"
:auto-upload="false"
:limit="1"
:on-preview="imgPreview"
:on-change="verifyFileType"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog v-model="dialogVisible">
<div style="text-align: center">
<img :src="form.$javaFieldName" style="width: 100%" />
</div>
</el-dialog>
<p class="hotel-intro__tip">只能上传一张图片</p>
</el-form-item>
""".trimIndent()
}
if (
checkIfShouldTypeSelect(javaFieldName)
) {
return """
<el-form-item label="$columnCommentShow">
<el-select v-model="form.${javaFieldName}" style="width: 35%">
<el-option
v-for="item in ${javaFieldName}Options"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
<span class="add-admin__detail">{{ detail }}</span>
</el-form-item>
<el-select v-model="selectedValue" filterable
:remote-method="handleSearch" :loading="loading" :remote="true">
<el-option v-for="option in options" :key="option.value"
:label="option.label" :value="option.value" />
</el-select>
""".trimIndent()
}
if (
checkIfShouldTypeTime(javaFieldName)
) {
return """
<el-form-item
label="$columnCommentShow"
class="search-filter__item"
v-if="date"
>
<el-date-picker
v-model="form.$javaFieldName"
type="daterange"
start-placeholder="开始日期"
end-placeholder="结束日期"
:disabledDate="disabledDate"
size="small"
>
</el-date-picker>
</el-form-item>
""".trimIndent()
}
if (
checkIfShouldTextAreaType(javaFieldName)
) {
return """
<el-form-item prop="$javaFieldName" label="$columnCommentShow">
<el-input
type="textarea"
v-model="form.$javaFieldName"
placeholder="输入其他内容"
maxlength="254"
rows="5"
show-word-limit
>
<template #prefix>
<i class="el-icon-lock form__icon"></i>
</template>
</el-input>
</el-form-item>
""".trimIndent()
}
if (
checkIfShouldTypePassword(javaFieldName)
) {
// label="密码"
return """
<el-form-item prop="$javaFieldName" >
$columnCommentShow
<el-input
v-model="form.$javaFieldName"
style="width: 200px"
placeholder="请输入密码(长度4-20的数字或字母或下划线)"
show-password
>
<template #prefix>
<i class="el-icon-lock form__icon"></i>
</template>
</el-input>
</el-form-item>
""".trimIndent()
}
// columnInfo.isDateType
// if (columnInfo.isNumberType) {
// return """
// <el-form-item prop="$javaFieldName" label="密码">
// <el-input
// v-model="form.$javaFieldName"
// placeholder="请输入密码(长度4-20的数字或字母或下划线)"
// show-password
// >
// <template #prefix>
// <i class="el-icon-lock form__icon"></i>
// </template>
// </el-input>
// </el-form-item>
// """.trimIndent()
// }
// if(
// checkIfShouldTypePassword(javaFieldName)
// )
// v-model
val v_model = if (columnInfo.isNumberType) {
"""
v-model.number
"""
} else {
"v-model"
}
val el_input_conf_type = if (columnInfo.isNumberType) {
"""
v-number-range="{ min: 0, max: 20 }"
type="number"
"""
} else {
"""
"""
}
val rules = if (haveRules) {
"""
:rules="rules.$javaFieldName"
"""
} else {
""
}
// v-number-range="{ min: 0, max: 20 }"
return """
<el-form-item
prop="$javaFieldName"
$rules
class="check-in__item"
>
$columnCommentShow
<el-input
placeholder="请输入$columnCommentShow"
:maxlength="10"
size="small"
clearable
style="width: 200px"
$v_model="form.$javaFieldName"
$el_input_conf_type
></el-input>
</el-form-item>
""".trimIndent()
}
fun gen_form_item_rows(columnInfos: List<ColumnInfo>): String {
val formItems = columnInfos.map { columnInfo ->
// gen_form_item_vue3(columnInfo)
gen_form_item_vue3_wrap_col(columnInfo)
}
println("formItems")
println(formItems)
return formItems.joinToString("\n")
}
fun rangeSelectCodeGen(columnInfo:ColumnInfo,formItems: MutableList<String>
,twoColSet:MutableSet<String>) {
val row = gen_form_item_vue3_wrap_col_search(columnInfo)
// twoColSet.
// if(row.)
if (
twoColSet.size == 2
) {
var twoColCode = ""
for (s in twoColSet) {
twoColCode += s + "\n"
}
val code= """
<el-row
type="flex"
justify="center"
style="flex-wrap: wrap; flex-direction: row"
>
$twoColCode
</el-row>
""".trimIndent()
formItems.add(code)
twoColSet.clear()
} else {
twoColSet.add(row)
}
}
fun mapToWholeName(inputString:String): String? {
// val map:HashMap<String,String> = mutableMapOf()
// val map:HashMap<String,String> =
// val map= mutableMapOf<String,String>()
// map.put("u","User")
// map.put("o","Order")
//
// if ("u".equals(toWhere, ignoreCase = true)) {
// toWhere="User"
// }else if("o".equals(toWhere, ignoreCase = true)){
//
// }
val map = mapOf(
"u" to "User",
"o" to "Order",
"r" to "Room",
)
// val inputString = "KEY1"
val matchingValue = map.values.find { it.equals(inputString, ignoreCase = true) }
return matchingValue
// println(matchingValue)
}
//fun genToTableFunc(columnInfo :ColumnInfo): String {
// if ("id".equals(columnInfo.javaFieldName, ignoreCase = true)) {
// return ""
// }
//// val forignTableList= mutableListOf<String>()
//
// if (StringUtils.containsIgnoreCase(columnInfo.javaFieldName,"id")) {
//
// val replaceIgnoreCase = StringUtils.replaceIgnoreCase(
// columnInfo.javaFieldName, "id", "")
//// room
//// roomId
// val entity=replaceIgnoreCase
// val toWhereShortWord= StringUtils.upperCaseFirst(replaceIgnoreCase)
//// if ("u".equals(toWhere, ignoreCase = true)) {
//// toWhere="User"
//// }else if("o".equals(toWhere, ignoreCase = true)){
////
//// }
// val toWhere= mapToWholeName(toWhereShortWord)
//// if(toWhere.equals())
//// columnInfo.columnCommentShow
// val javaFieldName= columnInfo.javaFieldName
// return """
// const user = reactive({});
// """.trimIndent()
// }
// return ""
//
//}
fun genToTableFunc(columnInfo :ColumnInfo): String {
if ("id".equals(columnInfo.javaFieldName, ignoreCase = true)) {
return ""
}
if (StringUtils.containsIgnoreCase(columnInfo.javaFieldName,"id")) {
val replaceIgnoreCase = StringUtils.replaceIgnoreCase(
columnInfo.javaFieldName, "id", "")
// room
// roomId
val entity=replaceIgnoreCase
val toWhereShortWord= StringUtils.upperCaseFirst(replaceIgnoreCase)
// if ("u".equals(toWhere, ignoreCase = true)) {
// toWhere="User"
// }else if("o".equals(toWhere, ignoreCase = true)){
//
// }
val toWhere= mapToWholeName(toWhereShortWord)
// if(toWhere.equals())
// columnInfo.columnCommentShow
val javaFieldName= columnInfo.javaFieldName
return """
const to${toWhere} = (item) => {
let ${columnInfo.javaFieldName} = item.${columnInfo.javaFieldName};
router.push({
name: 'Modify${toWhere}',
query: { oid: item.oid, number ,$javaFieldName },
params: { state: 1 },
});
};
""".trimIndent()
}
return ""
}
fun genForeignTableEntity(columnInfo :ColumnInfo): String {
val javaFieldName= columnInfo.javaFieldName
return """
const $javaFieldName = reactive({});
""".trimIndent()
}
fun genForeignTableUiSelectOne(columnInfo :ColumnInfo): String {
val javaFieldName= columnInfo.javaFieldName
// uid
return """
const $javaFieldName = reactive({});
UiUtil.selectOne(k.$javaFieldName, form,$javaFieldName)
""".trimIndent()
}
fun genToTableFuncExport(columnInfo :ColumnInfo): String {
if ("id".equals(columnInfo.javaFieldName, ignoreCase = true)) {
return ""
}
if (StringUtils.containsIgnoreCase(columnInfo.javaFieldName,"id")) {
val replaceIgnoreCase = StringUtils.replaceIgnoreCase(
columnInfo.javaFieldName, "id", "")
// room
// roomId
val entity=replaceIgnoreCase
// val toWhere= StringUtils.upperCaseFirst(replaceIgnoreCase)
val toWhereShortWord= StringUtils.upperCaseFirst(replaceIgnoreCase)
val toWhere= mapToWholeName(toWhereShortWord)
// columnInfo.columnCommentShow
val javaFieldName= columnInfo.javaFieldName
return """
to${toWhere} ,
""".trimIndent()
}
return ""
}
fun genToTableButton(columnInfo :ColumnInfo): String {
// StringUtils.
// columnInfo.javaFieldName.
// StringUtils.equ
// "id".equalsIgnoreCase
if ("id".equals(columnInfo.javaFieldName, ignoreCase = true)) {
return ""
}
if (StringUtils.containsIgnoreCase(columnInfo.javaFieldName,"id")) {
// equalsIgnoreCase
val replaceIgnoreCase = StringUtils.replaceIgnoreCase(
columnInfo.javaFieldName, "id", "")
// roomId
val toWhere= StringUtils.upperCaseFirst(replaceIgnoreCase)
// columnInfo.columnCommentShow
return """
<el-button
size="mini"
@click="to${toWhere}(scope.row)"
>
查看${columnInfo.columnCommentShow}
</el-button>
""".trimIndent()
}
return ""
}
fun gen_form_item_rows_search(columnInfos: List<ColumnInfo>): String {
// val formItems = columnInfos.map { columnInfo ->
//// gen_form_item_vue3(columnInfo)
// gen_form_item_vue3_wrap_col_search(columnInfo)
//
// }
// val formItems= listOf();
val formItems = mutableListOf<String>()
var code: String = "";
for (columnInfo in columnInfos) {
val isNumberOrDate = columnInfo.isNumberType || columnInfo.isDateType
if (!isNumberOrDate) {
val row = gen_form_item_vue3_wrap_col_search(columnInfo)
// columnInfo.javaFieldName.contains
// code += row + "\n"
// formItems
formItems.add(row)
}
}
val twoColSet = mutableSetOf<String>()
// val twoColSet= setOf<String>()
// twoColSet.se
val dateOrNumberList = columnInfos.filter { columnInfo ->
columnInfo.isDateType || columnInfo.isNumberType }.toList();
var idx=0
for (columnInfo in dateOrNumberList) {
// val isNumberOrDate= columnInfo.isNumberType|| columnInfo.isDateType
// if (columnInfo.isNumberType) {
// rangeSelectCodeGen(columnInfo, formItems, twoColSet)
// idx++
// }
rangeSelectCodeGen(columnInfo, formItems, twoColSet)
idx++
}
if(idx%2==1){
// 多余一个
val last = dateOrNumberList.last()
val row = gen_form_item_vue3_wrap_col_search(last)
formItems.add(row)
}
// for (columnInfo in columnInfos) {
//// val isNumberOrDate= columnInfo.isNumberType|| columnInfo.isDateType
// if (columnInfo.isNumberType) {
// rangeSelectCodeGen(columnInfo,formItems,twoColSet)
// idx++
//// val row = gen_form_item_vue3_wrap_col_search(columnInfo)
////// twoColSet.
////// if(row.)
//// if (
//// twoColSet.size == 2
//// ) {
//// var twoColCode = ""
//// for (s in twoColSet) {
//// twoColCode + s + "\n"
//// }
//// """
//// <el-row
//// type="flex"
//// justify="center"
//// style="flex-wrap: wrap; flex-direction: row"
//// >
//// $twoColCode
//// </el-row>
//// """.trimIndent()
////
//// twoColSet.clear()
//// } else {
//// twoColSet.add(row)
//// }
//
//
//// formItems.add(row)
// }
// }
//
// for (columnInfo in columnInfos) {
//// 两个一组的
//// val isNumberOrDate= columnInfo.isNumberType|| columnInfo.isDateType
// if (columnInfo.isDateType) {
// rangeSelectCodeGen(columnInfo,formItems,twoColSet)
//// val row = gen_form_item_vue3_wrap_col_search(columnInfo)
//// formItems.add(row)
// }
// }
println("formItems")
println(formItems)
return formItems.joinToString("\n")
}
fun gen_form_item_rows_add(columnInfos: List<ColumnInfo>): String {
val formItems = columnInfos.map { columnInfo ->
// 这里不能 return 不然直接return 这第一个了 是函数return了
gen_form_item_vue3(columnInfo)
// val javaFieldName = columnInfo.javaFieldName
// val columnCommentShow = columnInfo.columnCommentShow
// """
// <el-form-item prop="$javaFieldName" label="$columnCommentShow">
// <el-input
// v-model="form.$javaFieldName"
// placeholder="$columnCommentShow"
// class="add-room__input"
// >
// </el-input>
// </el-form-item>
// """.trimIndent()
}
println("formItems")
println(formItems)
return formItems.joinToString("\n")
}
//@Throws(Exception::class)
//fun genElementTableMybatisPlus(tableInfo: TableInfo): String? {
// var code = FileUtil.readResourceFileData("genCodeTemplate/elementUi/ElementTableMybatisPlus.vue")
// // String iViewFormInputs = genIViewFormInputs();
//// tableInfo.类名
// tableInfo.className
// val jsonDefaultNull: String = genJsonDefaultNull()
// // String iViewColumnsRows = genIViewColumnsRows();
// val elmCols: String = genElmCols()
// val elmFormItems: String = genElmFormItems()
// val elmQueryInputs: String = genElmQueryInputs()
// val elmQueryInputsSelectedRow: String = genElmQueryInputs("selectedRow")
// code = code // .replace("#formInputs#", iViewFormInputs)
// .replace("#类名#", 类名)
// .replace("#实体名#", 实体名) // .replace("#实体名#", 实体名)
// .replace("#elmFormItems#", elmFormItems)
// .replace("#elmCols#", elmCols)
// .replace("#jsonDefaultNull#", jsonDefaultNull)
// .replace("#elmQueryInputs#", elmQueryInputs)
// .replace("#elmFormItemsSelectedRow#", elmQueryInputsSelectedRow) // .replace("#jsonDefaultNull#", jsonDefaultNull)
// // .replace("#iViewColumnsRows#", iViewColumnsRows)
// val dictDataPath = Paths.get(pathFileString,
// "elementUi", "tableMybatisPlus", 类名 + "Table.vue")
// FileUtil.writeCode(dictDataPath, code)
// return code
//}
fun d() {
"""
{commentShow} <el-input
placeholder="请输入{commentShow}"
:maxlength="10"
size="small"
clearable
style="width: 200px"
v-model="query.{javaFieldName}"
></el-input>
""".trimIndent()
}
| 1 | null |
1
| 1 |
c9310066817292809bd0abfe6ac8c8c0136802d0
| 35,199 |
code-gen-starp
|
MIT License
|
domain/src/test/java/com/roxana/recipeapp/domain/home/GetRecipesSummaryUseCaseTest.kt
|
roxanapirlea
| 383,507,335 | false | null |
package com.roxana.recipeapp.domain.home
import com.roxana.recipeapp.domain.RecipeRepository
import com.roxana.recipeapp.domain.base.CommonDispatchers
import com.roxana.recipeapp.domain.model.CategoryType
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class GetRecipesSummaryUseCaseTest {
private val recipeRepository: RecipeRepository = mockk(relaxed = true)
private val testDispatcher = UnconfinedTestDispatcher()
private val dispatchers = CommonDispatchers(
main = testDispatcher,
io = testDispatcher,
default = testDispatcher
)
private lateinit var useCase: GetRecipesSummaryUseCase
@Before
fun setUp() {
useCase = GetRecipesSummaryUseCase(recipeRepository, dispatchers)
}
@Test
fun callRepositoryWithQuery_when_launched_given_queryNoExtraSpace() = runTest(testDispatcher) {
// Given
val query = "Query"
val input = GetRecipesSummaryUseCase.Input(
query = query,
totalTime = 1,
cookingTime = 2,
preparationTime = 3,
category = CategoryType.BREAKFAST
)
// When
useCase(input)
// Then
coVerify { recipeRepository.getRecipesSummary(query, 1, 2, 3, CategoryType.BREAKFAST) }
}
@Test
fun callRepositoryWithTrimmedQuery_when_launched_given_queryWithExtraSpace() = runTest(testDispatcher) {
// Given
val query = " Query "
val input = GetRecipesSummaryUseCase.Input(
query = query,
totalTime = 1,
cookingTime = 2,
preparationTime = 3,
category = CategoryType.BREAKFAST
)
// When
useCase(input)
// Then
val expectedQuery = "Query"
coVerify { recipeRepository.getRecipesSummary(expectedQuery, 1, 2, 3, CategoryType.BREAKFAST) }
}
}
| 0 |
Kotlin
|
0
| 1 |
8dc3e7040d806893dddd4538e15dd3a40faa80a4
| 2,115 |
RecipeApp
|
Apache License 2.0
|
SpokestackTray/src/main/java/io/spokestack/tray/ScrollingGradient.kt
|
hannesa2
| 358,793,021 | true |
{"Kotlin": 66836}
|
package io.spokestack.tray
import android.animation.TimeAnimator
import android.content.Context
import android.graphics.*
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
/**
* A scrolling gradient animation usable as a background.
* Adapted from https://stackoverflow.com/a/48696216/421784
*/
open class ScrollingGradient(val context: Context, private val pixelsPerSecond: Float) : Drawable(),
Animatable {
private val paint = Paint()
private var x: Float = 0.toFloat()
private val animator = TimeAnimator()
private val startColor = ContextCompat.getColor(context, R.color.spsk_colorGradientOne)
private val endColor = ContextCompat.getColor(context, R.color.spsk_colorGradientTwo)
init {
animator.setTimeListener(Updater())
}
override fun onBoundsChange(bounds: Rect) {
paint.shader = LinearGradient(
0f,
0f,
bounds.width().toFloat(),
0f,
startColor,
endColor,
Shader.TileMode.MIRROR
)
}
override fun draw(canvas: Canvas) {
canvas.clipRect(bounds)
canvas.translate(x, 0f)
canvas.drawPaint(paint)
}
override fun setAlpha(alpha: Int) {}
override fun setColorFilter(colorFilter: ColorFilter?) {}
override fun getOpacity(): Int = PixelFormat.OPAQUE
override fun start() {
animator.start()
}
override fun stop() {
animator.cancel()
}
override fun isRunning(): Boolean = animator.isRunning
inner class Updater : TimeAnimator.TimeListener {
override fun onTimeUpdate(animation: TimeAnimator, totalTime: Long, deltaTime: Long) {
x = pixelsPerSecond * totalTime / 1000
invalidateSelf()
}
}
}
| 0 |
Kotlin
|
0
| 2 |
5c0ff65262a7a88ce3f6adf69de8aefef799eb66
| 1,856 |
spokestack-tray-android
|
Apache License 2.0
|
core/src/main/java/com/manuelblanco/core/remote/MarvelApi.kt
|
mblancomu
| 344,092,407 | false | null |
package com.manuelblanco.core.remote
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
/**
* Calls for Marvel API using retrofit. Using Deferred for coroutines.
*/
interface MarvelApi {
@GET("/v1/public/characters")
fun getListCharacters(@Query("offset") offset: Int): Deferred<MarvelResponse>
@GET("/v1/public/characters/{characterId}")
fun getDetailCharacter(@Path("characterId") characterId: Int): Deferred<MarvelResponse>
}
| 0 | null |
0
| 0 |
48508d8cf472299e9857df21a76021a64f554508
| 514 |
opendemo
|
Apache License 2.0
|
vector/src/main/java/im/vector/app/features/location/LocationSharingService.kt
|
ANDR3LU1Z-dot
| 475,496,090 | true |
{"Kotlin": 11876819, "Java": 158817, "Shell": 31280, "HTML": 26741, "Python": 19964, "FreeMarker": 7767, "JavaScript": 1782, "Ruby": 1574, "Gherkin": 109}
|
/*
* Copyright (c) 2022 New Vector Ltd
*
* 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 im.vector.app.features.location
import android.content.Intent
import android.os.IBinder
import android.os.Parcelable
import dagger.hilt.android.AndroidEntryPoint
import im.vector.app.core.services.VectorService
import im.vector.app.features.notifications.NotificationUtils
import kotlinx.parcelize.Parcelize
import timber.log.Timber
import java.util.Timer
import java.util.TimerTask
import javax.inject.Inject
@AndroidEntryPoint
class LocationSharingService : VectorService(), LocationTracker.Callback {
@Parcelize
data class RoomArgs(
val sessionId: String,
val roomId: String,
val durationMillis: Long
) : Parcelable
@Inject lateinit var notificationUtils: NotificationUtils
@Inject lateinit var locationTracker: LocationTracker
private var roomArgsList = mutableListOf<RoomArgs>()
private var timers = mutableListOf<Timer>()
override fun onCreate() {
super.onCreate()
Timber.i("### LocationSharingService.onCreate")
// Start tracking location
locationTracker.addCallback(this)
locationTracker.start()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val roomArgs = intent?.getParcelableExtra(EXTRA_ROOM_ARGS) as? RoomArgs
Timber.i("### LocationSharingService.onStartCommand. sessionId - roomId ${roomArgs?.sessionId} - ${roomArgs?.roomId}")
if (roomArgs != null) {
roomArgsList.add(roomArgs)
// Show a sticky notification
val notification = notificationUtils.buildLiveLocationSharingNotification()
startForeground(roomArgs.roomId.hashCode(), notification)
// Schedule a timer to stop sharing
scheduleTimer(roomArgs.roomId, roomArgs.durationMillis)
}
return START_STICKY
}
private fun scheduleTimer(roomId: String, durationMillis: Long) {
Timer()
.apply {
schedule(object : TimerTask() {
override fun run() {
stopSharingLocation(roomId)
timers.remove(this@apply)
}
}, durationMillis)
}
.also {
timers.add(it)
}
}
private fun stopSharingLocation(roomId: String) {
Timber.i("### LocationSharingService.stopSharingLocation for $roomId")
synchronized(roomArgsList) {
roomArgsList.removeAll { it.roomId == roomId }
if (roomArgsList.isEmpty()) {
Timber.i("### LocationSharingService. Destroying self, time is up for all rooms")
destroyMe()
}
}
}
override fun onLocationUpdate(locationData: LocationData) {
Timber.i("### LocationSharingService.onLocationUpdate. Uncertainty: ${locationData.uncertainty}")
}
override fun onLocationProviderIsNotAvailable() {
stopForeground(true)
stopSelf()
}
private fun destroyMe() {
locationTracker.removeCallback(this)
timers.forEach { it.cancel() }
timers.clear()
stopSelf()
}
override fun onDestroy() {
super.onDestroy()
Timber.i("### LocationSharingService.onDestroy")
destroyMe()
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
companion object {
const val EXTRA_ROOM_ARGS = "EXTRA_ROOM_ARGS"
}
}
| 0 | null |
0
| 0 |
9c333c96c447693297e66c973d79ea9ca0ff95c3
| 4,131 |
element-android
|
Apache License 2.0
|
components/bridge/dao/impl/src/main/java/com/flipperdevices/bridge/dao/impl/api/key/UtilsKeyApiImpl.kt
|
flipperdevices
| 288,258,832 | false | null |
package com.flipperdevices.bridge.dao.impl.api.key
import com.flipperdevices.bridge.dao.api.delegates.key.SimpleKeyApi
import com.flipperdevices.bridge.dao.api.delegates.key.UtilsKeyApi
import com.flipperdevices.bridge.dao.api.model.FlipperFilePath
import com.flipperdevices.bridge.dao.api.model.FlipperKey
import com.flipperdevices.bridge.dao.api.model.FlipperKeyPath
import com.flipperdevices.bridge.dao.impl.ktx.toFlipperKey
import com.flipperdevices.bridge.dao.impl.model.SynchronizedStatus
import com.flipperdevices.bridge.dao.impl.repository.AdditionalFileDao
import com.flipperdevices.bridge.dao.impl.repository.key.UtilsKeyDao
import com.flipperdevices.core.di.AppGraph
import com.flipperdevices.core.di.provideDelegate
import com.flipperdevices.core.log.LogTagProvider
import com.flipperdevices.core.log.info
import com.squareup.anvil.annotations.ContributesBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Provider
@ContributesBinding(AppGraph::class, UtilsKeyApi::class)
class UtilsKeyApiImpl @Inject constructor(
utilsKeysDaoProvider: Provider<UtilsKeyDao>,
simpleKeyApiProvider: Provider<SimpleKeyApi>,
flipperAdditionalDaoProvider: Provider<AdditionalFileDao>
) : UtilsKeyApi, LogTagProvider {
override val TAG = "UtilsKeyApi"
private val utilsKeyDao by utilsKeysDaoProvider
private val simpleKeyApi by simpleKeyApiProvider
private val flipperAdditionalDao by flipperAdditionalDaoProvider
override suspend fun markAsSynchronized(
keyPath: FlipperKeyPath
) = withContext(Dispatchers.IO) {
utilsKeyDao.markSynchronized(
keyPath.path.pathToKey,
keyPath.deleted,
SynchronizedStatus.SYNCHRONIZED
)
}
override suspend fun updateNote(
keyPath: FlipperKeyPath,
note: String
) = withContext(Dispatchers.IO) {
utilsKeyDao.updateNote(keyPath.path.pathToKey, keyPath.deleted, note)
}
override fun search(text: String): Flow<List<FlipperKey>> {
val searchQuery = "%$text%"
return utilsKeyDao.search(searchQuery).map { list ->
list.map { it.toFlipperKey(flipperAdditionalDao) }
}
}
override suspend fun findAvailablePath(keyPath: FlipperKeyPath): FlipperKeyPath {
var newNameWithoutExtension = keyPath.path.nameWithoutExtension
var newPath = getKeyPathWithDifferentNameWithoutExtension(
keyPath,
newNameWithoutExtension
)
var index = 1
info {
"Start finding free name for path $newPath " +
"(newNameWithoutExtension=$newNameWithoutExtension)"
}
// Find empty key name
while (simpleKeyApi.getKey(newPath) != null) {
newNameWithoutExtension = "${keyPath.path.nameWithoutExtension}_${index++}"
newPath = getKeyPathWithDifferentNameWithoutExtension(
keyPath,
newNameWithoutExtension
)
info {
"Try $newPath ($newNameWithoutExtension)"
}
}
info { "Found free key name! $newPath" }
return newPath
}
}
private fun getKeyPathWithDifferentNameWithoutExtension(
keyPath: FlipperKeyPath,
nameWithoutExtension: String
): FlipperKeyPath {
return FlipperKeyPath(
FlipperFilePath(
keyPath.path.folder,
"$nameWithoutExtension.${keyPath.path.nameWithExtension.substringAfterLast('.')}"
),
keyPath.deleted
)
}
| 21 | null |
174
| 999 |
ef27b6b6a78a59b603ac858de2c88f75b743f432
| 3,652 |
Flipper-Android-App
|
MIT License
|
app/src/main/java/com/cheise_proj/e_commerce/data/db/entity/DeliveryEntity.kt
|
alvinmarshall
| 261,505,259 | false |
{"Kotlin": 313862}
|
package com.cheise_proj.e_commerce.data.db.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "delivery")
data class DeliveryEntity(
@PrimaryKey(autoGenerate = false)
val id: Int,
val name: String,
val duration: String,
val imageUrl: String,
val cost:Int
)
| 0 |
Kotlin
|
0
| 8 |
71208fcff45678d89b03bcb16216c8181a8418ed
| 318 |
E-commerce-UI
|
MIT License
|
hse-remind/src/main/kotlin/ru/darkkeks/telegram/hseremind/ruz/RuzApi.kt
|
darkkeks
| 293,167,561 | false | null |
package ru.darkkeks.telegram.hseremind.ruz
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface RuzApi {
@GET("search")
fun search(
@Query("term") term: String,
@Query("type") type: String? = null
): Call<List<SearchResult>>
@GET("schedule/{type}/{id}")
fun schedule(
@Path("type") type: String,
@Path("id") id: Long,
@Query("start") start: String? = null,
@Query("finish") finish: String? = null
): Call<List<ScheduleItem>>
}
class SearchResult(
val id: Long,
val label: String,
val description: String,
val type: String
)
class ScheduleItem(
// "Online (ауд бронь 13)",
val auditorium: String,
// 100,
val auditoriumAmount: Int?,
// 4861,
val auditoriumOid: Int?,
// "STAFF\\makrylova",
val author: String?,
// "09:30",
val beginLesson: String,
// "Покровский б-р, д.11",
val building: String?,
// 936106,
val contentOfLoadOid: Int?,
// "4159521155",
val contentOfLoadUID: String?,
// "2020-08-30T23:38:40Z00:00",
val createddate: String?,
// "2020.09.01",
val date: String,
// "\/Date(1598907600000+0300)\/",
val dateOfNest: String?,
// 2,
val dayOfWeek: Int?,
// "Вт",
val dayOfWeekString: String?,
// "",
val detailInfo: String?,
// "Алгоритмы и структуры данных 2 (углубленный курс) (рус)",
val discipline: String,
// 58722,
val disciplineOid: Int?,
// "3855949243",
val disciplineinplan: String?,
// 7,
val disciplinetypeload: Int?,
// 2,
val duration: Int?,
// "10:50",
val endLesson: String,
// "АиСД2(угл)_Б2019_ПМИИ_3_2#С#Алгоритмы и структуры данных 2 (углубленный курс)",
val group: String?,
// "3860348949"
val groupUID: String?,
// 28914,
val groupOid: Int?,
// 5588,
val group_facultyoid: Int?,
// 0,
val hideincapacity: Int?,
// false,
val isBan: Boolean?,
// "Практическое занятие",
val kindOfWork: String?,
// 964,
val kindOfWorkOid: Int?,
// "1861272403",
val kindOfWorkUid: String?,
// "ст.преп. Смирнов Иван Федорович",
val lecturer: String?,
// null,
val lecturerCustomUID: Int?,
// "[email protected]",
val lecturerEmail: String?,
// 47938,
val lecturerOid: Int?,
// "1963742336",
val lecturerUID: String?,
// 1,
val lessonNumberEnd: Int?,
// 1,
val lessonNumberStart: Int?,
// 7526334,
val lessonOid: Int,
// "2020-08-31T20:46:31Z00:00",
val modifieddate: String?,
// null,
val note: String?,
// "2к ПМИ 1,2 мод 2020\/2021",
val parentschedule: String?,
// null,
val replaces: String?,
// null,
val stream: String?,
// 0,
val streamOid: Int?,
// 0,
val stream_facultyoid: Int?,
// null,
val subGroup: String?,
// 0,
val subGroupOid: Int?,
// 0,
val subgroup_facultyoid: Int?,
// "https:\/\/zoom.us\/j\/97496250882",
val url1: String?,
// null,
val url1_description: String?,
// null,
val url2: String?,
// null
val url2_description: String?
)
| 1 | null |
1
| 2 |
0bce6623ca28d539644fb6084ac0432573eba807
| 3,280 |
telegram-bots
|
MIT License
|
UIViewLess/src/main/java/com/angcyo/uiview/less/AppGlideModule.kt
|
zhilangtaosha
| 223,696,624 | true |
{"Gradle": 15, "Markdown": 1, "Text": 1, "Ignore List": 4, "Proguard": 3, "XML": 468, "Java": 514, "Kotlin": 184, "JSON": 4, "Java Properties": 2}
|
package com.angcyo.uiview.less
import com.bumptech.glide.module.LibraryGlideModule
/**
*
* Email:[email protected]
*
* [https://github.com/bumptech/glide]
*
* @author angcyo
* @date 2019/09/26
* Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved.
*/
class AppGlideModule : LibraryGlideModule() {
}
| 0 | null |
2
| 0 |
8a09b91edaa4a21a43b356f67d3e063e72df3a19
| 322 |
UIKit
|
MIT License
|
src/main/java/com/mrkirby153/tgabot/ama/AmaManager.kt
|
mrkirby153
| 147,458,836 | false | null |
package com.mrkirby153.tgabot.ama
import com.mrkirby153.bfs.model.Model
import com.mrkirby153.tgabot.Bot
import com.mrkirby153.tgabot.db.models.AmaQuestion
import com.mrkirby153.tgabot.findEmoteById
import me.mrkirby153.kcutils.timing.Throttler
import net.dv8tion.jda.core.entities.User
import net.dv8tion.jda.core.events.message.guild.react.GuildMessageReactionAddEvent
import net.dv8tion.jda.core.hooks.ListenerAdapter
import java.util.concurrent.TimeUnit
object AmaManager {
const val GREEN_CHECK_ID = "414875062001205249"
const val RED_X_ID = "414875062336880640"
private val chanId = Bot.properties.getProperty("ama-channel")
private val amaThrottler = Throttler<User>(null)
private val greenTickEmote by lazy {
findEmoteById(GREEN_CHECK_ID) ?: throw IllegalStateException(
"Could not find green check emote")
}
private val redXEmote by lazy {
findEmoteById(RED_X_ID) ?: throw IllegalArgumentException("Could not find red X emote")
}
val amaChannel by lazy {
Bot.tgaGuild.getTextChannelById(this.chanId) ?: throw IllegalStateException(
"Could not get the AMA channel")
}
fun submitQuestion(submitter: User, question: String): AmaSubmitResponse {
try {
if (amaThrottler.throttled(submitter))
return AmaSubmitResponse(AmaSubmitResponse.Responses.THROTTLED, null)
amaThrottler.trigger(submitter, 5, TimeUnit.MINUTES)
val amaQuestion = AmaQuestion()
amaQuestion.submitter = submitter
amaQuestion.question = question
amaQuestion.save()
amaChannel.sendMessage(buildString {
appendln("----------------------------")
appendln("**ID:** ${amaQuestion.id}")
appendln(
"**Submitted By:** ${submitter.name}#${submitter.discriminator} (`${submitter.id}`)")
appendln()
appendln(question)
}).queue { m ->
amaQuestion.messageId = m.id
amaQuestion.save()
m.addReaction(greenTickEmote).queue()
m.addReaction(redXEmote).queue()
}
return AmaSubmitResponse(AmaSubmitResponse.Responses.SUCCESS, amaQuestion)
} catch (e: Exception) {
e.printStackTrace()
return AmaSubmitResponse(AmaSubmitResponse.Responses.UNKNOWN_ERROR, null)
}
}
fun approveQuestion(amaQuestion: AmaQuestion) {
Bot.logger.debug("Approving question ${amaQuestion.id}")
amaQuestion.approved = true
amaQuestion.save()
// TODO 11/8/18 Put it somewhere??
if (Bot.properties.getProperty("trello-enabled") == "true")
TrelloUtils.addQuestionToBoard(amaQuestion)
}
fun denyQuestion(amaQuestion: AmaQuestion) {
Bot.logger.debug("Denying question ${amaQuestion.id}")
amaQuestion.denied = true
amaQuestion.save()
amaChannel.deleteMessageById(amaQuestion.messageId).queueAfter(250, TimeUnit.MILLISECONDS)
}
class AmaSubmitResponse(val response: Responses, val question: AmaQuestion?) {
enum class Responses {
THROTTLED,
UNKNOWN_ERROR,
SUCCESS
}
}
class Listener : ListenerAdapter() {
override fun onGuildMessageReactionAdd(event: GuildMessageReactionAddEvent) {
if (event.member == event.guild.selfMember)
return
if (event.channel.id != chanId)
return
val amaQuestion = Model.query(AmaQuestion::class.java).where("message_id",
event.messageId).first() ?: return
if (amaQuestion.approved || amaQuestion.denied)
return
when (event.reactionEmote.emote) {
redXEmote -> denyQuestion(amaQuestion)
greenTickEmote -> approveQuestion(amaQuestion)
else -> event.reaction.removeReaction(event.user).queue()
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
12ea81ce527749ab7637db36a42adfd5829782c4
| 4,088 |
TGABot
|
MIT License
|
idea/testData/refactoring/safeDeleteMultiModule/byImplClassMemberVal/after/JS/src/test/test.kt
|
JakeWharton
| 99,388,807 | false | null |
package test
actual class Foo {
}
fun test(f: Foo) = f.foo
| 0 | null |
28
| 83 |
4383335168338df9bbbe2a63cb213a68d0858104
| 60 |
kotlin
|
Apache License 2.0
|
tabby-fp/src/commonMain/kotlin/com/sksamuel/tabby/results/catching.kt
|
sksamuel
| 280,509,527 | false | null |
package com.sksamuel.tabby.results
object Catch {
fun <A> Result<A>.get() = this.getOrThrow()
}
inline fun <R> catching(f: Catch.() -> R): Result<R> = runCatching { Catch.f() }
| 0 |
Kotlin
|
1
| 6 |
e49c41da4e0267f47a28b330524130621e7b891c
| 182 |
tabby
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ui/mainUI/explore/ExploreModule.kt
|
erenalpaslan
| 697,706,268 | false |
{"Kotlin": 144492, "Swift": 1139, "Shell": 228}
|
package ui.mainUI.explore
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module
/**
* Created by erenalpaslan on 5.10.2023.
*/
val exploreModule = module {
factoryOf(::ExploreViewModel)
}
| 0 |
Kotlin
|
0
| 1 |
7d5a345396901361ca2c24bbe7901fae1459a7a1
| 210 |
Fusion
|
Apache License 2.0
|
catan/src/main/kotlin/design/cardia/game/catan/repository/IWriteRepository.kt
|
Spanner41
| 419,025,235 | false |
{"Kotlin": 35031}
|
package design.cardia.game.catan.repository
import design.cardia.game.engine.event.Event
interface IWriteRepository {
fun addEvent(event: Event<*>)
}
| 0 |
Kotlin
|
0
| 0 |
1304ad30845c9426235c8fff9d0445961817967b
| 156 |
kt-board-game-engine
|
MIT License
|
app/src/main/java/com/ofalvai/bpinfo/ui/alertlist/dialog/NoticeFragment.kt
|
csc1995
| 131,722,358 | true |
{"Kotlin": 196557, "Java": 55212, "HTML": 3779}
|
/*
* Copyright 2016 Olivér Falvai
*
* 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.ofalvai.bpinfo.ui.alertlist.dialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.text.Html
import com.ofalvai.bpinfo.BpInfoApplication
import com.ofalvai.bpinfo.R
class NoticeFragment : DialogFragment() {
companion object {
const val KEY_NOTICE_TEXT = "notice_text"
@JvmStatic
fun newInstance(noticeText: String): NoticeFragment {
return NoticeFragment().apply {
this.noticeText = noticeText
}
}
}
private lateinit var noticeText: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
if (savedInstanceState.getString(KEY_NOTICE_TEXT) != null) {
noticeText = savedInstanceState.getString(KEY_NOTICE_TEXT, "")
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(activity)
.setTitle(R.string.dialog_notice_title)
.setMessage(Html.fromHtml(noticeText))
.setPositiveButton(R.string.dialog_notice_positive_button) { _, _ -> dismiss() }
.create()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(KEY_NOTICE_TEXT, noticeText)
super.onSaveInstanceState(outState)
}
override fun onDestroyView() {
super.onDestroyView()
BpInfoApplication.getRefWatcher(context).watch(this)
}
}
| 0 |
Kotlin
|
0
| 0 |
8a1d541d13c848b10a025bee10e81cb028156454
| 2,254 |
BPInfo
|
Apache License 2.0
|
dexfile/src/main/kotlin/com/github/netomi/bat/dexfile/value/EncodedNullValue.kt
|
netomi
| 265,488,804 | false |
{"Kotlin": 1925501, "Smali": 713862, "ANTLR": 25494, "Shell": 12074, "Java": 2326}
|
/*
* Copyright (c) 2020-2022 Thomas Neidhart.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinygears.bat.dexfile.value
import org.tinygears.bat.dexfile.DexFile
import org.tinygears.bat.dexfile.io.DexDataInput
import org.tinygears.bat.dexfile.io.DexDataOutput
import org.tinygears.bat.dexfile.value.visitor.EncodedValueVisitor
import org.tinygears.bat.dexfile.visitor.ReferencedIDVisitor
/**
* An class representing a null value inside a dex file.
*/
object EncodedNullValue : EncodedValue() {
override val valueType: EncodedValueType
get() = EncodedValueType.NULL
override fun readValue(input: DexDataInput, valueArg: Int) {}
override fun writeType(output: DexDataOutput): Int {
return writeType(output, 0)
}
override fun writeValue(output: DexDataOutput, valueArg: Int) {}
override fun accept(dexFile: DexFile, visitor: EncodedValueVisitor) {
visitor.visitNullValue(dexFile, this)
}
override fun referencedIDsAccept(dexFile: DexFile, visitor: ReferencedIDVisitor) {}
override fun hashCode(): Int {
return System.identityHashCode(this)
}
override fun equals(other: Any?): Boolean {
return this === other
}
override fun toString(): String {
return "EncodedNullValue[]"
}
}
| 1 |
Kotlin
|
3
| 10 |
5f5ec931c47dd34f14bd97230a29413ef1cf219c
| 1,828 |
bat
|
Apache License 2.0
|
myblog-kt/src/main/kotlin/com/site/blog/util/RequestHelper.kt
|
yzqdev
| 394,679,800 | false |
{"Kotlin": 453510, "Java": 239310, "Vue": 114812, "HTML": 47519, "TypeScript": 29771, "Go": 22465, "Less": 8160, "JavaScript": 7120, "CSS": 4588, "SCSS": 979}
|
package com.site.blog.util
import cn.hutool.core.lang.Console
import cn.hutool.http.useragent.UserAgent
import cn.hutool.http.useragent.UserAgentUtil
import com.site.blog.constants.BaseConstants
import com.site.blog.model.vo.UserVo
import org.apache.commons.lang3.RegExUtils
import org.apache.commons.lang3.StringUtils
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.web.context.request.RequestAttributes
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import java.time.LocalDateTime
import java.util.*
import jakarta.servlet.http.HttpServletRequest
/**
* 请求帮助
*
* @author yanni
* @date 2022/06/15
*/
object RequestHelper {
const val REQUEST_HEADER_USER_AGENT = "user-agent"
const val REQUEST_HEADER_REFERER = "referer"
const val protocol = "Sec-WebSocket-Protocol"
fun getWebSocketProtocol(httpServletRequest: HttpServletRequest): String {
return httpServletRequest.getHeader(protocol)
}
@JvmStatic
fun getRequest(): HttpServletRequest {
val req = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
return req.request
}
/**
* 获取session中的用户,添加全局对象
*
* @return
*/
@JvmStatic
fun getSessionUser(): UserVo? {
val requestAttributes =
RequestContextHolder.getRequestAttributes()
return requestAttributes!!.getAttribute(
BaseConstants.USER_ATTR,
RequestAttributes.SCOPE_REQUEST
) as UserVo?
}
/**
* 判断请求是否为Ajax请求.
*
* @param request
* @return
*/
fun isAjaxRequest(request: HttpServletRequest): Boolean {
return "XMLHttpRequest" == request.getHeader("X-Requested-With")
}
// 多次反向代理后会有多个IP值,第一个为 真实 ip
@JvmStatic
fun getRequestIp(): String {
val request = getRequest()
var ip = request.getHeader("X-Real-IP")
if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
return ip.trim { it <= ' ' }
}
ip = request.getHeader("X-Forwarded-For")
if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
// 多次反向代理后会有多个IP值,第一个为 真实 ip
return StringUtils.split(ip, ",")[0].trim { it <= ' ' }
}
ip = request.getHeader("Proxy-Client-IP")
if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
return ip.trim { it <= ' ' }
}
ip = request.getHeader("WL-Proxy-Client-IP")
if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
return ip.trim { it <= ' ' }
}
ip = request.getHeader("HTTP_CLIENT_IP")
if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
return ip.trim { it <= ' ' }
}
ip = request.getHeader("X-Cluster-Client-IP")
return if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
ip.trim { it <= ' ' }
} else request.remoteAddr
}
fun isApplicationJsonHeader(request: HttpServletRequest): Boolean {
val contentType = request.getHeader(HttpHeaders.CONTENT_TYPE)
return contentType != null && RegExUtils.replaceAll(
contentType.trim { it <= ' ' },
StringUtils.SPACE,
StringUtils.EMPTY
).contains(MediaType.APPLICATION_JSON_VALUE)
}
@JvmStatic
fun getRequestHeader(headerName: String): String {
Console.print(headerName)
val header = getRequest().getHeader(headerName)
return header ?: headerName
}
@JvmStatic
fun getUserAgentHeader(): String {
return getRequestHeader(REQUEST_HEADER_USER_AGENT)
}
@JvmStatic
fun getBrowserFull(): String {
return getUa().browser.toString() + getUa().version
}
@JvmStatic
fun getUa(): UserAgent {
return UserAgentUtil.parse(getUserAgentHeader())
}
@Throws(IOException::class)
fun getRequestMessage(request: HttpServletRequest): String {
val parameters = StringBuilder()
return getRequestMessage(request, parameters)
}
@Throws(IOException::class)
private fun getRequestMessage(request: HttpServletRequest, parameters: StringBuilder): String {
parameters.append("\n请求URL : ")
.append(request.requestURI)
.append("\n请求URI : ")
.append(request.requestURL)
.append("\n请求方式 : ")
.append(request.method)
.append(if (isAjaxRequest(request)) "\tajax请求" else "\t同步请求")
.append("\n请求者IP : ")
.append(request.remoteAddr)
.append("\nSESSION_ID : ")
.append(request.session.id)
.append("\n请求时间 : ")
.append(LocalDateTime.now())
// 请求头
val headerNames = request.headerNames
while (headerNames.hasMoreElements()) {
val element = headerNames.nextElement()
if (null != element) {
val header = request.getHeader(element)
parameters.append("\n请求头内容 : ").append(element).append("=").append(header)
}
}
parameters.append("\n请求参数 : ").append(getRequestBody(request))
// 请求Session内容
val sessionAttributeNames = request.session.attributeNames
while (sessionAttributeNames.hasMoreElements()) {
parameters.append("\nSession内容 : ").append(sessionAttributeNames.nextElement())
}
return parameters.toString()
}
@JvmStatic
fun getHttpServletRequest(): HttpServletRequest {
return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?)!!.request
}
/**
* 得到请求的根目录
*
* @return
*/
fun getBasePath(): String {
val request = getHttpServletRequest()
return request.scheme + "://" + request.serverName +
":" + request.serverPort + getContextPath()
}
/**
* 得到结构目录
*
* @return
*/
fun getContextPath(): String {
val request = getHttpServletRequest()
return request.contextPath
}
@Throws(IOException::class)
fun getRequestBody(request: HttpServletRequest): String {
val inputStream = request.inputStream
val reader =
BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
var s: String?
val sb = StringBuilder()
while (reader.readLine().also { s = it } != null) {
sb.append(s)
}
reader.close()
return sb.toString()
}
fun getRequestBody(): String {
val request = getHttpServletRequest()
val inputStream = request.inputStream
val reader =
BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
var s: String?
val sb = StringBuilder()
while (reader.readLine().also { s = it } != null) {
sb.append(s)
}
reader.close()
return sb.toString()
}
}
| 0 |
Kotlin
|
2
| 4 |
7f367dbe7883722bf1d650504265254d5224f69b
| 7,333 |
mild-blog
|
MIT License
|
src/jsMain/kotlin/firebase/app/firebase.index.firebase.app.kt
|
epabst
| 60,592,428 | false | null |
@file:[JsModule("firebase/app") JsNonModule]
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused")
package firebase.app
import firebase.analytics.Analytics
import firebase.auth.Auth
import firebase.database.Database
import firebase.firestore.Firestore
import firebase.functions.Functions
import firebase.installations.Installations
import firebase.messaging.Messaging
import firebase.performance.Performance
import firebase.remoteConfig.RemoteConfig
import firebase.storage.Storage
import kotlin.js.*
external interface App {
fun auth(): Auth
fun database(url: String? = definedExternally /* null */): Database
fun delete(): Promise<Any>
fun installations(): Installations
fun messaging(): Messaging
var name: String
var options: Any
fun storage(url: String? = definedExternally /* null */): Storage
fun firestore(): Firestore
fun functions(region: String? = definedExternally /* null */): Functions
fun performance(): Performance
fun remoteConfig(): RemoteConfig
fun analytics(): Analytics
}
| 14 |
Kotlin
|
2
| 3 |
5d5129e556c8b168b0a0b838eec694664af37902
| 1,157 |
kotlin-showcase
|
Apache License 2.0
|
entity/src/main/java/com/blank/entity/User.kt
|
yands11
| 220,658,559 | false | null |
package com.blank.entity
import com.google.gson.annotations.SerializedName
data class User(
@SerializedName("avatar_url")
val avatarUrl: String?,
val bio: String?,
val blog: String?,
val company: String?,
val email: String,
val followers: Int = 0,
val following: Int = 0,
val id: Int = 0,
val location: String?,
val login: String?,
val name: String?
)
| 0 |
Kotlin
|
0
| 0 |
30486b999efeaf5cdb3a64ad44bb9d727c021f68
| 401 |
OnGithub
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/common/SegmentedControlSegment.kt
|
JetBrains
| 93,250,841 | false |
{"Kotlin": 12159121, "JavaScript": 330528}
|
// Generated by Karakum - do not modify it manually!
package electron.common
typealias SegmentedControlSegment = electron.core.SegmentedControlSegment
| 40 |
Kotlin
|
165
| 1,319 |
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
| 155 |
kotlin-wrappers
|
Apache License 2.0
|
src/main/java/com/adityaamolbavadekar/hiphe/LauncherActivity.kt
|
AdityaBavadekar
| 421,028,992 | false | null |
/*******************************************************************************
* Copyright (c) 2021. <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 com.adityaamolbavadekar.hiphe
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.preference.PreferenceManager
import com.adityaamolbavadekar.hiphe.interaction.*
import com.adityaamolbavadekar.hiphe.models.ChangeLogInfo
import com.adityaamolbavadekar.hiphe.models.GitRawApi
import com.adityaamolbavadekar.hiphe.network.ConnectionLiveData
import com.adityaamolbavadekar.hiphe.utils.ConfigureTheme
import com.adityaamolbavadekar.hiphe.utils.constants
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class LauncherActivity : AppCompatActivity() {
private val loggedOutUserTimeOut: Long = 1500
private val normalTimeOut: Long = 700
private lateinit var connectionLiveData: ConnectionLiveData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
connectionLiveData = ConnectionLiveData(this)
if (intent.getStringExtra(getString(R.string.logs)) != null) {
HipheDebugLog(TAG, intent.getStringExtra(getString(R.string.logs)).toString())
}
connectionLiveData.observe(this, Observer {
if (!it) this.showToast(getString(R.string.you_are_offline))
})
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val loggedIn = prefs.getBoolean(constants.checkIsLoggedInPrefKey, false)
ConfigureTheme().configureThemeOnCreate(this, TAG)
setContentView(R.layout.activity_launcher)
if (loggedIn) {
loggedInUserNormalBehaviour()
HipheInfoLog(TAG, getString(R.string.user_is_logged_in_initiating_normal_call))
} else {
loggedOutUserClassicBehaviour()
HipheInfoLog(TAG, getString(R.string.User_is_not_logged_in_initiating_classic_call))
}
}
private fun loggedInUserNormalBehaviour() {
//checkUpdates()
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}, normalTimeOut)
}
private fun checkUpdates() {
try {
val pckMangr = this.packageManager.getPackageInfo(
this.packageName,
0
)
val buildVersionName = pckMangr.versionName
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val gitRawApi: GitRawApi = retrofit.create(GitRawApi::class.java)
val call = gitRawApi.getNewUpdatesCall()
val callback = object : Callback<List<ChangeLogInfo>> {
override fun onResponse(
call: Call<List<ChangeLogInfo>>,
responseResult: Response<List<ChangeLogInfo>>
) {
if (responseResult.isSuccessful) {
val response = responseResult.body()?.get(0)
val changeLogInfo: ChangeLogInfo? = response
HipheInfoLog(
TAG,
"@GET request was Successful"
)
HipheInfoLog(
TAG,
"@GET returned $changeLogInfo"
)
HipheInfoLog(
TAG,
"@GET request Release Notes were ${changeLogInfo?.releaseNotes}"
)
HipheInfoLog(
TAG,
"@GET request LatestVersion was ${changeLogInfo?.versionName}"
)
HipheInfoLog(
TAG,
"@GET request LatestVersionCode was ${changeLogInfo?.versionCode}"
)
HipheInfoLog(
TAG,
"@GET request apkURL was ${changeLogInfo?.apkURL}"
)
HipheInfoLog(
TAG,
"@GET request's headers ${responseResult.headers()}"
)
HipheInfoLog(
TAG,
"@GET request's raw ${responseResult.raw()}"
)
if (changeLogInfo != null) {
val versionNameResult = changeLogInfo.versionName
val versionCodeResult = changeLogInfo.versionCode
val releaseNotesResult = changeLogInfo.releaseNotes
if (buildVersionName != versionNameResult) {
[email protected]("You are on latest stable version of Hiphe i.e.$buildVersionName")
val b = MaterialAlertDialogBuilder(this@LauncherActivity)
b.setIcon(R.drawable.ic_baseline_system_update_24)
b.setTitle("Version $buildVersionName")
b.setMessage(
getString(
R.string.updated_version_of_hiphe_is_available_formatted,
versionNameResult,
buildVersionName,
versionNameResult,
releaseNotesResult
)
)
b.setPositiveButton(getString(R.string.ok_update_hiphe)) { dialogInterface, _ ->
[email protected]("Updating in background, you can continue exploring app")
dialogInterface.dismiss()
try {
UpdateHipheWithUrl().updateHipheWithChangeInfo(
this@LauncherActivity,
changeLogInfo
)
} catch (e: Exception) {
}
}
b.setNegativeButton(getString(R.string.cancel)) { dialogInterface, _ ->
dialogInterface.dismiss()
}
b.setCancelable(false)
b.create()
b.show()
} else if (buildVersionName == versionNameResult) {
// [email protected]("You are on latest stable version of Hiphe i.e.$buildVersionName")
//
// val b = MaterialAlertDialogBuilder(this@LauncherActivity)
// b.setIcon(R.drawable.ic_baseline_system_update_24)
// b.setTitle("Version $buildVersionName")
// b.setMessage(
// getString(
// R.string.your_are_on_latest_version_of_hiphe_formatted,
// buildVersionName,
// releaseNotesResult
// )
// )
// b.setPositiveButton(getString(R.string.ok_got_it)) { dialogInterface, _ ->
// dialogInterface.dismiss()
// }
// b.setCancelable(false)
// b.create()
// b.show()
}
}
} else {
HipheErrorLog(
HipheSettingsActivity.TAG,
"onResponse: Unsuccessful: ",
responseResult.code().toString()
)
[email protected]("Something went wrong...")
return
}
}
override fun onFailure(call: Call<List<ChangeLogInfo>>, t: Throwable) {
HipheErrorLog(
TAG,
"onFailure: LOCALIZED MESSAGE: ",
" ${t.localizedMessage}"
)
[email protected]("Please check that your Internet Connection is on")
HipheErrorLog(
TAG,
"onFailure: STACKTRACE: ",
t.stackTraceToString()
)
HipheErrorLog(
TAG,
"onFailure: DATA: ",
t.cause.toString()
)
}
}
call.enqueue(callback)
} catch (e: Exception) {
HipheErrorLog(TAG, "Error making call to $BASE_URL/changelog.json: ", e.toString())
}
}
private fun loggedOutUserClassicBehaviour() {
//checkUpdates()
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, IntroActivity::class.java)
startActivity(intent)
finish()
}, loggedOutUserTimeOut)
}
companion object {
const val TAG = "LauncherActivity"
const val BASE_URL =
"https://raw.githubusercontent.com/AdityaBavadekar/Hiphe/main/changelog/"
}
}
| 0 |
Kotlin
|
0
| 1 |
eb8608b7aa63ed3fca9ffd3b2e999824c1e072de
| 11,017 |
Hiphe
|
Apache License 2.0
|
app/src/main/java/com/example/jpmorgantest/data/sources/search/entities/WeatherDetailResponse.kt
|
Sushanth12361
| 861,347,513 | false |
{"Kotlin": 126062, "Java": 3448}
|
package com.example.jpmorgantest.data.sources.search.entities
data class WeatherDetailResponse(
val base: String,
val clouds: CloudsResponse,
val cod: Int,
val coord: CoordResponse,
val dt: Int,
val id: Int,
val main: MainResponse,
val name: String,
val sys: SysResponse,
val timezone: Int,
val visibility: Int,
val weather: List<WeatherResponse>,
val wind: WindResponse
)
| 0 |
Kotlin
|
0
| 0 |
6c0607adaba5018572237a7d51adcf0cd71a6540
| 426 |
JPMC
|
Apache License 2.0
|
app/src/main/java/com/example/ekologapp/fragment/LoginFragment.kt
|
hibatillah
| 729,487,030 | false |
{"Kotlin": 18142}
|
package com.example.ekologapp.fragment
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.fragment.app.FragmentTransaction
import com.example.ekologapp.MainActivity
import com.example.ekologapp.R
import com.example.ekologapp.databinding.FragmentLoginBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseAuthInvalidUserException
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.ktx.Firebase
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private lateinit var auth: FirebaseAuth
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentLoginBinding.inflate(layoutInflater)
auth = Firebase.auth
// get form element
val emailInput = binding.inputEmail
val passwordInput = binding.inputPassword
binding.submitLogin.setOnClickListener {
val email = emailInput.text.toString().trim()
val password = passwordInput.text.toString().trim()
// validate input
if (email.isEmpty()) {
Toast.makeText(requireContext(), "Email harus diisi!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (password.isEmpty()) {
Toast.makeText(requireContext(), "Password harus diisi!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// login process
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
val userId = user?.uid
val database = FirebaseDatabase.getInstance()
val reference = database.getReference("User")
userId?.let {
reference.child(it).get().addOnSuccessListener { snapshot ->
val intent = Intent(requireContext(), MainActivity::class.java)
startActivity(intent)
requireActivity().finish() // close current activity
}.addOnFailureListener { e ->
// login failed
Toast.makeText(requireContext(),
"Login gagal: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
} else {
// login failed
val exception = task.exception
if (exception is FirebaseAuthInvalidUserException
|| exception is FirebaseAuthInvalidCredentialsException) {
// wrong email or password
Toast.makeText(requireContext(),
"Email atau password salah", Toast.LENGTH_SHORT).show()
} else {
// other failure
Toast.makeText(requireContext(),
"Login gagal: ${exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
binding.btnBack.setOnClickListener{
val transaction: FragmentTransaction = requireFragmentManager().beginTransaction()
transaction.replace(R.id.container_onboard, OnboardingFragment())
transaction.commit()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
a610bbe613583b7e3d656de66d7fa590ee338106
| 3,952 |
ekolog-app
|
MIT License
|
app/src/main/java/com/picassos/betamax/android/presentation/television/launch/TelevisionLaunchActivity.kt
|
aelrahmanashraf
| 581,933,102 | false |
{"Kotlin": 768121}
|
package com.picassos.betamax.android.presentation.television.launch
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.Window
import android.view.WindowInsets
import android.view.WindowManager
import android.widget.Button
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.picassos.betamax.android.R
import com.picassos.betamax.android.core.configuration.Config
import com.picassos.betamax.android.core.utilities.Coroutines.collectLatestOnLifecycleStarted
import com.picassos.betamax.android.core.utilities.Helper
import com.picassos.betamax.android.core.utilities.Response.CREDENTIALS_NOT_SET
import com.picassos.betamax.android.core.view.Toasto.showToast
import com.picassos.betamax.android.databinding.ActivityTelevisionLaunchBinding
import com.picassos.betamax.android.di.AppEntryPoint
import com.picassos.betamax.android.presentation.app.auth.signin.SigninActivity
import com.picassos.betamax.android.presentation.app.launch.LaunchViewModel
import com.picassos.betamax.android.presentation.television.main.TelevisionMainActivity
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.EntryPointAccessors
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@SuppressLint("CustomSplashScreen")
@AndroidEntryPoint
class TelevisionLaunchActivity : AppCompatActivity() {
private lateinit var layout: ActivityTelevisionLaunchBinding
private val launchViewModel: LaunchViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val entryPoint = EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java)
Helper.darkMode(this)
layout = DataBindingUtil.setContentView(this, R.layout.activity_television_launch)
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
launchViewModel.requestLaunch()
collectLatestOnLifecycleStarted(launchViewModel.launch) { state ->
if (state.response != null) {
Log.d("Launch", state.response.toString())
when (state.response.configuration.responseCode) {
200 -> {
lifecycleScope.launch {
entryPoint.getAccountUseCase().invoke().collectLatest { account ->
delay(Config.LAUNCH_TIMEOUT)
when (account.token) {
CREDENTIALS_NOT_SET -> {
startActivity(Intent(this@TelevisionLaunchActivity, SigninActivity::class.java))
}
else -> {
startActivity(Intent(this@TelevisionLaunchActivity, TelevisionMainActivity::class.java))
}
}
finishAffinity()
}
}
}
else -> showToast(this@TelevisionLaunchActivity, getString(R.string.unknown_issue_occurred), 0, 1)
}
}
if (state.error != null) {
showInternetConnectionDialog()
showToast(this@TelevisionLaunchActivity, state.error, 1, 2)
}
}
}
private fun showInternetConnectionDialog() {
val dialog = Dialog(this@TelevisionLaunchActivity, R.style.DialogStyle).apply {
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.dialog_internet_connection)
setCancelable(false)
setCanceledOnTouchOutside(false)
}
dialog.findViewById<Button>(R.id.try_again).setOnClickListener {
launchViewModel.requestLaunch()
dialog.dismiss()
}
dialog.window?.let { window ->
window.apply {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT)
attributes.gravity = Gravity.CENTER
attributes.dimAmount = 0.0f
}
}
dialog.show()
}
}
| 0 |
Kotlin
|
0
| 0 |
004716ab1e75f18e85a88bed966078d439dd6e0a
| 4,950 |
betamax-android
|
MIT License
|
core/src/test/java/com/hrules/cryptokeys/domain/entities/serializers/ItemListSerializerTest.kt
|
hrules6872
| 118,738,366 | false | null |
/*
* Copyright (c) 2018. <NAME> - hrules6872
*
* 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.hrules.cryptokeys.domain.entities.serializers
import com.hrules.cryptokeys.Utils
import org.junit.Assert.assertFalse
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ItemListSerializerTest {
@Test
fun `given a valid json when deserialize to Item entity then ok`() {
val validJson = Utils.readFile("json/valid_items.json")
val items = ItemListSerializer.parse(validJson)
assertFalse(items.isEmpty())
}
}
| 0 |
Kotlin
|
0
| 1 |
025ca86889cfa95094febd0ebb3c74e734a526b5
| 1,110 |
CryptoKeys
|
Apache License 2.0
|
FFRv2/app/src/main/java/com/devingotaswitch/rankings/extras/SwipeDismissTouchListener.kt
|
jbailey2010
| 91,362,935 | false |
{"Kotlin": 694986}
|
package com.devingotaswitch.rankings.extras
import android.R
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.graphics.Rect
import android.os.SystemClock
import android.view.*
import android.widget.ListView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.*
import kotlin.math.abs
class SwipeDismissTouchListener(listView: RecyclerView, doAnimate: Boolean, callbacks: DismissCallbacks,
onClickListener: RecyclerViewAdapter.OnItemClickListener,
onLongClickListener: RecyclerViewAdapter.OnItemLongClickListener) : View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private val mSlop: Int
private val mMinFlingVelocity: Int
private val mMaxFlingVelocity: Int
private val mAnimationTime: Long
// Fixed properties
private val mListView: RecyclerView
private val mCallbacks: DismissCallbacks
private var mViewWidth = 1 // 1 and not 0 to prevent dividing by zero
// Transient properties
private val mPendingDismisses: MutableList<PendingDismissData> = ArrayList()
private var mDismissAnimationRefCount = 0
private var mDownX = 0f
private var mDownY = 0f
private var mSwiping = false
private var mSwipingSlop = 0
private var mVelocityTracker: VelocityTracker? = null
private var mDownPosition = 0
private var mDownView: View? = null
private var mPaused = false
private val mDoDismiss: Boolean
private val gestureDetector: GestureDetector
private val mOnClickListener: RecyclerViewAdapter.OnItemClickListener
private val mOnLongClickListener: RecyclerViewAdapter.OnItemLongClickListener
interface DismissCallbacks {
/**
* Called to determine whether the given position can be dismissed.
*/
fun canDismiss(view: View?): Boolean
/**
* Called when the user has indicated they she would like to dismiss one or more list item
* positions.
*
* @param listView The originating [ListView].
* @param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
fun onDismiss(listView: RecyclerView?, reverseSortedPositions: IntArray?, rightDismiss: Boolean)
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given list view.
*
* @param listView The list view whose items should be dismissable.
* @param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss one or more list items.
*/
constructor(listView: RecyclerView, callbacks: DismissCallbacks,
onClickListener: RecyclerViewAdapter.OnItemClickListener,
onLongClickListener: RecyclerViewAdapter.OnItemLongClickListener) : this(listView,
true, callbacks, onClickListener, onLongClickListener)
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* @param enabled Whether or not to watch for gestures.
*/
fun setEnabled(enabled: Boolean) {
mPaused = !enabled
}
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
if (mViewWidth < 2) {
mViewWidth = mListView.width
}
if (gestureDetector.onTouchEvent(motionEvent)) {
val layoutManager = mListView.layoutManager as LinearLayoutManager?
mOnClickListener.onItemClick(view, layoutManager!!.findFirstVisibleItemPosition())
return true
}
when (motionEvent.actionMasked) {
MotionEvent.ACTION_DOWN -> {
if (mPaused) {
return false
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
val rect = Rect()
val childCount = mListView.childCount
val listViewCoords = IntArray(2)
mListView.getLocationOnScreen(listViewCoords)
val x = motionEvent.rawX.toInt() - listViewCoords[0]
val y = motionEvent.rawY.toInt() - listViewCoords[1]
var child: View
var i = 0
while (i < childCount) {
child = mListView.getChildAt(i)
child.getHitRect(rect)
if (rect.contains(x, y)) {
mDownView = child
break
}
i++
}
if (mDownView != null) {
mDownX = motionEvent.rawX
mDownY = motionEvent.rawY
mDownPosition = mListView.getChildLayoutPosition(mDownView!!)
if (mCallbacks.canDismiss(mDownView)) {
mVelocityTracker = VelocityTracker.obtain()
mVelocityTracker!!.addMovement(motionEvent)
} else {
mDownView = null
}
}
return false
}
MotionEvent.ACTION_CANCEL -> {
if (mVelocityTracker != null) {
if (mDownView != null && mSwiping) {
// cancel
cancelSwipe()
}
mVelocityTracker!!.recycle()
mVelocityTracker = null
mDownX = 0f
mDownY = 0f
mDownView = null
mDownPosition = ListView.INVALID_POSITION
mSwiping = false
}
}
MotionEvent.ACTION_UP -> {
if (mVelocityTracker != null) {
val deltaX = motionEvent.rawX - mDownX
mVelocityTracker!!.addMovement(motionEvent)
mVelocityTracker!!.computeCurrentVelocity(1000)
val velocityX = mVelocityTracker!!.xVelocity
val absVelocityX = abs(velocityX)
val absVelocityY = abs(mVelocityTracker!!.yVelocity)
var dismiss = false
var dismissRight = false
if (abs(deltaX) > mViewWidth / 2.0 && mSwiping) {
dismiss = true
dismissRight = deltaX > 0
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = velocityX < 0 == deltaX < 0
dismissRight = mVelocityTracker!!.xVelocity > 0
}
if (dismiss && mDownPosition != ListView.INVALID_POSITION) {
// dismiss
val downView = mDownView // mDownView gets null'd before animation ends
val downPosition = mDownPosition
++mDismissAnimationRefCount
if (mDoDismiss) {
mDownView!!.animate()
.translationX(if (dismissRight) mViewWidth.toFloat() else -mViewWidth.toFloat())
.alpha(0f)
.setDuration(mAnimationTime)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
performDismiss(downView, downPosition, deltaX > 0)
}
})
} else {
val positions = IntArray(1)
positions[0] = downPosition
mCallbacks.onDismiss(mListView, positions, deltaX > 0)
cancelSwipe()
}
} else {
// cancel
cancelSwipe()
}
mVelocityTracker!!.recycle()
mVelocityTracker = null
mDownX = 0f
mDownY = 0f
mDownView = null
mDownPosition = ListView.INVALID_POSITION
mSwiping = false
}
}
MotionEvent.ACTION_MOVE -> {
if (mVelocityTracker != null && !mPaused) {
mVelocityTracker!!.addMovement(motionEvent)
val deltaX = motionEvent.rawX - mDownX
val deltaY = motionEvent.rawY - mDownY
if (abs(deltaX) > mSlop && abs(deltaY) < abs(deltaX) / 2) {
mSwiping = true
mSwipingSlop = if (deltaX > 0) mSlop else -mSlop
mListView.requestDisallowInterceptTouchEvent(true)
// Cancel ListView's touch (un-highlighting the item)
val cancelEvent = MotionEvent.obtain(motionEvent)
cancelEvent.action = MotionEvent.ACTION_CANCEL or
(motionEvent.actionIndex
shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
mListView.onTouchEvent(cancelEvent)
cancelEvent.recycle()
}
if (mSwiping) {
mDownView!!.translationX = deltaX - mSwipingSlop
if (mDoDismiss) {
mDownView!!.alpha = 0f.coerceAtLeast(
1f.coerceAtMost(
1f - 2f * abs(deltaX) / mViewWidth))
}
return true
}
}
}
}
return false
}
private fun cancelSwipe() {
mDownView!!.animate()
.translationX(0f)
.alpha(1f)
.setDuration(mAnimationTime)
.setListener(null)
}
internal class PendingDismissData(val position: Int, val view: View?) : Comparable<PendingDismissData> {
override fun compareTo(other: PendingDismissData): Int {
// Sort by descending position
return other.position - position
}
}
private fun performDismiss(dismissView: View?, dismissPosition: Int, rightDismiss: Boolean) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
val lp = dismissView!!.layoutParams
val originalHeight = dismissView.height
val animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime)
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
--mDismissAnimationRefCount
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
mPendingDismisses.sort()
val dismissPositions = IntArray(mPendingDismisses.size)
for (i in mPendingDismisses.indices.reversed()) {
dismissPositions[i] = mPendingDismisses[i].position
}
mCallbacks.onDismiss(mListView, dismissPositions, rightDismiss)
// Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
// animation with a stale position
mDownPosition = ListView.INVALID_POSITION
var lp: ViewGroup.LayoutParams
for (pendingDismiss in mPendingDismisses) {
// Reset view presentation
pendingDismiss.view!!.alpha = 1f
pendingDismiss.view.translationX = 0f
lp = pendingDismiss.view.layoutParams
lp.height = originalHeight
pendingDismiss.view.layoutParams = lp
}
// Send a cancel event
val time = SystemClock.uptimeMillis()
val cancelEvent = MotionEvent.obtain(time, time,
MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
mListView.dispatchTouchEvent(cancelEvent)
mPendingDismisses.clear()
}
}
})
animator.addUpdateListener { valueAnimator: ValueAnimator ->
lp.height = (valueAnimator.animatedValue as Int)
dismissView.layoutParams = lp
}
mPendingDismisses.add(PendingDismissData(dismissPosition, dismissView))
animator.start()
}
private inner class SingleTapConfirm : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(event: MotionEvent): Boolean {
return true
}
override fun onLongPress(event: MotionEvent) {
super.onLongPress(event)
val layoutManager = mListView.layoutManager as LinearLayoutManager?
mOnLongClickListener.onItemLongClick(mDownView, layoutManager!!.findFirstVisibleItemPosition())
}
}
init {
val vc = ViewConfiguration.get(listView.context)
mSlop = vc.scaledTouchSlop
mMinFlingVelocity = vc.scaledMinimumFlingVelocity * 16
mMaxFlingVelocity = vc.scaledMaximumFlingVelocity
mAnimationTime = listView.context.resources.getInteger(
R.integer.config_shortAnimTime).toLong()
mListView = listView
mCallbacks = callbacks
mDoDismiss = doAnimate
gestureDetector = GestureDetector(listView.context, SingleTapConfirm())
mOnClickListener = onClickListener
mOnLongClickListener = onLongClickListener
}
}
| 10 |
Kotlin
|
0
| 0 |
ba3fb10b541e67129c7b3ea81d90d64a7ab9694a
| 14,575 |
FFRv2
|
Apache License 2.0
|
kotest-plugins/kotest-plugins-pitest/src/jvmTest/kotlin/io/kotest/plugin/pitest/specs/StringSpecs.kt
|
junron
| 214,570,871 | false | null |
package io.kotest.plugin.pitest.specs
import io.kotest.shouldBe
import io.kotest.specs.StringSpec
class StringSpecs : StringSpec() {
init {
"passing test" { 1 shouldBe 1 }
"failing test" { 1 shouldBe 2 }
}
}
| 1 | null |
1
| 1 |
3a00e967d50a43e6200060f7c3df44c730d02610
| 221 |
kotlintest
|
Apache License 2.0
|
app/src/main/java/com/kiptechie/composedictionary/feature_dictionary/data/remote/dto/WordInfoDto.kt
|
kiptechie
| 430,399,451 | false | null |
package com.kiptechie.composedictionary.feature_dictionary.data.remote.dto
import com.kiptechie.composedictionary.feature_dictionary.data.local.entity.WordInfoEntity
data class WordInfoDto(
val meanings: List<MeaningDto>,
val origin: String,
val phonetic: String,
val phonetics: List<PhoneticDto>,
val word: String
) {
fun toWordInfoEntity(): WordInfoEntity {
return WordInfoEntity(
meanings = meanings.map { it.toMeaning() },
origin = origin,
phonetic = phonetic,
word = word
)
}
}
| 1 |
Kotlin
|
0
| 2 |
50a3121b3bfff36bf1331a3940111ba4a25b3ff8
| 576 |
ComposeDictionary
|
MIT License
|
app/src/main/java/com/example/marsphotos/ui/Nav/cambioPantalla.kt
|
Conkers1800
| 807,877,884 | false |
{"Kotlin": 68965}
|
package com.example.marsphotos.ui.Nav
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.marsphotos.data.PantallaPrincipal
import com.example.marsphotos.data.ViewModelLocal
import com.example.marsphotos.ui.screens.CargaAcademicaList
//import com.example.marsphotos.ui.screens.CargaAcademicaList
import com.example.marsphotos.ui.screens.PantallaCalificaciones
import com.example.marsphotos.ui.screens.PantallaInicio
import com.example.marsphotos.ui.screens.PantallaSesion
@Composable
fun App(
viewModel: PantallaPrincipal = viewModel(factory = PantallaPrincipal.Factory),
viewModel2: ViewModelLocal = viewModel(factory = ViewModelLocal.Factory),
context: Context
) {
val navController = rememberNavController()
val myViewModel: PantallaPrincipal = viewModel
val myViewModel2: ViewModelLocal = viewModel2
NavHost(
navController = navController,
startDestination = PantallasNav.Login.route
) {
composable(PantallasNav.Login.route) {
PantallaInicio(myViewModel,navController,context)
}
composable(PantallasNav.Session.route) {
PantallaSesion(myViewModel2,myViewModel, modifier = Modifier,navController,context)
//PantallaSesion(alumno = ALUMNO)
}
composable(PantallasNav.Carga.route) {
CargaAcademicaList(myViewModel,navController)
}
composable(PantallasNav.Calificacion.route) {
PantallaCalificaciones(myViewModel, modifier = Modifier,navController)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
91d7582f8ad04f524dd392bb3706f9ed48a156da
| 1,813 |
Autenticacion1-VersionFinal
|
Apache License 2.0
|
src/main/kotlin/org/dictat/wikistat/services/PageDao.kt
|
K0zka
| 22,078,440 | false |
{"JavaScript": 71587, "Kotlin": 67756, "CSS": 215}
|
package org.dictat.wikistat.services
import java.util.Date
import org.dictat.wikistat.model.PageActivity
import org.dictat.wikistat.model.TimeFrame
import org.dictat.wikistat.utils.LazyIterable
public trait PageDao {
fun getPageNames(lang : String): LazyIterable<String>
fun savePageEvent(name : String, lang : String, cnt : Int, time : Date, timeFrame : TimeFrame, special : Boolean)
fun removePageEvents(name : String, lang : String,times : List<Pair<Date, TimeFrame>>)
fun getPageActivity(name: String, lang : String) : List<PageActivity>
fun findPages(prefix : String, lang : String, max : Int) : List<String>
fun getLangs() : List<String>
fun removePage(page : String, lang : String) : Unit
fun markChecked(page: String, lang : String) : Unit
fun findUnchecked(lang : String) : LazyIterable<String>
/**
* Replace the activity with its sum
*/
fun replaceSum(page: String, lang : String, from : TimeFrame, to : TimeFrame, fromTime : Date, toTime : Date, sum : Int) : Unit
fun findExtraordinaryActivity(lang: String, date : Date): Iterable<String>
}
| 0 |
JavaScript
|
0
| 0 |
b6033f27fe8ef50171a0f83ed0aa76f3fa854462
| 1,111 |
wikistat
|
Apache License 2.0
|
src/main/kotlin/org/dictat/wikistat/services/PageDao.kt
|
K0zka
| 22,078,440 | false |
{"JavaScript": 71587, "Kotlin": 67756, "CSS": 215}
|
package org.dictat.wikistat.services
import java.util.Date
import org.dictat.wikistat.model.PageActivity
import org.dictat.wikistat.model.TimeFrame
import org.dictat.wikistat.utils.LazyIterable
public trait PageDao {
fun getPageNames(lang : String): LazyIterable<String>
fun savePageEvent(name : String, lang : String, cnt : Int, time : Date, timeFrame : TimeFrame, special : Boolean)
fun removePageEvents(name : String, lang : String,times : List<Pair<Date, TimeFrame>>)
fun getPageActivity(name: String, lang : String) : List<PageActivity>
fun findPages(prefix : String, lang : String, max : Int) : List<String>
fun getLangs() : List<String>
fun removePage(page : String, lang : String) : Unit
fun markChecked(page: String, lang : String) : Unit
fun findUnchecked(lang : String) : LazyIterable<String>
/**
* Replace the activity with its sum
*/
fun replaceSum(page: String, lang : String, from : TimeFrame, to : TimeFrame, fromTime : Date, toTime : Date, sum : Int) : Unit
fun findExtraordinaryActivity(lang: String, date : Date): Iterable<String>
}
| 0 |
JavaScript
|
0
| 0 |
b6033f27fe8ef50171a0f83ed0aa76f3fa854462
| 1,111 |
wikistat
|
Apache License 2.0
|
app/src/main/java/giuliolodi/brokersim/data/DataManagerImpl.kt
|
GLodi
| 85,128,848 | false | null |
/*
* Copyright 2017 GLodi
*
* 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 giuliolodi.brokersim.data
import android.content.Context
import giuliolodi.brokersim.data.api.ApiHelper
import giuliolodi.brokersim.data.db.DbHelper
import giuliolodi.brokersim.di.scope.AppContext
import giuliolodi.brokersim.models.SellRequest
import giuliolodi.brokersim.models.StockDb
import io.reactivex.Completable
import io.reactivex.Observable
import yahoofinance.Stock
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DataManagerImpl : DataManager {
private val TAG = "DataManager"
private val mContext: Context
private val mApiHelper: ApiHelper
private val mDbHelper: DbHelper
@Inject
constructor(@AppContext context: Context, apiHelper: ApiHelper, dbHelper: DbHelper) {
mContext = context
mApiHelper = apiHelper
mDbHelper = dbHelper
}
override fun downloadStock(stockSymbol: String): Observable<Stock> {
return mApiHelper.downloadStock(stockSymbol)
}
override fun downloadStockList(stockList: Array<String>): Observable<Map<String, Stock>> {
return mApiHelper.downloadStockList(stockList)
}
override fun storeFirstStock(stock: Stock, amount: Int, price: Double, date: String) {
return mDbHelper.storeFirstStock(stock, amount, price, date)
}
override fun storeSecondStock(stockDb: StockDb, amount: Int, price: Double, date: String) {
return mDbHelper.storeSecondStock(stockDb, amount, price, date)
}
override fun updateMoney(money: Double) {
return mDbHelper.updateMoney(money)
}
override fun getMoney(): Observable<Double> {
return mDbHelper.getMoney()
}
override fun downloadActiveStockSymbols(): Observable<List<String>> {
return mApiHelper.downloadActiveStockSymbols()
}
override fun getStocks(): Observable<List<StockDb>> {
return mDbHelper.getStocks()
}
override fun updateStockDb(stock: Stock, stockDb: StockDb) {
return mDbHelper.updateStockDb(stock, stockDb)
}
override fun updateListOfStockDb(stocks: List<Stock>, stockDbList: List<StockDb>) {
return mDbHelper.updateListOfStockDb(stocks, stockDbList)
}
override fun getStockWithSymbol(symbol: String): Observable<StockDb> {
return mDbHelper.getStockWithSymbol(symbol)
}
override fun sellStock(sellRequest: SellRequest): Completable {
return mDbHelper.sellStock(sellRequest)
}
}
| 0 | null |
3
| 9 |
c7dfff4b2fc5e30d9b3f4ca95b1e66f6b1de6ee0
| 3,032 |
BrokerSim
|
Apache License 2.0
|
src/test/kotlin/com/atlassian/performance/tools/hardware/report/HardwareExplorationTable.kt
|
atlassian
| 165,660,177 | false |
{"Kotlin": 198569, "HTML": 12071}
|
package com.atlassian.performance.tools.hardware.report
import com.atlassian.performance.tools.hardware.HardwareExplorationResult
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter
import java.io.File
import java.nio.file.Path
import java.time.Duration
internal class HardwareExplorationTable {
fun summarize(
results: List<HardwareExplorationResult>,
table: Path
): File {
val headers = arrayOf(
"jira",
"jira nodes",
"database",
"overall error average [%]",
"overall error spread [%]",
"max action error max [%]",
"max action error label [%]",
"max action error spread [%]",
"apdex average (0.0-1.0)",
"apdex spread (0.0-1.0)",
"throughput average [HTTP requests / second]",
"throughput spread [HTTP requests / second]",
"worth exploring?",
"reason"
)
val format = CSVFormat.DEFAULT.withHeader(*headers).withRecordSeparator('\n')
val tableFile = table.toFile()
tableFile.bufferedWriter().use { writer ->
val printer = CSVPrinter(writer, format)
results.forEach { exploration ->
val result = exploration.testResult
val hardware = exploration.decision.hardware
val throughputPeriod = Duration.ofSeconds(1)
if (result != null) {
printer.printRecord(
hardware.jira,
hardware.nodeCount,
hardware.db,
result.overallError.ratio.percent,
result.overallErrors.map { it.ratio.percent }.spread(),
result.maxActionError?.ratio?.percent ?: "-",
result.maxActionError?.actionLabel ?: "-",
result.maxActionErrors?.map { it.ratio.percent }?.spread() ?: "-",
result.apdex,
result.apdexes.spread(),
result.httpThroughput.scaleTime(throughputPeriod).change,
result.httpThroughputs.map { it.scaleTime(throughputPeriod).change }.spread(),
if (exploration.decision.worthExploring) "YES" else "NO",
exploration.decision.reason
)
} else {
printer.printRecord(
hardware.jira,
hardware.nodeCount,
hardware.db,
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
if (exploration.decision.worthExploring) "YES" else "NO",
exploration.decision.reason
)
}
}
}
return tableFile
}
private fun List<Double>.spread(): Double {
return max()!! - min()!!
}
}
| 2 |
Kotlin
|
11
| 7 |
a1f06d1cf0bf37e1e6c5ce186747c2ca56f1c5fe
| 3,203 |
jira-hardware-exploration
|
Apache License 2.0
|
data/src/main/kotlin/fobo66/valiutchik/core/model/repository/LocationRepositoryImpl.kt
|
fobo66
| 256,453,787 | false | null |
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 fobo66.valiutchik.core.model.repository
import android.Manifest
import androidx.annotation.RequiresPermission
import fobo66.valiutchik.core.model.datasource.GeocodingDataSource
import fobo66.valiutchik.core.model.datasource.LocationDataSource
import java.io.IOException
import javax.inject.Inject
import timber.log.Timber
class LocationRepositoryImpl @Inject constructor(
private val locationDataSource: LocationDataSource,
private val geocodingDataSource: GeocodingDataSource
) : LocationRepository {
@RequiresPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
override suspend fun resolveUserCity(defaultCity: String): String {
val response = try {
Timber.v("Resolving user's location")
val location = locationDataSource.resolveLocation()
Timber.v("Resolved user's location: %s", location)
geocodingDataSource.findPlace(location)
} catch (e: IOException) {
Timber.e(e, "Failed to determine user city")
emptyList()
}
Timber.v("Resolving user's city")
return response
.asSequence()
.map { it.address }
.filterNotNull()
.map { it.locality }
.firstNotNullOfOrNull { it }.also { city ->
city?.let {
Timber.v("Resolved user's city: %s", it)
}
} ?: defaultCity
}
}
| 6 |
Kotlin
|
0
| 1 |
77eb0807170e13aac95b5501d1d893ac3e0b899f
| 1,925 |
valiutchik-android
|
Apache License 2.0
|
app/src/main/java/cc/ayakurayuki/reminder/adapter/SetRingtoneAdapter.kt
|
AyakuraYuki
| 115,322,058 | false | null |
package cc.ayakurayuki.reminder.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.media.RingtoneManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import cc.ayakurayuki.reminder.R
import java.util.*
/**
* Created by ayakurayuki on 2017/12/27.
*/
class SetRingtoneAdapter(var context: Context) : RecyclerView.Adapter<SetRingtoneAdapter.ListViewHolder>(), View.OnClickListener {
private val ringtoneList: MutableList<String> = ArrayList()
private var listener: OnRecyclerViewItemClickListener? = null
init {
val ringtoneManager = RingtoneManager(context)
ringtoneManager.setType(RingtoneManager.TYPE_RINGTONE)
val cursor = ringtoneManager.cursor
if (cursor.moveToFirst()) {
do {
ringtoneList.add(cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX))
println(cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX))
} while (cursor.moveToNext())
}
}
@SuppressLint("InflateParams")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SetRingtoneAdapter.ListViewHolder {
val v = LayoutInflater.from(context).inflate(R.layout.ringtone_list, null).apply {
setOnClickListener(this@SetRingtoneAdapter)
}
return ListViewHolder(v)
}
override fun onBindViewHolder(holder: SetRingtoneAdapter.ListViewHolder, position: Int) {
holder.ringtonePath.text = ringtoneList[position]
holder.itemView.setTag(R.id.tag_first, ringtoneList[position])
holder.itemView.setTag(R.id.tag_second, position)
}
override fun getItemCount(): Int {
return ringtoneList.size
}
override fun onClick(v: View) {
if (listener != null) {
// 注意这里使用getTag方法获取数据
listener!!.onItemClick(v, v.getTag(R.id.tag_first) as String, v.getTag(R.id.tag_second) as Int)
}
}
fun setOnItemClickListener(listener: OnRecyclerViewItemClickListener) {
this.listener = listener
}
class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val ringtonePath: TextView = itemView.findViewById(R.id.tone_name) as TextView
}
//点击事件接口
interface OnRecyclerViewItemClickListener {
fun onItemClick(view: View, data: String, position: Int)
}
}
| 0 |
Kotlin
|
0
| 1 |
813ccc8e26083b14d05602a13a608d29d54cc31f
| 2,487 |
reminder
|
MIT License
|
compose-designer/testSrc/com/android/tools/idea/compose/preview/ComposePreviewRepresentationTest.kt
|
JetBrains
| 60,701,247 | false |
{"Kotlin": 43855938, "Java": 36698280, "HTML": 1216565, "Starlark": 735324, "C++": 216476, "Python": 101594, "C": 71515, "Lex": 66026, "NSIS": 58516, "AIDL": 32502, "Shell": 28591, "CMake": 21034, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
|
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.compose.preview
import com.android.tools.idea.common.model.NlModel
import com.android.tools.idea.common.surface.DesignSurface
import com.android.tools.idea.common.surface.DesignSurfaceListener
import com.android.tools.idea.compose.ComposeProjectRule
import com.android.tools.idea.compose.preview.navigation.ComposePreviewNavigationHandler
import com.android.tools.idea.concurrency.AndroidDispatchers.workerThread
import com.android.tools.idea.editors.build.ProjectStatus
import com.android.tools.idea.editors.fast.FastPreviewManager
import com.android.tools.idea.projectsystem.ProjectSystemService
import com.android.tools.idea.projectsystem.TestProjectSystem
import com.android.tools.idea.testing.addFileToProjectAndInvalidate
import com.android.tools.idea.uibuilder.editor.multirepresentation.PreferredVisibility
import com.android.tools.idea.uibuilder.scene.LayoutlibSceneManager
import com.android.tools.idea.uibuilder.surface.NlDesignSurface
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.diagnostic.LogLevel
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.runInEdtAndWait
import java.util.UUID
import java.util.concurrent.CountDownLatch
import javax.swing.JComponent
import javax.swing.JPanel
import kotlin.test.assertContains
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
internal class TestComposePreviewView(override val mainSurface: NlDesignSurface) :
ComposePreviewView {
override val component: JComponent
get() = JPanel()
override var bottomPanel: JComponent? = null
override val isMessageBeingDisplayed: Boolean = false
override var hasContent: Boolean = true
override var hasRendered: Boolean = true
override fun updateNotifications(parentEditor: FileEditor) {}
override fun updateVisibilityAndNotifications() {}
override fun updateProgress(message: String) {}
override fun onRefreshCancelledByTheUser() {}
override fun onRefreshCompleted() {}
override fun onLayoutlibNativeCrash(onLayoutlibReEnable: () -> Unit) {}
}
class ComposePreviewRepresentationTest {
private val logger = Logger.getInstance(ComposePreviewRepresentationTest::class.java)
@get:Rule
val projectRule =
ComposeProjectRule(
previewAnnotationPackage = "androidx.compose.ui.tooling.preview",
composableAnnotationPackage = "androidx.compose.runtime"
)
private val project
get() = projectRule.project
private val fixture
get() = projectRule.fixture
@Before
fun setup() {
Logger.getInstance(ComposePreviewRepresentation::class.java).setLevel(LogLevel.ALL)
Logger.getInstance(FastPreviewManager::class.java).setLevel(LogLevel.ALL)
Logger.getInstance(ProjectStatus::class.java).setLevel(LogLevel.ALL)
logger.info("setup")
val testProjectSystem = TestProjectSystem(project)
runInEdtAndWait { testProjectSystem.useInTests() }
logger.info("setup complete")
}
@Test
fun testPreviewInitialization() =
runBlocking(workerThread) {
val composeTest = runWriteActionAndWait {
fixture.addFileToProjectAndInvalidate(
"Test.kt",
// language=kotlin
"""
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.runtime.Composable
@Composable
@Preview
fun Preview1() {
}
@Composable
@Preview(name = "preview2", apiLevel = 12, group = "groupA", showBackground = true)
fun Preview2() {
}
"""
.trimIndent()
)
}
val navigationHandler = ComposePreviewNavigationHandler()
val mainSurface =
NlDesignSurface.builder(project, fixture.testRootDisposable)
.setNavigationHandler(navigationHandler)
.build()
val modelRenderedLatch = CountDownLatch(2)
mainSurface.addListener(
object : DesignSurfaceListener {
override fun modelChanged(surface: DesignSurface<*>, model: NlModel?) {
val id = UUID.randomUUID().toString().substring(0, 5)
logger.info("modelChanged ($id)")
(surface.getSceneManager(model!!) as? LayoutlibSceneManager)?.addRenderListener {
logger.info("renderListener ($id)")
modelRenderedLatch.countDown()
}
}
}
)
val composeView = TestComposePreviewView(mainSurface)
val preview =
ComposePreviewRepresentation(composeTest, PreferredVisibility.SPLIT) { _, _, _, _, _, _ ->
composeView
}
Disposer.register(fixture.testRootDisposable, preview)
withContext(Dispatchers.IO) {
logger.info("compile")
ProjectSystemService.getInstance(project).projectSystem.getBuildManager().compileProject()
logger.info("activate")
preview.onActivate()
modelRenderedLatch.await()
while (preview.status().isRefreshing || DumbService.getInstance(project).isDumb) kotlinx
.coroutines
.delay(250)
}
mainSurface.models.forEach { assertContains(navigationHandler.defaultNavigationMap, it) }
assertArrayEquals(
arrayOf("groupA"),
preview.availableGroups.map { it.displayName }.toTypedArray()
)
val status = preview.status()
val debugStatus = preview.debugStatusForTesting()
assertFalse(debugStatus.toString(), status.isOutOfDate)
// Ensure the only warning message is the missing Android SDK message
assertTrue(
debugStatus.renderResult
.flatMap { it.logger.messages }
.none { !it.html.contains("No Android SDK found.") }
)
preview.onDeactivate()
}
}
| 2 |
Kotlin
|
230
| 876 |
9c0a89784cca3c01ab99cf251b71a26cdb87cc47
| 6,675 |
android
|
Apache License 2.0
|
core/data/src/main/java/com/niyaj/data/data/repository/PaymentRepositoryImpl.kt
|
skniyajali
| 579,613,644 | false |
{"Kotlin": 2220123}
|
package com.niyaj.data.data.repository
import com.niyaj.common.utils.Resource
import com.niyaj.common.utils.ValidationResult
import com.niyaj.data.mapper.toEntity
import com.niyaj.data.repository.PaymentRepository
import com.niyaj.data.repository.validation.PaymentValidationRepository
import com.niyaj.data.utils.collectWithSearch
import com.niyaj.database.model.EmployeeEntity
import com.niyaj.database.model.PaymentEntity
import com.niyaj.database.model.toExternalModel
import com.niyaj.model.Employee
import com.niyaj.model.Payment
import com.niyaj.model.PaymentMode
import com.niyaj.model.PaymentType
import com.niyaj.model.filterEmployeeSalary
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.ext.query
import io.realm.kotlin.query.Sort
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.withContext
class PaymentRepositoryImpl(
config: RealmConfiguration,
private val ioDispatcher: CoroutineDispatcher
) : PaymentRepository, PaymentValidationRepository {
val realm = Realm.open(config)
override suspend fun getAllEmployee(): Flow<List<Employee>> {
return withContext(ioDispatcher) {
realm.query<EmployeeEntity>().find().asFlow().mapLatest { employees ->
employees.collectWithSearch(
transform = { it.toExternalModel() },
searchFilter = { it }
)
}
}
}
override suspend fun getEmployeeById(employeeId: String): Employee? {
return try {
withContext(ioDispatcher) {
realm
.query<EmployeeEntity>("employeeId == $0", employeeId)
.first()
.find()
?.toExternalModel()
}
} catch (e: Exception) {
null
}
}
override suspend fun getAllPayments(searchText: String): Flow<List<Payment>> {
return withContext(ioDispatcher) {
realm
.query<PaymentEntity>()
.sort("paymentDate", Sort.DESCENDING)
.find()
.asFlow()
.mapLatest { salaries ->
salaries.collectWithSearch(
transform = { it.toExternalModel() },
searchFilter = { it.filterEmployeeSalary(searchText) },
)
}
}
}
override suspend fun getPaymentById(paymentId: String): Resource<Payment?> {
return try {
val salary = withContext(ioDispatcher) {
realm.query<PaymentEntity>("paymentId == $0", paymentId).first().find()
}
Resource.Success(salary?.toExternalModel())
} catch (e: Exception) {
Resource.Error(e.message ?: "Unable to get Salary")
}
}
override suspend fun addOrUpdatePayment(
newPayment: Payment,
paymentId: String
): Resource<Boolean> {
return withContext(ioDispatcher) {
try {
val validateEmployee = validateEmployee(newPayment.employee?.employeeId ?: "")
val validateGivenDate = validateGivenDate(newPayment.paymentDate)
val validatePaymentType = validatePaymentType(newPayment.paymentType)
val validateSalary = validatePaymentAmount(newPayment.paymentAmount)
val validateSalaryNote = validatePaymentNote(newPayment.paymentNote)
val validateSalaryType = validatePaymentMode(newPayment.paymentMode)
val hasError = listOf(
validateEmployee,
validateSalary,
validateSalaryNote,
validateSalaryType,
validatePaymentType,
validateGivenDate
).any { !it.successful }
if (!hasError) {
val employee = realm.query<EmployeeEntity>(
"employeeId == $0",
newPayment.employee?.employeeId
).first().find()
if (employee != null) {
val salary =
realm.query<PaymentEntity>("paymentId == $0", paymentId).first()
.find()
if (salary != null) {
realm.write {
findLatest(salary)?.apply {
this.paymentAmount = newPayment.paymentAmount
this.paymentMode = newPayment.paymentMode.name
this.paymentDate = newPayment.paymentDate
this.paymentType = newPayment.paymentType.name
this.paymentNote = newPayment.paymentNote
this.updatedAt = System.currentTimeMillis().toString()
findLatest(employee)?.also {
this.employee = it
}
}
}
Resource.Success(true)
} else {
realm.write {
this.copyToRealm(newPayment.toEntity(findLatest(employee)))
}
Resource.Success(true)
}
} else {
Resource.Error("Unable to find employee")
}
} else {
Resource.Error("Unable to validate employee salary")
}
} catch (e: Exception) {
Resource.Error(e.message ?: "Failed to update employee.")
}
}
}
override suspend fun deletePayments(paymentIds: List<String>): Resource<Boolean> {
return try {
paymentIds.forEach { paymentId ->
withContext(ioDispatcher) {
val salary =
realm.query<PaymentEntity>("paymentId == $0", paymentId).first().find()
if (salary != null) {
realm.write {
findLatest(salary)?.let {
delete(it)
}
}
}
}
}
Resource.Success(true)
} catch (e: Exception) {
Resource.Error(e.message ?: "Unable to delete salary.")
}
}
override fun validateEmployee(employeeId: String): ValidationResult {
if (employeeId.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = "Employee name must not be empty",
)
}
return ValidationResult(
successful = true,
)
}
override fun validateGivenDate(givenDate: String): ValidationResult {
if (givenDate.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = "Given date must not be empty",
)
}
return ValidationResult(
successful = true,
)
}
override fun validatePaymentType(paymentType: PaymentType): ValidationResult {
if (paymentType.name.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = "Payment type must not be empty."
)
}
return ValidationResult(true)
}
override fun validatePaymentAmount(paymentAmount: String): ValidationResult {
if (paymentAmount.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = "Salary must not be empty",
)
}
if (paymentAmount.length < 2) {
return ValidationResult(
successful = false,
errorMessage = "Salary must greater than two digits",
)
}
if (paymentAmount.any { it.isLetter() }) {
return ValidationResult(
successful = false,
errorMessage = "Salary must not contain any characters",
)
}
return ValidationResult(
successful = true,
)
}
override fun validatePaymentNote(paymentNote: String, isRequired: Boolean): ValidationResult {
if (isRequired) {
if (paymentNote.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = "Salary note required because you paid using Cash and Online."
)
}
}
return ValidationResult(true)
}
override fun validatePaymentMode(paymentMode: PaymentMode): ValidationResult {
if (paymentMode.name.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = "Salary type must not be empty",
)
}
return ValidationResult(true)
}
}
| 34 |
Kotlin
|
0
| 1 |
2020b913df5030525c582218f6a91a7a3466ee2c
| 9,356 |
POS-Application
|
MIT License
|
app/src/test/java/io/trod/devutils/DateUtilsTests.kt
|
trod-123
| 158,179,184 | false | null |
/*
* Copyright 2018 <NAME> (TROD) at https://github.com/trod-123
*
* 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.trod.devutils
import io.trod.devutils.java.DateUtils
import org.joda.time.DateTime
import org.joda.time.DateTimeConstants
import org.junit.Assert
import org.junit.Test
import java.util.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class DateUtilsTests {
/**
* Assumes [DateUtils.getFirstDayOfWeekDateFromStartDate] is correct!
*/
@Test
fun testParseDateStringIntoDateTime() {
// region cases
val DATE_TIME = DateTime().withTimeAtStartOfDay()
val TEST_CASES = arrayOf(
"Today",
"Tomorrow",
"October 14th",
"October 14th 2019",
"October 14",
"October 14 2019",
"1st",
"2nd",
"3rd",
"4th",
"20th",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
"1 day",
"2 days",
"10 days",
"15 days",
"One day",
"Two days",
"Ten days",
"Fifteen days",
"1 week",
"2 weeks",
"10 weeks",
"15 weeks",
"One week",
"Two weeks",
"Ten weeks",
"Fifteen weeks",
"1.5 weeks",
"One point five weeks",
"1 and a half weeks",
"One and a half weeks",
"Half a week",
"1 and a 1/2 weeks",
"One and a 1/2 weeks",
"1/2 a week"
)
val TEST_CASE_PREFIXES = arrayOf("", "Expires on ", "On ", "In ", "The ", "On the ", "In the ")
val TEST_CASE_EXPECTED = arrayOf(
DATE_TIME,
DATE_TIME.plusDays(1),
DateTime(DATE_TIME.year, 10, 14, 0, 0),
DateTime(2019, 10, 14, 0, 0),
DateTime(DATE_TIME.year, 10, 14, 0, 0),
DateTime(2019, 10, 14, 0, 0),
DATE_TIME.withDayOfMonth(1),
DATE_TIME.withDayOfMonth(2),
DATE_TIME.withDayOfMonth(3),
DATE_TIME.withDayOfMonth(4),
DATE_TIME.withDayOfMonth(20),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.MONDAY, DATE_TIME.millis
),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.TUESDAY, DATE_TIME.millis
),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.WEDNESDAY, DATE_TIME.millis
),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.THURSDAY, DATE_TIME.millis
),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.FRIDAY, DATE_TIME.millis
),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.SATURDAY, DATE_TIME.millis
),
DateUtils.getFirstDayOfWeekDateFromStartDate(
DateTimeConstants.SUNDAY, DATE_TIME.millis
),
DATE_TIME.plusDays(1),
DATE_TIME.plusDays(2),
DATE_TIME.plusDays(10),
DATE_TIME.plusDays(15),
DATE_TIME.plusDays(1),
DATE_TIME.plusDays(2),
DATE_TIME.plusDays(10),
DATE_TIME.plusDays(15),
DATE_TIME.plusDays(7),
DATE_TIME.plusDays(7 * 2),
DATE_TIME.plusDays(7 * 10),
DATE_TIME.plusDays(7 * 15),
DATE_TIME.plusDays(7),
DATE_TIME.plusDays(7 * 2),
DATE_TIME.plusDays(7 * 10),
DATE_TIME.plusDays(7 * 15),
DATE_TIME.plusDays(11),
DATE_TIME.plusDays(11),
DATE_TIME.plusDays(11),
DATE_TIME.plusDays(11),
DATE_TIME.plusDays(4),
DATE_TIME.plusDays(11),
DATE_TIME.plusDays(11),
DATE_TIME.plusDays(4)
)
// endregion
val resultsMap = HashMap<String, String>()
val failedTestCases = ArrayList<String>()
for (prefix in TEST_CASE_PREFIXES) {
for (i in TEST_CASES.indices) {
val testCase = TEST_CASES[i]
val fullCase = prefix + testCase
try {
val result = DateUtils.parseDateFromString(prefix + testCase)
if (result.isEqual(TEST_CASE_EXPECTED[i])) {
resultsMap[fullCase] = DateUtils.formatDate(
result, null,
DateUtils.DateFormatComponents.SHORT_MONTH, DateUtils.DateFormatComponents.FULL_YEAR
)
} else {
failedTestCases.add(fullCase)
resultsMap[fullCase] = String.format(
"Failed: %s | Expected: %s",
DateUtils.formatDate(
result, null,
DateUtils.DateFormatComponents.SHORT_MONTH, DateUtils.DateFormatComponents.FULL_YEAR
),
DateUtils.formatDate(
TEST_CASE_EXPECTED[i], null,
DateUtils.DateFormatComponents.SHORT_MONTH, DateUtils.DateFormatComponents.FULL_YEAR
)
)
}
} catch (e: IllegalArgumentException) {
failedTestCases.add(fullCase)
resultsMap[fullCase] = ""
}
}
for (testCase in resultsMap.keys) {
println(String.format("%s => %s", testCase, resultsMap[testCase]))
}
if (!failedTestCases.isEmpty()) {
Assert.fail("Failed cases: " + Arrays.toString(failedTestCases.toTypedArray()))
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
e5a0d77cb3ba9318531406f6d8f9596b9a817a45
| 6,740 |
DevUtils
|
Apache License 2.0
|
java/com/mu/jan/problems/architecture/Room.kt
|
Mukuljangir372
| 359,095,214 | false | null |
package com.mu.jan.problems.architecture
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.room.*
/**
* Room is a modern way to work with SQLite
*
* Part of Room
* 1. Entity
* 2. Dao
* 3. Database
*/
@Entity(tableName = "profile")
data class Profile(
@ColumnInfo(name = "name")
val name: String
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "uid")
val uid: Int? = null
}
@Dao
interface MyDao{
@Insert
fun insert(profile: Profile)
@Update
fun update(profile: Profile)
@Delete
fun delete(profile: Profile)
@Query("SELECT * FROM profile")
fun getProfiles(): List<Profile>
@Query("SELECT * FROM profile WHERE uid LIKE :uid")
fun getProfile(uid: Int): Profile
}
@Database(entities = [Profile::class],exportSchema = false,version = 1)
abstract class AppDatabase: RoomDatabase() {
abstract fun profileDao() : MyDao
companion object{
const val DB_NAME = "myRoomDb1"
@Volatile
private var instance: AppDatabase? = null
fun getDb(mContext: Context): AppDatabase{
if(instance!=null) return instance!!
synchronized(this){
instance = Room.databaseBuilder(
mContext,AppDatabase::class.java, DB_NAME
).allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
}
return instance!!
}
}
}
class MyRoomActivity: AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//..
val db = AppDatabase.getDb(this)
}
}
| 0 |
Kotlin
|
0
| 1 |
bb15517c09041757d859126dc4f39d3409fdd35d
| 1,730 |
Android-Kotlin-Interview
|
Apache License 2.0
|
java/com/mu/jan/problems/architecture/Room.kt
|
Mukuljangir372
| 359,095,214 | false | null |
package com.mu.jan.problems.architecture
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.room.*
/**
* Room is a modern way to work with SQLite
*
* Part of Room
* 1. Entity
* 2. Dao
* 3. Database
*/
@Entity(tableName = "profile")
data class Profile(
@ColumnInfo(name = "name")
val name: String
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "uid")
val uid: Int? = null
}
@Dao
interface MyDao{
@Insert
fun insert(profile: Profile)
@Update
fun update(profile: Profile)
@Delete
fun delete(profile: Profile)
@Query("SELECT * FROM profile")
fun getProfiles(): List<Profile>
@Query("SELECT * FROM profile WHERE uid LIKE :uid")
fun getProfile(uid: Int): Profile
}
@Database(entities = [Profile::class],exportSchema = false,version = 1)
abstract class AppDatabase: RoomDatabase() {
abstract fun profileDao() : MyDao
companion object{
const val DB_NAME = "myRoomDb1"
@Volatile
private var instance: AppDatabase? = null
fun getDb(mContext: Context): AppDatabase{
if(instance!=null) return instance!!
synchronized(this){
instance = Room.databaseBuilder(
mContext,AppDatabase::class.java, DB_NAME
).allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
}
return instance!!
}
}
}
class MyRoomActivity: AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//..
val db = AppDatabase.getDb(this)
}
}
| 0 |
Kotlin
|
0
| 1 |
bb15517c09041757d859126dc4f39d3409fdd35d
| 1,730 |
Android-Kotlin-Interview
|
Apache License 2.0
|
cryptanil/src/main/java/com/primesoft/cryptanil/models/OrderTransaction.kt
|
narekignoyan
| 679,714,827 | false | null |
package com.primesoft.cryptanil.models
import com.primesoft.cryptanil.enums.NetworkType
import com.primesoft.cryptanil.utils.*
class OrderTransaction(
var coinDecimal: Double? = null,
var coinIconUrl: String? = null,
var coinType: String? = null,
var cryptanilOrderId: Int? = null,
var currencyCode: String? = null,
var currencyRate: Double? = null,
var currencyValueDecimal: Double? = null,
var depositDate: String? = null,
var fromAddress: String? = null,
var id: Int? = null,
var network: Int? = null,
var networkIconUrl: String? = null,
var networkName: String? = null,
var toAddress: String? = null,
var txId: String? = null,
var value: Double? = null,
var valueDecimal: Double? = null,
) : java.io.Serializable {
fun getNetworkDetailsURL() = when (NetworkType.getById(network)) {
NetworkType.TON -> TON_NETWORK.replace("{txid}", txId ?: "")
NetworkType.SOL -> SOL_NETWORK.replace("{txid}", txId ?: "")
NetworkType.BSC -> BSC_NETWORK.replace("{txid}", txId ?: "")
NetworkType.ETH -> ETH_NETWORK.replace("{txid}", txId ?: "")
NetworkType.BTC -> BTC_NETWORK.replace("{txid}", txId ?: "")
NetworkType.TRX -> TRX_NETWORK.replace("{txid}", txId ?: "")
else -> null
}
}
| 0 |
Kotlin
|
0
| 0 |
9f36b69efd24a33b5fb9b492c3ee016fb2788220
| 1,305 |
Cryptanil
|
MIT License
|
src/main/kotlin/org/piecesapp/client/models/ConversationTypeEnum.kt
|
pieces-app
| 726,212,140 | false |
{"Kotlin": 1451671}
|
/**
* Pieces Isomorphic OpenAPI
* Endpoints for Assets, Formats, Users, Asset, Format, User.
*
* The version of the OpenAPI document: 1.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.piecesapp.client.models
import com.squareup.moshi.Json
/**
* This is a type of conversation, for now just COPILOT.
* Values: cOPILOT
*/
enum class ConversationTypeEnum(val value: kotlin.String){
@Json(name = "COPILOT")
cOPILOT("COPILOT");
/**
This override toString avoids using the enum var name and uses the actual api value instead.
In cases the var name and value are different, the client would send incorrect enums to the server.
**/
override fun toString(): String {
return value
}
}
| 9 |
Kotlin
|
2
| 6 |
9371158b0978cae518a6f2584dd452a2556b394f
| 875 |
pieces-os-client-sdk-for-kotlin
|
MIT License
|
src/main/kotlin/dayFolders/day21/gasStation.kt
|
lilimapradhan9
| 255,344,059 | false | null |
package dayFolders.day21
fun canCompleteCircuit(gas: IntArray, cost: IntArray): Int {
var sum = 0
var curSum = 0
var index = 0
for (i in gas.indices) {
val diff = gas[i] - cost[i]
sum += diff
curSum += diff
if (curSum < 0) {
index = (i + 1) % gas.size
curSum = 0
}
}
return if (sum >= 0) index else -1
}
fun canCompleteCircuitTwoPointer(gas: IntArray, cost: IntArray): Int {
var start = gas.size - 1
var end = 0
var tank = gas[start] - cost[start]
while (start != end) {
if (tank >= 0) {
tank += gas[end] - cost[end]
end++
} else {
start--
tank += gas[start] - cost[start]
}
}
return if (tank < 0) -1 else start
}
| 0 |
Kotlin
|
0
| 0 |
356cef0db9f0ba1106c308d33c13358077aa0674
| 801 |
kotlin-problems
|
MIT License
|
features/tv/src/main/java/com/hrudhaykanth116/tv/data/datasources/remote/retrofit/RetroApis.kt
|
hrudhaykanth116
| 300,963,083 | false |
{"Kotlin": 456464}
|
package com.hrudhaykanth116.tv.data.datasources.remote.retrofit
import com.hrudhaykanth116.tv.data.models.constants.MoviesDbConstants
import com.hrudhaykanth116.tv.data.datasources.remote.models.MovieVideosResponse
import com.hrudhaykanth116.tv.data.datasources.remote.models.PopularMoviesResponse
import com.hrudhaykanth116.tv.data.datasources.remote.models.TvShowDataPagedResponse
import com.hrudhaykanth116.tv.data.datasources.remote.models.TvShowDetails
import com.hrudhaykanth116.tv.data.datasources.remote.models.UserPost
import com.hrudhaykanth116.tv.data.datasources.remote.models.discover.GetDiscoverTvResponse
import com.hrudhaykanth116.tv.data.datasources.remote.models.genres.GetTvGenresResponse
import com.hrudhaykanth116.tv.data.datasources.remote.models.search.TvShowSearchResults
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Path
import retrofit2.http.Query
public interface RetroApis {
// @GET("users/{user}/repos")
// fun listRepos(@Path("user") user: String?): Call<List<UserPost>>?
// @POST("/upload/{new}.json")
// fun setData(
// @Path("new") s1: String?,
// @Body user: User?
// ): Call<User?>?
//
// @GET("/upload/sushil.json")
// fun getData(): Call<User?>?
//
// @PUT("/upload/{new}.json")
// fun setDataWithoutRandomness(
// @Path("new") s1: String?,
// @Body user: User?
// ): Call<User?>?
@Headers("Content-Type: application/json")
@GET("user_posts/page{pageID}.json")
suspend fun getUserPosts(@Path("pageID") pageId: Int): Call<List<UserPost>>?
@GET("movie/popular")
suspend fun getPopularMoviesList(
@Query("page") pageId: Int,
@Query("api_key", encoded = true) apiKey: String = MoviesDbConstants.API_KEY,
): Response<PopularMoviesResponse>
@GET("tv/popular/")
suspend fun getPopularTvShows(
@Query("page") pageId: Int,
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
): Response<TvShowDataPagedResponse>
@GET("tv/top_rated/")
suspend fun getTopRatedTvShows(
@Query("page") pageId: Int,
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
): Response<TvShowDataPagedResponse>
@GET("tv/airing_today/")
suspend fun getAiringTodayShows(
@Query("page") pageId: Int,
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
): Response<TvShowDataPagedResponse>
@GET("tv/{tvShowId}")
suspend fun getTvShowDetails(
@Path("tvShowId") tvShowId: Int,
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
): Response<TvShowDetails>
@GET("movie/{movie_id}/videos")
suspend fun getMovieVideos(
@Path("movie_id") movieId: Int,
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
): Call<MovieVideosResponse>
@GET("search/tv")
suspend fun searchTv(
@Query("query") query: String,
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
@Query("language") language: String = "en-US",
@Query("page") page: String = "1",
@Query("include_adult") includeAdult: String = "false",
): Response<TvShowSearchResults>
@GET("genre/tv/list")
suspend fun getTvGenres(
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
@Query("language") language: String = "en-US",
): Response<GetTvGenresResponse>
@GET("discover/tv")
suspend fun discoverTv(
@Query("page") page: Int,
@Query("with_genres") genres: String?,
@Query("sort_by") sortBy: String = "popularity.desc",
@Query("api_key") apiKey: String = MoviesDbConstants.API_KEY,
@Query("language") language: String = "en-US",
): Response<GetDiscoverTvResponse>
}
| 0 |
Kotlin
|
0
| 0 |
6c30ac6918537a6f3a86f263d53dc2e9e29ff90a
| 3,842 |
MAFET
|
MIT License
|
app/common/src/desktopMain/kotlin/com/denchic45/studiversity/ui/components/ListItem.kt
|
denchic45
| 435,895,363 | false | null |
package com.denchic45.studiversity.ui.components
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import kotlin.math.max
@Composable
@ExperimentalMaterialApi
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)? = null,
secondaryText: @Composable (() -> Unit)? = null,
singleLineSecondaryText: Boolean = true,
overlineText: @Composable (() -> Unit)? = null,
trailing: @Composable (() -> Unit)? = null,
text: @Composable () -> Unit,
) {
val typography = MaterialTheme.typography
val styledText = applyTextStyle(typography.subtitle1, ContentAlpha.high, text)!!
val styledSecondaryText = applyTextStyle(typography.body2, ContentAlpha.medium, secondaryText)
val styledOverlineText = applyTextStyle(typography.overline, ContentAlpha.high, overlineText)
val styledTrailing = applyTextStyle(typography.caption, ContentAlpha.high, trailing)
val semanticsModifier = modifier.semantics(mergeDescendants = true) {}
if (styledSecondaryText == null && styledOverlineText == null) {
OneLine.ListItem(semanticsModifier, icon, styledText, styledTrailing)
} else if ((styledOverlineText == null && singleLineSecondaryText) || styledSecondaryText == null) {
TwoLine.ListItem(
semanticsModifier,
icon,
styledText,
styledSecondaryText,
styledOverlineText,
styledTrailing
)
} else {
ThreeLine.ListItem(
semanticsModifier,
icon,
styledText,
styledSecondaryText,
styledOverlineText,
styledTrailing
)
}
}
private object OneLine {
// TODO(popam): support wide icons
// TODO(popam): convert these to sp
// List item related defaults.
private val MinHeight = 48.dp
private val MinHeightWithIcon = 56.dp
// Icon related defaults.
private val IconMinPaddedWidth = 40.dp
private val IconLeftPadding = 16.dp
private val IconVerticalPadding = 8.dp
// Content related defaults.
private val ContentLeftPadding = 16.dp
private val ContentRightPadding = 16.dp
// Trailing related defaults.
private val TrailingRightPadding = 16.dp
@Composable
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)?,
text: @Composable (() -> Unit),
trailing: @Composable (() -> Unit)?,
) {
val minHeight = if (icon == null) MinHeight else MinHeightWithIcon
Row(modifier.heightIn(min = minHeight)) {
if (icon != null) {
Box(Modifier.align(Alignment.CenterVertically)
.widthIn(min = IconLeftPadding + IconMinPaddedWidth)
.padding(start = IconLeftPadding,
top = IconVerticalPadding,
bottom = IconVerticalPadding
),
contentAlignment = Alignment.CenterStart) { icon() }
}
Box(Modifier.weight(1f).align(Alignment.CenterVertically)
.padding(start = ContentLeftPadding, end = ContentRightPadding),
contentAlignment = Alignment.CenterStart) { text() }
if (trailing != null) {
Box(Modifier.align(Alignment.CenterVertically)
.padding(end = TrailingRightPadding)) { trailing() }
}
}
}
}
private object TwoLine {
// List item related defaults.
private val MinHeight = 64.dp
private val MinHeightWithIcon = 64.dp
// Icon related defaults.
private val IconMinPaddedWidth = 40.dp
private val IconLeftPadding = 16.dp
private val IconVerticalPadding = 16.dp
// Content related defaults.
private val ContentLeftPadding = 16.dp
private val ContentRightPadding = 16.dp
private val OverlineBaselineOffset = 24.dp
private val OverlineToPrimaryBaselineOffset = 20.dp
private val PrimaryBaselineOffsetNoIcon = 28.dp
private val PrimaryBaselineOffsetWithIcon = 32.dp
private val PrimaryToSecondaryBaselineOffsetNoIcon = 20.dp
private val PrimaryToSecondaryBaselineOffsetWithIcon = 20.dp
// Trailing related defaults.
private val TrailingRightPadding = 16.dp
@Composable
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)?,
text: @Composable (() -> Unit),
secondaryText: @Composable (() -> Unit)?,
overlineText: @Composable (() -> Unit)?,
trailing: @Composable (() -> Unit)?,
) {
val minHeight = if (icon == null) MinHeight else MinHeightWithIcon
Row(modifier.heightIn(min = minHeight)) {
val columnModifier =
Modifier.weight(1f).padding(start = ContentLeftPadding, end = ContentRightPadding)
if (icon != null) {
Box(Modifier.sizeIn(minWidth = IconLeftPadding + IconMinPaddedWidth,
minHeight = minHeight).padding(start = IconLeftPadding,
top = IconVerticalPadding,
bottom = IconVerticalPadding
),
contentAlignment = Alignment.CenterStart) { icon() }
}
if (overlineText != null) {
BaselinesOffsetColumn(listOf(
OverlineBaselineOffset,
OverlineToPrimaryBaselineOffset
), columnModifier) {
overlineText()
text()
}
} else {
BaselinesOffsetColumn(listOf(if (icon != null) {
PrimaryBaselineOffsetWithIcon
} else {
PrimaryBaselineOffsetNoIcon
}, if (icon != null) {
PrimaryToSecondaryBaselineOffsetWithIcon
} else {
PrimaryToSecondaryBaselineOffsetNoIcon
}), columnModifier) {
text()
secondaryText!!()
}
}
if (trailing != null) {
OffsetToBaselineOrCenter(if (icon != null) {
PrimaryBaselineOffsetWithIcon
} else {
PrimaryBaselineOffsetNoIcon
}) {
Box(
// TODO(popam): find way to center and wrap content without minHeight
Modifier.heightIn(min = minHeight).padding(end = TrailingRightPadding),
contentAlignment = Alignment.Center) { trailing() }
}
}
}
}
}
private object ThreeLine {
// List item related defaults.
private val MinHeight = 88.dp
// Icon related defaults.
private val IconMinPaddedWidth = 40.dp
private val IconLeftPadding = 16.dp
private val IconThreeLineVerticalPadding = 16.dp
// Content related defaults.
private val ContentLeftPadding = 16.dp
private val ContentRightPadding = 16.dp
private val ThreeLineBaselineFirstOffset = 28.dp
private val ThreeLineBaselineSecondOffset = 20.dp
private val ThreeLineBaselineThirdOffset = 20.dp
private val ThreeLineTrailingTopPadding = 16.dp
// Trailing related defaults.
private val TrailingRightPadding = 16.dp
@Composable
fun ListItem(
modifier: Modifier = Modifier,
icon: @Composable (() -> Unit)?,
text: @Composable (() -> Unit),
secondaryText: @Composable (() -> Unit),
overlineText: @Composable (() -> Unit)?,
trailing: @Composable (() -> Unit)?,
) {
Row(modifier.heightIn(min = MinHeight)) {
if (icon != null) {
val minSize = IconLeftPadding + IconMinPaddedWidth
Box(Modifier.sizeIn(minWidth = minSize, minHeight = minSize)
.padding(start = IconLeftPadding,
top = IconThreeLineVerticalPadding,
bottom = IconThreeLineVerticalPadding
),
contentAlignment = Alignment.CenterStart) { icon() }
}
BaselinesOffsetColumn(listOf(
ThreeLineBaselineFirstOffset,
ThreeLineBaselineSecondOffset,
ThreeLineBaselineThirdOffset
),
Modifier.weight(1f)
.padding(start = ContentLeftPadding, end = ContentRightPadding)) {
if (overlineText != null) overlineText()
text()
secondaryText()
}
if (trailing != null) {
OffsetToBaselineOrCenter(
ThreeLineBaselineFirstOffset - ThreeLineTrailingTopPadding,
Modifier.padding(top = ThreeLineTrailingTopPadding, end = TrailingRightPadding),
trailing)
}
}
}
}
/**
* Layout that expects [Text] children, and positions them with specific offsets between the
* top of the layout and the first text, as well as the last baseline and first baseline
* for subsequent pairs of texts.
*/
// TODO(popam): consider making this a layout composable in `foundation-layout`.
@Composable
private fun BaselinesOffsetColumn(
offsets: List<Dp>,
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(content, modifier) { measurables, constraints ->
val childConstraints = constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity)
val placeables = measurables.map { it.measure(childConstraints) }
val containerWidth = placeables.fold(0) { maxWidth, placeable ->
max(maxWidth, placeable.width)
}
val y = Array(placeables.size) { 0 }
var containerHeight = 0
placeables.forEachIndexed { index, placeable ->
val toPreviousBaseline = if (index > 0) {
placeables[index - 1].height - placeables[index - 1][LastBaseline]
} else 0
val topPadding =
max(0, offsets[index].roundToPx() - placeable[FirstBaseline] - toPreviousBaseline)
y[index] = topPadding + containerHeight
containerHeight += topPadding + placeable.height
}
layout(containerWidth, containerHeight) {
placeables.forEachIndexed { index, placeable ->
placeable.placeRelative(0, y[index])
}
}
}
}
/**
* Layout that takes a child and adds the necessary padding such that the first baseline of the
* child is at a specific offset from the top of the container. If the child does not have
* a first baseline, the layout will match the minHeight constraint and will center the
* child.
*/
// TODO(popam): support fallback alignment in AlignmentLineOffset, and use that here.
@Composable
private fun OffsetToBaselineOrCenter(
offset: Dp,
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(content, modifier) { measurables, constraints ->
val placeable = measurables[0].measure(constraints.copy(minHeight = 0))
val baseline = placeable[FirstBaseline]
val y: Int
val containerHeight: Int
if (baseline != AlignmentLine.Unspecified) {
y = offset.roundToPx() - baseline
containerHeight = max(constraints.minHeight, y + placeable.height)
} else {
containerHeight = max(constraints.minHeight, placeable.height)
y = Alignment.Center.align(IntSize.Zero,
IntSize(0, containerHeight - placeable.height),
layoutDirection).y
}
layout(placeable.width, containerHeight) {
placeable.placeRelative(0, y)
}
}
}
private fun applyTextStyle(
textStyle: TextStyle,
contentAlpha: Float,
icon: @Composable (() -> Unit)?,
): @Composable (() -> Unit)? {
if (icon == null) return null
return {
CompositionLocalProvider(LocalContentAlpha provides contentAlpha) {
ProvideTextStyle(textStyle, icon)
}
}
}
| 0 |
Kotlin
|
0
| 5 |
02d19321d16604a052f6dd29aa54be29343991e6
| 12,708 |
Studiversity
|
Apache License 2.0
|
src/main/kotlin/models/VoronoiDiagram3Point.kt
|
abc873693
| 157,052,325 | false | null |
package voronoiDiagram.models
import voronoiDiagram.libs.Utils
class VoronoiDiagram3Point(points: ArrayList<Point>) : VoronoiDiagram(points) {
override fun execute() {
println("points")
points.forEach {
println(it.toString())
}
if (points.size == 2) {
val pointA = points[0]
val pointB = points[1]
lines.add(Utils.getMidLine(pointA, pointB))
} else if (points.size == 3) {
lines.add(Utils.getMidLine(points[0], points[1]))
lines.add(Utils.getMidLine(points[1], points[2]))
lines.add(Utils.getMidLine(points[0], points[2]))
val middlePoint01 = Utils.getMidPoint(points[0], points[1])
val middlePoint12 = Utils.getMidPoint(points[1], points[2])
val middlePoint02 = Utils.getMidPoint(points[0], points[2])
val intersection01 = Utils.findIntersection(lines[0], lines[1])
val intersection12 = Utils.findIntersection(lines[1], lines[2])
val intersection02 = Utils.findIntersection(lines[0], lines[2])
val slope01 = Utils.getSlope(points[0], points[1])
val slope12 = Utils.getSlope(points[1], points[2])
val slope02 = Utils.getSlope(points[0], points[2])
val slopeMiddlePoint0 = Utils.getSlope(points[0], middlePoint12)
val slopeMiddlePoint1 = Utils.getSlope(points[1], middlePoint02)
val slopeMiddlePoint2 = Utils.getSlope(points[2], middlePoint01)
val angle012 = Utils.getAngle(points[0], points[1], points[2])
val angle021 = Utils.getAngle(points[0], points[1], points[2])
val angle102 = Utils.getAngle(points[1], points[0], points[2])
println("angle012 $angle012")
println("angle021 $angle021")
println("angle102 $angle102")
println("middlePoint01 ${middlePoint01.toString()}")
println("middlePoint12 ${middlePoint12.toString()}")
println("middlePoint02 ${middlePoint02.toString()}")
println("lines0 ${lines[0].toString()}")
println("lines1 ${lines[1].toString()}")
println("lines2 ${lines[2].toString()}")
if (intersection01.x in 0.0..600.0 && intersection01.y in 0.0..600.0) {
/*if (points[2].y in points[0].y..points[1].y || points[0].y >points[1].y) {
lines[0].end.x = intersection01.x
lines[0].end.y = intersection01.y
} else {
lines[0].start.x = intersection01.x
lines[0].start.y = intersection01.y
}
if (points[0].y in points[1].y..points[2].y || points[1].y>points[2].y) {
lines[1].end.x = intersection12.x
lines[1].end.y = intersection12.y
} else {
lines[1].start.x = intersection12.x
lines[1].start.y = intersection12.y
}
if (points[1].y in points[0].y..points[2].y || points[0].y < points[2].y) {
lines[2].end.x = intersection02.x
lines[2].end.y = intersection02.y
} else {
lines[2].start.x = intersection02.x
lines[2].start.y = intersection02.y
}*/
if (lines[0].start.x == 0.0) {
if (points[2].x > intersection01.x) {
lines[0].end.x = intersection01.x
lines[0].end.y = intersection01.y
} else {
lines[0].start.x = intersection01.x
lines[0].start.y = intersection01.y
}
} else if (lines[0].start.y == 0.0) {
if (points[2].y < intersection01.y) {
lines[0].end.x = intersection01.x
lines[0].end.y = intersection01.y
} else {
lines[0].start.x = intersection01.x
lines[0].start.y = intersection01.y
}
} else if (lines[0].start.y == 600.0) {
if (points[2].y > intersection01.y) {
lines[0].start.x = intersection01.x
lines[0].start.y = intersection01.y
} else {
lines[0].end.x = intersection01.x
lines[0].end.y = intersection01.y
}
}
if (lines[1].start.x == 0.0) {
if (points[0].x > intersection12.x) {
lines[1].end.x = intersection12.x
lines[1].end.y = intersection12.y
} else {
lines[1].start.x = intersection12.x
lines[1].start.y = intersection12.y
}
} else if (lines[1].start.y == 0.0) {
if (points[0].x < middlePoint12.x) {
lines[1].start.x = intersection12.x
lines[1].start.y = intersection12.y
} else {
lines[1].end.x = intersection12.x
lines[1].end.y = intersection12.y
}
} else if (lines[1].start.y == 600.0) {
if (points[0].x > intersection12.x) {
lines[1].end.x = intersection12.x
lines[1].end.y = intersection12.y
} else {
lines[1].start.x = intersection12.x
lines[1].start.y = intersection12.y
}
}
if (lines[2].start.x == 0.0) {
if (points[1].y > intersection02.y) {
lines[2].end.x = intersection02.x
lines[2].end.y = intersection02.y
} else {
lines[2].start.x = intersection02.x
lines[2].start.y = intersection02.y
}
} else if (lines[2].start.y == 0.0) {
if (points[1].y < intersection02.y) {
lines[2].start.x = intersection02.x
lines[2].start.y = intersection02.y
} else {
lines[2].end.x = intersection02.x
lines[2].end.y = intersection02.y
}
} else if (lines[2].start.y == 600.0) {
if (points[1].y < intersection02.y) {
lines[2].end.x = intersection02.x
lines[2].end.y = intersection02.y
} else {
lines[2].start.x = intersection02.x
lines[2].start.y = intersection02.y
}
}
} else {
lines.removeAt(2)
}
} else {
//TODO
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ed1adb638cfd7b15b1faa0491a58c7c3ea55bd64
| 7,126 |
voronoi-diagram
|
MIT License
|
app/src/main/java/com/ellison/flappybird/model/RoadState.kt
|
ellisonchan
| 387,158,613 | false |
{"Kotlin": 63870}
|
package com.ellison.flappybird.model
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
data class RoadState (var offset: Dp = RoadWidthOffset) {
fun move(): RoadState = copy(offset = offset - RoadMoveVelocity)
fun reset(): RoadState = copy(offset = TempRoadWidthOffset)
}
val RoadWidthOffset = 0.dp
val TempRoadWidthOffset = 300.dp
val RoadMoveVelocity = 10.dp
val RoadStateList = listOf(
RoadState(),
RoadState(offset = TempRoadWidthOffset)
)
| 0 |
Kotlin
|
44
| 209 |
1ac908f8899c9e4a54b248c897b3e8996a74c83f
| 484 |
ComposeBird
|
MIT License
|
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCall/explicitLambdaParameter.kt
|
ingokegel
| 72,937,917 | false | null |
// WITH_STDLIB
fun test() {
listOf(listOf(1)).<caret>flatMap { i -> i }
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 77 |
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/project22/myapplication/model/Destination.kt
|
reuben21
| 390,672,747 | false |
{"Kotlin": 155492}
|
package com.project22.myapplication.model
import com.google.firebase.Timestamp
import java.util.HashMap
//"originName" to originName,
//"destinationName" to destinationName,
//"originLatitude" to originNameLatitude,
//"originLongitude" to originNameLongitude,
//"destinationLatitude" to destinationNameLatitude,
//"destinationLongitude" to destinationNameLongitude,
//"startDate" to Timestamp(Date(startDateVar)) ,
//"endDate" to Timestamp(Date(endDateVar)) ,
//"chatName" to chatName,
//"ticketImageUrl" to ticketImageUrl,
//"destinationImageUrl" to destinationImageUrl
class Destination {
var id: String? = null
var creatorId: String? = null
var creatorName: String? = null
var chatId: String? = null
var originName: String? = null
var destinationName: String? = null
var chatName: String? = null
var ticketImageUrl: String? = null
var destinationImageUrl: String? = null
var originLatitude: Double? = null
var originLongitude: Double? = null
var destinationLatitude: Double? = null
var destinationLongitude: Double? = null
var startDate: Timestamp? = null
var endDate: Timestamp? = null
var travellers: Int? = null
constructor() {}
constructor(
id: String,
creatorId: String,
creatorName: String,
chatId: String,
originName: String,
destinationName: String,
chatName: String,
ticketImageUrl: String,
destinationImageUrl: String,
originLatitude: Double,
originLongitude: Double,
destinationLatitude: Double,
destinationLongitude: Double,
startDate: Timestamp,
endDate: Timestamp?,
travellers: Int
) {
this.id = id
this.creatorId = creatorId
this.creatorName = creatorName
this.originName = originName
this.destinationName = destinationName
this.chatName = chatName
this.ticketImageUrl = ticketImageUrl
this.destinationImageUrl = destinationImageUrl
this.originLatitude = originLatitude
this.originLongitude = originLongitude
this.destinationLatitude = destinationLatitude
this.destinationLongitude = destinationLongitude
this.startDate = startDate
this.endDate = endDate
this.travellers = travellers
this.chatId = chatId
}
}
| 0 |
Kotlin
|
0
| 0 |
ebea676857bd06960b249031ed589dd2ee0430e0
| 2,374 |
TravelMate
|
MIT License
|
uniko/src/main/java/com/mynus01/uniko/receiver/BaseReceiver.kt
|
mynus01
| 468,060,932 | false |
{"Kotlin": 21979}
|
package com.mynus01.uniko.receiver
import com.mynus01.uniko.extension.launch
import com.mynus01.uniko.action.InputAction
import com.mynus01.uniko.action.OutputAction
import com.mynus01.uniko.store.Store
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.reflect.KClass
open class BaseReceiver<I: InputAction, O: OutputAction>(
private val store: Store<I, O>,
private val coroutineDispatcher: CoroutineDispatcher = Dispatchers.Main
) : Receiver {
private val map: MutableMap<KClass<OutputAction>, MutableSharedFlow<OutputAction>> = mutableMapOf()
override suspend fun <T : OutputAction> observe(clazz: KClass<T>): SharedFlow<T>? {
clazz as KClass<OutputAction>
if (!map.containsKey(clazz)) {
map[clazz] = MutableSharedFlow()
}
launch(coroutineDispatcher) {
store.outputState.collect { action ->
if (action::class == clazz) {
map[clazz]?.emit(action)
}
}
}
return map[clazz]?.asSharedFlow() as? SharedFlow<T>?
}
}
| 1 |
Kotlin
|
0
| 1 |
998567d4a2908e2c857a0863a2069e5382eca196
| 1,095 |
uniko
|
MIT License
|
firearm-rpc/src/main/java/com/eaglesakura/firearm/rpc/service/BroadcastResult.kt
|
eaglesakura
| 244,919,501 | false | null |
@file:Suppress("MemberVisibilityCanBePrivate")
package com.eaglesakura.firearm.rpc.service
import android.os.Bundle
/**
* Service to all-client broadcast results.
*/
data class BroadcastResult(
val client: RemoteClient,
val result: Bundle?,
val error: Exception?
) {
/**
* Check success.
*/
val success: Boolean
get() = error != null
/**
* Check failed.
*/
val failed: Boolean
get() = !success
}
| 0 |
Kotlin
|
0
| 0 |
25db36e0fafa6061e88cf151840d3b6772b2747a
| 466 |
firearm-rpc
|
MIT License
|
wapp/src/main/java/com/example/wapp/demo/adapter/CollectUrlAdapter.kt
|
Asmewill
| 415,843,980 | false |
{"Kotlin": 1283329, "Java": 382535}
|
package com.example.wapp.demo.adapter
import android.text.TextUtils
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.wapp.R
import com.example.wapp.demo.bean.UrlBean
import com.example.wapp.demo.ext.setAdapterAnimation
import com.example.wapp.demo.widget.CollectView
/**
* Created by jsxiaoshui on 2021-10-22
*/
class CollectUrlAdapter():BaseQuickAdapter<UrlBean, BaseViewHolder>(R.layout.item_url) {
init {
this.setAdapterAnimation(2)
}
override fun convert(holder: BaseViewHolder, item: UrlBean) {
val tv_title=holder.getView<TextView>(R.id.tv_title)
val tv_url=holder.getView<TextView>(R.id.tv_url)
val cv_collect=holder.getView<CollectView>(R.id.cv_collect)
if(!TextUtils.isEmpty(item.name)){
tv_title.setText(item.name)
}
if(!TextUtils.isEmpty(item.link)){
tv_url.setText(item.link)
}
cv_collect.isChecked=true
}
}
| 0 |
Kotlin
|
0
| 0 |
eb98033b5f92b1ef363278f0031e117a0da1e455
| 1,054 |
JetpackMvvm
|
Apache License 2.0
|
Simple Search Engine/task/src/search/SearchStrategy.kt
|
Dimanaux
| 259,327,196 | false |
{"HTML": 16644, "Java": 13249, "Kotlin": 5716}
|
package search
enum class SearchStrategy {
ANY {
override fun find(query: Token, search: Search): Set<String> {
val hashSet = HashSet<String>()
query.keys.forEach { key ->
val found = search.find(key)
hashSet.addAll(found)
}
return hashSet
}
},
NONE {
override fun find(query: Token, search: Search): Set<String> {
val all = search.all()
val toExclude = ANY.find(query, search)
return all - toExclude
}
},
ALL {
override fun find(query: Token, search: Search): Set<String> {
val sets = query.keys.map { search.find(it) }
return sets.reduce { a, b -> a intersect b }
}
};
abstract fun find(query: Token, search: Search): Set<String>
fun find(query: String, search: Search): Set<String> = find(Token(query), search)
}
| 1 |
HTML
|
1
| 1 |
1c70f27405d5baf213a78bfaf72ceaa291cf9358
| 938 |
Simple-Search-Engine
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/oauth2server/security/NomisUserDetailsService.kt
|
uk-gov-mirror
| 356,783,105 | true |
{"Kotlin": 1669768, "HTML": 158306, "CSS": 9895, "Shell": 8311, "Mustache": 7004, "PLSQL": 6379, "TSQL": 1100, "Dockerfile": 1015, "Groovy": 780, "JavaScript": 439}
|
package uk.gov.justice.digital.hmpps.oauth2server.security
import com.microsoft.applicationinsights.TelemetryClient
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.oauth2server.service.MfaClientNetworkService
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
@Service("nomisUserDetailsService")
@Transactional(readOnly = true, noRollbackFor = [UsernameNotFoundException::class])
class NomisUserDetailsService(private val nomisUserService: NomisUserService) :
UserDetailsService, AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {
@PersistenceContext(unitName = "nomis")
private lateinit var nomisEntityManager: EntityManager
override fun loadUserByUsername(username: String): UserDetails {
val userPersonDetails =
nomisUserService.getNomisUserByUsername(username).orElseThrow { UsernameNotFoundException(username) }
// ensure that any changes to user details past this point are not persisted - e.g. by calling CredentialsContainer.eraseCredentials
nomisEntityManager.detach(userPersonDetails)
return userPersonDetails
}
override fun loadUserDetails(token: PreAuthenticatedAuthenticationToken): UserDetails = loadUserByUsername(token.name)
}
@Component
@Transactional(readOnly = true, noRollbackFor = [BadCredentialsException::class])
class NomisAuthenticationProvider(
nomisUserDetailsService: NomisUserDetailsService,
userRetriesService: UserRetriesService,
mfaClientNetworkService: MfaClientNetworkService,
userService: UserService,
telemetryClient: TelemetryClient,
) :
LockingAuthenticationProvider(nomisUserDetailsService, userRetriesService, mfaClientNetworkService, userService, telemetryClient)
| 0 |
Kotlin
|
0
| 0 |
f5a2a2f4eecc76459e206e7c84fde15d2c781758
| 2,332 |
ministryofjustice.hmpps-auth
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/oauth2server/security/NomisUserDetailsService.kt
|
uk-gov-mirror
| 356,783,105 | true |
{"Kotlin": 1669768, "HTML": 158306, "CSS": 9895, "Shell": 8311, "Mustache": 7004, "PLSQL": 6379, "TSQL": 1100, "Dockerfile": 1015, "Groovy": 780, "JavaScript": 439}
|
package uk.gov.justice.digital.hmpps.oauth2server.security
import com.microsoft.applicationinsights.TelemetryClient
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.oauth2server.service.MfaClientNetworkService
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
@Service("nomisUserDetailsService")
@Transactional(readOnly = true, noRollbackFor = [UsernameNotFoundException::class])
class NomisUserDetailsService(private val nomisUserService: NomisUserService) :
UserDetailsService, AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {
@PersistenceContext(unitName = "nomis")
private lateinit var nomisEntityManager: EntityManager
override fun loadUserByUsername(username: String): UserDetails {
val userPersonDetails =
nomisUserService.getNomisUserByUsername(username).orElseThrow { UsernameNotFoundException(username) }
// ensure that any changes to user details past this point are not persisted - e.g. by calling CredentialsContainer.eraseCredentials
nomisEntityManager.detach(userPersonDetails)
return userPersonDetails
}
override fun loadUserDetails(token: PreAuthenticatedAuthenticationToken): UserDetails = loadUserByUsername(token.name)
}
@Component
@Transactional(readOnly = true, noRollbackFor = [BadCredentialsException::class])
class NomisAuthenticationProvider(
nomisUserDetailsService: NomisUserDetailsService,
userRetriesService: UserRetriesService,
mfaClientNetworkService: MfaClientNetworkService,
userService: UserService,
telemetryClient: TelemetryClient,
) :
LockingAuthenticationProvider(nomisUserDetailsService, userRetriesService, mfaClientNetworkService, userService, telemetryClient)
| 0 |
Kotlin
|
0
| 0 |
f5a2a2f4eecc76459e206e7c84fde15d2c781758
| 2,332 |
ministryofjustice.hmpps-auth
|
MIT License
|
hideout-core/src/main/kotlin/dev/usbharu/hideout/core/external/job/ReceiveFollowTask.kt
|
usbharu
| 627,026,893 | false |
{"Kotlin": 1472831, "Mustache": 111614, "Gherkin": 21440, "JavaScript": 1112, "HTML": 936}
|
/*
* Copyright (C) 2024 usbharu
*
* 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.usbharu.hideout.core.external.job
import dev.usbharu.hideout.activitypub.domain.model.Follow
import dev.usbharu.owl.common.property.ObjectPropertyValue
import dev.usbharu.owl.common.property.PropertyValue
import dev.usbharu.owl.common.property.StringPropertyValue
import dev.usbharu.owl.common.task.Task
import dev.usbharu.owl.common.task.TaskDefinition
import org.springframework.stereotype.Component
data class ReceiveFollowTask(
val actor: String,
val follow: Follow,
val targetActor: String,
) : Task()
@Component
data object ReceiveFollowTaskDef : TaskDefinition<ReceiveFollowTask> {
override val type: Class<ReceiveFollowTask>
get() = ReceiveFollowTask::class.java
override fun serialize(task: ReceiveFollowTask): Map<String, PropertyValue<*>> {
return mapOf(
"actor" to StringPropertyValue(task.actor),
"follow" to ObjectPropertyValue(task.follow),
"targetActor" to StringPropertyValue(task.targetActor)
)
}
override fun deserialize(value: Map<String, PropertyValue<*>>): ReceiveFollowTask {
return ReceiveFollowTask(
value.getValue("actor").value as String,
value.getValue("follow").value as Follow,
value.getValue("targetActor").value as String,
)
}
}
| 40 |
Kotlin
|
0
| 11 |
2be6c182cedfe9d2fb033b82ebf490ac306daef2
| 1,919 |
Hideout
|
Apache License 2.0
|
app/src/main/java/io/github/maximmaxims/tsdbmobile/EpisodeActivity.kt
|
MaximMaximS
| 576,936,140 | false | null |
package io.github.maximmaxims.tsdbmobile
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.switchmaterial.SwitchMaterial
import io.github.maximmaxims.tsdbmobile.classes.Episode
import io.github.maximmaxims.tsdbmobile.classes.TSDBAPI
import io.github.maximmaxims.tsdbmobile.exceptions.TSDBException
import io.github.maximmaxims.tsdbmobile.exceptions.UserException
import io.github.maximmaxims.tsdbmobile.utils.ErrorType
import io.github.maximmaxims.tsdbmobile.utils.ErrorUtil
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
class EpisodeActivity : AppCompatActivity() {
private var episode: Episode? = null
companion object {
const val EPISODE_ID = "io.github.maximmaxims.tsdbmobile.EPISODE_ID"
}
private lateinit var watchedSwitch: SwitchMaterial
private lateinit var detailsButton: Button
private lateinit var prevButton: Button
private lateinit var nextButton: Button
private lateinit var progressBar: LinearProgressIndicator
private lateinit var titleTextView: TextView
private lateinit var premiereTextView: TextView
private lateinit var directedByTextView: TextView
private lateinit var writtenByTextView: TextView
private lateinit var episodeIdTextView: TextView
private fun loading(state: Boolean) {
val valid = episode != null && !state
runOnUiThread {
watchedSwitch.isEnabled = valid
detailsButton.isEnabled = valid
prevButton.isEnabled = valid
nextButton.isEnabled = valid
progressBar.visibility = if (state) LinearProgressIndicator.VISIBLE else LinearProgressIndicator.INVISIBLE
}
}
private fun updateView(newId: UInt, view: View) {
try {
loading(true)
val api = TSDBAPI.getInstance(this) ?: throw UserException(ErrorType.INVALID_URL)
api.getEpisode(newId, onSuccess = { episode ->
this.episode = episode
loading(false)
val instant = episode.premiere
runOnUiThread {
titleTextView.text = episode.title
premiereTextView.text =
instant.atZone(ZoneId.of("UTC"))
.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
directedByTextView.text = episode.directedBy
writtenByTextView.text = episode.writtenBy
watchedSwitch.isChecked = episode.watched
episodeIdTextView.text = episode.id.toString()
prevButton.isEnabled = episode.id != 1u
}
}, e = { e ->
loading(false)
ErrorUtil.showSnackbar(e, view)
})
} catch (e: TSDBException) {
loading(false)
ErrorUtil.showSnackbar(e, view)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_episode)
watchedSwitch = findViewById(R.id.watchedSwitch)
detailsButton = findViewById(R.id.plotButton)
prevButton = findViewById(R.id.prevButton)
nextButton = findViewById(R.id.nextButton)
progressBar = findViewById(R.id.progressBar)
titleTextView = findViewById(R.id.titleTextView)
premiereTextView = findViewById(R.id.premiereTextView)
directedByTextView = findViewById(R.id.directedByTextView)
writtenByTextView = findViewById(R.id.writtenByTextView)
episodeIdTextView = findViewById(R.id.episodeIdTextView)
updateView(intent.getIntExtra(EPISODE_ID, 0).toUInt(), progressBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
fun nextEpisode(view: View) {
val id = episode?.id ?: return
updateView(id + 1u, view)
}
fun prevEpisode(view: View) {
val id = episode?.id ?: return
if (id == 1u) return
updateView(id - 1u, view)
}
fun markEpisode(view: View) {
val episode = episode ?: return
val value = watchedSwitch.isChecked
if (episode.watched == value) return
try {
loading(true)
val api = TSDBAPI.getInstance(this) ?: throw UserException(ErrorType.INVALID_URL)
api.markEpisode(episode.id, value, onSuccess = {
updateView(episode.id, view)
}, e = { e ->
runOnUiThread {
watchedSwitch.isChecked = episode.watched
}
loading(false)
ErrorUtil.showSnackbar(e, view)
})
} catch (e: TSDBException) {
watchedSwitch.isChecked = episode.watched
loading(false)
ErrorUtil.showSnackbar(e, view)
}
}
fun showPlot(view: View) {
val episode = episode
val plot = episode?.plot
if (plot.isNullOrEmpty() || plot == "N/A") {
ErrorUtil.showSnackbar(UserException(ErrorType.NO_PLOT), view)
return
}
val intent = Intent(this, PlotActivity::class.java)
intent.putExtra(PlotActivity.PLOT, plot)
intent.putExtra(PlotActivity.TITLE, episode.title)
startActivity(intent)
}
}
| 0 |
Kotlin
|
0
| 0 |
fd5e06360f620f461c0b751daba9121fd0b5881a
| 5,840 |
TSDBMobile
|
MIT No Attribution
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.