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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
KotlinBasics/Tasklist/JsonSaver.kt | Tsyshnatiy | 561,408,519 | false | {"Kotlin": 64886, "JavaScript": 3306, "CSS": 1632, "HTML": 726} | package tasklist
import com.squareup.moshi.*
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import java.io.File
class JsonSerializer {
private val moshi: Moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val filename = "tasklist.json"
private val listTask = Types.newParameterizedType(List::class.java, Task::class.java)
private val jsonAdapter = moshi.adapter<List<Task>>(listTask)
fun save(tasks: List<Task>) {
val result = jsonAdapter.toJson(tasks)
val file = File(filename)
file.writeText(result)
}
fun load(): List<Task> {
val file = File(filename)
if (!file.exists()) {
return listOf()
}
val json = file.readText()
return jsonAdapter.fromJson(json) ?: return listOf()
}
} | 0 | Kotlin | 0 | 0 | 5c3ef96cca79e51cc8bc3f65cad6086e0c99ea2d | 849 | JetBrainsCourses | Apache License 2.0 |
rubik/rubik_plugins/src/main/java/com/rubik/plugins/shell/ShellPlugin.kt | baidu | 504,447,693 | false | {"Kotlin": 607049, "Java": 37304} | /**
* Copyright (C) Baidu Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rubik.plugins.shell
import com.ktnail.gradle.androidExtension
import com.ktnail.gradle.p
import com.ktnail.gradle.propertyOr
import com.ktnail.x.Logger
import com.rubik.pick.shellPackingLibWhat
import com.rubik.plugins.RubikPlugin
import com.rubik.plugins.basic.LogTags
import com.rubik.context.Ext
import com.rubik.plugins.basic.extra.addRubikRouterDependency
import com.rubik.picker.ContextPicker
import com.rubik.picker.extra.pickedContextsContainer
import com.rubik.plugins.shell.checker.context.CheckContextVersionTransform
import com.rubik.plugins.shell.checker.router.CheckRouterVersionTransform
import com.rubik.plugins.shell.controller.ShellConfigGeneratingController
import com.rubik.plugins.shell.controller.ShellSourceGeneratingController
import org.gradle.api.Project
/**
* The the plugin of rubik shell project (application).
* Provide the ability to pick contexts.
*
* @ Since:1.5
*/
class ShellPlugin : RubikPlugin() {
private val picker: ContextPicker by lazy { ContextPicker() }
override fun apply(project: Project) {
super.apply(project)
// project.fuzzyApplyRubikConfigFiles(project.projectDir)
ShellSourceGeneratingController(project).createTasks()
ShellConfigGeneratingController(project).createTasks()
project.afterEvaluate {
doPickContexts()
project.addRubikRouterDependency()
}
if (project.propertyOr(Ext.RUBIK_ENABLE_CHECK_ROUTER_VERSION, false) && CheckRouterVersionTransform.RULES.isNotEmpty()) {
Logger.p(LogTags.CHECK_CLASS, project) { " CHECK_ROUTER_VERSION enable ! " }
project.androidExtension?.registerTransform(CheckRouterVersionTransform(project))
}
if (project.propertyOr(Ext.RUBIK_ENABLE_CHECK_CONTEXT_VERSION, false) && CheckContextVersionTransform.RULES.isNotEmpty()) {
Logger.p(LogTags.CHECK_CLASS, project) { " CHECK_CONTEXT_VERSION enable ! " }
project.androidExtension?.registerTransform(CheckContextVersionTransform(project))
}
}
private fun doPickContexts() {
Logger.p(LogTags.DO_PICK, project) { " SHELL PICK COMPONENT :" }
picker.pick(pickedContextsContainer.pickCases(), project)
Logger.p(LogTags.DO_PICK, project) { " SHELL PICK CONTEXT LIBS :" }
picker.pick(shellPackingLibWhat(), project)
}
}
| 1 | Kotlin | 7 | 153 | 065ba8f4652b39ff558a5e3f18b9893e2cf9bd25 | 2,997 | Rubik | Apache License 2.0 |
src/commonMain/kotlin/main.kt | kriksD | 529,301,545 | false | null | import com.soywiz.korge.*
import com.soywiz.korge.scene.*
import com.soywiz.korim.color.*
import com.soywiz.korinject.*
import com.soywiz.korma.geom.*
import kotlin.reflect.*
suspend fun main() = Korge(Korge.Config(module = MainModule))
object MainModule : Module() {
override val bgcolor: RGBA = Colors["#0e5c60"]
override val mainScene: KClass<out Scene> = MenuScene::class
override val size = SizeInt(1000, 600)
override val windowSize = SizeInt(1000, 600)
override suspend fun AsyncInjector.configure() {
mapPrototype { PlayScene(get()) }
mapPrototype { MenuScene() }
}
}
| 0 | Kotlin | 0 | 0 | cf7835f715d10f40d5699cf231de023be03ebc68 | 619 | KorGE-test-game2 | MIT License |
core/src/main/kotlin/materialui/components/buttongroup/buttongroup.kt | chadmorrow | 254,712,121 | true | {"Kotlin": 344112} | package materialui.components.buttongroup
import kotlinx.html.DIV
import kotlinx.html.Tag
import kotlinx.html.TagConsumer
import materialui.components.StandardProps
import materialui.components.buttongroup.enums.ButtonGroupStyle
import org.w3c.dom.events.Event
import react.RBuilder
import react.RClass
import react.RProps
@JsModule("@material-ui/core/ButtonGroup")
private external val buttonGroupModule: dynamic
external interface ButtonGroupProps : StandardProps {
var color: String?
var disabled: Boolean?
var disableRipple: Boolean?
var disableTouchRipple: Boolean?
var fullWidth: Boolean?
var orientation: String?
var size: String?
var variant: String?
}
@Suppress("UnsafeCastFromDynamic")
private val buttonGroupComponent: RClass<ButtonGroupProps> = buttonGroupModule.default
fun RBuilder.buttonGroup(vararg classMap: Pair<ButtonGroupStyle, String>, block: ButtonGroupElementBuilder<DIV>.() -> Unit)
= child(ButtonGroupElementBuilder(buttonGroupComponent, classMap.toList()) { DIV(mapOf(), it) }.apply(block).create())
fun <T: Tag> RBuilder.buttonGroup(vararg classMap: Pair<ButtonGroupStyle, String>, factory: (TagConsumer<Unit>) -> T, block: ButtonGroupElementBuilder<T>.() -> Unit)
= child(ButtonGroupElementBuilder(buttonGroupComponent, classMap.toList(), factory).apply(block).create())
| 0 | null | 0 | 0 | ecc09e857677d20e967005370643fd7b8ba95d24 | 1,346 | kotlin-material-ui | MIT License |
kotlin/src/test/java/com/kevinmost/lifx/kt/BaseLifxTest.kt | mbStavola | 76,759,790 | true | {"INI": 1, "YAML": 1, "Gradle": 4, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "XML": 7, "Java Properties": 1, "Kotlin": 5, "Java": 31} | package com.kevinmost.lifx.kt
import com.kevinmost.lifx.EnvVar
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.junit.Before
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
abstract class BaseLifxTest {
val logger: Logger = LoggerFactory.getLogger(javaClass);
@Before fun setupLifxClient() {
lifxClient(
EnvVar.LIFX_ACCESS_TOKEN.value()!!,
OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(HttpLoggingInterceptor { message -> logger.warn(message) })
.build()
).buildAsDefault()
}
} | 0 | Java | 0 | 0 | d6a3137748fccb28d8b8f3788a938cd03d14050c | 752 | lifx-java | Apache License 2.0 |
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/SmileUpside.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36756847} | package compose.icons.cssggicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 compose.icons.CssGgIcons
public val CssGgIcons.SmileUpside: ImageVector
get() {
if (_smileUpside != null) {
return _smileUpside!!
}
_smileUpside = Builder(name = "SmileUpside", 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) {
moveTo(16.0f, 11.0f)
horizontalLineTo(14.0f)
curveTo(14.0f, 9.8954f, 13.1046f, 9.0f, 12.0f, 9.0f)
curveTo(10.8954f, 9.0f, 10.0f, 9.8954f, 10.0f, 11.0f)
horizontalLineTo(8.0f)
curveTo(8.0f, 8.7909f, 9.7909f, 7.0f, 12.0f, 7.0f)
curveTo(14.2091f, 7.0f, 16.0f, 8.7909f, 16.0f, 11.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.0f, 14.0f)
curveTo(10.0f, 13.4477f, 9.5523f, 13.0f, 9.0f, 13.0f)
curveTo(8.4477f, 13.0f, 8.0f, 13.4477f, 8.0f, 14.0f)
curveTo(8.0f, 14.5523f, 8.4477f, 15.0f, 9.0f, 15.0f)
curveTo(9.5523f, 15.0f, 10.0f, 14.5523f, 10.0f, 14.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.0f, 13.0f)
curveTo(15.5523f, 13.0f, 16.0f, 13.4477f, 16.0f, 14.0f)
curveTo(16.0f, 14.5523f, 15.5523f, 15.0f, 15.0f, 15.0f)
curveTo(14.4477f, 15.0f, 14.0f, 14.5523f, 14.0f, 14.0f)
curveTo(14.0f, 13.4477f, 14.4477f, 13.0f, 15.0f, 13.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(22.0f, 12.0f)
curveTo(22.0f, 6.4771f, 17.5228f, 2.0f, 12.0f, 2.0f)
curveTo(6.4771f, 2.0f, 2.0f, 6.4771f, 2.0f, 12.0f)
curveTo(2.0f, 17.5228f, 6.4771f, 22.0f, 12.0f, 22.0f)
curveTo(17.5228f, 22.0f, 22.0f, 17.5228f, 22.0f, 12.0f)
close()
moveTo(20.0f, 12.0f)
curveTo(20.0f, 7.5817f, 16.4183f, 4.0f, 12.0f, 4.0f)
curveTo(7.5817f, 4.0f, 4.0f, 7.5817f, 4.0f, 12.0f)
curveTo(4.0f, 16.4183f, 7.5817f, 20.0f, 12.0f, 20.0f)
curveTo(16.4183f, 20.0f, 20.0f, 16.4183f, 20.0f, 12.0f)
close()
}
}
.build()
return _smileUpside!!
}
private var _smileUpside: ImageVector? = null
| 15 | Kotlin | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 3,938 | compose-icons | MIT License |
src/main/kotlin/com/github/alikemalocalan/greentunnel4jvm/utils/HttpServiceUtils.kt | casebell | 263,804,808 | true | {"Kotlin": 13637, "Dockerfile": 16} | package com.github.alikemalocalan.greentunnel4jvm.utils
import arrow.core.*
import arrow.core.extensions.fx
import com.github.alikemalocalan.greentunnel4jvm.models.HttpRequest
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.util.concurrent.GenericFutureListener
import java.net.URI
import java.nio.charset.Charset
object HttpServiceUtils {
private const val clientHelloMTU: Int = 64
private fun readMainPart(buf: ByteBuf): String {
val lineBuf = StringBuffer()
fun readByteBuf(isReadable: Boolean, result: Option<String>): Option<String> {
return if (isReadable) {
val b: Byte = buf.readByte()
lineBuf.append(b.toChar())
val len: Int = lineBuf.length
return if (len >= 2 && lineBuf.substring(len - 2).equals("\r\n")) {
readByteBuf(isReadable = false, result = Some(lineBuf.substring(0, len - 2)))
} else readByteBuf(buf.isReadable, None)
} else result
}
return readByteBuf(buf.isReadable, None)
.getOrElse {
buf.release()
""
}
}
fun fromByteBuf(buf: ByteBuf): Option<HttpRequest> {
val chunky = readMainPart(buf)
return if (chunky.isEmpty()) None
else Some(parseByteBuf(chunky, buf))
}
private fun parseByteBuf(chunky: String, buf: ByteBuf): HttpRequest {
val firstLine = chunky.split(" ")
val method = firstLine[0]
val host = firstLine[1].toLowerCase()
val protocolVersion = firstLine[2]
return if (method.toUpperCase().startsWith("CONNECT")) { // Https request
val uri = if (host.startsWith("https://")) URI(host) else URI("https://$host")
val port = Either.fx<Exception, Int> { uri.port }.toOption().filter { n -> n != -1 }.getOrElse { 443 }
HttpRequest(method, uri, port = port, protocolVersion = protocolVersion, isHttps = true)
} else { // Http request
val uri = if (host.startsWith("http://")) URI(host) else URI("http://$host")
val port = Either.fx<Exception, Int> { uri.port }.toOption().filter { n -> n != -1 }.getOrElse { 80 }
val reqAsString: String = buf.asReadOnly().toString(Charset.defaultCharset())
val mainPart = reqAsString.split("\r\n\r\n") // until payload
val headerLines = mainPart.first().split("\r\n") // for headers
val payLoad = if (mainPart.size == 2) mainPart[1] else ""
val headers: List<Pair<String, String>> = headerLines
.map { h ->
val arr = h.split(":")
(arr[0] to arr[1])
}.toList().distinct()
.filterNot { k -> k.first == "Proxy-Connection" || k.first == "Via" }
return HttpRequest(
method,
uri,
protocolVersion,
port,
isHttps = false,
headers = Some(headers),
payload = Some(payLoad)
)
}
}
fun writeToHttps(buf: ByteBuf, remoteChannel: Channel): Unit {
if (buf.isReadable) {
val bufSize: Int = if (buf.readableBytes() > clientHelloMTU) clientHelloMTU else buf.readableBytes()
remoteChannel.writeAndFlush(buf.readSlice(bufSize).retain())
.addListener(GenericFutureListener { future: ChannelFuture ->
if (future.isSuccess) remoteChannel.read()
else future.channel().close()
})
writeToHttps(buf, remoteChannel)
}
}
fun closeOnFlush(ch: Channel) {
if (ch.isActive) ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE)
}
} | 0 | null | 0 | 0 | b037598790935c9d5c318d9a9fbe3a721993e09c | 3,959 | greentunnel4jvm | MIT License |
src/main/kotlin/com/vengateshm/entities/Users.kt | vengateshm | 426,101,996 | false | {"Kotlin": 14190} | package com.vengateshm.entities
import org.ktorm.schema.Table
import org.ktorm.schema.int
import org.ktorm.schema.varchar
object Users : Table<Nothing>("users") {
val id = int("id").primaryKey()
val username = varchar("username")
val password = varchar("<PASSWORD>")
} | 0 | Kotlin | 0 | 0 | 0f6b01fdb2197710e43edf9c8923c8c235d5e7ab | 306 | ktor_notes_app_REST_API | Apache License 2.0 |
spesialist-selve/src/main/kotlin/no/nav/helse/modell/kommando/TilbakedateringBehandlet.kt | navikt | 244,907,980 | false | {"Kotlin": 2818632, "PLpgSQL": 29687, "HTML": 1741, "Dockerfile": 258} | package no.nav.helse.modell.kommando
import com.fasterxml.jackson.databind.JsonNode
import no.nav.helse.mediator.GodkjenningMediator
import no.nav.helse.mediator.Kommandostarter
import no.nav.helse.mediator.meldinger.Personmelding
import no.nav.helse.mediator.oppgave.OppgaveService
import no.nav.helse.modell.automatisering.Automatisering
import no.nav.helse.modell.automatisering.AutomatiseringForEksisterendeOppgaveCommand
import no.nav.helse.modell.automatisering.SettTidligereAutomatiseringInaktivCommand
import no.nav.helse.modell.gosysoppgaver.OppgaveDataForAutomatisering
import no.nav.helse.modell.person.Person
import no.nav.helse.modell.sykefraværstilfelle.Sykefraværstilfelle
import no.nav.helse.modell.utbetaling.Utbetaling
import no.nav.helse.modell.vedtaksperiode.Periode
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.asLocalDate
import java.util.UUID
internal class TilbakedateringBehandlet private constructor(
override val id: UUID,
private val fødselsnummer: String,
val perioder: List<Periode>,
private val json: String,
) : Personmelding {
internal constructor(packet: JsonMessage) : this(
id = UUID.fromString(packet["@id"].asText()),
fødselsnummer = packet["fødselsnummer"].asText(),
perioder =
packet["perioder"].map {
Periode(it["fom"].asLocalDate(), it["tom"].asLocalDate())
},
json = packet.toJson(),
)
internal constructor(jsonNode: JsonNode) : this(
id = UUID.fromString(jsonNode["@id"].asText()),
fødselsnummer = jsonNode["fødselsnummer"].asText(),
perioder =
jsonNode["perioder"].map {
Periode(it["fom"].asLocalDate(), it["tom"].asLocalDate())
},
json = jsonNode.toString(),
)
override fun behandle(
person: Person,
kommandostarter: Kommandostarter,
) {
person.behandleTilbakedateringBehandlet(perioder)
kommandostarter {
val oppgaveDataForAutomatisering = finnOppgavedata(fødselsnummer) ?: return@kommandostarter null
tilbakedateringGodkjent(this@TilbakedateringBehandlet, person, oppgaveDataForAutomatisering)
}
}
override fun fødselsnummer() = fødselsnummer
override fun toJson(): String = json
}
internal class TilbakedateringGodkjentCommand(
fødselsnummer: String,
sykefraværstilfelle: Sykefraværstilfelle,
utbetaling: Utbetaling,
automatisering: Automatisering,
oppgaveDataForAutomatisering: OppgaveDataForAutomatisering,
oppgaveService: OppgaveService,
godkjenningMediator: GodkjenningMediator,
spleisBehandlingId: UUID?,
organisasjonsnummer: String,
søknadsperioder: List<Periode>,
) : MacroCommand() {
override val commands: List<Command> =
listOf(
VurderOmSøknadsperiodenOverlapperMedOppgave(oppgaveDataForAutomatisering, søknadsperioder),
ikkesuspenderendeCommand("fjernTilbakedatertEgenskap") {
oppgaveService.fjernTilbakedatert(oppgaveDataForAutomatisering.vedtaksperiodeId)
},
SettTidligereAutomatiseringInaktivCommand(
vedtaksperiodeId = oppgaveDataForAutomatisering.vedtaksperiodeId,
hendelseId = oppgaveDataForAutomatisering.hendelseId,
automatisering = automatisering,
),
AutomatiseringForEksisterendeOppgaveCommand(
fødselsnummer = fødselsnummer,
vedtaksperiodeId = oppgaveDataForAutomatisering.vedtaksperiodeId,
hendelseId = oppgaveDataForAutomatisering.hendelseId,
automatisering = automatisering,
godkjenningsbehovJson = oppgaveDataForAutomatisering.godkjenningsbehovJson,
godkjenningMediator = godkjenningMediator,
oppgaveService = oppgaveService,
utbetaling = utbetaling,
periodetype = oppgaveDataForAutomatisering.periodetype,
sykefraværstilfelle = sykefraværstilfelle,
spleisBehandlingId = spleisBehandlingId,
organisasjonsnummer = organisasjonsnummer,
),
)
}
| 1 | Kotlin | 3 | 0 | 85cee4011126da24ec113b7f9a52baba808a107d | 4,217 | helse-spesialist | MIT License |
solar/src/main/java/com/chiksmedina/solar/bold/essentionalui/HomeAngle.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.essentionalui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 com.chiksmedina.solar.bold.EssentionalUiGroup
val EssentionalUiGroup.HomeAngle: ImageVector
get() {
if (_homeAngle != null) {
return _homeAngle!!
}
_homeAngle = Builder(
name = "HomeAngle", 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 = EvenOdd
) {
moveTo(2.3354f, 7.8749f)
curveTo(1.7949f, 9.0023f, 1.9846f, 10.3208f, 2.3641f, 12.9579f)
lineTo(2.6428f, 14.8952f)
curveTo(3.1302f, 18.2827f, 3.374f, 19.9764f, 4.549f, 20.9882f)
curveTo(5.7241f, 22.0f, 7.4474f, 22.0f, 10.8939f, 22.0f)
horizontalLineTo(13.1061f)
curveTo(16.5526f, 22.0f, 18.2759f, 22.0f, 19.451f, 20.9882f)
curveTo(20.626f, 19.9764f, 20.8697f, 18.2827f, 21.3572f, 14.8952f)
lineTo(21.6359f, 12.9579f)
curveTo(22.0154f, 10.3208f, 22.2051f, 9.0023f, 21.6646f, 7.8749f)
curveTo(21.1242f, 6.7476f, 19.9738f, 6.0623f, 17.6731f, 4.6918f)
lineTo(16.2882f, 3.8669f)
curveTo(14.199f, 2.6223f, 13.1543f, 2.0f, 12.0f, 2.0f)
curveTo(10.8457f, 2.0f, 9.801f, 2.6223f, 7.7118f, 3.8669f)
lineTo(6.3269f, 4.6918f)
curveTo(4.0262f, 6.0623f, 2.8758f, 6.7476f, 2.3354f, 7.8749f)
close()
moveTo(8.2501f, 17.9998f)
curveTo(8.2501f, 17.5856f, 8.5859f, 17.2498f, 9.0001f, 17.2498f)
horizontalLineTo(15.0001f)
curveTo(15.4143f, 17.2498f, 15.7501f, 17.5856f, 15.7501f, 17.9998f)
curveTo(15.7501f, 18.414f, 15.4143f, 18.7498f, 15.0001f, 18.7498f)
horizontalLineTo(9.0001f)
curveTo(8.5859f, 18.7498f, 8.2501f, 18.414f, 8.2501f, 17.9998f)
close()
}
}
.build()
return _homeAngle!!
}
private var _homeAngle: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 2,816 | SolarIconSetAndroid | MIT License |
src/book/Book.kt | informramiz | 134,051,168 | false | {"Kotlin": 14872} | package book
open class Book(val title: String, val author: String) {
private var currentPage = 0;
open fun readPage() {
currentPage++
}
}
class eBook(title: String, author: String, val format: String = "text"): Book(title, author) {
private var wordCount = 0;
override fun readPage() {
wordCount += 250
}
} | 0 | Kotlin | 0 | 0 | 9cc1ea758015c98e735841f32b39db00a9aa17cd | 351 | kotlin-bootcamp | Apache License 2.0 |
src/main/kotlin/com/skillw/asahi/core/parser/prefix/Lang.kt | Skillw | 583,251,101 | false | {"Kotlin": 94989, "Java": 4431} | package com.skillw.asahi.core.parser.prefix
import com.skillw.asahi.api.annotation.AsahiMember
import com.skillw.asahi.api.member.ast.expr.Block
import com.skillw.asahi.api.member.ast.expr.DefFunction
import com.skillw.asahi.api.member.ast.expr.DefVar
import com.skillw.asahi.api.member.ast.expr.Sized
import com.skillw.asahi.api.member.ast.expr.compound.Unary
import com.skillw.asahi.api.member.ast.expr.compound.unary
import com.skillw.asahi.api.member.ast.parse
import com.skillw.asahi.api.member.runtime.Var
import com.skillw.asahi.api.member.runtime.obj.AsahiObject
import com.skillw.asahi.api.member.runtime.obj.basic.Function
import com.skillw.asahi.api.member.runtime.obj.basic.NumberObj
import com.skillw.asahi.api.member.runtime.obj.basic.StringObj
import com.skillw.asahi.api.member.tokenizer.ITokenStream.Companion.currentToken
import com.skillw.asahi.api.member.tokenizer.ITokenStream.Companion.nextToken
import com.skillw.asahi.api.member.tokenizer.TokenType
import com.skillw.asahi.api.member.tokenizer.source.NoSource
import com.skillw.asahi.api.member.tokenizer.tokens.CallVar
import com.skillw.asahi.api.member.tokenizer.tokens.Literal
import com.skillw.asahi.api.member.tokenizer.tokens.Number
import com.skillw.asahi.api.member.util.prefix
/**
* @className Lang
*
* @author Glom
* @date 2023/8/13 13:39 Copyright 2023 user. All rights reserved.
*/
//@AsahiMember(type = TokenType.CallVar)
//private fun callVar() = prefix {
// parser {
// val token = currentToken<CallVar>()
// unary(token, token.key.toSized())
// }
//
// evaluator<Unary> {
// variables()[it.right.eval()]
// }
//}
@AsahiMember
private fun number() = prefix {
parser(type = TokenType.Number) {
val token = currentToken<Number>()
NumberObj(token.number, source())
}
evaluator(NumberObj::class.java) {
it.eval()
}
}
@AsahiMember
private fun left() = prefix {
parser(type = TokenType.LBracket) {
parse(0).also { next() }
}
parser(type = TokenType.LeftBrace) {
parse(0).also { next() }
}
}
@AsahiMember
private fun define() = prefix {
parser(type = TokenType.Define) {
val source = source()
val key = nextToken<Literal>().string
if (expectSafely(TokenType.LBracket)) {
val params = ArrayList<String>()
while (!expectSafely(TokenType.RBracket)) {
params.add(nextToken<Literal>().string)
expectSafely(TokenType.Comma)
}
val body = Block(parse(), source())
DefFunction(key, params.toTypedArray(), body, source)
} else {
expect(TokenType.Assign)
val value = parse()
DefVar(key, value, source)
}
}
evaluator(DefFunction::class.java) {
val name = it.name
val params = it.params
val body = it.body
val function = Function(name, params = params, body = body, this)
addFunction(function)
function
}
evaluator(DefVar::class.java) {
val name = it.name
val value = it.value.eval<AsahiObject>()
val variable = Var(name, value)
variables()[name] = variable
variable
}
}
@AsahiMember
private fun callVar() = prefix {
parser(type = TokenType.CallVar) {
val token = currentToken<CallVar>()
unary(token, token.key.toSized())
}
evaluator<Unary>(type = TokenType.CallVar) {
val name = (it.right as Sized).eval().toString()
variables()[name] ?: StringObj("\$$name", NoSource)
}
}
// val params = ArrayList<Expression<out Any?>>()
// while (!expectSafely(TokenType.RBracket)) {
// params.add(parse())
// expectSafely(TokenType.Comma)
// }
// InvokeFunc(left.eval(), params.then { it.map { state -> state.eval() }.toTypedArray() }, source()) | 0 | Kotlin | 1 | 7 | a78bce9a19c066bd318ec81450fdfdd7dccfc831 | 3,876 | Asahi | Creative Commons Zero v1.0 Universal |
app/src/main/java/io/github/joaogouveia89/checkmarket/marketList/presentation/MarketListScreen.kt | joaogouveia89 | 842,192,758 | false | {"Kotlin": 143810} | package io.github.joaogouveia89.checkmarket.marketList.presentation
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import io.github.joaogouveia89.checkmarket.R
import io.github.joaogouveia89.checkmarket.core.model.MarketItemCategory
import io.github.joaogouveia89.checkmarket.core.presentation.topBars.CheckMarketAppBar
import io.github.joaogouveia89.checkmarket.marketList.presentation.components.MarketListContent
import io.github.joaogouveia89.checkmarket.marketList.presentation.state.MarketListUiState
@Composable
fun MarketListScreen(
uiState: MarketListUiState,
onMarketListItemClick: (MarketItemCategory, itemIndex: Int) -> Unit,
onNavigateToAddMarketItemClick: () -> Unit
) {
Scaffold(
topBar = {
CheckMarketAppBar(
title = R.string.market_list_title
)
}
) { paddingValues ->
MarketListContent(
modifier = Modifier
.fillMaxSize(),
marketItemsList = uiState.items,
isLoading = uiState.isLoading,
paddingValues = paddingValues,
onItemClick = onMarketListItemClick,
onNavigateToAddMarketItemClick = onNavigateToAddMarketItemClick
)
}
}
@Preview
@Composable
private fun MarketListScreenPreview() {
MarketListScreen(
uiState = MarketListUiState(),
onMarketListItemClick = {_, _ -> },
onNavigateToAddMarketItemClick = {}
)
} | 0 | Kotlin | 0 | 0 | 7f5849b6b729e8b05dc0f51d451dfe66c72b574b | 1,628 | CheckMarket | MIT License |
presentation/src/main/java/com/mikhaellopez/presentation/scenes/cardlist/CardListViewModel.kt | lopspower | 522,617,808 | false | {"Kotlin": 168656, "Java": 749} | package com.mikhaellopez.presentation.scenes.cardlist
import com.mikhaellopez.domain.model.Card
import com.mikhaellopez.domain.usecases.CheckCard
import com.mikhaellopez.domain.usecases.GetListCard
import com.mikhaellopez.domain.usecases.RefreshListCard
import com.mikhaellopez.presentation.exception.ErrorMessageFactory
import com.mikhaellopez.presentation.scenes.base.BaseViewModel
import com.mikhaellopez.ui.state.UiState
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flatMapLatest
import kotlin.coroutines.CoroutineContext
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
class CardListViewModel(
private val getListCard: GetListCard,
private val refreshListCard: RefreshListCard,
private val checkCard: CheckCard,
context: CoroutineContext,
errorMessageFactory: ErrorMessageFactory
) : BaseViewModel<CardListView>(context, errorMessageFactory) {
override fun attach(view: CardListView) {
super.attach(view)
val loadData = view.intentLoadData().flatMapConcat { loadData() }
val refresh = view.uiStateFlow.filterData<List<Card>>()
.flatMapLatest { previousData: List<Card> ->
view.intentRefreshData()
.flatMapConcat { refresh(previousData) }
}
val retry = view.uiStateFlow.filterError()
.flatMapLatest { previousErrorMessage ->
view.intentErrorRetry().flatMapConcat { retry(previousErrorMessage) }
}
val check = view.intentCheck()
.flatMapConcat { check(it) }
subscribeUiState(view, loadData, retry, refresh, check)
}
//region USE CASES TO UI STATE
private suspend fun loadData(): Flow<UiState> =
getListCard.execute(Unit).asResult()
private suspend fun refresh(
previousData: List<Card>
): Flow<UiState> =
refreshListCard.execute(Unit).asRefresh(previousData)
private suspend fun retry(
previousErrorMessage: String
): Flow<UiState> =
getListCard.execute(Unit).asRetry(previousErrorMessage)
private suspend fun check(card: Card): Flow<UiState> =
checkCard.execute(card)
.flatMapConcat { getListCard.execute(Unit) }
.asResult(withLoading = false)
//endregion
}
| 0 | Kotlin | 6 | 111 | ce41ce693cdb09facc455224b8af8fedcff74ad1 | 2,432 | PokeCardCompose | Apache License 2.0 |
hacker-tools/src/commonMain/kotlin/tech/lhzmrl/multi/hacker/netease/model/request/WebLogRequest.kt | lhzmrl | 266,673,231 | false | {"Kotlin": 22742} | package tech.lhzmrl.multi.hacker.netease.model.request
import kotlinx.serialization.Serializable
@Serializable
class WebLogRequest {
var logs: String? = null
} | 0 | Kotlin | 0 | 0 | a194ddd49610a15a4c87d980e8b3e1662c49fc69 | 165 | HackerTools | MIT License |
ktx/src/main/java/com/kotlin/android/ktx/ext/span/SpanExt.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.ktx.ext.span
import android.R
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.*
import android.text.style.*
import android.util.Range
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.kotlin.android.ktx.ext.dimension.dp
import com.kotlin.android.ktx.ext.dimension.sp
import java.util.regex.Pattern
/**
* 富文本 Span 设置
* 可指定范围 Range,也可以不指定,则默认全部。
*
* Created on 2020/9/16.
*
* @author o.s
*/
/**
* 图片链接默认占位字符
*/
const val LINK_IMAGE_PLACEHOLDER = "§"
fun CharSequence?.toSpan(): SpannableStringBuilder {
return SpannableStringBuilder(this ?: "").apply {
}
}
fun SpannableStringBuilder?.toBold(
vararg range: Range<Int>
): SpannableStringBuilder? {
this?.apply {
val styleSpan = StyleSpan(Typeface.BOLD)
if (range.isEmpty()) {
setSpan(styleSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
} else {
range.forEach {
if (it.upper <= length) {
setSpan(styleSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
}
}
return this
}
fun SpannableStringBuilder?.toUnderLine(
vararg range: Range<Int>
): SpannableStringBuilder? {
this?.apply {
val underLineSpan = UnderlineSpan()
if (range.isEmpty()) {
setSpan(underLineSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
} else {
range.forEach {
if (it.upper <= length) {
setSpan(underLineSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
}
}
return this
}
fun SpannableStringBuilder?.toColor(
vararg range: Range<Int>,
@ColorInt color: Int
): SpannableStringBuilder? {
this?.apply {
val colorSpan = ForegroundColorSpan(color)
if (range.isEmpty()) {
setSpan(colorSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
} else {
range.forEach {
if (it.upper <= length) {
setSpan(colorSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
}
}
return this
}
/**
* 设置超链接时,注意配置TextView、EditText属性:movementMethod = LinkMovementMethod.getInstance()
*/
fun SpannableStringBuilder?.toLink(
vararg range: Range<Int>,
action: ((view: View, key: String) -> Unit)? = null
): SpannableStringBuilder? {
this?.apply {
if (range.isEmpty()) {
val subStr = this.toString()
val clickSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
action?.invoke(widget, subStr)
}
}
setSpan(clickSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
} else {
range.forEach {
if (it.upper <= length) {
val subStr = substring(it.lower, it.upper)
val clickSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
action?.invoke(widget, subStr)
}
}
setSpan(clickSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
}
}
return this
}
/**
* (不带下划线)设置超链接时,注意配置TextView、EditText属性:movementMethod = LinkMovementMethod.getInstance()
*/
fun SpannableStringBuilder?.toLinkNotUnderLine(
vararg range: Range<Int>,
action: ((view: View, key: String) -> Unit)? = null
): SpannableStringBuilder? {
this?.apply {
if (range.isEmpty()) {
val subStr = this.toString()
val clickSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
action?.invoke(widget, subStr)
}
override fun updateDrawState(ds: TextPaint) {
ds.isUnderlineText = false
}
}
setSpan(clickSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
} else {
range.forEach {
if (it.upper <= length) {
val subStr = substring(it.lower, it.upper)
val clickSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
action?.invoke(widget, subStr)
}
override fun updateDrawState(ds: TextPaint) {
ds.isUnderlineText = false
}
}
setSpan(clickSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
}
}
return this
}
fun SpannableStringBuilder?.toUrl(
url: String,
action: ((url: String) -> Unit)? = null
): SpannableStringBuilder? {
this?.apply {
val urlSpan = object : URLSpan(url) {
override fun onClick(widget: View) {
action?.invoke(url)
}
}
setSpan(urlSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
return this
}
fun Drawable?.toImageSpan(
width: Int = 18.dp,
height: Int = 18.dp,
): SpannableStringBuilder {
val span = SpannableStringBuilder(LINK_IMAGE_PLACEHOLDER)
this?.apply {
setBounds(0, 0, width, height)
val imageSpan = ImageSpan(this, ImageSpan.ALIGN_BASELINE)
span.setSpan(imageSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
return span
}
fun Drawable?.toCenterImageSpan(
width: Int = 18.dp,
height: Int = 18.dp,
): SpannableStringBuilder {
val span = SpannableStringBuilder(LINK_IMAGE_PLACEHOLDER)
this?.apply {
setBounds(0, 0, width, height)
val imageSpan = CenterImageSpan(this)
span.setSpan(imageSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
return span
}
fun SpannableStringBuilder?.toTextSizeSpan(
textSize: Int = 14.sp,
vararg range: Range<Int>,
): SpannableStringBuilder? {
this?.apply {
//绝对值
val textSpan = AbsoluteSizeSpan(textSize, true)
if (range.isNotEmpty()) {
range.forEach {
if (it.upper <= length) {
setSpan(textSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
} else {
setSpan(textSpan, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
return this
}
fun String.getNumberTextSpan(
@ColorInt color: Int,
reverse: Boolean = false
): SpannableStringBuilder {
val span = SpannableStringBuilder(this)
val list = getNumberRegion(reverse)
list.forEach {
span.setSpan(
ForegroundColorSpan(color),
it.lower,
it.upper,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
}
return span
}
fun String.getNumberRegion(reverse: Boolean = false): List<Range<Int>> {
val list = ArrayList<Range<Int>>()
val pattern = Pattern.compile("\\d+")
val matcher = pattern.matcher(this)
val len = length
if (reverse) {
// 反向查找数字范围,记录除去数字的其他文本片段范围,默认从(0 至 len)
// 例如:"aaa111bbb",start = 3, end = 6, len = 9, [Region(0, 3), Region(6, 9)]
var start = 0
while (matcher.find()) {
list.add(Range(start, matcher.start()))
start = matcher.end()
}
list.add(Range(start, len))
} else {
// 查找数字找到它的范围区间
while (matcher.find()) {
list.add(Range(matcher.start(), matcher.end()))
}
}
return list
}
/**
* 匹配关键词的内容设置颜色
*/
fun convertToHtml(title: String, color: String, keyword: String): Spanned? {
val htmlKey = "<font color=\"${color}\">${keyword}</font>"
return Html.fromHtml(title.replace(keyword, htmlKey, false), Html.FROM_HTML_MODE_LEGACY)
}
/**
* 处理数字字体
*/
fun String.getNumberColorSizeBoldSpan(
@ColorInt color: Int,
textSize: Int = 13.sp,
textStyle: Int = Typeface.NORMAL
): SpannableStringBuilder {
val textSpan = AbsoluteSizeSpan(textSize, false)
val styleSpan = StyleSpan(textStyle)
val span = SpannableStringBuilder(this)
val list = getNumberRegion()
list.forEach {
span.setSpan(
ForegroundColorSpan(color),
it.lower,
it.upper,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
span.setSpan(textSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
span.setSpan(styleSpan, it.lower, it.upper, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
return span
}
fun String.addStartImage(context: Context, @DrawableRes res: Int): SpannableStringBuilder {
val str = "img $this"
val ssb = SpannableStringBuilder(str)
val imageSpan = ImageSpan(
context, res, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ImageSpan.ALIGN_CENTER
} else {
ImageSpan.ALIGN_BASELINE
}
)
ssb.setSpan(imageSpan, 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
return ssb
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 9,263 | Mtime | Apache License 2.0 |
app/src/main/java/com/zobaer53/zedmovies/ui/designsystem/component/Snackbar.kt | zobaer53 | 661,586,013 | false | {"Kotlin": 498107, "JavaScript": 344099, "C++": 10825, "CMake": 2160} |
package com.zobaer53.zedmovies.ui.designsystem.component
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import com.zobaer53.zedmovies.ui.designsystem.theme.zedMoviesTheme
@Composable
fun zedMoviesSnackbarHost(
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
shape: Shape = zedMoviesTheme.shapes.small,
containerColor: Color = zedMoviesTheme.colors.primaryVariant,
contentColor: Color = zedMoviesTheme.colors.textPrimaryVariant,
actionColor: Color = zedMoviesTheme.colors.accent
) {
SnackbarHost(
hostState = snackbarHostState,
modifier = modifier
) { snackbarData ->
Snackbar(
snackbarData = snackbarData,
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
actionColor = actionColor
)
}
}
val LocalSnackbarHostState = staticCompositionLocalOf<SnackbarHostState> {
error(LocalSnackbarHostStateErrorMessage)
}
private const val LocalSnackbarHostStateErrorMessage = "No SnackbarHostState provided."
| 0 | Kotlin | 3 | 6 | 1e70d46924b711942b573364745fa74ef1f8493f | 1,396 | NoFlix | Apache License 2.0 |
src/main/kotlin/dependencies/model/RepositoryInfoDto.kt | fraunhofer-iem | 738,423,065 | false | {"Kotlin": 67185, "Dockerfile": 1484} | package dependencies.model
import kotlinx.serialization.Serializable
@Serializable
data class RepositoryInfoDto(val url: String, val revision: String, val projects: List<ProjectDto>)
| 4 | Kotlin | 0 | 0 | d2dde21a9c6bf3ceb966f4f5d748e7bb6861721f | 185 | Libyear-ORT | MIT License |
baselib/src/main/java/com/dol/baselib/binding/ViewBinding.kt | dulijiedev | 213,852,322 | false | {"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "Proguard": 7, "Java": 26, "XML": 35, "Kotlin": 72, "INI": 2} | package com.dol.baselib.binding
import android.view.View
import androidx.databinding.BindingAdapter
import com.dol.baselib.command.BindingCommand
import java.util.concurrent.TimeUnit
import com.jakewharton.rxbinding3.view.clicks
/**
* Created by dlj on 2019/9/29.
*/
/**
* requireAll 是意思是是否需要绑定全部参数, false为否
* View的onClick事件绑定
* onClickCommand 绑定的命令,
* isThrottleFirst 是否开是否开启防止过快点击启防止过快点击
*/
@BindingAdapter(value = ["onClickCommand", "isThrottleFirst"], requireAll = false)
fun onClickCommand(view: View, clickCommand: BindingCommand<*>?, isThrottleFirst: Boolean = false) {
if (isThrottleFirst) {
view.clicks()
.subscribe {
if (clickCommand != null) {
clickCommand?.execute()
}
}
} else {
view.clicks()
.throttleFirst(1L, TimeUnit.SECONDS)//1秒钟内只允许点击1次
.subscribe {
if (clickCommand != null) {
clickCommand?.execute()
}
}
}
} | 0 | Kotlin | 0 | 0 | c935a0ace1af8824085163da72255f78860047c5 | 1,029 | AppRxDemo | Apache License 2.0 |
app/src/main/java/com/example/fitnesslog/core/utils/SafeCall.kt | Mark-Vasquez | 684,065,542 | false | {"Kotlin": 86378} | package com.example.fitnesslog.core.utils
suspend fun <T> safeCall(call: suspend () -> T): Resource<T> {
return try {
Resource.Success(data = call())
} catch (e: Exception) {
Resource.Error(errorMessage = e.toErrorMessage())
}
} | 2 | Kotlin | 0 | 0 | e68277218dd3f9c53cb9fecf9023307359404bf9 | 257 | Fitness-Log | Apache License 2.0 |
lib_webbasic/src/main/kotlin/io/clistery/webbasic/bridge/IBridge.kt | CListery | 563,166,095 | false | null | package io.clistery.webbasic.bridge
/**
* Bridge interface
*/
internal interface IBridge {
/**
* bridge connect create
*/
fun onBridgeCreate(token: String)
/**
* bridge connect state ready
*/
fun onBridgeReady()
/**
* callback by js call native
*/
fun onCallJSCallback(nativeCallName: String, jsCallbackId: String?, data: Any?): Boolean
/**
* receive message from js
*/
fun onReceiveJSMessage(jsCallbackId: String?, data: Any?): Boolean
}
| 0 | Kotlin | 1 | 0 | b276be451283999be287ed8b42bddbee152a96a2 | 529 | WebBasic | MIT License |
app/src/main/java/com/jymj/zhglxt/zjd/activity/FrameYewuDeteil.kt | wyh19950930 | 611,652,628 | false | null | package com.jymj.zhglxt.zjd.activity
import android.view.View
import com.jymj.zhglxt.R
import com.jymj.zhglxt.ldrkgl.home.bean.YlFolwEntity
import com.jymj.zhglxt.login.contract.FrameYewuContract
import com.jymj.zhglxt.login.model.FrameYewuModel
import com.jymj.zhglxt.login.presenter.FrameYewuPresenter
import com.setsuna.common.base.BaseActivity
class FrameYewuDeteil : BaseActivity<FrameYewuPresenter, FrameYewuModel>(), FrameYewuContract.View, View.OnClickListener {
/*override fun onCtglZhen(string: CTGLZhenBean.DataBean) {
}
override fun onCtglPqList(string: List<PQListBean.DataBean>) {
}
override fun onFrameJcxx(isSave: FrameJcxxBean.DataBean) {
}*/
var pointss : String = ""
var types : Int = 0
var frameTypes : Int = 0
override fun getLayoutId(): Int {
return R.layout.activity_frame_yewu_deteil
}
override fun initPresenter() {
mPresenter.setVM(this, mModel)
}
override fun initViews() {
/*val stringExtra = intent.getIntExtra("frameFlag", 0)
types = stringExtra
val points = intent.getStringExtra("framePoint")
pointss = points
val frameType = intent.getIntExtra("frameType",-1)
frameTypes = frameType
recy_sqgl_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recy_fjgl_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recy_lzgl_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recy_tcgl_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recy_environmental_show.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
if (stringExtra == 1) {
frame_yewu_det_sq_ll.visibility = View.VISIBLE
getSpData(points)
} else if (stringExtra == 2) {
frame_yewu_det_fj_ll.visibility = View.VISIBLE
getFjData(points)
} else if (stringExtra == 3) {
frame_yewu_det_lz_ll.visibility = View.VISIBLE
getLzData(points)
} else if (stringExtra == 4) {
frame_yewu_det_tc_ll.visibility = View.VISIBLE
getTcData(points)
} else if (stringExtra == 5) {
frame_yewu_det_hbqc_ll.visibility = View.VISIBLE
getHbjcData(points, 1)
} else if (stringExtra == 6) {
frame_yewu_det_wfxc_ll.visibility = View.VISIBLE
getWfxcData(points, 1)
} else if (stringExtra == 7) {
frame_yewu_det_wfxc_ll.visibility = View.VISIBLE
getWfxcData(points, 2)
}
for (i in 0..hbjcTitles.size - 1) {
tab_map_hbjc.addTab(tab_map_hbjc.newTab().setText(hbjcTitles[i]));
}
tab_map_hbjc.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabSelected(tab: TabLayout.Tab?) {
lastSelect = EnviorSupvsEnum.getIndex(hbjcTitles[tab!!.position])
getHbjcData(points, lastSelect)
}
})
initPopuStepMenu()*/
}
override fun initDatas() {
}
override fun returnSmewmcyl(msg: YlFolwEntity) {
}
/*override fun initDatas() {
}
override fun onPointFwqs(ylPointEntity: YLPointEntity) {
}
override fun onYztHoOwner(yztCountEntity: YztCountEntity) {
}
override fun onYztPoint(yztPointEntity: YztPointEntity) {
}
override fun onCtglPoint(yztPointEntity: CTGLPOINTBean.DataBean) {
}
override fun onYewuFrame(entity: YeWuFrameBean.DataBean) {
}
override fun onPolygonFwqs(polygonQueryEntity: PolygonQueryEntity) {
}
override fun onPolygonDetailFwqs(polygonDetailEntity: PolygonDetailEntity) {
}
override fun onPointTx(tdlyEntity: TdlyEntity) {
}
override fun onPolygonTx(list: MutableList<TxPolygonEntity>) {
}
override fun onPolygonDetailTx(tdlyDetail: TdlyDetail) {
}
override fun onPointCg(cgEntity: CgEntity) {
}
override fun onPolygonCg(list: MutableList<CgPolygonEntity>) {
}
override fun onPolygonDetailCg(cgDetail: CgDetail) {
}
override fun onPointLthy(lthyEntity: IthyEntity) {
}
override fun onPolygonLthy(list: MutableList<IthyEntity>) {
}
override fun onPolygonDetailLthy(cgDetail: LthyDetailEntity) {
}
override fun onPointTg(tgEntity: TgEntity) {
}
override fun onPolygonTg(list: MutableList<TgPolygonEntity>) {
}
override fun onPolygonDetailTg(tgDetail: TgDetail) {
}
override fun onBaseDataCe(baseDataEntity: XzDateEntity) {
}
override fun onBaseData(baseDataEntity: BaseDataEntity) {
}
override fun onCeSuan(list: MutableList<MoveCost>) {
}
override fun onCeSuan2(list: MutableList<MoveCost2>) {
}
override fun onCS(csEntity: CSEntity) {
}
override fun onYlByCun(list: MutableList<SysKxXzqData>) {
}
override fun onTxByCun(list: TxCunEntity) {
}
override fun onTgByCun(list: List<TGCunEntity>) {
}
override fun onCheckNydPoint(cjEntity: ZzyNydEntity) {
}
override fun onCheckNydZB(zzyNydEntity: ArrayList<CJEntity>) {
}
override fun onUpdateHt(zzyNydEntity: String) {
}
override fun onSaveZj(zzyNydEntity: String) {
}
override fun onUpdateZj(zzyNydEntity: String) {
}
override fun onDeleteZj(zzyNydEntity: String) {
}
override fun onDeleteFile(zzyNydEntity: String) {
}
override fun onQueryNydList(zzyNydEntity: List<ZzyNydEntity>) {
}
override fun onWfxcList(wfxcList: List<IllegalEntity>) {
}
override fun onWfxcSave(zzyNydEntity: String) {
}
override fun onWfxcCha(zzyNydEntity: YLEntity) {
}
override fun onLdrkCha(ldrkPointBean: LdrkPointBean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onWfxcUpdate(zzyNydEntity: String) {
if (types == 6){
getWfxcData(pointss, 1)
}else if (types == 7){
getWfxcData(pointss, 2)
}
ToastUtils.showShort("修改成功")
}
override fun onWfxcDelete(zzyNydEntity: String) {
if (types == 6){
getWfxcData(pointss, 1)
}else if (types == 7){
getWfxcData(pointss, 2)
}
ToastUtils.showShort("删除成功")
}
override fun onWfxcInfo(zzyNydEntity: List<XzqEntity.DataBean>) {
}
override fun onGhglList(zzyNydEntity: List<GhFhEntity>) {
}
override fun onHbjcList(zzyNydEntity: List<PjEnviorSupvsEntity>) {
}
override fun onHbLr(isSave: String) {
}
override fun onHbCha(point: String) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onLayerList(isSave: List<layerListBean>) {
}
override fun onYztList(isSave: List<AnalysisEnty>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onYztDelete(isSave: String) {
ToastUtils.showShort("删除成功")
}*/
override fun showLoading(title: String?) {
}
override fun stopLoading() {
}
override fun showErrorTip(msg: String?) {
}
override fun onClick(v: View?) {
}
/*private val hbjcTitles = arrayListOf<String>("待处理", "整改中", "验收完成")
private var lastSelect = 1
private var hbjcPosition = 0
private var stepMenuPopu: CommenPop? = null
private val selectedPhotos = ArrayList<String>()
private val intList = ArrayList<Int>()
private var picPop: CommenPop? = null
private var photoAdapter: PhotoAdapter? = null
private fun initPopuStepMenu() {
stepMenuPopu = CommenPop.getNormalPopu(this, R.layout.pop_step_menu, frame_yewu_det_top)
stepMenuPopu?.animationStyle = R.style.bottom_menu_anim
val contentView = stepMenuPopu?.contentView
val tvPics = contentView?.findViewById<TextView>(R.id.tv_pics_step_menu)
val tvUpPics = contentView?.findViewById<TextView>(R.id.tv_uploadpic_step_menu)
val tvDocs = contentView?.findViewById<TextView>(R.id.tv_docs_step_menu)
val tvUpDocs = contentView?.findViewById<TextView>(R.id.tv_uploaddoc_step_menu)
tvPics!!.setText("上传图片")
// tvUpPics!!.setText("查看图片")
tvUpPics!!.setText("查看详情")
tvUpDocs!!.setText("修改问题")
tvDocs!!.setText("删除问题")
tvPics?.setOnClickListener(this)
tvUpPics?.setOnClickListener(this)
tvDocs?.setOnClickListener(this)
tvUpDocs?.setOnClickListener(this)
}
fun getSpData(point: String) {
val jsonObject = JSONObject()
if (point.equals("1")) {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
} else {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
jsonObject.put("point", point)
}
val encrypt = AesEncryptUtils.encrypt(jsonObject.toString())
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.SQGL_queryList_URL).upJson(jsonObject).execute(object :
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
}
override fun onSuccess(response: Response<String>?) {
val baseMessage = response?.body()
if (baseMessage != null) {
val decrypt = AesEncryptUtils.decrypt(baseMessage)
val json = Gson().fromJson(decrypt, ZjdSqBean::class.java)
when (json.code) {
0 -> {
if (json.data.list.size > 0) {
recy_sqgl_list?.adapter = object : BaseQuickAdapter<ZjdSqBean.DataBean.ListBean, BaseViewHolder>(R.layout.item_sqgl_list, json.data.list) {
override fun convert(helper: BaseViewHolder, item: ZjdSqBean.DataBean.ListBean) {
if (frameTypes != -1) {
if (item.sptype != frameTypes) {
helper.itemView.layoutParams.height = 0
}
}
helper.setText(R.id.sqgl_item_cm, item.ylEntity.xzqmc)
.setText(R.id.sqgl_item_mph, item.ylEntity.mph)
.setText(R.id.sqgl_item_sqzt, item.sptypeText)
.setText(R.id.sqgl_item_sqr, item.sqName)
.setText(R.id.sqgl_item_sqdate, item.sqDate)
.setText(R.id.sqgl_item_iphone, item.iphone)
.setText(R.id.sqgl_item_remark, item.remark)
helper.itemView.setOnClickListener {
val intent = Intent(this@FrameYewuDeteil, SqglDetailActivity::class.java)
intent.putExtra("applyId", item.id)
intent.putExtra("sptype", item.sptype)
startActivity(intent)
}
}
}
}
}
}
} else {
}
}
override fun onFinish() {
super.onFinish()
}
override fun onError(response: Response<String>?) {
super.onError(response)
}
})
}
fun getFjData(point: String) {
val jsonObject = JSONObject()
if (point.equals("1")) {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
} else {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
jsonObject.put("point", point)
}
val encrypt = AesEncryptUtils.encrypt(jsonObject.toString())
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.JBQK_APPLY_LIST_URL).upJson(sss).execute(object :
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
}
override fun onSuccess(response: Response<String>?) {
val baseMessage = response?.body()
if (baseMessage != null) {
val decrypt = AesEncryptUtils.decrypt(baseMessage)
val json = Gson().fromJson(decrypt, ZjdFjBean::class.java)
when (json.code) {
0 -> {
if (json.data.list.size > 0) {
recy_fjgl_list?.adapter = object : BaseQuickAdapter<ZjdFjBean.DataBean.ListBean, BaseViewHolder>(R.layout.item_check_list, json.data.list) {
override fun convert(helper: BaseViewHolder, item: ZjdFjBean.DataBean.ListBean) {
if (frameTypes != -1) {
if (item.sptype != frameTypes) {
helper.itemView.layoutParams.height = 0
}
}
helper.setText(R.id.tv_fjgl_cm, item.ylEntity.xzqmc)
.setText(R.id.tv_fjgl_mph, item.ylEntity.mph)
.setText(R.id.tv_fjgl_sqzt, item.sptypeText)
.setText(R.id.tv_fjgl_sqr, item.name)
.setText(R.id.tv_fjgl_sqdate, item.sqDate)
.setText(R.id.tv_fjgl_iphone, item.iphone)
.setText(R.id.tv_fjgl_remark, item.remark)
helper.itemView.setOnClickListener {
val intent = Intent(this@FrameYewuDeteil, FjglDetailActivity::class.java)
intent.putExtra("applyId", item.id)
intent.putExtra("sptype", item.sptype)
startActivity(intent)
}
}
}
}
}
}
} else {
}
}
override fun onFinish() {
super.onFinish()
}
override fun onError(response: Response<String>?) {
super.onError(response)
}
})
}
fun getLzData(point: String) {
val jsonObject = JSONObject()
if (point.equals("1")) {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
} else {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
jsonObject.put("point", point)
}
val encrypt = AesEncryptUtils.encrypt(jsonObject.toString())
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.LZGL_ZjdLzList_URL).upJson(sss).execute(object :
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
}
override fun onSuccess(response: Response<String>?) {
val baseMessage = response?.body()
if (baseMessage != null) {
val decrypt = AesEncryptUtils.decrypt(baseMessage)
val json = Gson().fromJson(decrypt, ZjdLzBean::class.java)
when (json.code) {
0 -> {
if (json.data.list.size > 0) {
recy_lzgl_list?.adapter = object : BaseQuickAdapter<ZjdLzBean.DataBean.ListBean, BaseViewHolder>(R.layout.item_lzgl_list, json.data.list) {
override fun convert(helper: BaseViewHolder, item: ZjdLzBean.DataBean.ListBean) {
if (frameTypes != -1) {
if (item.sptype != frameTypes) {
helper.itemView.layoutParams.height = 0
}
}
helper.setText(R.id.lzgl_item_cm, item.ylEntity.xzqmc)
.setText(R.id.lzgl_item_mph, item.ylEntity.mph)
.setText(R.id.lzgl_item_sqzt, item.sptypeText)
.setText(R.id.lzgl_item_sqr, item.sqName)
.setText(R.id.lzgl_item_sqdate, item.sqDate)
.setText(R.id.lzgl_item_iphone, item.iphone)
.setText(R.id.lzgl_item_remark, item.remark)
helper.itemView.setOnClickListener {
val intent = Intent(this@FrameYewuDeteil, LzglDetailActivity::class.java)
intent.putExtra("applyId", item.id)
intent.putExtra("sptype", item.sptype)
startActivity(intent)
}
}
}
}
}
else -> {
}
}
} else {
}
}
override fun onFinish() {
super.onFinish()
}
override fun onError(response: Response<String>?) {
super.onError(response)
}
})
}
fun getTcData(point: String) {
val jsonObject = JSONObject()
if (point.equals("1")) {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
} else {
jsonObject.put("page", 1)
jsonObject.put("limit", 999)
jsonObject.put("point", point)
}
val encrypt = AesEncryptUtils.encrypt(jsonObject.toString())
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.EXIT_QUERY_LIST).upJson(sss).execute(object ://BaseRespose<List<MoveCost>>
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
}
override fun onSuccess(response: Response<String>?) {
val cash = response?.body()
if (cash != null) {
val decrypt = AesEncryptUtils.decrypt(cash)
val json = Gson().fromJson(decrypt, ZjdTcBean::class.java)
if (json.code == 0) {
if (json!!.data != null) {
recy_tcgl_list?.adapter = object : BaseQuickAdapter<ZjdTcBean.DataBean.ListBean, BaseViewHolder>(R.layout.item_tcgl, json.data.list) {
override fun convert(helper: BaseViewHolder, item: ZjdTcBean.DataBean.ListBean) {
if (frameTypes != -1) {
if (item.sptype != frameTypes) {
helper.itemView.layoutParams.height = 0
}
}
helper.setText(R.id.item_tcgl_cm, item.ylEntity.xzqmc)
.setText(R.id.item_tcgl_mph, item.ylEntity.mph)
.setText(R.id.item_tcgl_sqzt, item.sptypeText)
.setText(R.id.item_tcgl_sqr, item.sqName)
.setText(R.id.item_tcgl_sqdate, item.sqDate)
.setText(R.id.item_tcgl_iphone, item.iphone)
.setText(R.id.item_tcgl_remark, item.remark)
helper.itemView.setOnClickListener {
val intent = Intent(this@FrameYewuDeteil, TcglDetailActivity::class.java)
intent.putExtra("applyId", item.id)
intent.putExtra("sptype", item.sptype)
startActivity(intent)
}
}
}
} else {
}
} else {
}
}
}
override fun onFinish() {
super.onFinish()
}
override fun onError(response: Response<String>?) {
super.onError(response)
}
})
}
fun getHbjcData(point: String, page: Int) {
val jsonObject = JSONObject()
if (point.equals("1")) {
jsonObject.put("qutype", page)//当前页数,从1开始
jsonObject.put("limit", 1000)//当前页数,从1开始
jsonObject.put("page", 1)//当前页数,从1开始
} else {
jsonObject.put("qutype", page)//当前页数,从1开始
jsonObject.put("limit", 1000)//当前页数,从1开始
jsonObject.put("page", 1)//当前页数,从1开始
jsonObject.put("point", point)//当前页数,从1开始
}
val toJson = Gson().toJson(jsonObject).substring(18, Gson().toJson(jsonObject).toString().length - 1)
val encrypt = AesEncryptUtils.encrypt(toJson.toString())
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.ENVIORSUPVSLIST).upJson(sss).execute(object ://BaseRespose<List<MoveCost>>
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
}
override fun onSuccess(response: Response<String>?) {
if (response != null) {
if (response.body() != null) {
val decrypt = AesEncryptUtils.decrypt(response.body())
val json: EnviorListEntity = Gson().fromJson(decrypt, object : TypeToken<EnviorListEntity?>() {}.type)
if (json.code == 0) {
val cash = json.data
recy_environmental_show!!.setPullRefreshEnabled(false)
recy_environmental_show!!.setLoadingMoreEnabled(false)
val environmentalAdapter1 = EnvironmentalAdapter(this@FrameYewuDeteil, cash.list,1)
environmentalAdapter1.setOnClickEnvironLister(object : EnvironmentalAdapter.OnClickEnvironLister {
override fun onClick(position: Int) {
this@FrameYewuDeteil.hbjcPosition = position
val type = AppCache.getInstance().type
val intent = Intent(this@FrameYewuDeteil, HBJCDetailActivity::class.java)
intent.putExtra("pjenvior", cash.list.get(position))
startActivity(intent)
}
override fun onDeleteClick(position: Int) {
var dialog = SweetAlertDialog(this@FrameYewuDeteil, SweetAlertDialog.WARNING_TYPE)
dialog?.titleText = "是否删除?"
dialog?.confirmText = "确认"
dialog?.showCancelButton(true)
dialog?.showContentText(false)
dialog?.show()
dialog?.setConfirmClickListener {
val encrypt = AesEncryptUtils.encrypt("{\"ids\":[" + cash.list.get(position).id + "]}")
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.ENVIORSUPVSDELETES).upJson(sss).execute(object :
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
LoadingDialog.showDialogForLoading(this@FrameYewuDeteil)
}
override fun onSuccess(response: Response<String>?) {
val cash = response?.body()
if (cash != null) {
val decrypt = AesEncryptUtils.decrypt(cash)
val json: BaseRespose<*> = Gson().fromJson(decrypt, object : TypeToken<BaseRespose<*>?>() {}.type)
if (json.code == 0) {
getHbjcData(point, lastSelect)
ToastUtils.showShort("删除成功")
dialog.dismiss()
} else {
ToastUtils.showShort("删除失败")
dialog.dismiss()
}
} else {
ToastUtils.showShort("删除失败")
dialog.dismiss()
}
}
override fun onFinish() {
super.onFinish()
LoadingDialog.cancelDialogForLoading()
}
override fun onError(response: Response<String>?) {
super.onError(response)
ToastUtils.showShort("删除失败")
}
})
}
}
})
recy_environmental_show!!.adapter = environmentalAdapter1
} else {
}
} else {
}
} else {
}
}
override fun onFinish() {
super.onFinish()
}
override fun onError(response: Response<String>?) {
super.onError(response)
}
})
}
fun getWfxcData(point: String, type: Int) {
val jsonObject = JSONObject()
if (point.equals("1")) {
jsonObject.put("xzqmc", "")
jsonObject.put("type", type)
jsonObject.put("page", 1)
jsonObject.put("limit", 9999)
} else {
jsonObject.put("xzqmc", "")
jsonObject.put("type", type)
jsonObject.put("point", point)
jsonObject.put("page", 1)
jsonObject.put("limit", 9999)
}
val encrypt = AesEncryptUtils.encrypt(jsonObject.toString())
var sss = "{\"requestData\":\"" + encrypt + "\"}"
OkGo.post<String>(ApiConstants.ILLEGAL_LIST).upJson(sss).execute(object ://BaseRespose<List<MoveCost>>
BaseNet<String>() {
override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
super.onStart(request)
}
override fun onSuccess(response: Response<String>?) {
if (response != null) {
val decrypt = AesEncryptUtils.decrypt(response.body())
val json: BaseRespose<PageUtils<IllegalEntity>> = Gson().fromJson(decrypt, object : TypeToken<BaseRespose<PageUtils<IllegalEntity>>?>() {}.type)
if (json.code == 0) {
if (type == 1){
wfxc_tv_hz.visibility = View.VISIBLE
wfxc_tv_mph.visibility = View.VISIBLE
}else{
wfxc_tv_hz.visibility = View.GONE
wfxc_tv_mph.visibility = View.GONE
}
var wfxcAdapter = WfxcAdapter(R.layout.item_wfxc, json.data.list as List<IllegalEntity>,type)
wfxc_rlv!!.layoutManager = LinearLayoutManager(this@FrameYewuDeteil, LinearLayoutManager.VERTICAL, false)
wfxc_rlv!!.setAdapter(wfxcAdapter)
wfxcAdapter.setOnItemClickListener(BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
// ShowChoise(json.data.list.get(position))
var intent = Intent(this@FrameYewuDeteil,WfxcDetailActivity::class.java)
intent.putExtra("illegalEntity",json.data.list.get(position))
startActivity(intent)
})
wfxcAdapter.setOnWfxcClickLinear(object : WfxcAdapter.OnWfxcClickLinear{
override fun onDeleteClick(illegalEntity: IllegalEntity?) {
mPresenter.getWfxcDelete(illegalEntity!!.id.toString())
}
override fun onUpdateClick(illegalEntity: IllegalEntity?) {
showUpDatePop(illegalEntity!!)
}
})
} else {
}
} else {
}
}
override fun onFinish() {
super.onFinish()
}
override fun onError(response: Response<String>?) {
super.onError(response)
}
})
}
private fun ShowChoise(illegalEntity: IllegalEntity) {
val builder = AlertDialog.Builder(this@FrameYewuDeteil, android.R.style.Theme_Holo_Light_Dialog)
//builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("违法查询列表操作")
// 指定下拉列表的显示数据
val cities = arrayOf("删除", "修改", "查看")
// 设置一个下拉的列表选择项
builder.setItems(cities) { dialog, which ->
if (which == 0) {
mPresenter.getWfxcDelete(illegalEntity.id.toString())
} else if (which == 1) {
showUpDatePop(illegalEntity)
} else if (which == 2) {
showPicPop(illegalEntity)
}
}
val show = builder.show()
show.setCanceledOnTouchOutside(true)
show.window.setBackgroundDrawableResource(android.R.color.transparent)
}
private fun showUpDatePop(teskFiles: IllegalEntity) {
selectedPhotos.clear() //清空图片集合
intList.clear() //清空图片id集合
picPop = CommenPop.getNormalPopu(this@FrameYewuDeteil, R.layout.pop_wfxc_update, frame_yewu_det_top)
val contentView: View = picPop!!.getContentView()
val recy_map = contentView.findViewById<View>(R.id.sp_wfxc_pop) as Spinner
val butWfxcSure = contentView.findViewById<View>(R.id.but_wfxc_sure) as TextView
val rlvWfxcPop = contentView.findViewById<View>(R.id.rlv_tpsc_wfxc_pop) as RecyclerView
photoAdapter = PhotoAdapter(this@FrameYewuDeteil, selectedPhotos)
rlvWfxcPop.layoutManager = StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL)
rlvWfxcPop.adapter = photoAdapter
rlvWfxcPop.addOnItemTouchListener(RecyclerItemClickListener(this,
object : RecyclerItemClickListener.OnItemClickListener {
override fun onItemClick(view: View?, position: Int) {
if (photoAdapter!!.getItemViewType(position) === PhotoAdapter.TYPE_ADD) {
PhotoPicker.builder()
.setPhotoCount(PhotoAdapter.MAX)
.setShowCamera(true)
.setPreviewEnabled(false)
.setSelected(selectedPhotos)
.start(this@FrameYewuDeteil, Activity.RESULT_FIRST_USER)
} else {
PhotoPreview.builder()
.setPhotos(selectedPhotos)
.setCurrentItem(position)
.start(this@FrameYewuDeteil, Activity.RESULT_FIRST_USER)
}
}
}))
val spinnerAdapter = SpinnerAdapter(this@FrameYewuDeteil)
recy_map.adapter = spinnerAdapter
val stringList: MutableList<String> = java.util.ArrayList()
stringList.add("未完成")
stringList.add("已完成")
spinnerAdapter.setDatas(stringList)
recy_map.setSelection(teskFiles.statusInt)
picPop!!.showAtLocation(contentView, Gravity.CENTER, 0, 0)
butWfxcSure.setOnClickListener {
if (selectedPhotos.size > 0) {
for (i in selectedPhotos) {
uplodeUpdate(File(i), teskFiles, recy_map)
}
picPop!!.dismiss()
} else {
ToastUtils.showShort("请上传图片")
// mPresenter.getAdd(teskFiles.getXzqmc(),teskFiles.getObjectid()+"",etWfxcAddMqzk.getText().toString(),etWfxcAddRemark.getText().toString(),intList);
}
}
}
*//**
* 违法巡查修改上传图片
*
* @return
*//*
fun uplodeUpdate(file: File, teskFiles: IllegalEntity, recy_map: Spinner) {
val httpParams = HttpParams()
var substring = ""
substring = if (file.name.length > 30) {
val length = file.name.length
file.name.substring(length - 20, length - 5)
} else {
file.name.substring(0, file.name.length - 5)
}
httpParams.put(file.name, file)
OkGo.post<BaseRespose<IllegalFileEntity>>(ApiConstants.ILLEGAL_UPLOAD_FILE)
.params(httpParams)
.execute(object : BaseNet<BaseRespose<IllegalFileEntity>>() {
override fun onStart(request: Request<BaseRespose<IllegalFileEntity>, out Request<*, *>?>?) {
super.onStart(request)
if (!LoadingDialog.isShowing()) LoadingDialog.showDialogForLoading(this@FrameYewuDeteil)
}
override fun onSuccess(response: Response<BaseRespose<IllegalFileEntity>>) {
val body: BaseRespose<IllegalFileEntity> = response.body()
if (body.data != null) {
intList.add(body.data.getId())
}
if (selectedPhotos.size == intList.size) {
val selectedItem = recy_map.selectedItemPosition
if (selectedItem == 0) {
mPresenter.getWfxcUpdate(teskFiles.id.toString(), "0", intList)
} else if (selectedItem == 1) {
mPresenter.getWfxcUpdate(teskFiles.id.toString(), "10", intList)
}
} else {
ToastUtils.showShort("图片名太长或图片以损坏")
}
LoadingDialog.cancelDialogForLoading()
// showSuccessMsg("上传成功");
}
override fun onError(response: Response<BaseRespose<IllegalFileEntity>>) {
super.onError(response)
ToastUtils.showShort(response.getException().message)
// showErrorMsg(response.getException().message)
LoadingDialog.cancelDialogForLoading()
}
})
}
*//***
* 违法巡查查看图片
* @param teskFiles
*//*
private fun showPicPop(teskFiles: IllegalEntity) {
val picpicPop = CommenPop.getNormalPopu(this@FrameYewuDeteil, R.layout.pop_wfxc_pic, frame_yewu_det_top)
val contentView = picpicPop.contentView
val rlvPicWfxcPop = contentView.findViewById<View>(R.id.rlv_pic_wfxc_pop) as RecyclerView
val butWfxcSure = contentView.findViewById<View>(R.id.but_wfxc_pic_sure) as TextView
val baseQuickAdapter: BaseQuickAdapter<IllegalFileEntity, BaseViewHolder> = object : BaseQuickAdapter<IllegalFileEntity, BaseViewHolder>(R.layout.item_wfxc_pic, teskFiles.illegalFileEntityList) {
override fun convert(helper: BaseViewHolder, item: IllegalFileEntity) {
val view = helper.getView<ImageView>(R.id.iv_item_wfxc_pic)
// Glide.with(getActivity()).load(item.getPath()).load(view);
val options = RequestOptions() // .placeholder(R.drawable.video_default) // 正在加载中的图片
.error(R.drawable.error_center_x) // 加载失败的图片
// 磁盘缓存策略 .diskCacheStrategy(DiskCacheStrategy.ALL)
val UTL = ApiConstants.BASE_URL + item.path.substring(23, item.path.length)
val UTL1 = ApiConstants.BASE_URL + "" + item.path //.substring(23,item.getPath().length())
Glide.with(this@FrameYewuDeteil)
.load(UTL1) // 图片地址
.apply(options) // 参数
.into(view) // 需要显示的ImageView控件
view.setOnClickListener {
val intent = Intent(this@FrameYewuDeteil, BigPicActivity::class.java)
intent.putExtra("url", UTL1)
*//*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(getActivity(),
imgv_item_home_frag, "pic_local").toBundle();
mContext.startActivity(intent,options);
}else{*//*mContext.startActivity(intent)
*//* this@TcglDetailActivity!!.overridePendingTransition(R.anim.fade_in,
com.setsuna.common.R.anim.fade_out)
}*//*
}
}
}
rlvPicWfxcPop.layoutManager = GridLayoutManager(this@FrameYewuDeteil, 3)
rlvPicWfxcPop.adapter = baseQuickAdapter
picpicPop.showAtLocation(contentView, Gravity.CENTER, 0, 0)
butWfxcSure.setOnClickListener { picpicPop.dismiss() }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data) // && (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)
if (resultCode == Activity.RESULT_OK) {
var photos: ArrayList<String>? = null
selectedPhotos.clear()
if (data != null) {
photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS)
}
if (photos != null) {
selectedPhotos.addAll(photos)
}
if (photoAdapter != null) photoAdapter!!.notifyDataSetChanged()
}
}*/
}
| 0 | Kotlin | 0 | 0 | 0ec2ac3a76719d323eed98edcf9df48cdc4050da | 41,363 | ZHGLXT_YBC | Apache License 2.0 |
src/main/kotlin/ru/ogrezem/testTornado1/app/MyApp.kt | ogrezem | 146,788,223 | false | null | package ru.ogrezem.testTornado1.app
import ru.ogrezem.testTornado1.style.Styles
import ru.ogrezem.testTornado1.view.MainView
import tornadofx.App
import java.io.File
import java.util.logging.*
import java.io.FileOutputStream
import java.io.PrintStream
class MyApp: App(MainView::class, Styles::class) {
} | 0 | Kotlin | 0 | 0 | 6bff1fb1725c5b3096643884075c8a64fae69c23 | 308 | morseDecoder | Apache License 2.0 |
src/main/kotlin/com/swisschain/matching/engine/database/cache/AssetPairsCache.kt | swisschain | 255,464,363 | false | null | package com.swisschain.matching.engine.database.cache
import com.swisschain.matching.engine.daos.AssetPair
import com.swisschain.matching.engine.database.DictionariesDatabaseAccessor
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.util.stream.Collectors
import kotlin.concurrent.fixedRateTimer
@Component
class AssetPairsCache @Autowired constructor(
private val databaseAccessor: DictionariesDatabaseAccessor,
@Value("\${application.assets.pair.cache.update.interval}") updateInterval: Long? = null) : DataCache() {
private val knownAssetPairs = HashMap<String, MutableSet<String>>()
companion object {
private val LOGGER = LoggerFactory.getLogger(AssetPairsCache::class.java)
}
@Volatile
private var assetPairsById: Map<String, Map<String, AssetPair>> = HashMap()
@Volatile
private var assetPairsByPair: Map<String, Map<String, AssetPair>> = HashMap()
init {
this.assetPairsById = databaseAccessor.loadAssetPairs()
this.assetPairsByPair = generateAssetPairsMapByPair(assetPairsById)
assetPairsById.forEach {
val brokerPairs = knownAssetPairs.getOrPut(it.key) { HashSet() }
it.value.values.forEach{
brokerPairs.add(it.symbol)
}
}
LOGGER.info("Loaded ${assetPairsById.values.sumBy { it.size }} assets pairs")
updateInterval?.let {
fixedRateTimer(name = "Asset Pairs Cache Updater", initialDelay = it, period = it) {
update()
}
}
}
fun getAssetPair(brokerId: String, assetPair: String): AssetPair? {
return assetPairsById[brokerId]?.get(assetPair) ?: databaseAccessor.loadAssetPair(brokerId, assetPair)
}
fun getAssetPair(brokerId: String, assetId1: String, assetId2: String): AssetPair? {
return assetPairsByPair[brokerId]?.get(pairKey(assetId1, assetId2)) ?: assetPairsByPair[brokerId]?.get(pairKey(assetId2, assetId1))
}
fun getAssetPairByAssetId(brokerId: String, assetId: String): Set<AssetPair> {
return assetPairsById[brokerId]?.values
?.stream()
?.filter { it.quotingAssetId == assetId || it.baseAssetId == assetId }
?.collect(Collectors.toSet()) ?: HashSet()
}
override fun update() {
val newMap = databaseAccessor.loadAssetPairs()
if (newMap.isNotEmpty()) {
val newMapByPair = generateAssetPairsMapByPair(newMap)
assetPairsById = newMap
assetPairsByPair = newMapByPair
}
}
private fun generateAssetPairsMapByPair(assetPairsById: Map<String, Map<String, AssetPair>>): Map<String, Map<String, AssetPair>> {
val result = HashMap<String, Map<String, AssetPair>>()
assetPairsById.forEach { (brokerId, assetPairs) ->
result[brokerId] = assetPairs.values
.groupBy { pairKey(it.baseAssetId, it.quotingAssetId) }
.mapValues {
if (it.value.size > 1) {
LOGGER.error("Asset pairs count for baseAssetId=${it.value.first().baseAssetId} and quotingAssetId=${it.value.first().quotingAssetId} is more than 1")
}
it.value.first()
}
}
return result
}
private fun pairKey(assetId1: String, assetId2: String) = "${assetId1}_$assetId2"
} | 1 | null | 1 | 1 | 5ef23544e9c5b21864ec1de7ad0f3e254044bbaa | 3,588 | Exchange.MatchingEngine | Apache License 2.0 |
openrndr/src/main/kotlin/sketch/S18_GlowingGraph.kt | ericyd | 250,675,664 | false | null | /**
* WOW
* What did we learn today?
*
* Do NOT add excessive layers to the compositor.
* DO add nested loops within a single Layer to add all your things at once.
*
* Circle packing algorithm based on
* http://www.codeplastic.com/2017/09/09/controlled-circle-packing-with-processing/
*/
package sketch
import extensions.CustomScreenshots
import force.MovingBody
import org.openrndr.application
import org.openrndr.color.ColorRGBa
import org.openrndr.extra.compositor.blend
import org.openrndr.extra.compositor.compose
import org.openrndr.extra.compositor.draw
import org.openrndr.extra.compositor.layer
import org.openrndr.extra.compositor.post
import org.openrndr.extra.fx.blend.Add
import org.openrndr.extra.fx.blur.ApproximateGaussianBlur
import org.openrndr.extra.noise.random
import org.openrndr.extra.noise.simplex
import org.openrndr.extras.color.palettes.colorSequence
import org.openrndr.math.Vector2
import org.openrndr.math.Vector3
import org.openrndr.math.map
import org.openrndr.shape.Circle
import org.openrndr.shape.LineSegment
import util.generateMovingBodies
import util.packCirclesControlled
import util.timestamp
import kotlin.math.abs
import kotlin.random.Random
fun main() = application {
configure {
width = 2000
height = 2000
}
program {
val progName = this.name.ifBlank { this.window.title.ifBlank { "my-amazing-drawing" } }
var seed = random(0.0, Int.MAX_VALUE.toDouble()).toInt()
println("seed = $seed")
val screenshots = extend(CustomScreenshots()) {
quitAfterScreenshot = false
// Trying to figure out why scaling an image with filters looks like shit, but until I do this needs to be disabled
// scale = 3.0
// multisample = BufferMultisample.SampleCount(8)
name = "screenshots/$progName/${timestamp()}-seed-$seed.png"
captureEveryFrame = true
}
val nBodies = 1000
val radiusRange = 4.0 to 60.0
// These are more appropriate for width = 1000
// val nBodies = 700
// val radiusRange = 0.10 to 40.0
// Some very interesting things can happen if you don't honor the actual simplex range of [-1.0, 1.0]
val noiseRange = -0.65 to 0.5
val noiseScale = 200.0
val circleRadius = 3.5
val spectrum = colorSequence(
0.25 to
ColorRGBa.fromHex("0B8EDA"), // blue
0.5 to
ColorRGBa.fromHex("D091F2"), // purple
0.75 to
ColorRGBa.fromHex("F8AB54"), // orange
)
fun connectNodes(node: MovingBody, others: List<MovingBody>, tolerance: Double = 1.0): List<LineSegment> {
val segments = mutableListOf<LineSegment>()
val nearNodes = others.filter {
it != node && it.position.distanceTo(node.position) < (it.radius + node.radius) * tolerance
}
for (other in nearNodes) {
segments.add(LineSegment(node.position, other.position))
}
return segments
}
// Define some sick FX
val blur = ApproximateGaussianBlur().apply {
window = 30
sigma = 5.0
spread = 2.0
gain = 2.0
}
// this is OK but not as good as the ApproximateGaussianBlur
// val blur = Bloom().apply {
// blendFactor = 1.50
// brightness = 1.50
// downsamples = 10
// }
// Other cool blends include ColorDodge and Lighten - both subtly different but similar effects
val blendFilter = Add()
extend {
// get that rng
val rng = Random(seed.toLong())
val sizeFn = { body: MovingBody ->
val targetRadius = map(
noiseRange.first, noiseRange.second,
radiusRange.first, radiusRange.second,
simplex(seed, body.position / noiseScale)
)
// technically the value will never "arrive" but it gets very close very fast so, y'know ... good enough for me!
body.radius = abs(body.radius + targetRadius) / 2.0
}
// Using `incremental = false` will not return bodies until the packing is complete
var lastTime = System.currentTimeMillis()
val packed = packCirclesControlled(
bodies = generateMovingBodies(nBodies, Vector2(width * 0.5, height * 0.5), 10.0),
incremental = false, rng = rng, sizeFn = sizeFn
)
println("Circle packing complete. Took ${(System.currentTimeMillis() - lastTime) / 1000.0} seconds")
lastTime = System.currentTimeMillis()
val composite = compose {
// A layer for the non-blurred things
layer {
draw {
packed.bodies.forEachIndexed { index, body ->
val shade = simplex(seed, Vector3(body.position.x, body.position.y, index.toDouble()) / noiseScale) * 0.5 + 0.5
drawer.strokeWeight = 0.25
drawer.stroke = spectrum.index(shade)
drawer.circle(Circle(body.position, circleRadius))
drawer.lineSegments(connectNodes(body, packed.bodies, 1.25))
}
}
}
// And a layer for the blurred things 😎
layer {
blend(blendFilter)
draw {
// We duplicate the loop through `bodies` to reduce the number of layers `compositor` must process.
// It was crashing the program with all the extra layers that all required a post(blur) effect 😱
packed.bodies.forEachIndexed { index, body ->
val shade = simplex(seed, Vector3(body.position.x, body.position.y, index.toDouble()) / noiseScale) * 0.5 + 0.5
drawer.strokeWeight = 1.0
drawer.stroke = spectrum.index(shade) // .opacify(0.1)
drawer.lineSegments(connectNodes(body, packed.bodies, 1.25))
}
}
post(blur)
}
}
println("Composing layers complete. Took ${(System.currentTimeMillis() - lastTime) / 1000.0} seconds")
composite.draw(drawer)
// set seed for next iteration
if (screenshots.captureEveryFrame) {
seed = random(0.0, Int.MAX_VALUE.toDouble()).toInt()
screenshots.name = "screenshots/$progName/${timestamp()}-seed-$seed.png"
}
}
}
}
| 2 | Kotlin | 1 | 56 | 09511d4a78272f9de1e9fa9626de3c0cb7ba3177 | 6,057 | generative-art | MIT License |
app/src/main/java/com/act/code/Main.kt | BrinsLee | 682,033,488 | false | null | package com.act.code
import com.act.code.Config.activityClassMap
import com.act.code.Config.fragmentClassMap
import com.act.code.Config.normalClassMap
import com.act.code.tools.*
import java.io.File
object Main {
fun generateNomClass() {
val packageSize = Config.packageSize // 创建包的个数
repeat(packageSize) {
val packageName = Config.packageName + "." + generateDeclareObjectKey()
val listFile = mutableListOf<String>()
// 每个包里面有多少个类
repeat((5..10).random()) {
listFile.add("${generateClassKey((5.. 16).random())}.java")
}
normalClassMap[packageName] = listFile
}
normalClassMap.forEach {
println("-keep class "+ it.key + ".** { *; }")
it.value.forEach { name ->
FileUtils.generateFile(it.key, name, FileUtils::initFileContent)
}
}
}
/**
* 创建 activity
*/
fun generateActivityClass() {
val packageSize = Config.packageSize / 8 // 创建activity包的个数
repeat(packageSize) {
val packageName = Config.packageActName + "." + generateDeclareObjectKey()
val listFile = mutableListOf<String>()
// 每个包里面有多少个类
repeat((5..8).random()) {
listFile.add("${generateClassKey((5 .. 16).random())}Activity.java")
}
activityClassMap[packageName] = listFile
}
// 创建activity
activityClassMap.forEach {
println("-keep class "+ it.key + ".** { *; }")
it.value.forEach { name ->
FileUtils.generateFile(it.key, name, FileUtils::initActivityContent)
}
}
}
/**
* 创建Fragment
*/
fun generateFragmentClass() {
val packageSize = Config.packageSize / 8 // 创建fragment包的个数
repeat(packageSize) {
val packageName = Config.packageActName + "." + generateDeclareObjectKey()
val listFile = mutableListOf<String>()
// 每个包里面有多少个类
repeat((5..8).random()) {
listFile.add("${generateClassKey((5 .. 16).random())}Fragment.java")
}
fragmentClassMap[packageName] = listFile
}
// 创建activity
fragmentClassMap.forEach {
println("-keep class "+ it.key + ".** { *; }")
it.value.forEach { name ->
FileUtils.generateFile(it.key, name, FileUtils::initFragmentContent)
}
}
}
fun generateManifestClass() {
val path = "./src/main"
val fileName = "AndroidManifest.xml"
val createSuccess = GenerateFileTools.generateFile(path, fileName)
val buffer = StringBuffer()
buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
buffer.append("<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"${Config.applicationId}\">\n")
buffer.append("<application >\n")
activityClassMap.forEach { map ->
map.value.forEach {
buffer.append("<activity android:screenOrientation=\"sensorLandscape\" android:exported=\"true\" android:name=\"${map.key}.${it.split(".")[0]}\" />\n")
}
}
buffer.append(" </application>\n")
buffer.append("</manifest>\n")
if (createSuccess) {
val file = File("$path/$fileName")
file.writeText(buffer.toString())
}
}
}
fun main() {
val startTime = System.currentTimeMillis()
println("开始创建普通类")
println("...")
Main.generateNomClass() // 普通类
println("创建完成")
println("开始创建activity 和 相关布局文件")
println("...")
Main.generateActivityClass() // Activity 的类
println("创建完成")
println("开始创建清单文件")
Main.generateManifestClass()
println("创建完成")
println("开始创建fragment 和 相关布局文件")
println("...")
Main.generateFragmentClass() // Fragment 的类
println("创建完成")
println("===================all file size ======================")
totalFiles()
var activitySize = 0
var normalClass = 0
allFile.forEach {
if (it.contains("Activity")) {
activitySize += 1
} else {
normalClass += 1
}
}
println("总计:${allFile.size} activity $activitySize class : $normalClass \n 用时:${System.currentTimeMillis() - startTime}")
if (GenerateFileTools.generateFile("./", "allFile.txt")) {
val file = File("./allFile.txt")
val buffer = StringBuffer()
allFile.forEach {
buffer.append(it).append("\n")
}
file.writeText(buffer.toString())
}
}
| 0 | Kotlin | 0 | 0 | 4438a0ec789aa2da1822fe63be909f2107ef676b | 4,673 | GenerateCode | Apache License 2.0 |
icp_kotlin_kit/src/main/java/com/bity/icp_kotlin_kit/data/datasource/api/model/ContentApiModel.kt | ThomasConstantinBity | 824,624,205 | false | {"Kotlin": 554595, "Rust": 313094} | package com.bity.icp_kotlin_kit.data.datasource.api.model
import com.bity.icp_kotlin_kit.data.datasource.api.enum.ContentRequestType
import com.bity.icp_kotlin_kit.util.OrderIndependentHash
import com.fasterxml.jackson.annotation.JsonProperty
// Need to use sneak case because of order independent hash
internal abstract class ContentApiModel(
val request_type: ContentRequestType,
val sender: ByteArray,
val nonce: ByteArray,
val ingress_expiry: Long
) {
fun calculateRequestId(): ByteArray = OrderIndependentHash(this)
} | 1 | Kotlin | 2 | 0 | e3e7f9086aebf3997cf7747f98efec81f3a654bb | 544 | ICP-Kotlin-Kit | MIT License |
ConnectSDK/src/test/kotlin/com/zendesk/connect/TestLogAppender.kt | isabella232 | 478,424,464 | true | {"INI": 2, "YAML": 1, "Gradle": 10, "Shell": 3, "Markdown": 4, "Batchfile": 2, "Proguard": 4, "Text": 1, "Ignore List": 4, "Java": 112, "Java Properties": 2, "XML": 25, "Kotlin": 45} | package com.zendesk.connect
import com.zendesk.logger.Logger
class TestLogAppender: Logger.LogAppender {
val logs = arrayListOf<String>()
override fun log(priority: Logger.Priority?, tag: String?, message: String?, throwable: Throwable?) {
logs.add(message.orEmpty())
}
fun contains(message: String): Boolean = logs.contains(message)
fun lastLog(): String = logs.last()
fun reset() = logs.clear()
}
| 0 | null | 0 | 0 | 3a274bae492516d922f4f4046be5d1bb4f341772 | 439 | connect-android-sdk | Apache License 2.0 |
src/main/java/catmoe/fallencrystal/moefilter/network/bungee/util/event/EventCallMode.kt | CatMoe | 638,486,044 | false | null | /*
* Copyright 2023. CatMoe / FallenCrystal
*
* 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 catmoe.fallencrystal.moefilter.network.bungee.util.event
enum class EventCallMode {
AFTER_INIT, // This will call event when connection incoming. Whether they are blocked by throttle or by firewall or not.
NON_FIREWALL, // When the connection is not blocked by a firewall. It will call event. (priority: firewall > throttle)
READY_DECODING, // Call event before decoder. If is canceled. We will close the pipeline. (Throttle may close the connection first.)
AFTER_DECODER, // Call the event after the base pipeline process and decoder. ( not recommend )
DISABLED // Call the void :D. to save performance.
} | 4 | Kotlin | 0 | 8 | a9d69f468eea2f5dfdcb07aa7a9a6e4496938c17 | 1,246 | MoeFilter | Apache License 2.0 |
app/src/main/java/space/pal/sig/view/splash/SplashViewModel.kt | icatalin201 | 179,758,397 | false | null | package space.pal.sig.view.splash
import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import space.pal.sig.service.DataSyncWorker
import space.pal.sig.service.ScheduleManager
import space.pal.sig.util.SharedPreferencesUtil
import space.pal.sig.view.BaseViewModel
/**
SpaceNow
Created by Catalin on 12/13/2020
**/
class SplashViewModel(
application: Application,
sharedPreferencesUtil: SharedPreferencesUtil
) : BaseViewModel(application) {
companion object {
const val IS_FIRST_TIME = "SpaceNow.IsFirstTime"
}
private val safeForStart = MediatorLiveData<Boolean>()
private val syncResult = ScheduleManager
.launchOneTimeSync(application, DataSyncWorker.DATA_SYNC_WORKER_TAG)
init {
val isFirstTime = sharedPreferencesUtil.get(IS_FIRST_TIME, true)
if (isFirstTime) {
safeForStart.addSource(syncResult) { workInfoList ->
val finished = workInfoList[0].state.isFinished
safeForStart.value = finished
sharedPreferencesUtil.save(IS_FIRST_TIME, false)
}
} else {
safeForStart.value = true
}
}
fun isSafeForStart(): LiveData<Boolean> {
return safeForStart
}
} | 0 | Kotlin | 0 | 0 | 9f8485e7ef1580be8c84dd34babd99571bed277a | 1,309 | SpaceNow | Apache License 2.0 |
api/src/main/kotlin/com/myna/mnbt/codec/BinaryCodecInstances.kt | Cmyna | 594,304,817 | false | null | package com.myna.mnbt.codec
import com.myna.mnbt.utils.Extensions.toBasic
import com.myna.mnbt.utils.Extensions.toBytes
import com.myna.mnbt.tag.*
import com.myna.mnbt.reflect.TypeCheckTool
import java.lang.IllegalArgumentException
import com.myna.mnbt.*
import com.myna.mnbt.core.CodecTool
import com.myna.mnbt.presets.BitsArrayLengthGetter
import com.myna.mnbt.utils.CodecIntentExentions.decodeHead
import com.myna.mnbt.utils.CodecIntentExentions.tryGetId
import java.lang.NullPointerException
typealias RArray = java.lang.reflect.Array
object BinaryCodecInstances {
val intCodec = object: NumberTypeFlatCodec<Int, PrimitiveTag.IntTag>(IdTagInt, 0) {
override fun createTag(name: String?, value: Int) = PrimitiveTag.IntTag(name, value)
} as DefaultCodec<Int>
val byteCodec = object: NumberTypeFlatCodec<Byte, PrimitiveTag.ByteTag>(IdTagByte, 0.toByte()) {
override fun createTag(name: String?, value: Byte) = PrimitiveTag.ByteTag(name, value)
} as DefaultCodec<Byte>
val shortCodec = object: NumberTypeFlatCodec<Short, PrimitiveTag.ShortTag>(IdTagShort, 0.toShort()) {
override fun createTag(name: String?, value: Short) = PrimitiveTag.ShortTag(name, value)
} as DefaultCodec<Short>
val longCodec = object: NumberTypeFlatCodec<Long, PrimitiveTag.LongTag>(IdTagLong, 0.toLong()) {
override fun createTag(name: String?, value: Long) = PrimitiveTag.LongTag(name, value)
} as DefaultCodec<Long>
val floatCodec = object: NumberTypeFlatCodec<Float, PrimitiveTag.FloatTag>(IdTagFloat,0.0f) {
override fun createTag(name: String?, value: Float) = PrimitiveTag.FloatTag(name, value)
} as DefaultCodec<Float>
val doubleCodec = object: NumberTypeFlatCodec<Double, PrimitiveTag.DoubleTag>(IdTagDouble,0.0) {
override fun createTag(name: String?, value: Double) = PrimitiveTag.DoubleTag(name, value)
} as DefaultCodec<Double>
val nullTagCodec = NullTagCodec()
val stringCodec = StringCodec() as DefaultCodec<String>
val byteArrayCodec = FixPayloadArrayTagFlatCodec<Byte, ByteArray>(
IdTagByteArray, 1, { name, value-> ArrayTag.ByteArrayTag(name, value)},
{bytes,pointer,arr,i -> arr[i] = bytes.toBasic(pointer, 0.toByte())},
{arr,i-> arr[i].toBytes()},
BitsArrayLengthGetter::defaultToInt,
ByteArray::class.java
) as DefaultCodec<ByteArray>
val intArrayCodec = FixPayloadArrayTagFlatCodec<Int, IntArray>(
IdTagIntArray, 4, { name, value-> ArrayTag.IntArrayTag(name, value)},
{bytes,pointer,arr,i -> arr[i] = bytes.toBasic(pointer, 0)},
{arr,i-> arr[i].toBytes()},
BitsArrayLengthGetter::defaultToInt,
IntArray::class.java) as DefaultCodec<IntArray>
val longArrayCodec = FixPayloadArrayTagFlatCodec<Long, LongArray>(
IdTagLongArray, 8, { name, value-> ArrayTag.LongArrayTag(name, value)},
{bytes,pointer,arr,i -> arr[i] = bytes.toBasic(pointer, 0.toLong())},
{arr,i-> arr[i].toBytes()},
BitsArrayLengthGetter::defaultToInt,
LongArray::class.java) as DefaultCodec<LongArray>
private class StringCodec: DefaultCodec<String>(IdTagString, String::class.java) {
override fun encodeValue(value: String, intent: EncodeOnStream):CodecFeedback {
val valueBits = value.toByteArray(Charsets.UTF_8)
if (valueBits.size > 65535) throw IllegalArgumentException("String Tag value length is over 65535!")
val valueLen = valueBits.size
intent.outputStream.write(valueLen.toShort().toBytes())
intent.outputStream.write(valueBits)
return object:CodecFeedback {}
}
override fun decodeToValue(intent: DecodeOnStream): String {
val inputStream = intent.inputStream
val bitsLen = inputStream.readNBytes(2).toBasic<Short>(0, 0).toInt()
return inputStream.readNBytes(bitsLen).toString(Charsets.UTF_8)
}
override fun createTag(name: String?, value: String): Tag<String> {
return PrimitiveTag.StringTag(name, value)
}
}
@Suppress("UNCHECKED_CAST")
/**
* now this class should not be implemented in other place, because it only support limit of subclass from Number.
* the main reason is the extend function not supported
*/
private abstract class NumberTypeFlatCodec<V:Number, T: Tag<V>>(id:Byte, val inst:V) :
DefaultCodec<V>(id, inst::class.java as Class<V>) {
val instSize = inst.toBytes().size
override fun encodeValue(value: V, intent: EncodeOnStream):CodecFeedback {
intent.outputStream.write(value.toBytes())
return object:CodecFeedback {}
}
override fun decodeToValue(intent: DecodeOnStream):V {
return intent.inputStream.readNBytes(instSize).toBasic(0, inst)
}
}
/**
* here restrict the Tag sub-class related generic type is an array by check generic type ET of input parameters clazz
*/
private class FixPayloadArrayTagFlatCodec<E:Any, ARR:Any>
(
id:Byte,
val elementSize:Int,
val tagCreation: (name: String?, value: ARR) -> Tag<ARR>,
val setBytesElementToArray: (data:ByteArray, start:Int, arrInst:ARR, elementIndex:Int)->Unit,
val elementToBits: (elementArr:ARR, index:Int)->ByteArray,
val bitsToArrayLength: (data:ByteArray, start:Int)->Int, // bits to array length function
valueTypeToken:Class<ARR>,
) : DefaultCodec<ARR>(id, valueTypeToken) {
init {
//check Tag value type is fix payload array (has actual type)
if (
(!TypeCheckTool.isArray(valueTypeToken)) ||
(valueTypeToken.componentType) !is Class<*>) {
throw IllegalArgumentException("the Codec class can not accept a type that is $valueTypeToken" +
"with component ${valueTypeToken.componentType}!"+
"Codec can only accept tag value type which is an actual Array with fix payload!")
}
}
override fun createTag(name: String?, value: ARR): Tag<ARR> = tagCreation(name, value)
@Suppress("UNCHECKED_CAST")
override fun encodeValue(value: ARR, intent: EncodeOnStream):CodecFeedback {
val elementNum = RArray.getLength(value)
val outputStream = intent.outputStream
outputStream.write(elementNum.toBytes())
for (i in 0 until elementNum) {
val elementBits = elementToBits(value, i)
outputStream.write(elementBits)
}
return object:CodecFeedback {}
}
@Suppress("UNCHECKED_CAST")
override fun decodeToValue(intent: DecodeOnStream): ARR {
val inputStream = intent.inputStream
// read element num
val size = bitsToArrayLength(inputStream.readNBytes(ArraySizePayload), 0)
if (size < 0) throw IllegalArgumentException("get invalid binary Nbt data, array size $size is negative!")
val array = RArray.newInstance(valueTypeToken.componentType, size) as ARR
for (i in 0 until size) {
setBytesElementToArray(inputStream.readNBytes(elementSize), 0, array, i)
}
return array
}
}
@Suppress("UNCHECKED_CAST")
class ListTagCodec(override var proxy: Codec<Any>)
: HierarchicalCodec<AnyTagList> {
override val id: Byte = IdTagList
override val valueTypeToken = MutableList::class.java as Class<AnyTagList>
override fun encode(tag: Tag<out AnyTagList>, intent: CodecCallerIntent):CodecFeedback {
intent as EncodeHead; intent as EncodeOnStream
val hasHead = intent.encodeHead
val parents = (intent as RecordParentsWhenEncoding).parents
if (tag !is ListTag<*>) throw IllegalArgumentException("List Tag Codec can only handle tag type that is ListTag, but ${tag::class.java} is passed")
val name = if (hasHead) tag.name?: throw NullPointerException("want serialize tag with tag head, but name was null!") else null
if (name != null) CodecTool.writeTagHead(id, name, intent.outputStream)
// write element id
intent.outputStream.write(tag.elementId.toInt())
// write array size
intent.outputStream.write(tag.value.size.toBytes())
val proxyIntent = toProxyIntent(false, parents, intent.outputStream)
for (tags in tag.value) {
proxy.encode(tags, proxyIntent)
}
return object:OutputStreamFeedback{
override val outputStream = intent.outputStream
}
}
override fun decode(intent: CodecCallerIntent): TagFeedback<AnyTagList> {
intent as DecodeOnStream;
// read tag head if intent wants
val name = if (intent is DecodeHead) intent.decodeHead(id) else null
// read element id
val elementId = intent.inputStream.read().toByte()
// read list size
val size = intent.inputStream.readNBytes(4).toBasic(0,0)
val nbtlist = ListTag<Any>(elementId, name)
val proxyIntent = toProxyIntent(intent, false, elementId)
for (i in 0 until size) {
val feedback = proxy.decode(proxyIntent)
nbtlist.add(feedback.tag)
}
return object:TagFeedback<AnyTagList> {
override val tag: Tag<AnyTagList> = nbtlist
}
}
}
class CompoundTagCodec(override var proxy: Codec<Any>)
: DefaultCodec<AnyCompound>(IdTagCompound, Collection::class.java as Class<AnyCompound>),HierarchicalCodec<AnyCompound> {
override fun createTag(name: String?, value: AnyCompound): Tag<AnyCompound> {
return CompoundTag(name, value)
}
override fun encodeValue(value: AnyCompound, intent: EncodeOnStream):CodecFeedback {
val parents = (intent as RecordParentsWhenEncoding).parents
val proxyIntent = toProxyIntent(true, parents, intent.outputStream)
value.onEach {
checkNotNull(it.value.name) // name should not be null
proxy.encode(it.value, proxyIntent)
}
// write TagEnd
intent.outputStream.write(IdTagEnd.toInt())
return object: CodecFeedback{}
}
override fun decodeToValue(intent: DecodeOnStream): AnyCompound {
var subTagId = intent.tryGetId()
val compound = mutableMapOf<String, Tag<out Any>>()
while (subTagId != IdTagEnd) {
val proxyIntent = toProxyIntent(intent, true, subTagId, true)
val feedback = proxy.decode(proxyIntent)
compound[feedback.tag.name!!] = feedback.tag
subTagId = intent.tryGetId()
}
//inputStream.read()
return compound
}
}
class NullTagCodec : Codec<Unit> {
override val id: Byte = IdTagEnd
// hacky way, because can not init TypeToken<Nothing>(or TypeToken<void>)
override val valueTypeToken = Unit::class.java
override fun encode(tag: Tag<out Unit>, intent: CodecCallerIntent):CodecFeedback {
intent as EncodeOnStream
intent.outputStream.write(IdTagEnd.toInt())
return object:CodecFeedback{}
}
override fun decode(intent: CodecCallerIntent): TagFeedback<Unit> {
intent as DecodeOnStream; intent as DecodeHead
val inputStream = intent.inputStream
if (!intent.ignoreIdWhenDecoding)CodecTool.checkNbtFormat(inputStream, id)
return object:TagFeedback<Unit> {
override val tag = NullTag.inst
}
}
}
} | 0 | Kotlin | 0 | 0 | 66cb51428a0aeec7773929a510b57530d4846eca | 12,134 | mnbt-in-development- | Apache License 2.0 |
src/commonMain/kotlin/CastleScene.kt | darknightz0 | 827,206,568 | false | {"Kotlin": 328817} |
import korlibs.datastructure.*
import korlibs.event.*
import korlibs.io.file.std.*
import korlibs.korge.input.*
import korlibs.korge.scene.*
import korlibs.korge.view.*
import korlibs.korge3d.*
import korlibs.korge3d.format.*
import korlibs.korge3d.format.gltf2.*
import korlibs.korge3d.shape.*
import korlibs.math.geom.*
import korlibs.time.*
import java.awt.*
class CastleScene:Scene() {
var degh = 0.degrees//鏡頭開始角度(水平)Z+看向Z-
var degv = 30.degrees//鏡頭開始角度(垂直 俯角)0~180度 Y+看向Y-
val dt = 30.milliseconds//按鍵偵測間隔
val dt_animate_s = 0.1.seconds//動畫播放間隔
var dt_animate = dt_animate_s
val sp_s = 0.3f//跑速 (跑速/按鍵偵測間隔=m/s)
//var msfix=false
var sp = sp_s
val jf = 20f//彈跳力
val gravity = Vector3.DOWN * 30f//加速度
var dis = 20f//鏡頭對人物距離
lateinit var chrac:GLTF2View
lateinit var scene3D:Stage3DView
lateinit var camera3D:Camera3D
fun cameraFix() {
camera3D.orbitAround(chrac.position, dis, degh, degv)
}
fun moveModel(theta: Angle) {
// 平移點
val translatedX = camera3D.x - chrac.x
val translatedZ = camera3D.z - chrac.z
// 應用旋轉矩陣
val rotatedX = translatedX * cosf(theta) - translatedZ * sinf(theta)
val rotatedZ = translatedX * sinf(theta) + translatedZ * cosf(theta)
// 平移回原位置
chrac.lookAt(rotatedX + chrac.x, chrac.y, rotatedZ + chrac.z)
chrac.updateAnimationDelta(dt_animate)
chrac.z += sp * cosf(degh + 180.degrees - theta)
chrac.x += sp * sinf(degh + 180.degrees - theta)
cameraFix()
}
override suspend fun SContainer.sceneInit() {
scene3D {
val centerPointAxisLines = axisLines(length = 100f)
centerPointAxisLines.position(0f,0f,0f)
camera3D=camera.positionLookingAt(
0f, 2f, 30f,
0f, 0f, 0f)
/* val library = resourcesVfs["human/chara2.dae"].readColladaLibrary()
val model = library.geometryDefs.values.first()
val view = mesh(model.mesh)*/
val boxx = mesh(resourcesVfs["human/chara2.dae"].readColladaLibrary().geometryDefs.values.first().mesh)
.position(0, 5, 0)
.rigidBody(RigidBody3D(1f, true))
chrac = gltf2View(resourcesVfs["Gest.glb"].readGLTF2(), autoAnimate = false)//載入人物移動動畫
.position(0, 0, 10)
.rigidBody(RigidBody3D(1f, true))
.name("player")
addChild(chrac)
cameraFix()
camera.speed=0.05f
}
}
override suspend fun SContainer.sceneMain() {
keys {
up(Key.SHIFT) {
sp = sp_s
}
justDown(Key.SHIFT) {
sp += 0.2f
}
justDown(Key.SPACE) {
chrac.rigidBody!!.velocity = Vector3.UP * jf
}
downFrame(listOf(Key.LEFT, Key.A), dt) {
if (input.keys[Key.W] || input.keys[Key.UP])
moveModel((-45).degrees)
else if (input.keys[Key.S] || input.keys[Key.DOWN])
moveModel((-135).degrees)
else
moveModel((-90).degrees)
}
downFrame(listOf(Key.RIGHT, Key.D), dt) {
if (input.keys[Key.W] || input.keys[Key.UP])
moveModel(45.degrees)
else if (input.keys[Key.S] || input.keys[Key.DOWN])
moveModel(135.degrees)
else
moveModel(90.degrees)
}
downFrame(listOf(Key.UP, Key.W), dt) {
if (!(input.keys[Key.A] || input.keys[Key.LEFT] || input.keys[Key.D] || input.keys[Key.RIGHT]))
moveModel(0.degrees)
}
downFrame(listOf(Key.DOWN, Key.S), dt) {
if (!(input.keys[Key.A] || input.keys[Key.LEFT] || input.keys[Key.D] || input.keys[Key.RIGHT]))
moveModel(180.degrees)
}
}
onScroll {
if (it.scrollDeltaYPixels > 0 && dis > 10) {//後滑
dis -= 1
} else if (it.scrollDeltaYPixels < 0 && dis < 30) {//前滑
dis += 1
}
cameraFix()
}
onClick {
it.doubleClick {
awtCursor.lock = !awtCursor.lock
if (awtCursor.lock) {
awtWindow?.cursor=invisibleCursor
} else {
awtWindow?.cursor=Cursor.getDefaultCursor()
}
}
}
val rigidBody = chrac.rigidBody
rigidBody?.acceleration = gravity
var pp=Vector3F.ZERO
addUpdater {
time ->
if (awtCursor.lock) {
degh += ((awtCursor.dxy.x)*camera3D.speed).degrees
degv += ((awtCursor.dxy.y)*camera3D.speed).degrees
if (degv < 30.degrees) {
degv = 30.degrees
}
if (degv > 110.degrees) {
degv = 110.degrees
}
awtCursor.dxy=Vector2D.ZERO
}
pp = (chrac.position + rigidBody!!.velocity * time.seconds)
if (pp.y < 0) {
pp = Vector3(pp.x, 0f, pp.z)
rigidBody.velocity = Vector3(rigidBody.velocity.x, 0f, rigidBody.velocity.z)
} else {
rigidBody.velocity += rigidBody.acceleration * time.seconds
}
chrac.position = pp
cameraFix()
}
/*
addUpdater {
/*
scene3D?.stage3D.foreachDescendant { maj ->
val rigid = maj.rigidBody
val collider = maj.collider
if (rigid != null && collider != null && rigidBody.useGravity) {
rigid.acceleration = gravity
rigid.velocity += rigidBody.acceleration * dt.seconds
scene3D?.stage3D.foreachDescendant { other ->
if (other !== maj) {
val otherCollider = other.collider
if (otherCollider != null) {
val collision =
Colliders.collide(collider, maj.transform, otherCollider, other.transform)
if (collision != null) {
maj.position += rigid.velocity.normalized() * collision.separation
rigid.velocity = rigid.velocity.reflected(collision.normal) * 0.8
}
}
}
}
}
}*/
}*/
}
}
| 0 | Kotlin | 0 | 0 | 39b506c69ec18ac6e95aeb62570c1ee8d17bfdb8 | 6,795 | korge-k3d-0.0.5_exercise | MIT License |
src/main/kotlin/br/com/zup/chavePix/registroChave/RegistroChaveRequest.kt | Thalyta-dev | 385,303,397 | true | {"Kotlin": 24609, "Smarty": 1792, "Dockerfile": 115} | package br.com.zup.chavePix.registroChave
import br.com.zup.edu.shared.validation.ValidUUID
import com.zup.PixRegistraRequest
import io.micronaut.core.annotation.Introspected
import java.util.*
import javax.validation.constraints.NotNull
@Introspected
data class RegistroChaveRequest(
@field: NotNull val tipoChave: TipoChave,
val valorChave: String,
@field: NotNull val tipoConta: TipoConta
) {
fun toGrpcRequest(clienteId: String): PixRegistraRequest {
return PixRegistraRequest.newBuilder()
.setIdCliente(clienteId)
.setTipoChave(com.zup.TipoChave.valueOf(tipoChave.toString()))
.setValorChave(valorChave)
.setTipoConta(com.zup.TipoConta.valueOf(tipoConta.toString())).build()
}
}
enum class TipoChave {
EMAIL {
override fun validaChave(chave: String): Boolean {
return chave.matches("^[a-zA-Z0-9.!#\$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*\$".toRegex())
}
},
TELEFONE {
override fun validaChave(chave: String): Boolean {
return chave.matches("^[0-9]{11}\$".toRegex())
}
},
CPF {
override fun validaChave(chave: String): Boolean {
return chave.matches("^([0-9]{3}+-[0-9]{3}+-[0-9]{3}+.[0-9]{2})\$".toRegex())
}
},
ALEATORIA {
override fun validaChave(chave: String): Boolean {
return true
}
},
DEFAULT {
override fun validaChave(chave: String): Boolean {
return true
}
};
abstract fun validaChave(chave: String): Boolean
}
enum class TipoConta {
CONTA_CORRENTE ,
CONTA_POUPANCA,
DEFAULTCONTA
}
| 0 | Kotlin | 0 | 0 | 00a93ac6eb71af323fd774d3cdf263d1500d60d7 | 1,712 | orange-talents-05-template-pix-keymanager-rest | Apache License 2.0 |
auth/src/main/java/studio/crud/feature/auth/authentication/mfa/model/MfaTypePairPojo.kt | crud-studio | 390,327,908 | false | null | package studio.crud.feature.auth.authentication.mfa.model
import studio.crud.feature.auth.authentication.mfa.enums.MfaType
data class MfaTypePairPojo(val entityId: Long, val mfaType: MfaType) | 6 | Kotlin | 0 | 0 | 6cb1d5f7b3fc7117c9fbaaf6708ac93ae631e674 | 193 | feature-depot | MIT License |
serialization/src/main/kotlin/io/github/airflux/serialization/core/value/ValueNode.kt | airflux | 336,002,943 | false | null | /*
* Copyright 2021-2023 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.github.airflux.serialization.core.value
import io.github.airflux.serialization.core.path.PropertyPath
public sealed class ValueNode {
public abstract val nameOfType: String
}
public object NullNode : ValueNode() {
override val nameOfType: String = "null"
override fun toString(): String = "null"
}
public sealed class BooleanNode(public val get: Boolean) : ValueNode() {
override val nameOfType: String = BooleanNode.nameOfType
public object True : BooleanNode(true)
public object False : BooleanNode(false)
override fun toString(): String = get.toString()
public companion object {
public fun valueOf(value: Boolean): BooleanNode = if (value) True else False
public const val nameOfType: String = "boolean"
}
}
public class StringNode(public val get: String) : ValueNode() {
override val nameOfType: String = StringNode.nameOfType
override fun toString(): String = """"$get""""
override fun equals(other: Any?): Boolean =
this === other || (other is StringNode && this.get == other.get)
override fun hashCode(): Int = get.hashCode()
public companion object {
public const val nameOfType: String = "string"
}
}
public fun NumericNode.Integer.Companion.valueOf(value: Byte): NumericNode.Integer = valueOrNullOf(value.toString())!!
public fun NumericNode.Integer.Companion.valueOf(value: Short): NumericNode.Integer = valueOrNullOf(value.toString())!!
public fun NumericNode.Integer.Companion.valueOf(value: Int): NumericNode.Integer = valueOrNullOf(value.toString())!!
public fun NumericNode.Integer.Companion.valueOf(value: Long): NumericNode.Integer = valueOrNullOf(value.toString())!!
public sealed class NumericNode private constructor(public val get: String) : ValueNode() {
override fun toString(): String = get
override fun equals(other: Any?): Boolean =
this === other || (other is NumericNode && this.get == other.get)
override fun hashCode(): Int = get.hashCode()
public class Integer private constructor(value: String) : NumericNode(value) {
override val nameOfType: String = Integer.nameOfType
public companion object {
public const val nameOfType: String = "integer"
private val pattern = "^-?(0|[1-9][0-9]*)$".toRegex()
public fun valueOrNullOf(value: String): Integer? = if (value.matches(pattern)) Integer(value) else null
}
}
public class Number(value: String) : NumericNode(value) {
override val nameOfType: String = Number.nameOfType
public companion object {
public const val nameOfType: String = "number"
private val pattern = "^(-?(0|[1-9][0-9]*))((\\.[0-9]+)?|(\\.[0-9]+)?[eE][+-]?[0-9]+)$".toRegex()
public fun valueOrNullOf(value: String): Number? = if (value.matches(pattern)) Number(value) else null
}
}
}
public class ArrayNode<out T : ValueNode>(private val items: List<T> = emptyList()) : ValueNode(), Iterable<T> {
override val nameOfType: String = ArrayNode.nameOfType
public operator fun get(idx: PropertyPath.Element.Idx): ValueNode? = get(idx.get)
public operator fun get(idx: Int): ValueNode? = items.getOrNull(idx)
public val size: Int
get() = items.size
public fun isEmpty(): Boolean = items.isEmpty()
override fun iterator(): Iterator<T> = items.iterator()
override fun toString(): String = items.joinToString(prefix = "[", postfix = "]")
override fun equals(other: Any?): Boolean =
this === other || (other is ArrayNode<*> && this.items == other.items)
override fun hashCode(): Int = items.hashCode()
public companion object {
public const val nameOfType: String = "array"
public operator fun <T : ValueNode> invoke(vararg elements: T): ArrayNode<T> = ArrayNode(elements.toList())
}
}
public class StructNode(
private val properties: Map<String, ValueNode> = emptyMap()
) : ValueNode(),
Iterable<Map.Entry<String, ValueNode>> {
override val nameOfType: String = StructNode.nameOfType
public operator fun get(key: PropertyPath.Element.Key): ValueNode? = get(key.get)
public operator fun get(key: String): ValueNode? = properties[key]
public val count: Int
get() = properties.size
public fun isEmpty(): Boolean = properties.isEmpty()
override fun iterator(): Iterator<Map.Entry<String, ValueNode>> = properties.iterator()
override fun toString(): String = properties.map { (name, value) -> """"$name": $value""" }
.joinToString(prefix = "{", postfix = "}")
override fun equals(other: Any?): Boolean =
this === other || (other is StructNode && this.properties.keys == other.properties.keys)
override fun hashCode(): Int = properties.keys.hashCode()
public companion object {
public const val nameOfType: String = "object"
public operator fun invoke(vararg properties: Pair<String, ValueNode>): StructNode =
StructNode(properties.toMap())
}
}
| 0 | Kotlin | 3 | 3 | 9dfcfe4ec288e27f150beeef12dff45f131d0805 | 5,667 | airflux-serialization | Apache License 2.0 |
mewwalletkit/src/androidTest/java/com/myetherwallet/mewwalletkit/eip/eip2930/Eip2930TransactionTest.kt | MyEtherWallet | 225,455,950 | false | {"Kotlin": 656659} | package com.myetherwallet.mewwalletkit.eip.eip2930
import com.myetherwallet.mewwalletkit.bip.bip44.Address
import com.myetherwallet.mewwalletkit.bip.bip44.Network
import com.myetherwallet.mewwalletkit.bip.bip44.PrivateKey
import com.myetherwallet.mewwalletkit.core.extension.hexToByteArray
import com.myetherwallet.mewwalletkit.core.extension.sign
import org.junit.Assert
import org.junit.Test
/**
* Created by BArtWell on 14.07.2021.
*/
class Eip2930TransactionTest {
private val testVectors = arrayOf(
TestVector(
0,
"0x00",
"0x01",
"0x3b9aca00",
"0x62d4",
"0xdf0a88b2b68c673713a8ec826003676f272e3573",
ByteArray(0),
arrayOf(AccessList(Address("0x0000000000000000000000000000000000001337"), arrayOf("0x0000000000000000000000000000000000000000000000000000000000000000".hexToByteArray()))),
null,
null,
"0x01f8a587796f6c6f76337880843b9aca008262d494df0a88b2b68c673713a8ec826003676f272e35730180f838f7940000000000000000000000000000000000001337e1a0000000000000000000000000000000000000000000000000000000000000000080a0294ac94077b35057971e6b4b06dfdf55a6fbed819133a6c1d31e187f1bca938da00be950468ba1c25a5cb50e9f6d8aa13c8cd21f24ba909402775b262ac76d374d",
"0xbbd570a3c6acc9bb7da0d5c0322fe4ea2a300db80226f7df4fef39b2d6649eec",
"0x796f6c6f763378",
"0xfad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19"
),
TestVector(
1,
"0x",
"0x",
"0x",
"0x",
"0x0101010101010101010101010101010101010101",
"0x010200".hexToByteArray(),
arrayOf(AccessList(Address("0x0101010101010101010101010101010101010101"), arrayOf("0x0101010101010101010101010101010101010101010101010101010101010101".hexToByteArray()))),
"0x01f858018080809401010101010101010101010101010101010101018083010200f838f7940101010101010101010101010101010101010101e1a00101010101010101010101010101010101010101010101010101010101010101",
"0x78528e2724aa359c58c13e43a7c467eb721ce8d410c2a12ee62943a3aaefb60b",
null,
null,
"0x01",
"0x4646464646464646464646464646464646464646464646464646464646464646"
)
)
@Test
fun shouldSignTransactionAndReturnsTheExpectedSignature() {
for (vector in testVectors) {
val transaction = vector.transaction
val privateKey = PrivateKey.createWithPrivateKey(vector.pkBytes, Network.ETHEREUM)
if (vector.unsignedTransactionRlpBytes != null) {
Assert.assertArrayEquals(vector.unsignedTransactionRlpBytes, transaction.serialize())
}
if (vector.unsignedHashBytes != null) {
Assert.assertArrayEquals(vector.unsignedHashBytes, transaction.hash(transaction.chainId, true))
}
transaction.sign(privateKey)
Assert.assertNotNull(transaction.signature)
vector.signedTransactionRlpBytes?.let {
val serialized = transaction.serialize()
Assert.assertArrayEquals(it, serialized)
}
val signedHash = transaction.hash(transaction.chainId, false)
vector.signedHashBytes?.let {
Assert.assertArrayEquals(it, signedHash)
}
}
}
data class TestVector(
val id: Int,
val nonce: String,
val value: String,
val gasPrice: String,
val gasLimit: String,
val to: String,
val data: ByteArray = ByteArray(0),
val accessList: Array<AccessList>? = null,
val unsignedTransactionRlp: String? = null,
val unsignedHash: String? = null,
val signedTransactionRlp: String? = null,
val signedHash: String? = null,
val chainId: String,
val pk: String
) {
val pkBytes = pk.hexToByteArray()
val transaction: Eip2930Transaction
val unsignedTransactionRlpBytes = unsignedTransactionRlp?.hexToByteArray()
val unsignedHashBytes = unsignedHash?.hexToByteArray()
val signedTransactionRlpBytes = signedTransactionRlp?.hexToByteArray()
val signedHashBytes = signedHash?.hexToByteArray()
init {
val privateKey = PrivateKey.createWithPrivateKey(pkBytes, Network.ETHEREUM)
transaction = Eip2930Transaction(
nonce,
gasPrice,
gasLimit,
Address(to),
value,
data,
privateKey.address(),
accessList ?: arrayOf(AccessList.EMPTY),
chainId.hexToByteArray()
)
}
}
} | 3 | Kotlin | 31 | 55 | 20eddbc0ca5bb973ca5e5ba4a8b4de7d745f12a9 | 4,787 | mew-wallet-android-kit | MIT License |
vertx-consul-service/src/main/kotlin/io/vertx/kotlin/ext/consul/ServiceEntry.kt | tsegismont | 156,562,152 | true | {"Java": 63718, "Kotlin": 30327, "Shell": 333} | package io.vertx.kotlin.ext.consul
import io.vertx.ext.consul.ServiceEntry
import io.vertx.ext.consul.Check
import io.vertx.ext.consul.Node
import io.vertx.ext.consul.Service
fun ServiceEntry(
checks: Iterable<io.vertx.ext.consul.Check>? = null,
node: io.vertx.ext.consul.Node? = null,
service: io.vertx.ext.consul.Service? = null): ServiceEntry = io.vertx.ext.consul.ServiceEntry().apply {
if (checks != null) {
this.setChecks(checks.toList())
}
if (node != null) {
this.setNode(node)
}
if (service != null) {
this.setService(service)
}
}
| 0 | Java | 0 | 0 | ab2732d6e3eee1c1b28f711bca35e640eaac5cba | 574 | vertx-client-services | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/SortCircle.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.SortCircle: ImageVector
get() {
if (_sortCircle != null) {
return _sortCircle!!
}
_sortCircle = Builder(name = "SortCircle", 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(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-4.962f, 0.0f, -9.0f, -4.037f, -9.0f, -9.0f)
reflectiveCurveTo(7.038f, 3.0f, 12.0f, 3.0f)
reflectiveCurveToRelative(9.0f, 4.037f, 9.0f, 9.0f)
reflectiveCurveToRelative(-4.037f, 9.0f, -9.0f, 9.0f)
close()
moveTo(5.25f, 13.0f)
horizontalLineToRelative(13.5f)
lineToRelative(-5.689f, 5.561f)
curveToRelative(-0.586f, 0.586f, -1.535f, 0.586f, -2.121f, 0.0f)
lineToRelative(-5.69f, -5.561f)
close()
moveTo(18.75f, 11.0f)
lineTo(5.25f, 11.0f)
lineToRelative(5.69f, -5.561f)
curveToRelative(0.586f, -0.586f, 1.535f, -0.586f, 2.121f, 0.0f)
lineToRelative(5.689f, 5.561f)
close()
}
}
.build()
return _sortCircle!!
}
private var _sortCircle: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,453 | icons | MIT License |
kodando-rxjs/src/main/kotlin/kodando/rxjs/observable/Timer.kt | kodando | 81,663,289 | false | null | @file:Suppress("UnsafeCastFromDynamic")
package kodando.rxjs.observable
import kodando.rxjs.JsFunction
import kodando.rxjs.Observable
import kodando.rxjs.fromModule
import kodando.rxjs.import
import kotlin.js.Date
private val timer_: JsFunction =
fromModule("rxjs") import "timer"
fun timer(initialDelay: Int, period: Int): Observable<Int> {
return timer_.call(null, initialDelay, period)
}
fun timer(initialDelay: Date, period: Int): Observable<Int> {
return timer_.call(null, initialDelay, period)
}
| 12 | Kotlin | 5 | 76 | f1428066ca01b395c1611717fde5463ba0042b19 | 514 | kodando | MIT License |
app/src/main/java/com/msa/oneway/core/BaseMixSideEffect.kt | abhimuktheeswarar | 291,122,473 | false | null | package com.msa.oneway.core
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.CoroutineScope
import kotlin.coroutines.CoroutineContext
/**
* Created by Abhi Muktheeswarar on 19-August-2020
*/
@Suppress("LeakingThis")
abstract class BaseMixSideEffect(
private val store: Store<*>,
private val threadExecutor: ThreadExecutor,
protected val coroutineDispatcherProvider: CoroutineDispatcherProvider,
protected val schedulerProvider: SchedulerProvider,
private val compositeDisposable: CompositeDisposable
) : SideEffect, CoroutineScope {
override val coroutineContext: CoroutineContext = coroutineDispatcherProvider.coroutineContext
init {
store.sideEffects.add(this)
}
override fun getActionThreadExecutor() = threadExecutor
protected fun addDisposable(disposable: Disposable) {
compositeDisposable.add(disposable)
}
fun dispatch(action: Action) {
store.dispatch(action)
}
@Suppress("UNCHECKED_CAST")
fun <S : State> state(): S = store.state as S
} | 0 | Kotlin | 0 | 1 | 3916ccacabe7303a01806ea94087d420edf6d902 | 1,112 | OneWayAndroid | Apache License 2.0 |
app/src/main/java/at/deflow/materialcalculator/domain/Operation.kt | Flowdawan | 539,007,326 | false | null | package at.deflow.materialcalculator.domain
enum class Operation(val symbol: Char) {
ADD('+'),
SUBTRACT('-'),
MULTIPLY('x'),
DIVIDE('/'),
PERCENT('%'),
}
val operationSymbols = Operation.values().map { it.symbol }.joinToString("")
fun operationFromSymbol(symbol: Char): Operation {
return Operation.values().find { it.symbol == symbol }
?: throw IllegalArgumentException("Invalid symbol")
} | 0 | Kotlin | 0 | 0 | d8d46de23c33ae52036a57145404804361f06d4a | 425 | SimpleAndroidCalculator | MIT License |
door-runtime/src/commonMain/kotlin/com/ustadmobile/door/util/WeakRefOf.kt | UstadMobile | 344,538,858 | false | {"Kotlin": 1028056, "JavaScript": 1100, "HTML": 430, "Shell": 89} | package com.ustadmobile.door.util
expect fun <T: Any> weakRefOf(target: T): IWeakRef<T>
| 5 | Kotlin | 1 | 162 | 9912ce18848c6f3d4c5e78e06aeb78542e2670a5 | 89 | door | Apache License 2.0 |
composeApp/src/commonMain/kotlin/data/local/DataStoreRepository.kt | AbdulRehmanNazar | 812,858,902 | false | {"Kotlin": 6177, "Swift": 594} | package data.local
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.map
/**
* @Author: <NAME>
*/
public class DataStoreRepository(private val dataStore: DataStore<Preferences>) {
companion object {
val TIMESTAMP_KEY = longPreferencesKey(name = "saved_timestamp")
}
suspend fun saveTimeStamp(timeStamp: Long): Boolean = try {
dataStore.edit { preferences ->
preferences.set(key = TIMESTAMP_KEY, value = timeStamp)
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
fun readTimeStamp(): Flow<Long> =
dataStore.data
.catch { emptyFlow<Long>() }
.map { prefrences ->
prefrences[TIMESTAMP_KEY] ?: 0L
}
} | 0 | Kotlin | 0 | 0 | 43f1dfe6e09edf65bf2f70f5deb92eeab41d2a60 | 1,062 | KMPDataStore | Apache License 2.0 |
app/src/main/java/co/kaush/msusf/movies/MSMovieVm.kt | anandpurushottam | 150,232,875 | true | {"Kotlin": 28721} | package co.kaush.msusf.movies
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import co.kaush.msusf.MSApp
import co.kaush.msusf.movies.MSMovieEvent.ClickMovieEvent
import co.kaush.msusf.movies.MSMovieEvent.ClickMovieFromHistoryEvent
import co.kaush.msusf.movies.MSMovieEvent.ScreenLoadEvent
import co.kaush.msusf.movies.MSMovieEvent.SearchMovieEvent
import co.kaush.msusf.movies.MSMovieResult.ClickMovieResult
import co.kaush.msusf.movies.MSMovieResult.ScreenLoadResult
import co.kaush.msusf.movies.MSMovieResult.SearchMovieResult
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
/**
* For this example, a simple ViewModel would have sufficed,
* but in most real world examples we would use an AndroidViewModel
*
* Our Unit tests should still be able to run given this
*/
class MSMainVm(
app: MSApp,
private val movieRepo: MSMovieRepository
) : AndroidViewModel(app) {
private var viewState: MSMovieViewState = MSMovieViewState()
fun send(vararg es: Observable<out MSMovieEvent>): Observable<MSMovieViewState> {
// gather events
val events: Observable<out MSMovieEvent> = Observable.mergeArray(*es)
.doOnNext { Timber.d("----- event ${it.javaClass.simpleName}") }
// events -> results (use cases)
val results: Observable<Lce<out MSMovieResult>> = results(events)
.doOnNext { Timber.d("----- result $it") }
// results -> view state
return render(results)
.doOnNext { Timber.d("----- viewState $it") }
}
// -----------------------------------------------------------------------------------
// Internal helpers
private fun results(events: Observable<out MSMovieEvent>): Observable<Lce<out MSMovieResult>> {
return events.publish { o ->
Observable.merge(
o.ofType(ScreenLoadEvent::class.java).compose(onScreenLoad()),
o.ofType(SearchMovieEvent::class.java).compose(onMovieSearch()),
o.ofType(ClickMovieEvent::class.java).compose(onMovieSelect()),
o.ofType(ClickMovieFromHistoryEvent::class.java).compose(onMovieFromHistorySelect())
)
}
}
private fun render(results: Observable<Lce<out MSMovieResult>>): Observable<MSMovieViewState> {
return results.scan(viewState) { state, result ->
when (result) {
is Lce.Content -> {
when (result.packet) {
is ScreenLoadResult -> state.copy(searchBoxText = "")
is SearchMovieResult -> {
val movie: MSMovie = result.packet.movie
state.copy(
searchedMovieTitle = movie.title,
searchedMovieRating = movie.ratingSummary,
searchedMoviePoster = movie.posterUrl,
searchedMovieReference = movie
)
}
is ClickMovieResult -> {
(result.packet.clickedMovie)
?.let {
val adapterList: MutableList<MSMovie> =
mutableListOf(*state.adapterList.toTypedArray())
adapterList.add(it)
state.copy(adapterList = adapterList)
} ?: state.copy()
}
}
}
is Lce.Loading -> {
state.copy(
searchBoxText = null,
searchedMovieTitle = "Searching Movie...",
searchedMovieRating = "",
searchedMoviePoster = "",
searchedMovieReference = null
)
}
is Lce.Error -> {
when (result.packet) {
is SearchMovieResult -> {
val movie: MSMovie = result.packet.movie
state.copy(searchedMovieTitle = movie.errorMessage!!)
}
else -> throw RuntimeException("Unexpected result LCE state")
}
}
}
}
.distinctUntilChanged()
.doOnNext { viewState = it }
}
// -----------------------------------------------------------------------------------
// use cases
private fun onScreenLoad(): ObservableTransformer<ScreenLoadEvent, Lce<ScreenLoadResult>> {
return ObservableTransformer { upstream ->
upstream.map { Lce.Content(ScreenLoadResult) }
}
}
private fun onMovieSearch(): ObservableTransformer<SearchMovieEvent, Lce<SearchMovieResult>> {
return ObservableTransformer { upstream ->
upstream.switchMap { searchMovieEvent ->
movieRepo.searchMovie(searchMovieEvent.searchedMovieTitle)
.subscribeOn(Schedulers.io())
.map {
if (it.errorMessage?.isNullOrBlank() == false) {
Lce.Error(SearchMovieResult(it))
} else {
Lce.Content(SearchMovieResult(it))
}
}
.startWith(Lce.Loading())
}
}
}
private fun onMovieSelect(): ObservableTransformer<ClickMovieEvent, Lce<ClickMovieResult>> {
return ObservableTransformer { upstream ->
upstream.map {
val movieResult: MSMovie = viewState.searchedMovieReference!!
if (!viewState.adapterList.contains(movieResult)) {
Lce.Content(ClickMovieResult(movieResult))
} else {
Lce.Content(ClickMovieResult(null))
}
}
}
}
private fun onMovieFromHistorySelect(): ObservableTransformer<ClickMovieFromHistoryEvent,
Lce<SearchMovieResult>> {
return ObservableTransformer { upstream ->
upstream.map { Lce.Content(SearchMovieResult(it.movieFromHistory)) }
}
}
}
// -----------------------------------------------------------------------------------
// LCE
sealed class Lce<T> {
class Loading<T> : Lce<T>()
data class Content<T>(val packet: T) : Lce<T>()
data class Error<T>(val packet: T) : Lce<T>()
}
// -----------------------------------------------------------------------------------
class MSMainVmFactory(
private val app: MSApp,
private val movieRepo: MSMovieRepository
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return MSMainVm(app, movieRepo) as T
}
}
| 0 | Kotlin | 0 | 0 | ac06b1bed0bd9e117c5f8384f15c2380f7c27808 | 7,121 | movies-usf | Apache License 2.0 |
graphql-dgs/src/test/kotlin/com/netflix/graphql/dgs/OpenDirective.kt | Netflix | 317,375,887 | false | {"Kotlin": 1530406, "Java": 286741, "HTML": 14098, "Python": 8827, "TypeScript": 3328, "JavaScript": 2934, "Makefile": 1328} | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.netflix.graphql.dgs
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.idl.SchemaDirectiveWiring
import graphql.schema.idl.SchemaDirectiveWiringEnvironment
/**
* An `@DgsDirective` example for test purpose.
*/
@DgsDirective
open class OpenDirective : SchemaDirectiveWiring {
override fun onField(env: SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition>): GraphQLFieldDefinition {
return env.element
}
}
| 88 | Kotlin | 289 | 3,037 | bd2d0c524e70a9d1d625d518a94926c7b53a7e7c | 1,054 | dgs-framework | Apache License 2.0 |
src/main/kotlin/org/valkyrienskies/physics_api/Aliases.kt | ValkyrienSkies | 377,763,637 | false | null | package org.valkyrienskies.physics_api
typealias ConstraintId = Int
typealias PhysicsBodyId = Int
| 0 | Kotlin | 0 | 0 | ce7fb72a5751e69c2d517f8b385c9a98da3080c6 | 99 | Valkyrien-Skies-Physics-API | Apache License 2.0 |
androidApp/src/main/java/app/trian/mvi/feature/quiz/listQuiz/ListQuizState.kt | triandamai | 652,614,502 | false | null | package app.trian.mvi.feature.quiz.listQuiz
import android.os.Parcelable
import app.trian.mvi.data.model.Quiz
import app.trian.mvi.data.utils.dummyQuiz
import app.trian.mvi.ui.extensions.Empty
import app.trian.mvi.ui.internal.contract.MviState
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
import javax.annotation.concurrent.Immutable
@Immutable
@Parcelize
data class ListQuizState(
val a: String = String.Empty,
val quiz: @RawValue List<Quiz> = dummyQuiz,
override val effect: @RawValue ListQuizEffect = ListQuizEffect.Nothing
) :MviState<ListQuizEffect>(), Parcelable
| 0 | Kotlin | 0 | 2 | f5793b7cf9cd6b2d5eb89df1813666f7794da1ca | 609 | mvi | MIT License |
app/src/main/java/com/immortalidiot/wishescompose/logic/ClipboardHandler.kt | ImmortalIdiot | 862,416,448 | false | {"Kotlin": 64913} | package com.immortalidiot.wishescompose.logic
import android.content.Context
interface ClipboardHandler {
suspend fun copy(context: Context, copiedMessage: String)
suspend fun getLatestRecord(context: Context): String
}
| 0 | Kotlin | 0 | 0 | ac0cada634a64ea4d34d286cb8100e07b8bffdf8 | 230 | WishesCompose | MIT License |
src/main/kotlin/no/nav/aap/proxy/config/ServiceuserConfig.kt | navikt | 422,128,379 | false | {"Kotlin": 47051} | package no.nav.aap.proxy.config
import java.nio.charset.StandardCharsets.UTF_8
import java.util.*
import java.util.Base64.*
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("serviceuser")
data class ServiceuserConfig (val username: String, val password: String) {
val credentials = getEncoder().encodeToString("$username:$password".toByteArray(UTF_8))
}
| 0 | Kotlin | 0 | 2 | fbd7d535fcaa235f10f74c7c1312a79b9474def2 | 412 | aap-fss-proxy | MIT License |
app/src/main/java/com/syleiman/gingermoney/ui/activities/add_edit_account/fragments/add/dependency_injection/AddAccountFragmentModuleBinds.kt | AlShevelev | 158,343,218 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 4, "XML": 137, "Kotlin": 385, "JSON": 1} | package com.syleiman.gingermoney.ui.activities.add_edit_account.fragments.add.dependency_injection
import com.syleiman.gingermoney.ui.activities.add_edit_account.fragments.add.model.AddAccountModelImpl
import com.syleiman.gingermoney.ui.activities.add_edit_account.fragments.add.model.AddAccountModel
import dagger.Binds
import dagger.Module
@Module
abstract class AddAccountFragmentModuleBinds {
@Binds
abstract fun provideAddAccountModel(model: AddAccountModelImpl): AddAccountModel
} | 1 | null | 1 | 1 | 91ef2b9bd5c19043104734b588940841fa6f9f4f | 496 | ginger-money | MIT License |
common/src/main/java/net/sistr/flexibleguns/client/overlay/HudOverlayRenderer.kt | SistrScarlet | 437,250,021 | false | {"Kotlin": 239434, "Java": 36089} | package net.sistr.flexibleguns.client.overlay
import com.google.common.collect.Lists
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.minecraft.client.MinecraftClient
import net.minecraft.client.util.math.MatrixStack
import net.sistr.flexibleguns.util.HudRenderable
import net.sistr.flexibleguns.util.ItemInstanceHolder
@Environment(EnvType.CLIENT)
class HudOverlayRenderer {
val overlays = Lists.newArrayList<Overlay>()
companion object {
val INSTANCE = HudOverlayRenderer()
}
fun render(mc: MinecraftClient, matrices: MatrixStack, tickDelta: Float) {
overlays.forEach { it.render(mc, matrices, tickDelta) }
}
fun tick(mc: MinecraftClient) {
}
fun register(overlay: Overlay) {
overlays.add(overlay)
}
interface Overlay {
fun render(mc: MinecraftClient, matrices: MatrixStack, tickDelta: Float)
fun tick(mc: MinecraftClient)
}
} | 0 | Kotlin | 0 | 2 | c00fbbfbd98a253f971cb9f5c87a4cf3eef9b6a2 | 951 | FlexibleGuns | MIT License |
src/Chapter07/7.4_DestructuringDeclarations.kt | ldk123456 | 157,306,847 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "XML": 11, "Kotlin": 180, "Java": 5} | package Chapter07.DestructuringDeclarations
data class Point(val x: Int, val y: Int)
fun main() {
val point = Point(10, 20)
val (x, y) = point //声明变量x、y,然后用p的组件来初始化
println(x) //>>>10
println(y) //>>>20
} | 1 | null | 1 | 1 | 301ea7daa495231ff878317311d7ded3a0fbcbc8 | 225 | KotlinInAction | Apache License 2.0 |
khelius-cli/src/main/kotlin/com/dgsd/khelius/cli/nft/GetNftEventsCommand.kt | dlgrech | 566,134,665 | false | {"Kotlin": 109465, "Shell": 106} | package com.dgsd.khelius.cli.nft
import com.dgsd.khelius.cli.util.accountArgument
import com.dgsd.khelius.nft.NftApi
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.requireObject
import kotlinx.coroutines.runBlocking
/**
* Returns all NFT events for a specific account.
*/
internal class GetNftEventsCommand : CliktCommand(
name = "events",
help = "Returns all NFT events for a specific account."
) {
private val nftApi by requireObject<NftApi>()
private val account by accountArgument()
override fun run() = runBlocking {
val events = nftApi.getEvents(account)
echo(events)
}
} | 0 | Kotlin | 0 | 2 | eec38ab3e3597902fcf25eae5f2edbf7606f46cc | 639 | khelius | Apache License 2.0 |
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/filled/Trophy.kt | wiryadev | 380,639,096 | false | null | package com.wiryadev.bootstrapiconscompose.bootstrapicons.filled
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 com.wiryadev.bootstrapiconscompose.bootstrapicons.FilledGroup
public val FilledGroup.Trophy: ImageVector
get() {
if (_trophy != null) {
return _trophy!!
}
_trophy = Builder(name = "Trophy", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp,
viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(2.5f, 0.5f)
arcTo(0.5f, 0.5f, 0.0f, false, true, 3.0f, 0.0f)
horizontalLineToRelative(10.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f)
curveToRelative(0.0f, 0.538f, -0.012f, 1.05f, -0.034f, 1.536f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, -1.133f, 5.89f)
curveToRelative(-0.79f, 1.865f, -1.878f, 2.777f, -2.833f, 3.011f)
verticalLineToRelative(2.173f)
lineToRelative(1.425f, 0.356f)
curveToRelative(0.194f, 0.048f, 0.377f, 0.135f, 0.537f, 0.255f)
lineTo(13.3f, 15.1f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.3f, 0.9f)
lineTo(3.0f, 16.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.3f, -0.9f)
lineToRelative(1.838f, -1.379f)
curveToRelative(0.16f, -0.12f, 0.343f, -0.207f, 0.537f, -0.255f)
lineTo(6.5f, 13.11f)
verticalLineToRelative(-2.173f)
curveToRelative(-0.955f, -0.234f, -2.043f, -1.146f, -2.833f, -3.012f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, -1.132f, -5.89f)
arcTo(33.076f, 33.076f, 0.0f, false, true, 2.5f, 0.5f)
close()
moveTo(2.599f, 3.04f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 0.72f, 3.935f)
curveToRelative(-0.333f, -1.05f, -0.588f, -2.346f, -0.72f, -3.935f)
close()
moveTo(12.682f, 6.975f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 0.72f, -3.935f)
curveToRelative(-0.133f, 1.59f, -0.388f, 2.885f, -0.72f, 3.935f)
close()
}
}
.build()
return _trophy!!
}
private var _trophy: ImageVector? = null
| 0 | Kotlin | 0 | 2 | 1c199d953dc96b261aab16ac230dc7f01fb14a53 | 3,021 | bootstrap-icons-compose | MIT License |
library/src/commonMain/kotlin/dev/kryptonreborn/cbor/encoder/BaseEncoder.kt | KryptonReborn | 792,268,202 | false | {"Kotlin": 172331} | package dev.kryptonreborn.cbor.encoder
import com.ionspin.kotlin.bignum.integer.BigInteger
import com.ionspin.kotlin.bignum.integer.toBigInteger
import dev.kryptonreborn.cbor.CborEncoder
import dev.kryptonreborn.cbor.CborException
import dev.kryptonreborn.cbor.model.AdditionalInformation
import dev.kryptonreborn.cbor.model.CborElement
import dev.kryptonreborn.cbor.model.MajorType
import dev.kryptonreborn.cbor.model.symbol
import kotlinx.io.Sink
abstract class BaseEncoder<T : CborElement>(
protected val sink: Sink,
protected val encoder: CborEncoder,
) {
companion object {
val MINUS_ONE = (-1).toBigInteger()
val UINT64_MAX_PLUS_ONE = "18446744073709551616".toBigInteger()
}
@Throws(CborException::class)
abstract fun encode(data: T)
@Throws(CborException::class)
protected fun writeIndefiniteLengthType(majorType: MajorType) {
var symbol = majorType.symbol
symbol = symbol or AdditionalInformation.INDEFINITE.value
writeBytes(symbol.toByte())
}
@Throws(CborException::class)
protected fun writeType(
majorType: MajorType,
length: Long,
) {
var symbol = majorType.symbol
when {
length <= 23L -> {
writeBytes(
(symbol.toLong() or length).toByte(),
)
}
length <= 255L -> {
symbol = symbol or AdditionalInformation.ONE_BYTE.value
writeBytes(
symbol.toByte(),
length.toByte(),
)
}
length <= 65535L -> {
symbol = symbol or AdditionalInformation.TWO_BYTES.value
writeBytes(
symbol.toByte(),
(length shr 8).toByte(),
(length and 0xFFL).toByte(),
)
}
length <= 4294967295L -> {
symbol = symbol or AdditionalInformation.FOUR_BYTES.value
writeBytes(
symbol.toByte(),
((length shr 24) and 0xFFL).toByte(),
((length shr 16) and 0xFFL).toByte(),
((length shr 8) and 0xFFL).toByte(),
(length and 0xFFL).toByte(),
)
}
else -> {
symbol = symbol or AdditionalInformation.EIGHT_BYTES.value
writeBytes(
symbol.toByte(),
((length shr 56) and 0xFFL).toByte(),
((length shr 48) and 0xFFL).toByte(),
((length shr 40) and 0xFFL).toByte(),
((length shr 32) and 0xFFL).toByte(),
((length shr 24) and 0xFFL).toByte(),
((length shr 16) and 0xFFL).toByte(),
((length shr 8) and 0xFFL).toByte(),
(length and 0xFFL).toByte(),
)
}
}
}
@Throws(CborException::class)
protected fun writeType(
majorType: MajorType,
length: BigInteger,
) {
val negative = majorType === MajorType.NEGATIVE_INTEGER
var symbol = majorType.symbol
when {
length < 24.toBigInteger() -> {
writeBytes(
(symbol or length.intValue()).toByte(),
)
}
length < 256.toBigInteger() -> {
symbol = symbol or AdditionalInformation.ONE_BYTE.value
writeBytes(
symbol.toByte(),
length.intValue().toByte(),
)
}
length < 65536L.toBigInteger() -> {
symbol = symbol or AdditionalInformation.TWO_BYTES.value
val twoByteValue = length.longValue()
writeBytes(
symbol.toByte(),
(twoByteValue shr 8).toByte(),
(twoByteValue and 0xFFL).toByte(),
)
}
length < 4294967296L.toBigInteger() -> {
symbol = symbol or AdditionalInformation.FOUR_BYTES.value
val fourByteValue = length.longValue()
writeBytes(
symbol.toByte(),
((fourByteValue shr 24) and 0xFFL).toByte(),
((fourByteValue shr 16) and 0xFFL).toByte(),
((fourByteValue shr 8) and 0xFFL).toByte(),
(fourByteValue and 0xFFL).toByte(),
)
}
length < UINT64_MAX_PLUS_ONE -> {
symbol = symbol or AdditionalInformation.EIGHT_BYTES.value
val mask = (0xFF).toBigInteger()
writeBytes(
symbol.toByte(),
length.shr(56).and(mask).ubyteValue().toByte(),
length.shr(48).and(mask).ubyteValue().toByte(),
length.shr(40).and(mask).ubyteValue().toByte(),
length.shr(32).and(mask).ubyteValue().toByte(),
length.shr(24).and(mask).ubyteValue().toByte(),
length.shr(16).and(mask).ubyteValue().toByte(),
length.shr(8).and(mask).ubyteValue().toByte(),
length.and(mask).ubyteValue().toByte(),
)
}
else -> {
if (negative) {
writeType(MajorType.TAG, 3)
} else {
writeType(MajorType.TAG, 2)
}
val bytes = length.toByteArray()
writeType(MajorType.BYTE_STRING, bytes.size.toLong())
writeBytes(*bytes)
}
}
}
@Throws(CborException::class)
protected fun writeBytes(vararg bytes: Byte) {
try {
sink.write(bytes)
} catch (e: IndexOutOfBoundsException) {
throw CborException(
"Error writing to output, startIndex or endIndex is out of range of source array indices.",
e,
)
} catch (e: IllegalArgumentException) {
throw CborException("Error writing to output, startIndex > endInde.", e)
} catch (e: IllegalStateException) {
throw CborException("Error writing to output, the sink is closed.", e)
}
}
}
| 3 | Kotlin | 0 | 0 | 9e6601fae30474e9a675ea0cbc4e877efcfa0cd4 | 6,390 | kotlin-cbor | Apache License 2.0 |
app/src/main/kotlin/app/home/me/profile/ProfileViewImpl.kt | stoyicker | 291,049,724 | false | {"Java": 646382, "Kotlin": 423127, "Shell": 885} | package app.home.me.profile
import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.widget.ContentLoadingProgressBar
import com.makeramen.roundedimageview.RoundedTransformationBuilder
import com.squareup.picasso.Picasso
import domain.profile.DomainGetProfileAnswer
import org.stoyicker.dinger.R
import java.util.Calendar
import java.util.Calendar.DATE
import java.util.Calendar.MONTH
import java.util.Calendar.YEAR
import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt
internal class ProfileViewImpl(
private val profileImage: ImageView,
private val titleLabel: TextView,
private val occupationLabel: TextView,
private val locationLabel: TextView,
private val bioLabel: TextView,
private val distanceFilterLabel: TextView,
private val distanceFilter: ProgressBar,
private val ageFilterLabel: TextView,
private val ageFilterMin: ProgressBar,
private val ageFilterMax: ProgressBar,
private val progress: ContentLoadingProgressBar) : ProfileView {
private val content = arrayOf(
profileImage,
titleLabel,
occupationLabel,
locationLabel,
bioLabel,
distanceFilterLabel,
distanceFilter,
ageFilterLabel,
ageFilterMin,
ageFilterMax)
@SuppressLint("ClickableViewAccessibility")
override fun setup() = content.forEach { it.setOnTouchListener(ON_TOUCH_LISTENER_DISALLOW) }
override fun setData(data: DomainGetProfileAnswer) {
profileImage.apply {
when (val it = data.photos?.firstOrNull()) {
null -> visibility = View.GONE
else -> {
Picasso.get()
.load(it.url)
.fit()
.centerCrop()
.transform(RoundedTransformationBuilder()
.borderColor(ContextCompat.getColor(context, R.color.text_primary))
.borderWidthDp(2f)
.cornerRadiusDp(1000F) // Needed for some reason, else we get a square
.oval(false)
.build())
.into(this)
}
}
}
titleLabel.text = data.birthDate.run {
if (this == null) {
data.name
} else {
titleLabel.context.resources.getString(
R.string.profile_title_pattern, data.name, birthDateToAgeString())
}
}
occupationLabel.apply {
if (data.jobs?.any() ?: data.schools?.any() != null) {
visibility = View.VISIBLE
text = data.jobs?.firstOrNull()?.title?.name ?: data.schools?.firstOrNull()?.name
} else {
visibility = View.GONE
}
}
locationLabel.apply {
if (data.positionInfo != null) {
visibility = View.VISIBLE
text = data.positionInfo!!.city?.name ?: data.positionInfo!!.country?.name
} else {
visibility = View.GONE
}
}
bioLabel.text = data.bio
distanceFilterLabel.text = distanceFilterLabel.context.getString(
R.string.distance_filter_label_pattern, (data.distanceFilter ?: 0).milesToRoundedKms())
distanceFilter.progress = (data.distanceFilter ?: 0).milesToRoundedKms()
ageFilterLabel.text = ageFilterLabel.context.getString(
R.string.age_filter_label_pattern,
data.ageFilterMin.toString(),
(data.ageFilterMax ?: 0).run {
if (this > ageFilterLabel.context.resources.getInteger(R.integer.age_filter_max))
ageFilterLabel.context.resources.getString(R.string.age_filter_max_infinite)
else
this.toString()
})
ageFilterMin.progress = data.ageFilterMin ?: 0
ageFilterMax.progress = data.ageFilterMax ?: 0
content.forEach { it.visibility = View.VISIBLE }
progress.hide()
}
override fun setProgress() {
progress.show()
content.forEach { it.visibility = View.GONE }
}
override fun setError() {
progress.hide()
content.forEach { it.visibility = View.GONE }
}
}
internal fun Date?.birthDateToAgeString(): String {
if (this == null) {
return ""
}
val a = asCalendar()
val b = Date().asCalendar()
var diff = b.get(YEAR) - a.get(YEAR)
if (a.get(MONTH) > b.get(MONTH) || a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE)) {
diff--
}
return "$diff"
}
internal fun Int.milesToRoundedKms() = (this * MILE_TO_KMS_RATIO).roundToInt()
private fun Date.asCalendar() = Calendar.getInstance(Locale.US).apply {
time = this@asCalendar
}
private val ON_TOUCH_LISTENER_DISALLOW = { _: View?, _: MotionEvent? -> true }
private const val MILE_TO_KMS_RATIO = 1.609344 // This is the amount of kms in a mile
| 1 | null | 1 | 1 | fecfefd7a64dc8c9397343850b9de4d52117b5c3 | 4,763 | dinger-unpublished | MIT License |
movie_streaming_app/android/app/src/main/kotlin/me/chromicle/movie_streaming_app/MainActivity.kt | ajay-prabhakar | 262,766,287 | false | null | package me.chromicle.movie_streaming_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 2 | Dart | 129 | 929 | 1b2099fdb7151731d0caf55ae7ab483238a3f963 | 137 | awesome-flutter-ui | MIT License |
TrackMySleepQualityRoomAndTesting/app/src/main/java/com/example/android/trackmysleepquality/database/SleepDatabaseDao.kt | markgray | 230,240,820 | true | {"Kotlin": 1356167} | /*
* Copyright 2019, 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.example.android.trackmysleepquality.database
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
/**
* Defines methods for using the [SleepNight] class with Room. The `@Dao` annotation marks the class
* as a Data Access Object. Data Access Objects are the main classes where you define your database
* interactions. They can include a variety of query methods. The class marked with `@Dao` should
* either be an interface or an abstract class. At compile time, Room will generate an implementation
* of this class when it is referenced by a Database. An abstract `@Dao` class can optionally have a
* constructor that takes a Database as its only parameter. It is recommended to have multiple Dao
* classes in your codebase depending on the tables they touch.
*/
@Dao
interface SleepDatabaseDao {
/**
* The `@Insert` annotation marks this as an insert method. It just inserts its parameter into
* the database.
*
* @param night the [SleepNight] to insert into the database.
*/
@Insert
fun insert(night: SleepNight)
/**
* The `@Update` annotation marks this as an update method. The implementation of the method will
* update its parameter in the database if it already exists (checked by primary key). If it
* doesn't already exist, this method will not change the database.
*
* @param night [SleepNight] row value to update.
*/
@Update
fun update(night: SleepNight)
/**
* The `@Query` annotation marks this as an query method. The value of the annotation includes
* the query that will be run when this method is called. This query is verified at compile time
* by Room to ensure that it compiles fine against the database. The arguments of the method will
* be bound to the bind arguments in the SQL statement when they are prefixed by ":".
*
* Selects and returns the row that matches the supplied `nightId`, which is our primary key.
*
* @param key `nightId` primary key to match.
* @return the [SleepNight] whose `nightId` column primary key is our parameter [key].
*/
@Query("SELECT * from daily_sleep_quality_table WHERE nightId = :key")
fun get(key: Long): SleepNight?
/**
* The `@Query` annotation marks this as an query method. The value of the annotation includes
* the query that will be run when this method is called.
*
* Deletes all values from the table. This does not delete the table, only its contents.
*/
@Query("DELETE FROM daily_sleep_quality_table")
fun clear()
/**
* Selects and returns the latest night.
*
* @return the newest [SleepNight] added to the database.
*/
@Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC LIMIT 1")
fun getTonight(): SleepNight?
/**
* Selects and returns all rows in the table, sorted by `nightId` in descending order.
*
* @return a [LiveData] wrapped list of all of the [SleepNight] entries in our database sorted
* by the `nightId` column primary key in descending order.
*/
@Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC")
fun getAllNights(): LiveData<List<SleepNight>>
} | 0 | Kotlin | 0 | 0 | d914a0382556892b880393e35689111af98d999f | 3,951 | android-kotlin-fundamentals-apps | Apache License 2.0 |
app/src/main/java/com/example/suitmediamobiletest2024/ui/navigation/NavigationGraph.kt | ghaziakmalf | 840,893,769 | false | {"Kotlin": 30924} | package com.example.suitmediamobiletest2024.ui.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.suitmediamobiletest2024.ui.screens.FirstScreen
import com.example.suitmediamobiletest2024.ui.screens.SecondScreen
import com.example.suitmediamobiletest2024.ui.screens.ThirdScreen
@Composable
fun NavigationGraph(navController: NavHostController) {
NavHost(
navController = navController,
startDestination = "first_screen"
) {
composable("first_screen") {
FirstScreen(navController = navController)
}
composable("second_screen/{name}") { backStackEntry ->
val name = backStackEntry.arguments?.getString("name") ?: ""
val selectedUser = backStackEntry.savedStateHandle.get<String>("selected_user")
SecondScreen(navController = navController, name = name, selectedUser = selectedUser)
}
composable("third_screen") {
ThirdScreen(navController = navController) { selectedUser ->
navController.previousBackStackEntry?.savedStateHandle?.set("selected_user", selectedUser)
}
}
}
}
| 0 | Kotlin | 0 | 0 | a33185400109be455a19a7d48c417f454a934792 | 1,293 | Suitmedia-Mobile-Test-2024 | MIT License |
app/src/main/java/com/example/suitmediamobiletest2024/ui/navigation/NavigationGraph.kt | ghaziakmalf | 840,893,769 | false | {"Kotlin": 30924} | package com.example.suitmediamobiletest2024.ui.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.suitmediamobiletest2024.ui.screens.FirstScreen
import com.example.suitmediamobiletest2024.ui.screens.SecondScreen
import com.example.suitmediamobiletest2024.ui.screens.ThirdScreen
@Composable
fun NavigationGraph(navController: NavHostController) {
NavHost(
navController = navController,
startDestination = "first_screen"
) {
composable("first_screen") {
FirstScreen(navController = navController)
}
composable("second_screen/{name}") { backStackEntry ->
val name = backStackEntry.arguments?.getString("name") ?: ""
val selectedUser = backStackEntry.savedStateHandle.get<String>("selected_user")
SecondScreen(navController = navController, name = name, selectedUser = selectedUser)
}
composable("third_screen") {
ThirdScreen(navController = navController) { selectedUser ->
navController.previousBackStackEntry?.savedStateHandle?.set("selected_user", selectedUser)
}
}
}
}
| 0 | Kotlin | 0 | 0 | a33185400109be455a19a7d48c417f454a934792 | 1,293 | Suitmedia-Mobile-Test-2024 | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/ThirdMedal.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.ThirdMedal: ImageVector
get() {
if (_thirdMedal != null) {
return _thirdMedal!!
}
_thirdMedal = Builder(name = "ThirdMedal", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(24.021f, 0.0f)
horizontalLineToRelative(-9.284f)
lineToRelative(-2.741f, 5.541f)
lineTo(9.261f, 0.0f)
lineTo(-0.021f, 0.0f)
lineToRelative(4.772f, 9.671f)
curveToRelative(-1.1f, 1.493f, -1.752f, 3.336f, -1.752f, 5.329f)
curveToRelative(0.0f, 4.963f, 4.037f, 9.0f, 9.0f, 9.0f)
reflectiveCurveToRelative(9.0f, -4.037f, 9.0f, -9.0f)
curveToRelative(0.0f, -1.998f, -0.654f, -3.845f, -1.76f, -5.34f)
lineTo(24.021f, 0.0f)
close()
moveTo(4.806f, 3.0f)
horizontalLineToRelative(2.59f)
lineToRelative(1.716f, 3.476f)
curveToRelative(-0.743f, 0.252f, -1.442f, 0.6f, -2.084f, 1.027f)
lineToRelative(-2.221f, -4.503f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-3.309f, 0.0f, -6.0f, -2.691f, -6.0f, -6.0f)
reflectiveCurveToRelative(2.691f, -6.0f, 6.0f, -6.0f)
reflectiveCurveToRelative(6.0f, 2.691f, 6.0f, 6.0f)
reflectiveCurveToRelative(-2.691f, 6.0f, -6.0f, 6.0f)
close()
moveTo(16.964f, 7.496f)
curveToRelative(-0.641f, -0.426f, -1.34f, -0.772f, -2.082f, -1.023f)
lineToRelative(1.718f, -3.473f)
horizontalLineToRelative(2.589f)
lineToRelative(-2.225f, 4.496f)
close()
moveTo(15.0f, 16.5f)
curveToRelative(0.0f, 1.379f, -1.121f, 2.5f, -2.5f, 2.5f)
horizontalLineToRelative(-2.5f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.5f)
curveToRelative(0.275f, 0.0f, 0.5f, -0.225f, 0.5f, -0.5f)
reflectiveCurveToRelative(-0.225f, -0.5f, -0.5f, -0.5f)
horizontalLineToRelative(-1.5f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(1.0f)
curveToRelative(0.275f, 0.0f, 0.5f, -0.225f, 0.5f, -0.5f)
reflectiveCurveToRelative(-0.225f, -0.5f, -0.5f, -0.5f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.0f)
curveToRelative(1.379f, 0.0f, 2.5f, 1.121f, 2.5f, 2.5f)
curveToRelative(0.0f, 0.424f, -0.107f, 0.824f, -0.294f, 1.175f)
curveToRelative(0.488f, 0.456f, 0.794f, 1.105f, 0.794f, 1.825f)
close()
}
}
.build()
return _thirdMedal!!
}
private var _thirdMedal: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,858 | icons | MIT License |
src/main/kotlin/br/com/zup/osmarjunior/model/enums/TipoConta.kt | osmar-jr | 412,536,861 | true | {"Kotlin": 27801} | package br.com.zup.osmarjunior.model.enums
import br.com.zup.osmarjunior.TipoDeConta
enum class TipoConta(val grpcTipoDeConta: TipoDeConta) {
CONTA_CORRENTE(TipoDeConta.CONTA_CORRENTE),
CONTA_POUPANCA(TipoDeConta.CONTA_POUPANCA);
}
| 0 | Kotlin | 0 | 0 | 1a5c8c269c87b3f85e2c91926afe3728db682971 | 242 | orange-talents-07-template-pix-keymanager-rest | Apache License 2.0 |
demo-projects/arrow-books-library/src/main/kotlin/org/jesperancinha/arrow/books/Main.kt | jesperancinha | 565,555,551 | false | {"Kotlin": 137277, "Makefile": 21431, "Java": 7568, "Scala": 3899, "Shell": 3824, "Fortran": 3072, "Common Lisp": 2510, "COBOL": 2254, "Clojure": 2232, "Haskell": 1370, "Scheme": 870, "Go": 709, "Dockerfile": 700, "Standard ML": 644, "Erlang": 522, "C": 438} | package org.jesperancinha.arrow.books
import org.jesperancinha.arrow.books.collections.MemoizationService
import org.jesperancinha.arrow.books.coroutines.races.RacesService
import org.jesperancinha.arrow.books.design.either.TheVillageOfThePeople
import org.jesperancinha.arrow.books.immutable.optics.TheVillageOfThePeopleService
import org.jesperancinha.arrow.books.resilience.circuit.UrsusService
import org.jesperancinha.arrow.books.resilience.saga.LibraryService
import org.jesperancinha.arrow.books.typed.raise.BooksWithErrorsService
fun printSeparator(title: String) =
"-------".run { println("$this $title") }
fun main() {
RacesService.main()
MemoizationService.main()
LibraryService.main()
UrsusService.main()
TheVillageOfThePeople.main()
TheVillageOfThePeopleService.main()
BooksWithErrorsService.main()
}
| 0 | Kotlin | 0 | 0 | dacd8b4a6d6d2c5a36109c04fa5d3a6581c072de | 849 | asnsei-the-right-waf | Apache License 2.0 |
src/main/kotlin/io/framed/framework/matcher/TreeMatcher.kt | pixix4 | 180,147,298 | false | null | package io.framed.framework.matcher
import io.framed.framework.ModelTree
import io.framed.model.bpmn.model.BpmnElement
import io.framed.model.bros.model.BrosElement
class TreeMatcher(
private val bpmnTree: ModelTree<BpmnElement>,
private val brosTree: ModelTree<BrosElement>
) {
private val matcherList = mutableListOf<Matcher>()
fun register(matcher: Matcher) {
matcherList += matcher
}
fun match(predefinedMatches: List<PredefinedMatch>): Int? {
val bpmnSequence = bpmnTree.asSequence<BpmnElement>().toList()
val brosSequence = brosTree.asSequence<BrosElement>().toList()
var bpmnState = bpmnSequence.associateWith { it.matchingElements.toSet() }
var brosState = brosSequence.associateWith { it.matchingElements.toSet() }
var hasChanged = true
var remainingRounds = MAX_ROUNDS
while (hasChanged && remainingRounds > 0) {
remainingRounds--
hasChanged = false
for (bpmn in bpmnSequence) {
for (bros in brosSequence) {
for (matcher in matcherList) {
if (matcher.filterBpmn(bpmn) && matcher.filterBros(bros) && matcher.match(bpmn, bros)) {
bpmn.matchingElementsMap.getOrPut(bros) { mutableSetOf() } += matcher.name
bros.matchingElementsMap.getOrPut(bpmn) { mutableSetOf() } += matcher.name
}
}
for (match in predefinedMatches) {
if (bpmn.element.id == match.bpmn && bros.element.id == match.bros) {
when (match.type) {
PredefinedMatch.Type.MATCH -> {
bpmn.matchingElementsMap.getOrPut(bros) { mutableSetOf() } += "PredefinedMatcher"
bros.matchingElementsMap.getOrPut(bpmn) { mutableSetOf() } += "PredefinedMatcher"
}
PredefinedMatch.Type.NOMATCH -> {
bpmn.matchingElementsMap -= bros
bros.matchingElementsMap -= bpmn
}
}
}
}
}
}
val newBpmnState = bpmnSequence.associateWith { it.matchingElements.toSet() }
val newBrosState = brosSequence.associateWith { it.matchingElements.toSet() }
if (newBpmnState != bpmnState) {
hasChanged = true
}
if (newBrosState != brosState) {
hasChanged = true
}
bpmnState = newBpmnState
brosState = newBrosState
}
if (remainingRounds <= 0) return null
return MAX_ROUNDS - remainingRounds
}
companion object {
const val MAX_ROUNDS = 100
}
}
| 0 | Kotlin | 0 | 0 | 99095e08c0377c5647da4b546e2c0ed61a099604 | 2,990 | bpmn-bros-verifier | MIT License |
rigel/src/main/java/com/artear/rigel/extensions/FragmentExt.kt | Artear | 164,138,931 | false | null | /*
* Copyright 2019 <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.artear.rigel.extensions
import androidx.fragment.app.Fragment
/**
* @return The last fragment on fragments list of child fragment manager.
*/
fun Fragment.getChildActiveFragment(): Fragment {
return childFragmentManager.fragments.last()
}
/**
* Useful to get a unique id an launch a fragment vertically.
*
* @return An id with child count +1.
*/
fun Fragment.getIdWithChildFragmentCount(description: String): String {
return "${description}_${childFragmentManager.backStackEntryCount + 1}"
} | 0 | Kotlin | 0 | 0 | c80fdcb8eb62ee2470537a1219636feb924688a6 | 1,112 | app_lib_rigel_android | Apache License 2.0 |
src/main/kotlin/io/crstudio/tutor/auth/repo/SignUpCodeRepo.kt | crstudio-io | 808,890,404 | false | {"Kotlin": 54203, "HTML": 1160, "Dockerfile": 343} | package io.crstudio.tutor.auth.repo
import io.crstudio.tutor.auth.model.SignUpCode
import org.springframework.data.jpa.repository.JpaRepository
import java.time.LocalDateTime
interface SignUpCodeRepo : JpaRepository<SignUpCode, Long> {
fun findByCodeAndValidUntilAfter(code: String, now: LocalDateTime): SignUpCode?
} | 2 | Kotlin | 0 | 0 | ab053d5c8c1428ebb897770bf5a708e8f82989a5 | 323 | boot-aps-tutor | MIT License |
2020 Fall - Mobile Application Development (Kotiln | Java)/Task3-Different Layouts/app/src/main/java/com/example/layoutsexample/ui/constraints/ConstraintsViewModel.kt | iamaydan | 342,936,046 | false | null | package com.example.layoutsexample.ui.constraints
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class ConstraintsViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is constraints layout example"
}
val text: LiveData<String> = _text
} | 0 | Kotlin | 0 | 0 | 9269a4df73bf3bf35749d5f44acc69b15a3243a3 | 366 | University | Apache License 2.0 |
app/src/main/java/com/example/exchange/ui/exchange/ExchangeFragment.kt | Arrowsome | 481,321,609 | false | {"Kotlin": 25331} | package com.example.exchange.ui.exchange
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil.inflate
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.example.exchange.R
import com.example.exchange.databinding.FragmentExchangeBinding
import com.example.exchange.utils.EventObserver
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ExchangeFragment : Fragment() {
private lateinit var binding: FragmentExchangeBinding
private val viewModel: ExchangeViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = inflate(inflater, R.layout.fragment_exchange, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
viewModel.snackEvent.observe(viewLifecycleOwner, EventObserver { msgResId ->
Snackbar.make(binding.root, msgResId, Snackbar.LENGTH_SHORT).show()
})
viewModel.sellInputChangeEvent.observe(viewLifecycleOwner, EventObserver { amount ->
if (viewModel.isFocusedOnSelling.value == true) {
if (amount == "-1.0") {
binding.receiveAmountInput.setText("")
} else {
binding.receiveAmountInput.setText(amount)
}
}
})
viewModel.receiveInputChangeEvent.observe(viewLifecycleOwner, EventObserver { amount ->
if (viewModel.isFocusedOnReceiving.value == true) {
if (amount == "-1.0") {
binding.sellAmountInput.setText("")
} else {
binding.sellAmountInput.setText(amount)
}
}
})
viewModel.updateOriginCurrencyEvent.observe(viewLifecycleOwner, EventObserver { index ->
binding.originCurrencySpinner.setSelection(index)
})
viewModel.updateTargetCurrencyEvent.observe(viewLifecycleOwner, EventObserver { index ->
binding.targetCurrencySpinner.setSelection(index)
})
viewModel.insufficientBalance.observe(viewLifecycleOwner, EventObserver { insufficient ->
val color = if (insufficient) android.R.color.holo_red_dark else android.R.color.black
binding.sellAmountInput.setTextColor(ContextCompat.getColor(requireContext(), color))
})
binding.sellAmountInput.requestFocus()
setHasOptionsMenu(true)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Handler(Looper.getMainLooper()).postDelayed({
binding.targetCurrencySpinner.setSelection(1)
}, 500,
)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.app_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.item_aboutUs -> {
findNavController()
.navigate(R.id.action_exchangeFragment_to_aboutUsFragment)
true
}
else -> return super.onOptionsItemSelected(item)
}
}
} | 0 | Kotlin | 0 | 0 | 69989b545ddd9b70f0e0cc1771e42d85e6b20c69 | 3,739 | android-exchange-sample | MIT License |
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantWith/simple2.kt | ingokegel | 72,937,917 | true | null | // WITH_STDLIB
fun test(s: String) {
with<caret> (s, {
println("1")
println("2")
})
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 109 | intellij-community | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantWith/simple2.kt | ingokegel | 72,937,917 | true | null | // WITH_STDLIB
fun test(s: String) {
with<caret> (s, {
println("1")
println("2")
})
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 109 | intellij-community | Apache License 2.0 |
app/src/main/java/com/rifqimfahmi/alldogbreeds/data/network/model/giphy/Meme.kt | rifqimfahmi | 125,337,589 | false | null | package com.rifqimfahmi.alldogbreeds.data.network.model.giphy
import com.google.gson.annotations.SerializedName
/*
* Created by <NAME> on 26/02/18.
*/
data class Meme (
@SerializedName("slug")
val slug: String,
@SerializedName("url")
val giphySource: String,
@SerializedName("bitly_gif_url")
val shortLink: String,
@SerializedName("images")
val images: MemeImage
) | 0 | Kotlin | 1 | 4 | b29dfdd8c690780f649825ef471ab8c590bebd0c | 433 | all-dog-breeds | Apache License 2.0 |
src/integration/kotlin/org/springframework/samples/petclinic/restassured/RestAssuredMockMvcTest.kt | junoyoon | 664,329,578 | false | null | package org.springframework.samples.petclinic.restassured
import com.fasterxml.jackson.databind.ObjectMapper
import io.kotest.data.headers
import io.kotest.inspectors.forAll
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.collections.shouldNotHaveSize
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.restassured.config.ObjectMapperConfig
import io.restassured.http.ContentType
import io.restassured.mapper.ObjectMapperType
import io.restassured.module.mockmvc.RestAssuredMockMvc
import io.restassured.module.mockmvc.kotlin.extensions.Given
import io.restassured.module.mockmvc.kotlin.extensions.Then
import io.restassured.module.mockmvc.kotlin.extensions.When
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.samples.petclinic.fixtures.Fixtures
import org.springframework.samples.petclinic.restassured.extensions.extractBodyAs
import org.springframework.samples.petclinic.rest.dto.OwnerDto
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.web.servlet.MockMvc
import org.springframework.transaction.annotation.Transactional
@Transactional
@WithMockUser(roles = ["OWNER_ADMIN"])
@AutoConfigureMockMvc
@SpringBootTest
class RestAssuredMockMvcTest(
@Autowired mockMvc: MockMvc,
@Autowired objectMapper: ObjectMapper
) {
init {
RestAssuredMockMvc.mockMvc(mockMvc)
RestAssuredMockMvc.requestSpecification = Given {
contentType(ContentType.JSON)
accept(ContentType.JSON)
headers("common_header_key1", "common_header_value1")
}
RestAssuredMockMvc.config = RestAssuredMockMvc.config().objectMapperConfig(
ObjectMapperConfig()
.defaultObjectMapperType(ObjectMapperType.JACKSON_2)
.jackson2ObjectMapperFactory { _, _ -> objectMapper }
)
}
@Test
fun testOne() {
Given {
contentType(MediaType.APPLICATION_JSON)
headers("key1", "value1", "key2", "value2")
} When {
get("/api/owners/1")
} Then {
status(HttpStatus.OK)
body("pets[0].name", equalTo("Leo"))
extractBodyAs<OwnerDto>().shouldNotBeNull()
log().all()
}
}
@Test
fun testAll() {
Given {
log().all()
contentType(MediaType.APPLICATION_JSON)
// body(newOwner) post 의 경우 이런 식으로 데이터 주입
} When {
headers("key", "value")
get("/api/owners")
} Then {
status(HttpStatus.OK)
body("[0].firstName", equalTo("George"))
body("findAll { it.firstName == 'George' }.lastName",
everyItem(equalTo("Franklin")))
body("firstName", everyItem(not(nullValue())))
body("firstName.size()", greaterThan(0))
// dto 로 역직렬화 하여 검증. extractBodyAs 는 직접 정의한 extension method
extractBodyAs<List<OwnerDto>>().should {
it shouldNotHaveSize 0
it.forAll { owner ->
owner.firstName shouldNotBe null
owner.pets shouldNotBe null
}
}
}
}
// mock mvc 는 트랜잭션 가능
@Transactional
@Test
fun testPost() {
val newOwner = Fixtures.giveMeOneFreshOwner()
Given {
headers("key1", "value1", "key2", "value2")
body(newOwner)
} When {
post("/api/owners")
} Then {
status(HttpStatus.CREATED)
extractBodyAs<OwnerDto>().should { dto ->
dto.lastName shouldBe newOwner.lastName
dto.firstName shouldBe newOwner.firstName
dto.id shouldNotBe null
dto.pets.shouldNotBeNull() shouldHaveSize 0
}
log().all()
}
}
@Disabled("mockmvc 는 webflux 를 인식하지 못함")
@Test
fun testWebFlux() {
Given {
contentType(MediaType.APPLICATION_JSON)
} When {
get("/api/owners-webflux/1")
} Then {
status(HttpStatus.OK)
body("$.pets[*].name", equalTo("Leo"))
extractBodyAs<OwnerDto>().shouldNotBeNull()
log().all()
}
}
}
| 0 | Kotlin | 0 | 0 | c339ab5260583d07871bfb2617f35f754d8b3492 | 4,747 | fastcampus-test | Apache License 2.0 |
publish-component/src/main/java/com/kotlin/android/publish/component/widget/editor/EditorMenuTextSizeView.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.publish.component.widget.editor
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.kotlin.android.ktx.ext.core.getDrawable
import com.kotlin.android.ktx.ext.core.getShapeDrawable
import com.kotlin.android.ktx.ext.core.setBackground
import com.kotlin.android.ktx.ext.dimension.dpF
import com.kotlin.android.ktx.ext.statelist.getDrawableStateList
import com.kotlin.android.publish.component.R
import com.kotlin.android.publish.component.databinding.EditorMenuBarTextSizeBinding
import com.kotlin.android.publish.component.widget.article.sytle.TextFontSize
/**
* 编辑器菜单:文字大小
*
* Created on 2022/4/21.
*
* @author o.s
*/
class EditorMenuTextSizeView : FrameLayout {
constructor(context: Context) : super(context) {
initView()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
initView()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initView()
}
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes) {
initView()
}
private var mBinding: EditorMenuBarTextSizeBinding? = null
private var cornerRadius = 6.dpF
private var _textFontSize: TextFontSize? = TextFontSize.STANDARD
var textFontSize: TextFontSize?
get() = _textFontSize
set(value) {
_textFontSize = value
when (value) {
TextFontSize.SMALL -> select(0)
TextFontSize.STANDARD -> select(1)
TextFontSize.BIG -> select(2)
TextFontSize.LARGER -> select(3)
else -> reset()
}
}
var action: ((TextFontSize) -> Unit)? = null
private fun select(index: Int) {
selected(index)
}
private fun initView() {
mBinding = EditorMenuBarTextSizeBinding.inflate(LayoutInflater.from(context))
addView(mBinding?.root)
setBackground(
colorRes = R.color.color_ffffff,
cornerRadius = 8.dpF
)
mBinding?.apply {
setBgSelector(itemView1)
setBgSelector(itemView2)
setBgSelector(itemView3)
setBgSelector(itemView4)
itemView1.setOnClickListener {
selected(view = it, textFontSize = TextFontSize.SMALL, isClick = true)
}
itemView2.setOnClickListener {
selected(view = it, textFontSize = TextFontSize.STANDARD, isClick = true)
}
itemView3.setOnClickListener {
selected(view = it, textFontSize = TextFontSize.BIG, isClick = true)
}
itemView4.setOnClickListener {
selected(view = it, textFontSize = TextFontSize.LARGER, isClick = true)
}
}
selected(index = 1)
}
private fun selected(index: Int) {
mBinding?.apply {
when (index) {
0 -> {
selected(view = itemView1, textFontSize = TextFontSize.SMALL)
}
1 -> {
selected(view = itemView2, textFontSize = TextFontSize.STANDARD)
}
2 -> {
selected(view = itemView3, textFontSize = TextFontSize.BIG)
}
3 -> {
selected(view = itemView4, textFontSize = TextFontSize.LARGER)
}
}
}
}
private fun selected(view: View, textFontSize: TextFontSize, isClick: Boolean = false) {
if (!view.isSelected) {
reset()
_textFontSize = textFontSize
view.isSelected = true
if (isClick){
action?.invoke(textFontSize)
}
}
}
private fun setBgSelector(view: View) {
view.background = getDrawableStateList(
normal = getDrawable(R.color.transparent),
pressed = getShapeDrawable(
colorRes = R.color.color_f2f3f6,
cornerRadius = cornerRadius
),
selected = getShapeDrawable(
colorRes = R.color.color_f2f3f6,
cornerRadius = cornerRadius
),
)
}
private fun reset() {
mBinding?.apply {
itemView1.isSelected = false
itemView2.isSelected = false
itemView3.isSelected = false
itemView4.isSelected = false
}
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 4,765 | Mtime | Apache License 2.0 |
src/main/kotlin/ru/jmorozov/prodkalendar/telegram/bot/service/ProductiveKalendarClient.kt | jmorozov | 147,013,123 | false | null | package ru.jmorozov.prodkalendar.telegram.bot.service
import ru.jmorozov.prodkalendar.telegram.dto.DateRange
import ru.jmorozov.prodkalendar.telegram.dto.DayType
import java.time.LocalDate
interface ProductiveKalendarClient {
fun getHolidaysBetween(range: DateRange): String?
fun getWorkdaysBetween(range: DateRange): String?
fun isHoliday(date: LocalDate): Boolean?
fun isHolidayTomorrow(): Boolean?
fun getDayType(date: LocalDate): DayType?
fun getTomorrowType(): DayType?
} | 0 | Kotlin | 0 | 1 | 1ce1279d38e55494874201a034de9681e55d8fa0 | 505 | productive-kalendar-telegram-bot | MIT License |
app/src/main/java/com/yesser/booknotes/BookListAdapter.kt | yessermiranda13 | 320,678,774 | false | null | package com.yesser.booknotes
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ExpandableListView
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.list_item.view.*
class BookListAdapter (private val context: Context,
private val onDeleteClickListener: OnDeleteClickListener) : RecyclerView.Adapter<BookListAdapter.BookViewHolder>() {
interface OnDeleteClickListener {
fun onDeleteClickListener(myBook: Book)
}
private var bookList: List<Book> = mutableListOf()
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): BookListAdapter.BookViewHolder {
val itemView = LayoutInflater.from(context).inflate(R.layout.list_item,parent, false)
return BookViewHolder(itemView)
}
override fun onBindViewHolder(holder: BookListAdapter.BookViewHolder, position: Int) {
val book = bookList[position]
holder.setData(book.author, book.book, position)
holder.setListeners()
}
override fun getItemCount(): Int = bookList.size
fun setBooks(books: List<Book>) {
bookList = books
notifyDataSetChanged()
}
inner class BookViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
private var pos: Int = 0
fun setData(author: String, book: String, position: Int){
itemView.tvAuthor.text = author
itemView.tvBook.text = book
this.pos = position
}
fun setListeners()
{
itemView.ivRowEdit.setOnClickListener {
val intent = Intent(context,EditBookActivity::class.java)
intent.putExtra("id", bookList[pos].id)
intent.putExtra("author",bookList[pos].author)
intent.putExtra("book",bookList[pos].book)
(context as Activity).startActivityForResult(intent,MainActivity.UPDATE_NOTE_ACTIVITY_REQUEST_CODE)
}
itemView.ivRowDelete.setOnClickListener {
onDeleteClickListener.onDeleteClickListener(bookList[pos])
}
}
}
} | 0 | Kotlin | 0 | 0 | 1a0eee4b5eb2f738d693ae8f89760b8c78a970c4 | 2,339 | GuardaLibrosAndroid | MIT License |
db-objekts-core/src/main/kotlin/com/dbobjekts/codegen/writer/SchemaSourceBuilder.kt | jaspersprengers | 576,889,038 | false | {"Kotlin": 1251609, "PLpgSQL": 45872, "Dockerfile": 2463} | package com.dbobjekts.codegen.writer
import com.dbobjekts.codegen.metadata.DBSchemaDefinition
import com.dbobjekts.util.StringUtil
class SchemaSourceBuilder(val schema: DBSchemaDefinition) {
private val strBuilder = StringBuilder()
fun buildForApplication(): String {
strBuilder.append("package ${schema.packageName}\n")
strBuilder.append("import com.dbobjekts.metadata.Schema\n")
val tables = schema.tables.map { it.asClassName() }.joinToString(", ")
val fields = schema.tables.map { """
/**
* Refers to metadata object for table ${it.tableName.value}
*/
val ${StringUtil.initLowerCase(it.asClassName())} = ${it.asClassName()}
""" }.joinToString("")
val source = """
/**
* Auto-generated metadata object representing a schema consisting of one or more tables.
*
* Do not edit this file manually! Always use [com.dbobjekts.codegen.CodeGenerator] when the metadata model is no longer in sync with the database.
*/
object ${schema.schemaName.metaDataObjectName} : Schema("${schema.schemaName.value}", listOf($tables)){
$fields
}
"""
strBuilder.append(source)
return strBuilder.toString()
}
}
| 0 | Kotlin | 2 | 4 | 5b66aae10cae18a95f77c29ce55b11b03e53500b | 1,229 | db-objekts | Apache License 2.0 |
app/src/main/java/com/donnelly/steve/twitterapp/TwitterApplication.kt | sdonn3 | 151,998,993 | false | null | package com.donnelly.steve.twitterapp
import android.app.Application
import android.util.Log
import com.twitter.sdk.android.core.DefaultLogger
import com.twitter.sdk.android.core.Twitter
import com.twitter.sdk.android.core.TwitterAuthConfig
import com.twitter.sdk.android.core.TwitterConfig
class TwitterApplication : Application() {
override fun onCreate() {
super.onCreate()
val config = TwitterConfig.Builder(this)
.logger(DefaultLogger(Log.DEBUG))
.twitterAuthConfig(TwitterAuthConfig("<KEY>", "<KEY>"))
.debug(true)
.build()
Twitter.initialize(config)
}
} | 0 | Kotlin | 0 | 0 | 5108e3be46ccd53927eefd04c871fccb899047b5 | 660 | TwitterApp | Apache License 2.0 |
app/src/main/java/com/example/solarsystemclean/di/UseCaseModule.kt | luizcjr | 347,671,875 | false | null | package com.example.solarsystemclean.di
import com.example.solarsystemclean.domain.usecase.*
import org.koin.dsl.module
val useCaseModule = module {
factory<UserUseCase> {
UserUseCaseImpl(get())
}
factory<PlanetsUseCase> {
PlanetsUseCaseImpl(get())
}
factory<PlanetsFavoritesUseCase> {
PlanetsFavoritesUseCaseImpl(get())
}
} | 0 | Kotlin | 0 | 0 | 41c8c1809b95994320e91761ea3758be078565f2 | 377 | solar_system | MIT License |
ktex/src/main/java/nay/lib/ktex/broadcast/receiver/OnEachBroadcastReceiver.kt | Naaatan | 395,909,215 | false | null | /*
* Created by Naaatan on 2021/10/22 10:11
* Copyright (c) 2021 . All rights reserved.
* Last modified 2021/10/22 9:52
*/
package nay.lib.ktex.broadcast.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
fun broadcastReceiver(f: OnEachBroadcastReceiver.(Context?, Intent?) -> Unit): BroadcastReceiver =
OnEachBroadcastReceiver().apply {
doOnReceive { context, intent -> this.f(context, intent) }
}
/**
* Create a BroadcastReceiver easily.
*
* ```kotlin
* val receiver = broadcastReceiver { context, intent ->
* when (intent?.action) {
* BROADCAST_DEFAULT_ALBUM_CHANGED -> handleAlbumChanged()
* BROADCAST_CHANGE_TYPE_CHANGED -> handleChangeTypeChanged()
* }
* }
*/
class OnEachBroadcastReceiver : BroadcastReceiver() {
private var onReceiveRunner: OnReceiveRunner? = null
override fun onReceive(context: Context?, intent: Intent?) {
onReceiveRunner?.run(context, intent)
}
inner class OnReceiveRunner(private val runner: (Context?, Intent?) -> Unit) {
fun run(ctx: Context?, intent: Intent?) = runner.invoke(ctx, intent)
}
fun doOnReceive(run: (Context?, Intent?) -> Unit) {
onReceiveRunner = OnReceiveRunner(run)
}
} | 0 | Kotlin | 0 | 0 | f528b1269967362d91032e31c8833ed46734ff93 | 1,291 | android-nay-ktex | Apache License 2.0 |
app/src/main/java/in/co/droidcon/android/MainActivity.kt | droidcon-india | 238,626,734 | false | null | package `in`.co.droidcon.android
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import `in`.co.droidcon.android.adapter.MainAdapter
import `in`.co.droidcon.models.BreedModel
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
@ExperimentalCoroutinesApi
class MainActivity : AppCompatActivity() {
companion object {
val TAG = MainActivity::class.java.simpleName
}
private lateinit var adapter: MainAdapter
private lateinit var model: BreedModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
model = BreedModel {
print(it)
adapter.submitList(it.allItems)
}
adapter =
MainAdapter(model::updateBreedFavorite)
breed_list.adapter = adapter
breed_list.layoutManager = LinearLayoutManager(this)
model.getBreedsFromNetwork()
}
override fun onDestroy() {
super.onDestroy()
model.onDestroy()
}
}
| 2 | Kotlin | 0 | 2 | de406b9e68fefe85742445d0173d04f42f6ce913 | 1,166 | droidcon-india-app-2020 | Apache License 2.0 |
app/src/main/java/com/timepack/countpose/home/HomeScreen.kt | Oleur | 344,594,254 | 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.timepack.countpose.home
import android.graphics.Typeface
import android.text.format.DateUtils
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandIn
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.timepack.countpose.R
import com.timepack.countpose.TimePackViewModel
import com.timepack.countpose.theme.blue700
import com.timepack.countpose.theme.green200
import com.timepack.countpose.theme.greenLight700
import com.timepack.countpose.theme.red700
import com.timepack.countpose.theme.typography
@ExperimentalAnimationApi
@Composable
fun HomeScreen(timePackViewModel: TimePackViewModel) {
val context = LocalContext.current
val playPauseState = remember { mutableStateOf(true) }
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (topBar, wave, playButton, resetButton, timesUpText) = createRefs()
TopAppBar(
title = {
Text(
text = context.getString(R.string.app_name),
style = typography.h5
)
},
actions = {
IconButton(
onClick = {
if (playPauseState.value) {
timePackViewModel.addTime(10)
}
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_more_time_24),
contentDescription = "Add 10 seconds",
tint = Color.White
)
}
},
elevation = 4.dp,
modifier = Modifier
.constrainAs(topBar) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.fillMaxWidth()
.height(56.dp)
)
TimeWave(
timeSpec = timePackViewModel.timeState.value!! * DateUtils.SECOND_IN_MILLIS,
playPauseState.value,
timePackViewModel,
modifier = Modifier
.constrainAs(wave) {
top.linkTo(topBar.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
)
val isAlertMessageVisible by timePackViewModel.alertMessage.observeAsState(initial = false)
AnimatedVisibility(
visible = isAlertMessageVisible,
enter = expandIn(animationSpec = spring()),
modifier = Modifier.constrainAs(timesUpText) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
) {
Text(
text = context.getString(R.string.timesup),
style = typography.h3.copy(color = red700),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(32.dp)
.border(width = 4.dp, color = red700, RoundedCornerShape(8.dp))
.graphicsLayer {
shadowElevation = 8.dp.toPx()
}
.background(color = greenLight700, RoundedCornerShape(8.dp))
.padding(32.dp)
)
}
AnimatedVisibility(
modifier = Modifier
.constrainAs(playButton) {
end.linkTo(parent.end, margin = 32.dp)
bottom.linkTo(parent.bottom, margin = 32.dp)
},
visible = playPauseState.value,
enter = slideInHorizontally(
initialOffsetX = { fullWidth ->
fullWidth + fullWidth / 2
}
) + fadeIn(),
exit = slideOutHorizontally(
targetOffsetX = { fullWidth ->
fullWidth + fullWidth / 2
}
) + fadeOut()
) {
ActionButton(
res = R.drawable.ic_play_24
) {
playPauseState.value = false
timePackViewModel.startTimer()
}
}
AnimatedVisibility(
visible = !playPauseState.value,
modifier = Modifier
.constrainAs(resetButton) {
start.linkTo(parent.start, margin = 32.dp)
bottom.linkTo(parent.bottom, margin = 32.dp)
}
) {
ActionButton(
res = R.drawable.ic_reset
) {
playPauseState.value = true
timePackViewModel.stop(10)
}
}
}
}
@Composable
fun TimeWave(
timeSpec: Long,
init: Boolean,
timePackViewModel: TimePackViewModel,
modifier: Modifier
) {
val animColor by animateColorAsState(
targetValue = if (init) green200 else red700,
animationSpec = TweenSpec(if (init) 0 else timeSpec.toInt(), easing = LinearEasing)
)
val deltaXAnim = rememberInfiniteTransition()
val dx by deltaXAnim.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(500, easing = LinearEasing)
)
)
val screenWidthPx = with(LocalDensity.current) {
(LocalConfiguration.current.screenHeightDp * density) - 150.dp.toPx()
}
val animTranslate by animateFloatAsState(
targetValue = if (init) 0f else screenWidthPx,
animationSpec = TweenSpec(if (init) 0 else timeSpec.toInt(), easing = LinearEasing)
)
val waveHeight by animateFloatAsState(
targetValue = if (init) 125f else 0f,
animationSpec = TweenSpec(if (init) 0 else timeSpec.toInt(), easing = LinearEasing)
)
val infiniteScale = rememberInfiniteTransition()
val animAlertScale by infiniteScale.animateFloat(
initialValue = 0.95f,
targetValue = 1.05f,
animationSpec = infiniteRepeatable(
animation = tween(500, easing = FastOutSlowInEasing),
repeatMode = RepeatMode.Reverse
)
)
val waveWidth = 200
val originalY = 150f
val path = Path()
val textPaint = Paint().asFrameworkPaint()
Canvas(
modifier = modifier.fillMaxSize(),
onDraw = {
translate(top = animTranslate) {
drawPath(path = path, color = animColor)
path.reset()
val halfWaveWidth = waveWidth / 2
path.moveTo(-waveWidth + (waveWidth * dx), originalY.dp.toPx())
for (i in -waveWidth..(size.width.toInt() + waveWidth) step waveWidth) {
path.relativeQuadraticBezierTo(
halfWaveWidth.toFloat() / 2,
-waveHeight,
halfWaveWidth.toFloat(),
0f
)
path.relativeQuadraticBezierTo(
halfWaveWidth.toFloat() / 2,
waveHeight,
halfWaveWidth.toFloat(),
0f
)
}
path.lineTo(size.width, size.height)
path.lineTo(0f, size.height)
path.close()
}
translate(top = animTranslate * 0.92f) {
scale(scale = if (timePackViewModel.alertState.value!!) animAlertScale else 1f) {
drawIntoCanvas {
textPaint.apply {
isAntiAlias = true
textSize = 48.sp.toPx()
typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
}
it.nativeCanvas.drawText(
DateUtils.formatElapsedTime(timePackViewModel.timeState.value!!),
(size.width / 2) - 64.dp.toPx(),
120.dp.toPx(),
textPaint
)
}
}
}
}
)
}
@Composable
fun ActionButton(res: Int, action: () -> Unit) {
Button(
shape = RoundedCornerShape(36.dp),
onClick = {
action.invoke()
},
colors = ButtonDefaults.buttonColors(backgroundColor = blue700),
modifier = Modifier.size(72.dp)
) {
Image(
painter = painterResource(id = res),
contentDescription = "Action Button",
modifier = Modifier.fillMaxSize()
)
}
}
| 0 | Kotlin | 3 | 18 | d1305184cbccf0de2817ce2f5a9fbda38a022eb9 | 12,035 | TimePack-CountPose | Apache License 2.0 |
analysis/analysis-api/testData/components/resolver/singleByPsi/nestedTypes/ResolveNamedCompanionInCompanionType.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | package foo.bar.baz
class X {
companion object COMP {
fun lol() {}
}
}
class E {
val x = foo.bar.baz.X.CO<caret>MP
} | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 138 | kotlin | Apache License 2.0 |
EvoMaster/core/src/main/kotlin/org/evomaster/core/problem/rest/service/BlackBoxRestFitness.kt | BrotherKim | 397,139,860 | false | {"Markdown": 32, "Shell": 14, "Maven POM": 66, "Text": 16, "Ignore List": 13, "Java": 1366, "SQL": 44, "YAML": 13, "JSON": 37, "JavaScript": 183, "XML": 14, "Mermaid": 1, "Java Properties": 36, "INI": 15, "HTML": 52, "Dockerfile": 2, "CSS": 8, "JSON with Comments": 3, "Less": 8, "SVG": 16, "Kotlin": 541, "OASv2-yaml": 1, "XSLT": 3, "Python": 3, "Graphviz (DOT)": 1, "OASv2-json": 18, "BibTeX": 1, "R": 5, "OASv3-json": 12, "ANTLR": 4} | package org.evomaster.core.problem.rest.service
import com.google.inject.Inject
import org.evomaster.core.problem.rest.RestAction
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestCallResult
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.remote.service.RemoteController
import org.evomaster.core.search.ActionResult
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.FitnessValue
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class BlackBoxRestFitness : RestFitness() {
companion object {
private val log: Logger = LoggerFactory.getLogger(BlackBoxRestFitness::class.java)
}
@Inject(optional = true)
private lateinit var rc: RemoteController
override fun doCalculateCoverage(individual: RestIndividual): EvaluatedIndividual<RestIndividual>? {
if(config.bbExperiments){
/*
If we have a controller, we MUST reset the SUT at each test execution.
This is to avoid memory leaks in the dat structures used by EM.
Eg, this was a huge problem for features-service with AdditionalInfo having a
memory leak
*/
rc.resetSUT()
}
val fv = FitnessValue(individual.size().toDouble())
val actionResults: MutableList<ActionResult> = mutableListOf()
//used for things like chaining "location" paths
val chainState = mutableMapOf<String, String>()
//run the test, one action at a time
for (i in 0 until individual.seeActions().size) {
val a = individual.seeActions()[i]
var ok = false
if (a is RestCallAction) {
ok = handleRestCall(a, actionResults, chainState, mapOf())
} else {
throw IllegalStateException("Cannot handle: ${a.javaClass}")
}
if (!ok) {
break
}
}
handleResponseTargets(fv, individual.seeActions(), actionResults)
return EvaluatedIndividual(fv, individual.copy() as RestIndividual, actionResults)
}
protected fun handleResponseTargets(
fv: FitnessValue,
actions: List<RestAction>,
actionResults: List<ActionResult>) {
(0 until actionResults.size)
.filter { actions[it] is RestCallAction }
.filter { actionResults[it] is RestCallResult }
.forEach {
val status = (actionResults[it] as RestCallResult)
.getStatusCode() ?: -1
val name = actions[it].getName()
//objective for HTTP specific status code
val statusId = idMapper.handleLocalTarget("$status:$name")
fv.updateTarget(statusId, 1.0, it)
}
}
} | 1 | null | 1 | 1 | a7a120fe7c3b63ae370e8a114f3cb71ef79c287e | 2,934 | ASE-Technical-2021-api-linkage-replication | MIT License |
library/plugins/influxdb/influxdb2-plugin/src/main/kotlin/io/github/cdsap/talaiot/plugin/influxdb2/Influxdb2Configuration.kt | cdsap | 157,973,716 | false | {"Kotlin": 394787, "JavaScript": 16950, "Shell": 6008, "Dockerfile": 2382, "CSS": 1662, "HTML": 737} | package io.github.cdsap.talaiot.plugin.influxdb2
import groovy.lang.Closure
import io.github.cdsap.talaiot.publisher.PublishersConfiguration
import io.github.cdsap.talaiot.publisher.influxdb2.InfluxDb2PublisherConfiguration
import org.gradle.api.Project
class Influxdb2Configuration(project: Project) : PublishersConfiguration(project) {
var influxDb2Publisher: InfluxDb2PublisherConfiguration? = null
/**
* Configuration accessor within the [PublishersConfiguration] for the [InfluxDb2Publisher]
*
* @param configuration Configuration block for the [InfluxDb2PublisherConfiguration]
*/
fun influxDb2Publisher(configuration: InfluxDb2PublisherConfiguration.() -> Unit) {
influxDb2Publisher = InfluxDb2PublisherConfiguration().also(configuration)
}
/**
* Configuration accessor within the [PublishersConfiguration] for the [InfluxDb2Publisher]
*
* @param closure closure for the [InfluxDb2PublisherConfiguration]
*/
fun influxDb2Publisher(closure: Closure<*>) {
influxDb2Publisher = InfluxDb2PublisherConfiguration()
closure.delegate = influxDb2Publisher
closure.call()
}
}
| 26 | Kotlin | 37 | 583 | 5a1fe716c92aa5d9895f543e75ddeebfd7d47df2 | 1,178 | Talaiot | MIT License |
app/src/main/java/jp/yitt/mixedimage/example/MainActivity.kt | yt-tkhs | 119,998,851 | false | {"Java": 10809, "Kotlin": 5029} | package jp.yitt.mixedimage.example
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ImageView
import android.widget.SeekBar
import jp.yitt.mixedimage.MixedImage
class MainActivity : AppCompatActivity() {
companion object {
private const val resultWidth = 1280f
private const val resultHeight = 720f
private const val angle = 15.0
}
val imageView: ImageView by lazy { findViewById<ImageView>(R.id.imageView) }
private lateinit var bitmaps: List<Bitmap>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val widthSeekBar = findViewById<SeekBar>(R.id.widthSeekBar)
val heightSeekBar = findViewById<SeekBar>(R.id.heightSeekBar)
val angleSeekBar = findViewById<SeekBar>(R.id.angleSeekBar)
val bitmap1 = BitmapFactory.decodeResource(resources, R.drawable.example1)
val bitmap2 = BitmapFactory.decodeResource(resources, R.drawable.example2)
val bitmap3 = BitmapFactory.decodeResource(resources, R.drawable.example3)
val bitmap4 = BitmapFactory.decodeResource(resources, R.drawable.example4)
bitmaps = listOf(bitmap1, bitmap2, bitmap3, bitmap4)
widthSeekBar.progress = resultWidth.toInt()
heightSeekBar.progress = resultHeight.toInt()
angleSeekBar.progress = angle.toInt()
widthSeekBar.setOnSeekBarChangeListener(onProgressChanged = { _, progress, _ ->
if (progress == 0) return@setOnSeekBarChangeListener
MixedImage.from(*bitmaps.toTypedArray())
.size(progress.toFloat(), heightSeekBar.progress.toFloat())
.angle(angleSeekBar.progress.toDouble())
.into(imageView)
})
heightSeekBar.setOnSeekBarChangeListener(onProgressChanged = { _, progress, _ ->
if (progress == 0) return@setOnSeekBarChangeListener
MixedImage.from(*bitmaps.toTypedArray())
.size(widthSeekBar.progress.toFloat(), progress.toFloat())
.angle(angleSeekBar.progress.toDouble())
.into(imageView)
})
angleSeekBar.setOnSeekBarChangeListener(onProgressChanged = { _, progress, _ ->
MixedImage.from(*bitmaps.toTypedArray())
.size(widthSeekBar.progress.toFloat(), heightSeekBar.progress.toFloat())
.angle(progress.toDouble())
.into(imageView)
})
MixedImage.from(*bitmaps.toTypedArray())
.size(resultWidth, resultHeight)
.angle(angle)
.into(imageView)
}
private fun SeekBar.setOnSeekBarChangeListener(
onProgressChanged: ((SeekBar, Int, Boolean) -> Unit)? = null,
onStartTrackingTouch: ((SeekBar) -> Unit)? = null,
onStopTrackingTouch: ((SeekBar) -> Unit)? = null
) {
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
onProgressChanged?.invoke(seekBar, progress, fromUser)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
onStartTrackingTouch?.invoke(seekBar)
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
onStopTrackingTouch?.invoke(seekBar)
}
})
}
}
| 1 | Java | 1 | 1 | f032d1f22184e32242d805b1815465d2786d8cd4 | 3,611 | MixedImage | Apache License 2.0 |
src/main/kotlin/groupnet/gn/GNDiagram.kt | AlmasB | 174,802,362 | false | null | package groupnet.gn
import groupnet.euler.*
import groupnet.gui.SettingsController
import groupnet.network.NetworkEdge
import groupnet.network.NetworkGraph
import groupnet.util.Log
import groupnet.util.combinations2
import groupnet.util.numIntersectionsLinePolygon
import groupnet.util.symmetricDifference
/**
*
*
* @author <NAME> (<EMAIL>)
*/
class GNDiagram(val GND: GNDescription,
val d: EulerDiagram,
val g: NetworkGraph) {
fun embedIntoZone(az: AbstractZone, gnd: GNDiagram): GNDiagram {
Log.i("Embedding ${gnd.d.actualDescription} into zone $az")
val new_GND = GND + gnd.GND
val new_d = d.drawIntoZone(az, gnd.d)
val V1 = V(g).toMutableList()
val E1 = E(g).toMutableList()
val V2 = V(gnd.g)
val E2 = E(gnd.g)
// replace edges (v1, v2) : v1 or v2 is in V2 with v1 / v2 from V2
V2.filter { it in V1 }.forEach { v ->
E(g).filter { v.isIncidentWith(it) }.forEach { e ->
E1 -= e
if (e.v1 == v) {
E1 += NetworkEdge(v, e.v2)
} else {
E1 += NetworkEdge(e.v1, v)
}
}
// find the zone in new_d where v lives and position in that zone randomly
val zone = (Z(new_d) + new_d.outsideZone).find { it.az == new_GND.aloc(v.label) }!!
v.pos = zone.visualCenter.add(Math.random(), Math.random())
}
// removed duplicated vertices from V1
// Note: V2 does not have duplications since our method duplicates vertices and adds to V1 only
V1 -= V2
// we now have a situation where some nodes in V1 that lived in az have to move
// since we just slotted gnd.d into az
// so, reposition unique G1 nodes that are in zone of az
val zone = (Z(new_d) + new_d.outsideZone ).find { it.az == az }!!
V1.filter { new_GND.aloc(it.label) == az }.forEach { v ->
v.pos = zone.visualCenter.add(Math.random(), Math.random())
}
// add unique G1 nodes, unique G2 nodes
// add unique G1 edges, unique G2 edges
val new_g = NetworkGraph(V1 + V2, E1 + E2)
return GNDiagram(new_GND, new_d, new_g)
}
fun computeNodeNodeCrossings(): Int {
return combinations2(V(g)).count { (v1, v2) -> v1.crossesNode(v2) }
}
fun computeEdgeNodeCrossings(): Int {
return E(g).sumBy { computeEdgeNodeCrossing(it) }
}
fun computeEdgeCrossings(): Int {
return combinations2(E(g)).filter { (e1, e2) -> !e1.isAdjacent(e2) && e1.crosses(e2) }.count()
}
/**
* @return edge-curve crossing number = actual - abstract min
*/
fun computeEdgeCurveCrossings(): Int {
return E(g).sumBy { computeEdgeCurveCrossing(it) }
}
private fun computeEdgeCurveCrossing(e: NetworkEdge): Int {
val az1 = GND.aloc(e.v1.label).labels
val az2 = GND.aloc(e.v2.label).labels
val abstractMin = az1.symmetricDifference(az2).size
val actual = C(d).sumBy { c -> numCrosses(c, e) }
return actual - abstractMin
}
private fun numCrosses(c: Curve, e: NetworkEdge): Int {
return numIntersectionsLinePolygon(e.v1.pos, e.v2.pos, c.getPolygon())
}
private fun computeEdgeNodeCrossing(e: NetworkEdge): Int {
return V(g).count { it.isNonIncidentAndOnEdge(e, (SettingsController.NODE_SIZE)) }
}
// in case description parent is not captured?
//gnd.GND.description = gnd.d.originalDescription
} | 2 | null | 1 | 1 | 4aaa9de60ecdba5b9402b809e1e6e62489a1d790 | 3,583 | D2020 | Apache License 2.0 |
rxhttp/src/main/java/rxhttp/wrapper/await/AwaitTimeout.kt | FrozenFreeFall | 260,648,176 | true | {"Java Properties": 2, "Markdown": 1, "Java": 101, "Proguard": 2, "Kotlin": 35} | package rxhttp.wrapper.await
import kotlinx.coroutines.withTimeout
import rxhttp.IAwait
/**
* 请求超时处理
* User: ljx
* Date: 2020/3/21
* Time: 17:06
*/
internal class AwaitTimeout<T>(
private val iAwait: IAwait<T>,
private var timeoutMillis: Long = 0L
) : IAwait<T> {
override suspend fun await() = withTimeout(timeoutMillis) { iAwait.await() }
} | 0 | null | 0 | 1 | 9da130ca5a320dfb455ad1aaf40f951dc542811f | 362 | okhttp-RxHttp | Apache License 2.0 |
app/src/main/java/view/splash/SplashActivity.kt | ariesvelasquez | 168,901,580 | false | {"Kotlin": 16657, "Java": 322} | package view.splash
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import com.android.wordspeak.R
import timber.log.Timber
import view.BaseActivity
import java.util.*
import kotlin.concurrent.schedule
class SplashActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
Timber.e("asdf Test")
// Add splash fragment if this is first creation
if (savedInstanceState == null) {
val splashFragment = SplashFragment()
// Load Splash Fragment
supportFragmentManager.beginTransaction()
.add(R.id.fragmentMainContainer, splashFragment, SplashFragment.TAG)
.commit()
}
showVoiceFragment()
}
/** Shows the Voice listener Fragment */
private fun showVoiceFragment() {
val fragment = VoiceFragment()
// Load Voice Fragment after some seconds.
Timer("RedirectingToMainPage", false).schedule(3000) {
supportFragmentManager
.beginTransaction()
.replace(R.id.fragmentMainContainer, fragment, VoiceFragment.TAG)
.commit()
}
}
/** Shows the Video player Fragment */
fun showVideoFragment(position: Int) {
val fragment = VideoFragment.forVideo(position)
supportFragmentManager
.beginTransaction()
.addToBackStack("video")
.replace(R.id.fragmentMainContainer, fragment, VideoFragment.TAG)
.commit()
}
override fun onBackPressed() {
val count = supportFragmentManager.backStackEntryCount
if (count == 0) {
super.onBackPressed()
//additional code
} else {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
supportFragmentManager.popBackStack()
}
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
}
}
| 0 | Kotlin | 0 | 0 | f4e2b286af65d285e34d27f018902d8394747b10 | 2,141 | WordSpeak | MIT License |
app/src/main/java/knf/kuma/favorite/FavoriteViewModel.kt | jordyamc | 119,774,950 | false | null | package knf.kuma.favorite
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import knf.kuma.commons.PrefsUtil
import knf.kuma.database.CacheDB
import knf.kuma.pojos.FavoriteObject
class FavoriteViewModel : ViewModel() {
fun getData(): LiveData<MutableList<FavoriteObject>> {
return if (PrefsUtil.showFavSections())
FavSectionHelper.init()
else
when (PrefsUtil.favsOrder) {
1 -> CacheDB.INSTANCE.favsDAO().allID
else -> CacheDB.INSTANCE.favsDAO().all
}
}
}
| 24 | null | 39 | 159 | 99d8108ca5a9c32b89952aeb217319693df57688 | 573 | UKIKU | MIT License |
plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/GitLabToolWindowTabViewModel.kt | sutrosoftware | 251,488,669 | false | {"Text": 7106, "INI": 573, "YAML": 412, "Ant Build System": 10, "Batchfile": 34, "Shell": 621, "Markdown": 678, "Ignore List": 120, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 244, "XML": 7056, "SVG": 3569, "Kotlin": 47685, "Java": 80051, "HTML": 3248, "Java Properties": 212, "Gradle": 431, "Maven POM": 81, "JavaScript": 213, "CSS": 70, "JFlex": 31, "JSON": 1355, "Groovy": 3308, "XSLT": 113, "desktop": 1, "Python": 14973, "JAR Manifest": 17, "PHP": 47, "Gradle Kotlin DSL": 460, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Diff": 135, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 1, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 66, "GraphQL": 54, "OpenStep Property List": 47, "Tcl": 1, "fish": 1, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 5, "XML Property List": 81, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "C": 87, "TOML": 151, "Proguard": 2, "PlantUML": 6, "Checksums": 58, "Java Server Pages": 8, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 18, "C++": 33, "Handlebars": 1, "Rust": 9, "Makefile": 2, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 14, "Regular Expression": 3, "JSON5": 4} | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui
import com.intellij.collaboration.async.mapStateScoped
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.plugins.gitlab.GitLabProjectsManager
import org.jetbrains.plugins.gitlab.api.GitLabProjectConnection
import org.jetbrains.plugins.gitlab.api.GitLabProjectConnectionManager
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager
import org.jetbrains.plugins.gitlab.mergerequest.data.GitLabMergeRequestsListLoader
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabToolWindowTabViewModel.NestedViewModel.MergeRequests
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabToolWindowTabViewModel.NestedViewModel.Selectors
internal class GitLabToolWindowTabViewModel(scope: CoroutineScope,
private val connectionManager: GitLabProjectConnectionManager,
private val projectsManager: GitLabProjectsManager,
private val accountManager: GitLabAccountManager) {
val nestedViewModelState: StateFlow<NestedViewModel> = connectionManager.state.mapStateScoped(scope) { scope, connection ->
if (connection != null) {
MergeRequests(scope, connection)
}
else {
Selectors(GitLabRepositoryAndAccountSelectorViewModel(scope, connectionManager, projectsManager, accountManager))
}
}
internal sealed interface NestedViewModel {
class Selectors(val selectorVm: GitLabRepositoryAndAccountSelectorViewModel) : NestedViewModel
class MergeRequests(scope: CoroutineScope, connection: GitLabProjectConnection) : NestedViewModel {
val listVm: GitLabMergeRequestsListViewModel =
GitLabMergeRequestsListViewModelImpl(scope) {
GitLabMergeRequestsListLoader(connection.apiClient, connection.repo.repository)
}
}
}
} | 1 | null | 1 | 1 | fea02a6d5406d10ce0c18b1c23eb10a4acbd018e | 2,068 | intellij-community | Apache License 2.0 |
kdroidext/src/main/java/com/nowfal/kdroidext/kotx/ext/basic/Uri.kt | nowfalsalahudeen | 167,347,983 | false | null |
package com.nowfal.kdroidext.kotx.ext.basic
import android.net.Uri
/**
* Returns query parameter matching [param].
*/
operator fun Uri.get(param: String): String? = getQueryParameter(param)
| 1 | null | 1 | 29 | fb91a3febf73a3bb5f3582de2694c6f829cf3c58 | 197 | KdroidExt | Apache License 2.0 |
src/main/kotlin/org/intellij/plugin/tracker/utils/CredentialsManager.kt | JetBrains-Research | 277,519,535 | false | null | package org.intellij.plugin.tracker.utils
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.generateServiceName
import com.intellij.ide.passwordSafe.PasswordSafe
/**
* This class handles the logic of storing web-hosted repository platforms' (e.g. GitHub, Gitlab) users' credentials
*
* It handles the logic of both storing and retrieving the credentials, upon request.
*/
class CredentialsManager {
companion object {
private fun createCredentialAttributes(key: String): CredentialAttributes {
return CredentialAttributes(generateServiceName("Link tracker", key))
}
/**
* Stores the credentials (token) of a user identified by a username and a specific platform
*/
fun storeCredentials(platform: String, username: String, token: String) {
val credentialAttributes: CredentialAttributes = createCredentialAttributes("$platform-$username")
val passwordSafe: PasswordSafe = PasswordSafe.instance
val credentials = Credentials(username, token)
passwordSafe.set(credentialAttributes, credentials)
}
/**
* Gets the credentials (token), if any, of a user identified by a username and platform
*/
fun getCredentials(platform: String, username: String): String? {
val credentialAttributes: CredentialAttributes = createCredentialAttributes("$platform-$username")
val credentials: Credentials? = PasswordSafe.instance.get(credentialAttributes)
if (credentials != null) {
return credentials.getPasswordAsString()
}
return null
}
}
}
| 5 | null | 1 | 2 | 831e3eaa7ead78ffe277cb415b6f993139fb4de3 | 1,767 | linktracker | Apache License 2.0 |
rewrite-groovy/src/test/kotlin/org/openrewrite/groovy/tree/UnaryTest.kt | rahulvramesh | 561,633,409 | true | {"INI": 2, "Gradle Kotlin DSL": 30, "Shell": 6, "Markdown": 8, "Git Attributes": 1, "Batchfile": 2, "Text": 4, "Ignore List": 3, "Kotlin": 451, "Java": 1134, "YAML": 31, "JSON": 2, "ANTLR": 21, "EditorConfig": 12, "Groovy": 3, "XML": 1} | /*
* Copyright 2021 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.groovy.tree
import org.junit.jupiter.api.Test
import org.openrewrite.Issue
import org.openrewrite.groovy.Assertions.groovy
import org.openrewrite.test.RewriteTest
@Suppress("GroovyUnusedAssignment", "GroovyUnusedIncOrDec", "GrUnnecessarySemicolon")
class UnaryTest : RewriteTest {
@Test
fun format() = rewriteRun(
groovy(
"""
int i = 0;
int j = ++i;
int k = i ++;
"""
)
)
@Test
fun postfix() = rewriteRun(
groovy(
"""
int k = i ++;
"""
)
)
@Test
fun prefix() = rewriteRun(
groovy(
"""
int k = ++i;
"""
)
)
@Suppress("GroovyPointlessBoolean")
@Issue("https://github.com/openrewrite/rewrite/issues/1524")
@Test
fun negation() = rewriteRun(
groovy(
"""
def a = !true
"""
)
)
}
| 0 | null | 0 | 1 | dca13eabf5551d603dcade7a4be27d1e8536ee80 | 1,623 | rewrite | Apache License 2.0 |
panel/src/main/java/com/effective/android/panel/utils/CusShortUtil.kt | uni7corn | 276,338,530 | false | null | package com.effective.android.panel.utils
import android.view.View
import com.effective.android.panel.utils.cutShort.*
/**
* 刘海计算
* Created by yummyLau on 20-03-27
* Email: yummyl.lau@gmail.com
* blog: yummylau.com
*/
object CusShortUtil {
private val HUAWEI: DeviceCutShort = HuaweiCutShort()
private val OFFICIAL: DeviceCutShort = OfficialCutShort()
private val OPPO: DeviceCutShort = OppoCutShort()
private val VIVO: DeviceCutShort = ViVoCutShort()
private val XIAOMI: DeviceCutShort = XiaoMiCutShort()
private val SAMSUNG: DeviceCutShort = SamSungCutShort()
@JvmStatic
fun getDeviceCutShortHeight(view: View): Int {
val context = view.context
if (HUAWEI.hasCutShort(context)) {
return HUAWEI.getCurrentCutShortHeight(view)
}
if (OPPO.hasCutShort(context)) {
return OPPO.getCurrentCutShortHeight(view)
}
if (VIVO.hasCutShort(context)) {
return VIVO.getCurrentCutShortHeight(view)
}
if (XIAOMI.hasCutShort(context)) {
return XIAOMI.getCurrentCutShortHeight(view)
}
return if (SAMSUNG.hasCutShort(context)) {
SAMSUNG.getCurrentCutShortHeight(view)
} else OFFICIAL.getCurrentCutShortHeight(view)
}
} | 0 | Kotlin | 1 | 0 | ac4f611f12d6c44e70b1fc7e1bb4ecebe9a6ea60 | 1,292 | emoji_keyboard | Apache License 2.0 |
src/main/kotlin/com/github/lppedd/cc/lookupElement/CommitFooterValueLookupElement.kt | lppedd | 208,670,987 | false | {"Kotlin": 415756, "HTML": 49996, "Java": 9014, "Lex": 4027} | package com.github.lppedd.cc.lookupElement
import com.github.lppedd.cc.*
import com.github.lppedd.cc.api.CommitFooterValue
import com.github.lppedd.cc.api.CommitToken
import com.github.lppedd.cc.parser.CCParser
import com.github.lppedd.cc.parser.ValidToken
import com.github.lppedd.cc.psiElement.CommitFooterValuePsiElement
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElementPresentation
/**
* @author <NAME>
*/
internal class CommitFooterValueLookupElement(
private val psiElement: CommitFooterValuePsiElement,
private val commitFooterValue: CommitFooterValue,
) : CommitTokenLookupElement() {
override fun getToken(): CommitToken =
commitFooterValue
override fun getPsiElement(): CommitFooterValuePsiElement =
psiElement
override fun getLookupString(): String =
commitFooterValue.getValue()
override fun getItemText(): String =
commitFooterValue.getText()
override fun renderElement(presentation: LookupElementPresentation) {
presentation.icon = CCIcons.Tokens.Footer
super.renderElement(presentation)
}
override fun handleInsert(context: InsertionContext) {
val editor = context.editor
val document = editor.document
val (lineStartOffset) = editor.getCurrentLineRange()
val lineText = document.getSegment(lineStartOffset, document.textLength)
val footer = CCParser.parseFooter(lineText).footer
val newFooterValueString = " ${commitFooterValue.getValue()}"
if (footer is ValidToken) {
// Replace an existing footer value
editor.replaceString(
lineStartOffset + footer.range.startOffset,
lineStartOffset + footer.range.endOffset,
newFooterValueString,
)
} else {
// No footer value was present, just insert the string
editor.insertStringAtCaret(newFooterValueString)
}
}
}
| 34 | Kotlin | 19 | 333 | 5d55768a47a31a10147e7d69f2be261d028d1b85 | 1,889 | idea-conventional-commit | MIT License |
app/src/main/java/com/hummingbirdgraph/MainActivity.kt | sujeet-kumar-mehta | 166,382,339 | false | {"Gradle": 4, "XML": 50, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 2, "Kotlin": 12, "INI": 2} | package com.hummingbirdgraph
import android.content.res.Resources
import android.os.Bundle
import android.support.design.card.MaterialCardView
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.CardView
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.butterflybarchart.*
import kotlinx.android.synthetic.main.activity_main.*
import java.text.DecimalFormat
class MainActivity : AppCompatActivity() {
var maxYPoint = 188
var maxXPoint = 24
var verticalBarArray: FloatArray =
floatArrayOf(0.2f, 0.4f, 0.6f, 0.1f, 1f, 0.5f, 0.3f, 0.8f, 0.2f, 0.4f, 0.6f, 0.1f, 1f, 0.5f, 0.3f, 0.8f)
lateinit var triangleView: TriangleView
lateinit var triangleViewShadow: TriangleView
lateinit var suggestionCardView: MaterialCardView
lateinit var graphTipCardView: MaterialCardView
lateinit var overall_summary_card_view: CardView
lateinit var suggestionCircularMatericalCard: MaterialCardView
lateinit var horizontalRecyclerView: RecyclerView
lateinit var verticalValueRecyclerView: RecyclerView
lateinit var verticalValueIndicatorRecylerView: RecyclerView
lateinit var titleTV: TextView
lateinit var llTitle: LinearLayout
lateinit var dateRangeTV: TextView
lateinit var morethanTV: TextView
lateinit var morethanDataTV: TextView
lateinit var suggestionTextView: TextView
lateinit var reportInfoTextView: TextView
lateinit var overallDataTV: TextView
lateinit var overallTV: TextView
lateinit var textviewYInfo: TextView
lateinit var minutesAnalysedTV: TextView
lateinit var tipDateRangeTextView: TextView
lateinit var activatePlanTV: TextView
lateinit var tip2DateRangeTextView: TextView
lateinit var tipLayout: LinearLayout
lateinit var unpaidLayout: LinearLayout
lateinit var yAxisValue1: TextView
lateinit var yAxisValue2: TextView
lateinit var yAxisValue3: TextView
lateinit var yAxisValue4: TextView
lateinit var yAxisValue5: TextView
var yAxisTextViewArray: Array<TextView>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
maxYPoint =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 188.toFloat(), resources?.displayMetrics).toInt()
maxXPoint =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24.toFloat(), resources?.displayMetrics).toInt()
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
setGraphUi()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
fun setGraphUi() {
llTitle = findViewById(R.id.ll_title)
titleTV = findViewById(R.id.reportTitleTV)
dateRangeTV = findViewById(R.id.dateRangeTV)
overallDataTV = findViewById(R.id.overall_data_tv)
overallTV = findViewById(R.id.overall_data_title_tv)
morethanDataTV = findViewById(R.id.more_than_data_tv)
morethanTV = findViewById(R.id.more_than_title_tv)
minutesAnalysedTV = findViewById(R.id.minutes_analyzed_data_tv)
tipDateRangeTextView = findViewById(R.id.tip_date_text_view)
overall_summary_card_view = findViewById(R.id.overall_summary_card_view)
activatePlanTV = findViewById(R.id.active_plan_tv)
tip2DateRangeTextView = findViewById(R.id.tip_date2_text_view)
tipLayout = findViewById(R.id.tool_tip_info_layout)
unpaidLayout = findViewById(R.id.not_paid_layout)
textviewYInfo = findViewById(R.id.textviewYInfo)
triangleView = findViewById(R.id.trangleView)
triangleViewShadow = findViewById(R.id.trangleViewShadow)
suggestionCardView = findViewById(R.id.suggestion_materical_card)
suggestionTextView = findViewById(R.id.suggestion_tv)
reportInfoTextView = findViewById(R.id.report_info_text_view)
graphTipCardView = findViewById(R.id.graph_tip_card_view)
suggestionCircularMatericalCard = findViewById(R.id.suggestion_circular_materical_card)
horizontalRecyclerView = findViewById(R.id.vertical_bar_recyler_view)
verticalValueRecyclerView = findViewById(R.id.horizontal_bar_recyler_view)
verticalValueIndicatorRecylerView = findViewById(R.id.vertical_bar_info_recyler_view)
yAxisValue1 = findViewById(R.id.pertextview1)
yAxisValue2 = findViewById(R.id.pertextview2)
yAxisValue3 = findViewById(R.id.pertextview3)
yAxisValue4 = findViewById(R.id.pertextview4)
yAxisValue5 = findViewById(R.id.pertextview5)
yAxisTextViewArray = arrayOf(yAxisValue5, yAxisValue4, yAxisValue3, yAxisValue2, yAxisValue1)
val linearLayoutManager = LinearLayoutManager(baseContext, LinearLayoutManager.HORIZONTAL, false)
var vertical_bar_recyler_view: RecyclerView = findViewById(R.id.vertical_bar_recyler_view)
vertical_bar_recyler_view.layoutManager = linearLayoutManager
var verticalBarList: ArrayList<VerticalBar>? = arrayListOf()
if (verticalBarArray != null) {
for (i in verticalBarArray?.indices!!) {
var verticalBar = VerticalBar()
verticalBar.percentage = verticalBarArray[i]
verticalBar.isClicable = true
verticalBar.paid = true
verticalBar?.tip = "This is a very useful app to improve your driving speed"
verticalBar?.commentAbs = "This is a very useful app to improve your driving speed"
verticalBar?.commentProgression = "Put this information in progress and keep improving"
verticalBar?.dateString = "8 Jan -14 Nov 2018"
verticalBarList?.add(verticalBar)
}
} else {
}
val verticalBarAdapter = VerticalBarAdapter(this, verticalBarList!!)
verticalBarAdapter.sizeOfClickableNumber = verticalBarList.size
vertical_bar_recyler_view.adapter = verticalBarAdapter
verticalBarAdapter.notifyDataSetChanged()
vertical_bar_recyler_view.smoothScrollToPosition(verticalBarList!!.size)
verticalBarAdapter.onVerticalBarClick = { verticalBar ->
onItemClickEvent(verticalBar)
}
if (verticalBarList?.size!! < 5 && verticalBarList?.size > 0) {
var lastverticalBar: VerticalBar? = VerticalBar()
var xArray: FloatArray = floatArrayOf(0f, (maxXPoint / 2).toFloat(), maxXPoint.toFloat())
for (i in xArray.indices) {
lastverticalBar?.pointsOrange?.add(Point(xArray[i], verticalBarList.last().pointsOrange[2].y))
lastverticalBar?.pointsGreen?.add(Point(xArray[i], verticalBarList.last().pointsGreen[2].y))
lastverticalBar?.pointsYellow?.add(Point(xArray[i], verticalBarList.last().pointsYellow[2].y))
lastverticalBar?.pointsRed?.add(Point(xArray[i], verticalBarList.last().pointsRed[2].y))
// Log.i("extraPoint", "x: " + verticalBarList.last().pointsRed[2].x + " y: " + verticalBarList.last().pointsRed[2].y)
}
for (i in 0..4 - verticalBarList.size) {
lastverticalBar?.isClicable = false
lastverticalBar?.tip = ""
lastverticalBar?.commentAbs = ""
lastverticalBar?.commentProgression = ""
lastverticalBar?.paid = true
verticalBarList?.add(lastverticalBar!!)
}
}
val mValueVerticalList = ArrayList<String>()
val reportValueInterval = 100?.div(5)
var percentage = ""
for (i in 5 downTo 1) {
var interval = DecimalFormat("###.#").format(reportValueInterval?.times(i)!!)
mValueVerticalList.add("$interval$percentage")
yAxisTextViewArray!![i - 1].text = "$interval$percentage"
}
// mValueVerticalList.add("")
textviewYInfo.text = "Speed"
val verticalValueAdapter = VerticalValueAdapter(this, mValueVerticalList)
verticalValueRecyclerView.adapter = verticalValueAdapter
verticalBarAdapter.notifyDataSetChanged()
// // onItemClickEvent(mBarArrayList.get(position), holder);
// if (verticalBarList.size <= 5) {
// verticalValueIndicatorRecylerView.visibility = View.VISIBLE
// verticalValueIndicatorRecylerView.layoutManager =
// LinearLayoutManager( itemView.context, LinearLayoutManager.VERTICAL, false)
// verticalValueIndicatorRecylerView.adapter =
// VerticalValueIndicatorAdapter( itemView.context as Activity)
// } else
// verticalValueIndicatorRecylerView.visibility = View.GONE
}
fun onItemClickEvent(verticalBar: VerticalBar) {
triangleView.setColor(resources.getColor(verticalBar.backGroundColor))
graphTipCardView.strokeColor = resources.getColor(verticalBar.backGroundColor)
suggestionCardView.setCardBackgroundColor(resources.getColor(verticalBar.alphaBackGroundColor))
suggestionCircularMatericalCard.setCardBackgroundColor(
resources.getColor(
verticalBar.backGroundColor
)
)
tipDateRangeTextView.text = verticalBar.dateString
tip2DateRangeTextView.text = verticalBar.dateString
suggestionTextView.setText(verticalBar.tip)
var progression: String =
if (!TextUtils.isEmpty(verticalBar?.commentProgression)) "\n" + verticalBar?.commentProgression else ""
reportInfoTextView.setText(verticalBar.commentAbs + progression)
// tipDateRangeTextView.setText() - Util.convertDpToPixel(64f)
triangleView.animate()
.x(verticalBar.getxPoint() - convertDpToPixel(64f))
.setDuration(200)
.start()
triangleViewShadow.animate()
.x(verticalBar.getxPoint() - convertDpToPixel(64f))
.setDuration(200)
.start()
// overall_summary_card_view.setCardBackgroundColor(resources.getColor(if (verticalBar?.paid!!) R.color.violent else R.color.grey))
unpaidLayout.visibility = if (verticalBar?.paid!!) View.GONE else View.VISIBLE
tipLayout.visibility = if (verticalBar?.paid!!) View.VISIBLE else View.GONE
// activatePlanTV.text = Html.fromHtml("To check your analysis <u><font color='#23b9f8'>Activate your plan</font></u>")
// activatePlanTV.setOnClickListener {
// activatePaidPlan?.invoke()
// }
horizontalRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
private var overallXScroll = 0
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
overallXScroll = overallXScroll.plus(dx)
val changeX = verticalBar.getxPoint() - convertDpToPixel(64f) - overallXScroll
triangleView.animate()
.x(changeX)
.setDuration(0)
.start()
Log.i("scroll_x", "x: " + -recyclerView.computeHorizontalScrollOffset() + " setX: $changeX")
triangleViewShadow.animate()
.x(changeX)
.setDuration(0)
.start()
}
})
}
fun convertDpToPixel(dp: Float): Float {
val metrics = Resources.getSystem().displayMetrics
val px = dp * (metrics.densityDpi / 160f)
return Math.round(px).toFloat()
}
}
| 0 | Kotlin | 0 | 6 | c218a5af78a30be1b6cdc6584a8c299d5072ee28 | 12,850 | HummingbirdGraphLibrary | MIT License |
src/main/kotlin/com/baulsupp/cooee/p/SuggestionType.kt | yschimke | 159,716,451 | false | null | // Code generated by Wire protocol buffer compiler, do not edit.
// Source: com.baulsupp.cooee.p.SuggestionType in api.proto
package com.baulsupp.cooee.p
import com.squareup.wire.EnumAdapter
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.Syntax.PROTO_3
import com.squareup.wire.WireEnum
import kotlin.Int
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic
public enum class SuggestionType(
public override val `value`: Int,
) : WireEnum {
UNKNOWN(0),
/**
* Returns a link to redirect (message is secondary to link)
*/
LINK(1),
/**
* Returns a command that can be executed via a POST, with preview etc
*/
COMMAND(2),
/**
* Returns a command prefix that allows further comment
*/
PREFIX(3),
/**
* Returns subcommands
*/
LIST(4),
/**
* Shows a preview or information (link is secondary to message)
*/
INFORMATION(5),
;
public companion object {
@JvmField
public val ADAPTER: ProtoAdapter<SuggestionType> = object : EnumAdapter<SuggestionType>(
SuggestionType::class,
PROTO_3,
SuggestionType.UNKNOWN
) {
public override fun fromValue(`value`: Int): SuggestionType? = SuggestionType.fromValue(value)
}
@JvmStatic
public fun fromValue(`value`: Int): SuggestionType? = when (value) {
0 -> UNKNOWN
1 -> LINK
2 -> COMMAND
3 -> PREFIX
4 -> LIST
5 -> INFORMATION
else -> null
}
}
}
| 0 | Kotlin | 0 | 1 | 6cd597836e163fa57017490e13f6457706277679 | 1,451 | cooee-cli | Apache License 2.0 |
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/mocks/virksomhet/person/v3/PersonstatusAdapter.kt | navikt | 254,055,233 | false | null | package no.nav.pensjon.vtp.mocks.virksomhet.person.v3
import no.nav.pensjon.vtp.testmodell.kodeverk.Endringstype
import no.nav.pensjon.vtp.testmodell.personopplysning.PersonstatusModell
import no.nav.pensjon.vtp.util.asXMLGregorianCalendar
import no.nav.tjeneste.virksomhet.person.v3.informasjon.PersonstatusPeriode
import no.nav.tjeneste.virksomhet.person.v3.informasjon.Personstatuser
import no.nav.tjeneste.virksomhet.person.v3.metadata.Endringstyper
import java.time.LocalDate
import java.time.LocalDate.of
const val ENDRET_AV = "vtp"
fun Endringstype.asEndringstyper(): Endringstyper = Endringstyper.fromValue(name)
fun Endringstype?.asEndringstyperOrNy() = this?.asEndringstyper() ?: Endringstyper.NY
fun statsborgerskap(allePersonstatus: List<PersonstatusModell>) = allePersonstatus
.map {
PersonstatusPeriode().apply {
endretAv = ENDRET_AV
endringstidspunkt = LocalDate.now().asXMLGregorianCalendar()
endringstype = it.endringstype.asEndringstyperOrNy()
personstatus = Personstatuser().apply {
kodeverksRef = "Personstatuser"
kodeRef = it.kode.name
value = it.kode.name
}
periode = periode(
fom = it.fom ?: of(2000, 1, 1),
tom = it.tom ?: of(2050, 1, 1)
)
}
}
| 14 | Kotlin | 0 | 2 | cd270b5f698c78c1eee978cd24bd788163c06a0c | 1,364 | vtp-pensjon | MIT License |
src/main/kotlin/org/vitrivr/cottontail/math/knn/kernels/binary/plain/SquaredEuclideanKernel.kt | corner4world | 331,901,507 | true | {"Kotlin": 1810171, "Dockerfile": 478} | package org.vitrivr.cottontail.math.knn.kernels.binary.plain
import org.vitrivr.cottontail.database.queries.planning.cost.Cost
import org.vitrivr.cottontail.math.knn.basics.MinkowskiKernel
import org.vitrivr.cottontail.math.knn.kernels.KernelNotFoundException
import org.vitrivr.cottontail.model.values.*
import org.vitrivr.cottontail.model.values.types.VectorValue
import kotlin.math.pow
/**
* A [MinkowskiKernel] implementation to calculate the Squared Euclidean or squared L2 distance between a [query] and a series of [VectorValue]s.
*
* @author <NAME>
* @version 1.0.0
*/
sealed class SquaredEuclideanKernel<T : VectorValue<*>>(final override val query: T) : MinkowskiKernel<T> {
companion object {
/**
* Returns the [SquaredEuclideanKernel] implementation for the given [VectorValue].
*
* @param query [VectorValue] The [VectorValue] to return the [SquaredEuclideanKernel] for.
* @return [SquaredEuclideanKernel]
* @throws KernelNotFoundException If no supported [SquaredEuclideanKernel] could not be found.
*/
fun kernel(query: VectorValue<*>) = when (query) {
is Complex64VectorValue -> SquaredEuclideanKernel.Complex64Vector(query)
is Complex32VectorValue -> SquaredEuclideanKernel.Complex32Vector(query)
is DoubleVectorValue -> SquaredEuclideanKernel.DoubleVector(query)
is FloatVectorValue -> SquaredEuclideanKernel.FloatVector(query)
is IntVectorValue -> SquaredEuclideanKernel.IntVector(query)
is LongVectorValue -> SquaredEuclideanKernel.LongVector(query)
else -> throw KernelNotFoundException(SquaredEuclideanKernel::class.java.simpleName, query)
}
/**
* Calculates the cost of applying a [SquaredEuclideanKernel] of dimension [d] to a vector.
*
* @param d The dimension used for cost calculation.
* @return Estimated cost.
*/
fun cost(d: Int) = d * (3.0f * Cost.COST_FLOP + 2.0f * Cost.COST_MEMORY_ACCESS)
}
/** The [p] value for an [SquaredEuclideanKernel] instance is always 2. */
final override val p: Int = 2
/** The cost of applying this [SquaredEuclideanKernel] to a single [VectorValue]. */
override val cost: Float
get() = cost(this.d)
/**
* [EuclideanKernel] for a [Complex64VectorValue].
*/
class Complex64Vector(query: Complex64VectorValue) : SquaredEuclideanKernel<Complex64VectorValue>(query) {
override fun invoke(vector: Complex64VectorValue): DoubleValue {
var sum = 0.0
for (i in this.query.data.indices) {
sum += (this.query.data[i] - vector.data[i]).pow(2)
}
return DoubleValue(sum)
}
}
/**
* [EuclideanKernel] for a [Complex32VectorValue].
*/
class Complex32Vector(query: Complex32VectorValue) : SquaredEuclideanKernel<Complex32VectorValue>(query) {
override fun invoke(vector: Complex32VectorValue): DoubleValue {
var sum = 0.0
for (i in this.query.data.indices) {
sum += (this.query.data[i] - vector.data[i]).pow(2)
}
return DoubleValue(sum)
}
}
/**
* [SquaredEuclideanKernel] for a [DoubleVectorValue].
*/
class DoubleVector(query: DoubleVectorValue) : SquaredEuclideanKernel<DoubleVectorValue>(query) {
override fun invoke(vector: DoubleVectorValue): DoubleValue {
var sum = 0.0
for (i in this.query.data.indices) {
sum += (this.query.data[i] - vector.data[i]).pow(2)
}
return DoubleValue(sum)
}
}
/**
* [EuclideanKernel] for a [FloatVectorValue].
*/
class FloatVector(query: FloatVectorValue) : SquaredEuclideanKernel<FloatVectorValue>(query) {
override fun invoke(vector: FloatVectorValue): DoubleValue {
var sum = 0.0
for (i in this.query.data.indices) {
sum += (this.query.data[i] - vector.data[i]).pow(2)
}
return DoubleValue(sum)
}
}
/**
* [EuclideanKernel] for a [LongVectorValue].
*/
class LongVector(query: LongVectorValue) : SquaredEuclideanKernel<LongVectorValue>(query) {
override fun invoke(vector: LongVectorValue): DoubleValue {
var sum = 0.0
for (i in this.query.data.indices) {
sum += (this.query.data[i] - vector.data[i]).toDouble().pow(2)
}
return DoubleValue(sum)
}
}
/**
* [EuclideanKernel] for a [IntVectorValue].
*/
class IntVector(query: IntVectorValue) : SquaredEuclideanKernel<IntVectorValue>(query) {
override fun invoke(vector: IntVectorValue): DoubleValue {
var sum = 0.0
for (i in this.query.data.indices) {
sum += (this.query.data[i] - vector.data[i]).toDouble().pow(2)
}
return DoubleValue(sum)
}
}
} | 0 | Kotlin | 0 | 0 | 7303b1b7ee5486a69cb88752127088956ebde6ba | 5,055 | cottontaildb | MIT License |
core/src/main/java/com/ustadmobile/httpoveripc/core/ext/RawHttpRequestExt.kt | UstadMobile | 609,104,373 | false | null | package com.ustadmobile.httpoveripc.core
import com.ustadmobile.httpoveripc.core.ext.toSimpleMap
import io.ktor.http.*
import rawhttp.core.RawHttpRequest
fun RawHttpRequest.asSimpleTextRequest(): SimpleTextRequest {
return SimpleTextRequest(
method = SimpleTextRequest.Method.valueOf(method.uppercase()),
url = Url(uri),
headers = headers.toSimpleMap(),
)
}
| 0 | Kotlin | 0 | 0 | ef190faf3de68fc4551f21df1bd3d021c1cfd992 | 392 | httpoveripc | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.