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
kotlin-remix-run-router/src/jsMain/generated/remix/run/router/warning.kt
JetBrains
93,250,841
false
{"Kotlin": 11400167, "JavaScript": 146545}
@file:JsModule("@remix-run/router") package remix.run.router external fun warning(cond: Any?, message: String): Unit
28
Kotlin
173
1,250
d1f8f5d805ffa18431dfefb7a1aa2f67f48915f6
120
kotlin-wrappers
Apache License 2.0
site/src/jsMain/kotlin/dev/bitspittle/droidconSf24/utilities/DomUtilities.kt
bitspittle
791,114,618
false
{"Kotlin": 73574, "CSS": 1373}
package dev.bitspittle.droidconSf24.utilities import org.w3c.dom.* fun HTMLCollection.walk(onEach: (Element) -> Unit) { (0 until length) .mapNotNull { i: Int -> this[i] } .forEach { child -> onEach(child) child.children.walk(onEach) } } fun NodeList.walk(onEach: (Node) -> Unit) { (0 until length) .mapNotNull { i: Int -> this[i] } .forEach { node -> onEach(node) node.childNodes.walk(onEach) } } val HTMLElement.ancestors: Sequence<HTMLElement> get() { var curr: HTMLElement? = this return sequence { while (curr != null) { yield(curr!!) curr = curr!!.parentElement as? HTMLElement } } }
0
Kotlin
0
2
1a22a985d6f9d0fd9c63da814bcf0c26f3d69908
785
droidcon-sf-24
MIT License
shared/src/commonMain/kotlin/br/com/devsrsouza/mcheads/common/Const.kt
DevSrSouza
207,658,750
false
null
package br.com.devsrsouza.mcheads.common const val API_URL = "http://mcheads.devsrsouza.com.br" const val MOJANG_TEXTURE_API = "http://textures.minecraft.net/texture/"
0
Kotlin
0
5
48947b6e6951f4900127665ff7cd7e94d9241ba4
169
MCHeads
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/DocumentPaid.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.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 me.localx.icons.straight.Icons public val Icons.Filled.DocumentPaid: ImageVector get() { if (_documentPaid != null) { return _documentPaid!! } _documentPaid = Builder(name = "DocumentPaid", 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(5.1f, 13.6f) curveToRelative(0.496f, 0.0f, 0.9f, 0.404f, 0.9f, 0.9f) reflectiveCurveToRelative(-0.404f, 0.9f, -0.9f, 0.9f) horizontalLineToRelative(-0.5f) verticalLineToRelative(-1.8f) horizontalLineToRelative(0.5f) moveToRelative(5.136f, 0.106f) lineToRelative(0.638f, 3.295f) horizontalLineToRelative(-1.262f) lineToRelative(0.624f, -3.295f) moveTo(17.0f, 0.586f) verticalLineToRelative(4.414f) horizontalLineToRelative(4.414f) lineTo(17.0f, 0.586f) close() moveTo(15.0f, 7.0f) lineTo(15.0f, 0.0f) lineTo(5.0f, 0.0f) curveToRelative(-1.657f, 0.0f, -3.0f, 1.343f, -3.0f, 3.0f) verticalLineToRelative(21.0f) horizontalLineToRelative(20.0f) lineTo(22.0f, 7.0f) horizontalLineToRelative(-7.0f) close() moveTo(16.4f, 12.0f) horizontalLineToRelative(2.3f) curveToRelative(1.269f, 0.0f, 2.3f, 1.031f, 2.3f, 2.3f) verticalLineToRelative(3.4f) curveToRelative(0.0f, 1.269f, -1.031f, 2.3f, -2.3f, 2.3f) horizontalLineToRelative(-2.3f) verticalLineToRelative(-8.0f) close() moveTo(13.8f, 12.0f) horizontalLineToRelative(1.6f) verticalLineToRelative(8.0f) horizontalLineToRelative(-1.6f) verticalLineToRelative(-8.0f) close() moveTo(10.256f, 12.0f) curveToRelative(0.757f, 0.0f, 1.226f, 0.524f, 1.346f, 1.192f) lineToRelative(1.397f, 6.807f) horizontalLineToRelative(-1.488f) lineToRelative(-0.262f, -1.474f) horizontalLineToRelative(-2.006f) lineToRelative(-0.275f, 1.474f) horizontalLineToRelative(-1.469f) lineToRelative(1.372f, -6.833f) curveToRelative(0.103f, -0.58f, 0.628f, -1.167f, 1.385f, -1.167f) close() moveTo(4.599f, 16.999f) verticalLineToRelative(3.0f) horizontalLineToRelative(-1.6f) verticalLineToRelative(-8.0f) horizontalLineToRelative(2.1f) curveToRelative(1.381f, 0.0f, 2.5f, 1.119f, 2.5f, 2.5f) reflectiveCurveToRelative(-1.119f, 2.5f, -2.5f, 2.5f) horizontalLineToRelative(-0.5f) close() moveTo(19.4f, 17.699f) curveToRelative(0.0f, 0.386f, -0.314f, 0.7f, -0.7f, 0.7f) reflectiveCurveToRelative(-0.7f, 0.0f, -0.7f, 0.0f) verticalLineToRelative(-4.802f) reflectiveCurveToRelative(0.314f, 0.0f, 0.7f, 0.0f) reflectiveCurveToRelative(0.7f, 0.314f, 0.7f, 0.7f) verticalLineToRelative(3.4f) close() } } .build() return _documentPaid!! } private var _documentPaid: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,414
icons
MIT License
src/com/zypus/SLIP/views/StateRendering.kt
zypus
213,665,750
false
null
package com.zypus.SLIP.views import com.zypus.SLIP.models.SimulationState import com.zypus.SLIP.models.terrain.Terrain import com.zypus.utilities.percent import javafx.scene.canvas.GraphicsContext import javafx.scene.paint.Color import javafx.scene.text.Text /** * TODO Add description * * @author fabian <<EMAIL>> * * @created 23/04/16 */ /** * Draws the state (spring and terrain). Also renders a distance representation [drawMarkers] * * @param state The current simulation state. */ fun GraphicsContext.drawSimulationState(state: SimulationState, markers: Boolean = true, tracking: Boolean = true, linesize: Double = 1.0) { // Clear the context. clearRect(0.0, 0.0, canvas.width, canvas.height) // Extract the state information. val (position, velocity, angle, restLength, length, springConstant, mass, radius, standPosition) = state.slip val (x, y) = position.elements val (gravity, terrain) = state.environment // Shift the viewport to be centered on the slip. save() scale(1.0, -1.0) val offset = if (tracking) x else 0.0 translate(canvas.width / 2 - offset, -canvas.height) // Set line attributes. lineWidth = linesize stroke = Color.BLACK // Draw the terrain. val start = offset - canvas.width / 2 val end = offset + canvas.width / 2 drawTerrain(start, end, 3000, terrain) // Draw slip. // Draw the mass. strokeOval(x - radius, y - radius, 2 * radius, 2 * radius) // Draw spring. drawSpring(x - Math.sin(angle) * radius, y - Math.cos(angle) * radius, angle, length, restLength, 6, 10.percent) // Restore the original state. restore() // Draw markers. if (markers) drawMarkers(start, end, canvas.width / 2 - offset, 50, 10, 6.0, 3.0) // Draw Info. drawStateInfo(state) } /** * Uses the provided spring information and render hints to render a semi realistic 2d spring. * * @param xs Starting x coordinate of the spring. * @param ys Starting y coordinate of the spring. * @param angle Angle of the spring. * @param ls Current length of the spring. * @param Ls Length of the spring in rest position. * * @param segs Number of spring segments to be rendered. * @param fixedPercentage Percentage of the spring at start and end of the spring which will be stiff. */ fun GraphicsContext.drawSpring(xs: Double, ys: Double, angle: Double, ls: Double, Ls: Double, segs: Int, fixedPercentage: Double) { var l = ls // Cap spring length. if (ls > Ls) { l = Ls } beginPath() // Draw the anchor. moveTo(xs, ys) lineTo(xs - Math.sin(angle) * Ls * fixedPercentage, ys - Math.cos(angle) * Ls * fixedPercentage) // Spring range. val Rs = Ls * (1 - 2 * fixedPercentage) val rs = l - Ls * 2 * fixedPercentage // Compute compression. val comp = rs / Rs // Compute the delta. val dSeg = rs / segs // Draw the spring segements. for (i in 0..segs - 1) { val dir = if (i % 2 == 0) 1 else -1 val dy = dir * 0.5 * (dSeg / comp) //val dy = dir * 0.5 * sqrt(pow(Rs/segs,2)+pow(0.5*rs/segs,2)); val nx = xs - Math.sin(angle) * (Ls * fixedPercentage + (0.5 + i) * dSeg) + Math.cos(angle) * dy val ny = ys - Math.cos(angle) * (Ls * fixedPercentage + (0.5 + i) * dSeg) - Math.sin(angle) * dy lineTo(nx, ny); } lineTo(xs - Math.sin(angle) * (Ls * fixedPercentage + rs), ys - Math.cos(angle) * (Ls * fixedPercentage + rs)) // Draw the tip. lineTo(xs - Math.sin(angle) * l, ys - Math.cos(angle) * l) // Stroke path. stroke() } /** * Uses the terrain x -> y mapping and renders a sequence of lines. * * @param start Left most visible x coordinate. * @param end Right most visible y coordinate. * @param steps Resolution of the terrain. * @param terrain Function which maps x to y coordinates, which are interpreted as terrain. */ fun GraphicsContext.drawTerrain(start: Double, end: Double, steps: Int, terrain: Terrain) { // Compute the size of each step. val stepSize = (end - start) / steps beginPath() moveTo(start, terrain(start)) // Fill in all line segments. for (i in 0..steps) { val x = start + stepSize * i lineTo(x, terrain(x)) } // Draw the terrain. stroke() } /** * Draws a vertical bar, with major and minor ticks, where the major ticks are labeled to represent the distance from the origin. * Function must called in untransformed state, because inversion of the y axis makes it kinda difficult to draw text *not* upside down. * * @param start Left most visible x coordinate. * @param end Right most visible y coordinate. * @param offset X offset to position markers in view. * @param major Distance between major ticks. * @param minor Distance between minor ticks. * @param majorHeight Height of the major ticks. * @param minorHeight Height of the minor ticks. */ fun GraphicsContext.drawMarkers(start: Double, end: Double, offset: Double, major: Int, minor: Int, majorHeight: Double = 6.0, minorHeight: Double = 3.0) { var majors = start - start % major - major var minors = start - start % minor // Draw minors while (minors < end) { strokeLine(minors + offset, canvas.height - font.size, minors + offset, canvas.height - minorHeight - font.size) minors += minor } // Draw majors. while (majors < end + major) { strokeLine(majors + offset, canvas.height - font.size, majors + offset, canvas.height - majorHeight - font.size) val s = "${majors.toInt()}" // Using the text element to get the actual string length once rendered val textWidth = Text(s).layoutBounds.width fillText(s, majors + offset - textWidth / 2, canvas.height - 2.0) majors += major } } fun GraphicsContext.drawStateInfo(state: SimulationState) { // val slip = state.slip // // E_pot = m * g * h // val potentialEnergy = slip.mass * -state.environment.gravity.y * (slip.position.y - slip.radius - state.environment.terrain(slip.position.y)) // // E_kin = 0.5 * m * v^2 // val kineticEnergy = 0.5 * slip.mass * slip.velocity.norm2 // // E_ela = 0.5 * k * dl^2 // val elasticEnergy = 0.5 * slip.springConstant * Math.pow(slip.restLength - slip.length, 2.0) // val totalEnergy = potentialEnergy + kineticEnergy + elasticEnergy // var i = 0 // fillText("Potential Energy: ${(potentialEnergy * 100).toInt() / 100.0}", 10.0, 20.0 * ++i) // fillText("Kinetic Energy : ${(kineticEnergy * 100).toInt() / 100.0}", 10.0, 20.0 * ++i) // fillText("Elastic Energy : ${(elasticEnergy * 100).toInt() / 100.0}", 10.0, 20.0 * ++i) // fillText("------------------------", 10.0, 20.0 * ++i) // fillText("Total Energy : ${(totalEnergy * 100).toInt() / 100.0}", 10.0, 20.0 * ++i) }
0
Kotlin
0
0
418ee8837752143194fd769e86fac85e15136929
6,508
SLIP
MIT License
change/bin/changeCalculator.kt
rhdeck
149,451,550
false
{"HTML": 520884, "Kotlin": 473204, "JavaScript": 320372, "CSS": 230580}
// INCOMPLETE - this is only the greedy method ,ao dILA NONCANONICAL TESTS data class ChangeCalculator(val coins:List<Int>) { fun computeMostEfficientChange(value: Int) : List<Int> { if(value < 0) throw IllegalArgumentException("Negative totals are not allowed.") var newval = value val out = coins.sorted().asReversed().fold(mutableListOf<Int>()) { l, c -> val count = newval / c print("For ${newval} Adding ${count} couns of value ${c}\n") if(count > 0) for (i in 1..count) l.add(c) newval = newval % c l }.asReversed() if(newval > 0) throw IllegalArgumentException("The total ${value} cannot be represented in the given currency.") return out } }
0
HTML
0
0
d73f466f1417efe418fb597dd5b0a9cb94c37661
768
exercism-kotlin
MIT License
ariesframework/src/androidTest/java/org/hyperledger/ariesframework/oob/OutOfBandInvitationTest.kt
hyperledger
685,515,500
false
{"Kotlin": 545679, "Java": 6968}
package org.hyperledger.ariesframework.oob import kotlinx.serialization.json.Json import org.hyperledger.ariesframework.agent.MessageSerializer import org.hyperledger.ariesframework.connection.messages.TrustPingMessage import org.hyperledger.ariesframework.oob.messages.OutOfBandInvitation import org.hyperledger.ariesframework.oob.models.HandshakeProtocol import org.hyperledger.ariesframework.oob.models.OutOfBandDidDocumentService import org.hyperledger.ariesframework.oob.models.PublicDidService import org.hyperledger.ariesframework.util.DIDParser import org.junit.Assert.assertEquals import org.junit.Test class OutOfBandInvitationTest { @Test fun testToUrl() { val domain = "https://example.com/ssi" val json = """ { "@type": "https://didcomm.org/out-of-band/1.1/invitation", "services": ["did:sov:LjgpST2rjsoxYegQDRm7EL"], "@id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "label": "Faber College", "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "handshake_protocols": ["https://didcomm.org/didexchange/1.0", "https://didcomm.org/connections/1.0"] } """.trimIndent() val invitation = Json.decodeFromString<OutOfBandInvitation>(json) val invitationUrl = invitation.toUrl(domain) val decodedInvitation = OutOfBandInvitation.fromUrl(invitationUrl) assertEquals(invitation.id, decodedInvitation.id) assertEquals(invitation.type, decodedInvitation.type) assertEquals(invitation.label, decodedInvitation.label) assertEquals(invitation.goalCode, decodedInvitation.goalCode) assertEquals(invitation.goal, decodedInvitation.goal) assertEquals(invitation.handshakeProtocols, decodedInvitation.handshakeProtocols) } @Test fun testFromUrl() { val invitationUrl = "http://example.com/ssi?oob=eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiI2OTIxMmEzYS1kMDY4LTRmOWQtYTJkZC00NzQxYmNhODlhZjMiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIEZhYmVyIENvbGxlZ2UgR3JhZHVhdGUgY3JlZGVudGlhbCIsImhhbmRzaGFrZV9wcm90b2NvbHMiOlsiaHR0cHM6Ly9kaWRjb21tLm9yZy9kaWRleGNoYW5nZS8xLjAiLCJodHRwczovL2RpZGNvbW0ub3JnL2Nvbm5lY3Rpb25zLzEuMCJdLCJzZXJ2aWNlcyI6WyJkaWQ6c292OkxqZ3BTVDJyanNveFllZ1FEUm03RUwiXX0K" // ktlint-disable max-line-length val invitation = OutOfBandInvitation.fromUrl(invitationUrl) assertEquals(invitation.id, "69212a3a-d068-4f9d-a2dd-4741bca89af3") assertEquals(invitation.type, "https://didcomm.org/out-of-band/1.1/invitation") assertEquals(invitation.label, "Faber College") assertEquals(invitation.goalCode, "issue-vc") assertEquals(invitation.goal, "To issue a Faber College Graduate credential") assertEquals( invitation.handshakeProtocols, listOf(HandshakeProtocol.DidExchange10, HandshakeProtocol.Connections), ) if (invitation.services[0] is PublicDidService) { assertEquals((invitation.services[0] as PublicDidService).did, "did:sov:LjgpST2rjsoxYegQDRm7EL") } else { throw Exception("Expected did service") } } @Test fun testFromJson() { val json = """ { "@type": "https://didcomm.org/out-of-band/1.1/invitation", "@id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "label": "Faber College", "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "handshake_protocols": ["https://didcomm.org/didexchange/1.0", "https://didcomm.org/connections/1.0"], "services": ["did:sov:LjgpST2rjsoxYegQDRm7EL"] } """ val invitation = Json.decodeFromString<OutOfBandInvitation>(json) assertEquals(invitation.label, "Faber College") } @Test fun testLegacyProtocolType() { val json = """ { "@type": "https://didcomm.org/out-of-band/1.1/invitation", "@id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "label": "Faber College", "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "handshake_protocols": ["did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/didexchange/1.0", "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0"], "services": ["did:sov:LjgpST2rjsoxYegQDRm7EL"] } """ val invitation = OutOfBandInvitation.fromJson(json) assertEquals(invitation.label, "Faber College") } @Test fun testInvitationWithService() { val json = """ { "@type": "https://didcomm.org/out-of-band/1.1/invitation", "@id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "label": "Faber College", "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "handshake_protocols": ["https://didcomm.org/didexchange/1.0", "https://didcomm.org/connections/1.0"], "services": [ { "id": "#inline", "type": "did-communication", "recipientKeys": ["did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th"], "routingKeys": ["did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th"], "serviceEndpoint": "https://example.com/ssi" } ] } """ val invitation = Json.decodeFromString<OutOfBandInvitation>(json) if (invitation.services[0] is OutOfBandDidDocumentService) { val didDocument = invitation.services[0] as OutOfBandDidDocumentService assertEquals(didDocument.id, "#inline") assertEquals(didDocument.recipientKeys[0], "did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th") assertEquals(didDocument.routingKeys?.get(0), "did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th") assertEquals(didDocument.serviceEndpoint, "https://example.com/ssi") } else { throw Exception("Expected OutOfBandDidDocumentService service") } } @Test fun testFingerprints() { val json = """ { "@type": "https://didcomm.org/out-of-band/1.1/invitation", "@id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "label": "Faber College", "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "handshake_protocols": ["https://didcomm.org/didexchange/1.0", "https://didcomm.org/connections/1.0"], "services": [ { "id": "#inline", "type": "did-communication", "recipientKeys": ["did:key:z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th"], "serviceEndpoint": "https://example.com/ssi" }, "did:sov:LjgpST2rjsoxYegQDRm7EL", { "id": "#inline", "type": "did-communication", "recipientKeys": ["did:key:123", "did:key:456"], "serviceEndpoint": "https://example.com/ssi" } ] } """ val invitation = Json.decodeFromString<OutOfBandInvitation>(json) assertEquals(invitation.fingerprints(), listOf("z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th", "123", "456")) assertEquals(invitation.invitationKey(), DIDParser.convertFingerprintToVerkey("z6MkmjY8GnV5i9YTDtPETC2uUAW6ejw3nk5mXF5yci5ab7th")) } @Test fun testRequests() { val invitation = OutOfBandInvitation("test invitation", services = listOf(PublicDidService("did:sov:LjgpST2rjsoxYegQDRm7EL"))) val trustPing = TrustPingMessage("test") MessageSerializer.registerMessage(TrustPingMessage.type, TrustPingMessage::class) invitation.addRequest(trustPing) val requests = invitation.getRequestsJson() assertEquals(requests.size, 1) val request = Json.decodeFromString<TrustPingMessage>(requests[0]) assertEquals(request.comment, "test") } @Test fun testParseLargeInvitation() { val url = "http://example.com?oob=eyJAdHlwZSI6Imh0dHBzOi8vZGlkY29tbS5vcmcvb3V0LW9mLWJhbmQvMS4xL2ludml0YXRpb24iLCJAaWQiOiJlODM1NzRjYy1kY2ExLTQwZmEtYWZmMS1kYzg0MDQzOWYzN2IiLCJsYWJlbCI6IkZhYmVyIENvbGxlZ2UiLCJnb2FsX2NvZGUiOiJpc3N1ZS12YyIsImdvYWwiOiJUbyBpc3N1ZSBhIGNyZWRlbnRpYWwiLCJhY2NlcHQiOlsiZGlkY29tbS9haXAxIiwiZGlkY29tbS9haXAyO2Vudj1yZmMxOSJdLCJoYW5kc2hha2VfcHJvdG9jb2xzIjpbImh0dHBzOi8vZGlkY29tbS5vcmcvZGlkZXhjaGFuZ2UvMS4wIiwiaHR0cHM6Ly9kaWRjb21tLm9yZy9jb25uZWN0aW9ucy8xLjAiXSwic2VydmljZXMiOlt7ImlkIjoiI2lubGluZS0wIiwic2VydmljZUVuZHBvaW50IjoiaHR0cDovL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Uk5hbFY0VDFSbk0wMVVSVFZOYW10M1QwUkJlazFxVFROT2Fra3lUVVJOTTAxRVl6Rk9SR00xVGxSak1VbHNNV1JtVTNkcFltMDVkVmt5VldsUGFVa3dUMFJCZWs5VVJYZFBSRmt4VDBSWmVFMXFVVEZOUkVFd1QxUkplRTVxWjJsbVVUMDlJbjE5WFgwPSJ9fV19" // ktlint-disable max-line-length val invitation = OutOfBandInvitation.fromUrl(url) assertEquals(invitation.goalCode, "issue-vc") assertEquals(invitation.requests?.size, 1) } @Test fun testJsonEmbeddingInvitation() { val url = "http://127.0.0.1:8000?oob=eyJAdHlwZSI6ICJodHRwczovL2RpZGNvbW0ub3JnL291dC1vZi1iYW5kLzEuMC9pbnZpdGF0aW9uIiwgIkBpZCI6ICI2Y2E1ZDQ1NC1lNzdiLTQzMmItOThiOC01NDA4ZGFkZWJlMDIiLCAicmVxdWVzdHN-YXR0YWNoIjogW3siQGlkIjogInJlcXVlc3QtMCIsICJtaW1lLXR5cGUiOiAiYXBwbGljYXRpb24vanNvbiIsICJkYXRhIjogeyJqc29uIjogeyJAdHlwZSI6ICJodHRwczovL2RpZGNvbW0ub3JnL2lzc3VlLWNyZWRlbnRpYWwvMS4wL29mZmVyLWNyZWRlbnRpYWwiLCAiQGlkIjogImZiYzVhNjNlLTE2ODktNDYxNi05NGNmLThkZTE4ZmZkMjQ5NSIsICJ-dGhyZWFkIjogeyJwdGhpZCI6ICI2Y2E1ZDQ1NC1lNzdiLTQzMmItOThiOC01NDA4ZGFkZWJlMDIifSwgImNyZWRlbnRpYWxfcHJldmlldyI6IHsiQHR5cGUiOiAiaHR0cHM6Ly9kaWRjb21tLm9yZy9pc3N1ZS1jcmVkZW50aWFsLzEuMC9jcmVkZW50aWFsLXByZXZpZXciLCAiYXR0cmlidXRlcyI6IFt7Im5hbWUiOiAibmFtZSIsICJtaW1lLXR5cGUiOiAidGV4dC9wbGFpbiIsICJ2YWx1ZSI6ICJBbGljZSBTbWl0aCJ9LCB7Im5h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jeE5qVTRNREUwTlRNM09UY3hNams0TWprME9EVTBPRGN5TlRRNE5EazBNVFExTXpnd056WTNOakV5TmpNNU16YzNNalkzTnpZd01EVTVNamcwTURVMk1qWTVOVEk0TlRNeE9UVTROekkxTkRVME56a3lOall3TlRjMk9UazBPRGsyT1RRM01ERXhOakUwTVRjeE5qVXhOVEF3TVRrNU5qWXpPRFl4T1RReU1ESTFNamd5TVRVME1EQTRNamczT0RjNU9USXlNVFF4TXpjeU56YzVOekEyT1RnM09EQTVPRGd6T0RZek1EWXhPREk0TVRFd016WTFOREV4TURBNE5EVXdOalEwT0RBM05UYzFNamcyTlRrek1EQXpORE13TVRneE16Y3pNRFUxTURJNU1UTXhOVGMzT0RJME1URTVOREV6TVRrME9UUTJOell5TlRRM01qY3pOVEk0TlRjeU9UWXhOelV4TkRRME5UTTBPRGsyTlRnMU5ESXlNVE16TmpNME1URXpPRGt5TVRZM01qVTJOelk0TlRJMU1EQTVPVFExT0RFM09EQTBOall3TWpZeU1UQTVNalE0T0RJMU1qZzROemcwTkRRME1EZ3dOakk0TlRBNE1ERTBNamt5TnprM01qY3hNakV6TWpZNE9ETTBOekF4T1RrNU1qUTNNREEyTmpNeE5UZzJNakUyT1Rnd09URTBNekV5T0RrM05UY3pNRGd4TkRFME1qSTRNamM1TWpZNE5qQTBPVGs0T1RZd01qUTFPRGt3TURNek1UTTBOemd6TkRrNU9URXlOelV3TkRZeE5EVTBNREl5T1RNeE9ETTRORGcxTURJME5UVXlPRGN6TWpNNU5EWTROamc1TkRZME16QTJPVFUzT1RFNE16WTNPREV4TkRrd05qTXhPRE15TkRJM05ERTVNemcyTnpVek9ERXlNekkyTmpNNE5UVTRPRGd6TVRFeU9ERTVOamcyT1RrMk56WTRPVFl4TlRnek56Z3lOREUwTnpRMk1UY3hPVGswTXpJNU1UUTBOemd6TXpNeE5qTTBOVE00TURNM09ERTVOakV5TnpBMk5USTFPVEkwTlNJc0lDSjRjbDlqWVhBaU9pQmJXeUowYVcxbGMzUmhiWEFpTENBaU9UazRNamN6TkRRME5qTXpOakk1TmpnMU5UZzROamszT1RrME1UTXlOREl3TkRrNU9EQXdNRGd4TXpVeU9USTFOVGcyT0RVME5qY3hOalk0TnpVeU16STRNRFl3TmpVMk56RTNNVEV6TWpNd05EUXlNelV6TlRRNU16SXhNalkzTkRZNE1ETTJORGcxTXpNME5UVTVNamt6TVRrMU1UazNORGsyT1RJMU9ESTRPVE13TmpreE5UQTFOekl6TmpVNE1qWXlNekExTURneU9Ea3hNREl6TmpReE56YzNNakUyTVRFeU16RTROell5TkRrME9UUTRPVEkyTWpZeE5Ea3lORE14TVRjM05EQTFNemsyTXpNNU5ESXlPREl3TlRFMU16ZzROakF4TkRrNE5UUTVOelk0TWpRNE9EVTRNVEkxTmpZMk1EUTNOek14TnpFd05URTJPVFk1TURReE5ERTBNVGc0T1RZd05qWXdOVGs0TVRrMU1qY3lNakUwTXprNU56STRNVEEyT0RZM056Z3pNekV4TkRneU1qazNPRGcyTURrME56YzVOekkyTVRnM01UZ3dNems1TURrNE5EUTFNRE0zT0RreE1EQXhPVFV6TXpnME5UZ3hNemMyTnpBMU5qYzBNams0TkRreU1USTFNamd6TlRVME1UVTJOVFl3TmpNNE9UWTBOalUyT0RjME1UYzJNVEUzT1RrME9EQXdNemMxTURnMU5UQTJPVGswTkRZMk9ERTROalF4TkRNeE1UVTNORGt6T1RVeE5EZ3hOVFUyTlRFNU5qZzBNREU1T0RZNU1EWXdOelUyTWpNNU5qTTFNVEF4TURNek1qZ3dNekU0TkRRNE1URXlPREl3TVRrMU9EZzVOelk0TURVNU9UZzVORGcwTVRVM05EQTJPVFk0TkRFMU1ERTBOVE00TWpneU1URTFOVGd5TlRBeU9UVTFPRE16TXpjeE9USXhOemc0TkRFM09USTFNalV6T0RRME9EQXdNemM1TkRVME16YzBNak16TWprd016STBNRGd3T1RZME1qQTFNRGc0TlRVNE1UVTVOREEyTVRjeE9ERXhOVE0zTkRJME1qVTFOemcwTWprM09EYzNOVGMwTlRNeU9UTXpNakE0TnpZNU1UUTVNVFUwTURBd056TTNORE0xTmpZM01EY3dPVFV4TVRjek5UWTNOVGd3TWpZMk1qSTNPRFV6TmpZaVhTd2dXeUprWldkeVpXVWlMQ0FpTWpNM09UTTFNVFF3TWpZNE5UTTJNVFF3TmpRM01UYzROVFE1T0RVNU1qVTFORFF6TlRFd016azBPVEV3TWpBeU9UZzNNakl4TkRNM056a3lOakkxTVRrek9EazJORFF5TWpZNE9ERXpNek15TlRjeU16QTJOalF5TnpNNU56QTVOelV5TVRFeE56YzVOVEV3TXprMU5UYzBOVEE1TXpZMk5UVXdOVFkwTURRd01EazFNRFEyT0RRNU16QTFNVFEwTWpNek1qazBOemt5T1Rnd01EUXdPRGcwT0RNek5qRTRPVEV4TWpZME5EQTVNRFl4TXpBeU1qTXhNVE00TWpVd01UWTNOamsyT0RRM01EVXpOVEV6TURVM09URXhOamN6TURnNU16RXlNVFl4TkRRMk5ETTFNRGt5T1RVeE56STFPVGMxT1RrMU5ETXpOemcwTURZMU9EWXhOekl4TkRZM01USTNOVGcxTURFeU9UWXdOVFl3T1RNM01UQTRNak0wTVRBM016Z3pNVFUzTkRFNE5qRTJNRFV4TmprME1qazFNalV5TmpnNU1UVXhOalF4TlRVME5EUXhNREF4TkRNeE56RTJNVEF5TVRFeE9UazFNelUxTkRRM05EVXpOalF6TURBME9EWTJOVE16TVRVeE5USTNPVFEyTWpjMU5UZ3pNVGszTXprNE9EYzFNekl5T0RneE5EUXdOVFU1TWpneE9EY3pOakk1T0RVek1UYzNNek0yTVRneU1ERTVNRFEwTnpZNE5EWXlORGswT0RBMU16STBOell3TnpJek9UY3pOems0TXpReE1UTTFNamM0T0RnNE1UTTRNakE0TXpVd05qQXpNakEzTURFek1EVXhOemMwTmpneE9UZ3dNakUyTURVM056TTJNVFE0TWpRMk1USTROakU0TWpRMk16UXpOemMxTXpjeU1qTTVORGt4T0RnMU5qWTNOalF3T1RBMU1USTNOVFE0T1RVME5qZzBNalU1T1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OVFl5TWpJeU1UQTNOamN6TXpJMk5qVTJNREU1TWpNM05UQTBPVFE1TURZMk1UQXdNalk1TVRRek9USTBPVGd6TURNMU1ERTFOemMxTnpNNE9UWTNOelkyT0Rrd056QXdNVFEwTnpVek5UTXlORGcyTURNM056Z3pOekExT1RJME1ESXlNRFk1TlRJNE9UTTBOVEF4TnpVMk9Ea3hOamN5TXpNek56UXlNakEyTWpjME9ETTVOelU1TXpnMk16QXpNamcyTmprM01qVTVNVEl4TkRJNU5qazVNekE0TURjNU9EYzVPRFl4TmpFME16YzVOakkyTURFek16RTNORE0xTVRBd01EQTNORE16TlRBeE9EWXpOakUyTlRnM05qYzBNVE14TWpJMU16QTFNamN3TURVMU5UazFNamMyT0RreU1UWXpNemMzT0RZM09EazBNRFF5TURFM016QTVNRE14T1Rnd09EQTVNREl5T0RRek5EUTJPVGszTkRFeE16VXhORGcxTkRNeU16azBNVEEwTXpNNE1USXpNelUyT0RVNU16STBNakkwT1RZek1ESTFNemM0TlRRMU9ESXlPVGd3TURjeU5EWTFPRFUxT1Rjd09UYzVNVFkyT1Rnd01UWTVNalUyTkRFMU1UQTNNRFV6TXlKZExDQmJJbTFoYzNSbGNsOXpaV055WlhRaUxDQWlNVFU0TmprNU9UUXhNRE15T1RVek1UWTBPRGN3TnpjMk56WXdNVFl5TlRZeE9EVTVOemMwT1RNMk5USTVOVFl5TmpreE5qTXpORFUzTWpjNU5qTXhNak0xTkRBMk5qZzFPVFkxTkRJeE1ETTFOakUzTWpreU1qTXhOalExTkRVM05USXpNemcwTXpZNE1USXlPVFF5TURZeE9ESTFNVFl4TmpFMk9UVTROVEExTnpNNE1USTBPVGc0TlRFd09EQTJOemc0T0RRMk5UTXlNREF5TURJeE56STROREU1TXpJM09Ea3hOamcxTVRjeU1UazBPRFF6TlRRNE5ESXpOVE0xTWpZMk1EazNNRGN5TXpJNU56RXdOak01T1RFeU56QTBNalV6TmpBeU9EWXhNelkwTnpnd016WXpOVFEyTkRFeU1URXlPRGs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5pY2F0aW9uIiwgInJlY2lwaWVudEtleXMiOiBbImRpZDprZXk6ejZNa2Z6aUFpWW9SWkUzV3d3TEI2aVBObVY0ZkhjNmJvUXJnc01ZVXFERGl6aGIzIl0sICJzZXJ2aWNlRW5kcG9pbnQiOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIn1dfQ==" // ktlint-disable max-line-length val invitation = OutOfBandInvitation.fromUrl(url) assertEquals(invitation.requests?.size, 1) } }
0
Kotlin
6
7
ebf6bc3dff6320189a51e636e4f3e3b3075efeeb
29,024
aries-framework-kotlin
Apache License 2.0
app/src/main/java/com/sama/users/infrastructure/jpa/UserJpaRepository.kt
sama-app
363,692,054
false
null
package com.sama.users.infrastructure.jpa import com.sama.common.NotFoundException import java.util.UUID import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Modifying import org.springframework.data.jpa.repository.Query import org.springframework.stereotype.Repository @Repository interface UserJpaRepository : JpaRepository<UserEntity, Long> { @Query("select u.id from UserEntity u") fun findAllIds(): Set<Long> fun findByEmail(email: String): UserEntity? fun findByPublicId(publicId: UUID): UserEntity? fun existsByEmail(email: String): Boolean @Query("select u.id from UserEntity u where email = ?1") fun findIdByEmail(email: String): Long? @Query("select u.id from UserEntity u where email IN (?1)") fun findIdsByEmail(emails: Set<String>): Set<Long> @Query("select u.id from UserEntity u where publicId = ?1") fun findIdByPublicId(userPublicId: UUID): Long? @Modifying(clearAutomatically = true) @Query( "DELETE FROM sama.user_firebase_credential WHERE user_id != :ownerUserId AND device_id IN :deviceIds", nativeQuery = true ) fun deleteFirebaseCredentials(ownerUserId: Long, deviceIds: Collection<UUID>) } fun UserJpaRepository.findByEmailOrThrow(email: String) = findByEmail(email) ?: throw NotFoundException(UserEntity::class, "email", email) fun UserJpaRepository.findIdByEmailOrThrow(email: String) = findIdByEmail(email) ?: throw NotFoundException(UserEntity::class, "email", email) fun UserJpaRepository.findByPublicIdOrThrow(publicId: UUID) = findByPublicId(publicId) ?: throw NotFoundException(UserEntity::class, "userId", publicId) fun UserJpaRepository.findIdByPublicIdOrThrow(publicId: UUID) = findIdByPublicId(publicId) ?: throw NotFoundException(UserEntity::class, "userId", publicId)
0
Kotlin
1
2
a73319e26a22bf09aeb6bcc1cc2feaf3723ba0b9
1,866
sama-service
Apache License 2.0
app/src/main/java/com/dvt/weather/interview/presentation/ui/home/CurrentWeatherScreen.kt
Ryggs
815,102,045
false
{"Kotlin": 216639, "Ruby": 2550}
package com.dvt.weather.interview.presentation.ui.home import android.Manifest import android.content.res.Configuration import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Menu import androidx.compose.material.icons.sharp.LocationOn import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.PullRefreshState import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.LastBaseline import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Devices.NEXUS_5 import androidx.compose.ui.tooling.preview.Devices.PIXEL_4_XL import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.google.android.gms.maps.model.LatLng import com.dvt.weather.interview.R import com.dvt.weather.interview.domain.enums.ActionType import com.dvt.weather.interview.presentation.component.WeatherScaffold import com.dvt.weather.interview.presentation.model.CurrentWeatherViewData import com.dvt.weather.interview.presentation.model.HourWeatherViewData import com.dvt.weather.interview.presentation.model.factory.previewCurrentWeatherViewData import com.dvt.weather.interview.presentation.theme.WeaposeTheme import com.dvt.weather.interview.presentation.ui.Screen import com.dvt.weather.interview.presentation.ui.WeatherAppState import com.dvt.weather.interview.presentation.utils.Constants import kotlinx.coroutines.flow.collectLatest @OptIn(ExperimentalPermissionsApi::class, ExperimentalMaterialApi::class) @Composable fun CurrentWeather( appState: WeatherAppState, viewModel: CurrentWeatherViewModel = viewModel(), ) { val state by viewModel.state.collectAsStateWithLifecycle() val pullRefreshState = rememberPullRefreshState( refreshing = state.isRefresh, onRefresh = { viewModel.onRefreshCurrentWeather() }, ) val context = LocalContext.current val locationPermissionState = rememberMultiplePermissionsState( listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, ) ) { permissions -> when { permissions.all { it.value } -> viewModel.getCurrentLocation() else -> viewModel.permissionIsNotGranted() } } // Get data from back LaunchedEffect(true) { appState.getDataFromNextScreen(Constants.Key.ADDRESS_NAME, "")?.collect { if (it.isNotBlank()) { viewModel.getWeatherByAddressName(addressName = it) appState.removeDataFromNextScreen<LatLng>(Constants.Key.ADDRESS_NAME) } } } LaunchedEffect(true) { appState.getDataFromNextScreen(Constants.Key.LAT_LNG, Constants.Default.LAT_LNG_DEFAULT)?.collect { if (it != LatLng(0.0, 0.0)) { viewModel.getWeatherByLocation(it) appState.removeDataFromNextScreen<LatLng>(Constants.Key.LAT_LNG) } } } // Locale change LaunchedEffect(true) { appState.localChange.collectLatest { viewModel.onRefreshCurrentWeather(false) } } // Get event LaunchedEffect(state) { val navigateToSearch = state.navigateSearch val requestPermission = state.isRequestPermission when { requestPermission -> { when { locationPermissionState.allPermissionsGranted -> { viewModel.getCurrentLocation() } locationPermissionState.shouldShowRationale -> { viewModel.permissionIsNotGranted() } else -> { locationPermissionState.launchMultiplePermissionRequest() } } } navigateToSearch != null -> { appState.navigateToSearchByText(Screen.CurrentWeather, navigateToSearch) } else -> return@LaunchedEffect } viewModel.cleanEvent() } CurrentWeatherScreen( state = state, pullRefreshState = pullRefreshState, snackbarHostState = appState.snackbarHost, onDrawer = { appState.openDrawer() }, onShowSnackbar = { appState.showSnackbar(it) }, onDismissErrorDialog = { viewModel.hideError() }, onNavigateSearch = { viewModel.navigateToSearchByMap() }, onErrorPositiveAction = { action, _ -> action?.let { when (it) { ActionType.RETRY_API -> { viewModel.retry() } ActionType.OPEN_PERMISSION -> { appState.openAppSetting(context) } } } }, ) } @OptIn(ExperimentalMaterialApi::class) @Composable fun CurrentWeatherScreen( state: CurrentWeatherViewState, pullRefreshState: PullRefreshState, snackbarHostState: SnackbarHostState = SnackbarHostState(), onDrawer: () -> Unit = {}, onDismissErrorDialog: () -> Unit = {}, onShowSnackbar: (message: String) -> Unit = {}, onNavigateSearch: () -> Unit = {}, onErrorPositiveAction: (action: ActionType?, value: Any?) -> Unit = { _, _ -> }, ) { Box( modifier = Modifier .fillMaxSize() ) { // Background state.currentWeather?.let { currentWeather -> Spacer(modifier = Modifier .fillMaxWidth() .height(200.dp) .background(Color.Transparent) ) Image( modifier = Modifier .fillMaxSize() .alpha(0.3f), painter = painterResource(id = currentWeather.background), contentDescription = null, contentScale = ContentScale.FillBounds, ) } CurrentWeatherAppBar( modifier = Modifier .statusBarsPadding() .zIndex(1f), city = state.currentWeather?.city, onDrawer = onDrawer, onNavigateSearch = onNavigateSearch, ) Scaffold( modifier = Modifier.fillMaxSize(), snackbarHost = { snackbarHostState }, ) { innerPadding -> WeatherScaffold( modifier = Modifier .fillMaxSize() .padding(innerPadding) .padding(top = AppBarHeight), state = state, snackbarHostState = snackbarHostState, onDismissErrorDialog = onDismissErrorDialog, onShowSnackbar = onShowSnackbar, onErrorPositiveAction = onErrorPositiveAction, ) { _, viewState -> Box( modifier = Modifier .fillMaxSize() .pullRefresh(pullRefreshState) ) { viewState.currentWeather?.let { HomeContent( currentWeather = it, listHourly = viewState.listHourlyWeatherToday, ) } PullRefreshIndicator( refreshing = state.isRefresh, state = pullRefreshState, modifier = Modifier.align(Alignment.TopCenter) ) } } } } } private val AppBarHeight = 56.dp @Composable fun HomeContent( currentWeather: CurrentWeatherViewData, listHourly: List<HourWeatherViewData>, ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { NowWeather( modifier = Modifier .fillMaxSize() .height(400.dp), currentWeather = currentWeather, ) Spacer(modifier = Modifier.height(36.dp)) Text( text = "Today's Hourly Forecast", style = MaterialTheme.typography.titleLarge, modifier = Modifier .padding(horizontal = 16.dp, vertical = 5.dp) ) LazyRow( contentPadding = PaddingValues(vertical = 15.dp), horizontalArrangement = Arrangement.spacedBy(20.dp), ) { items( count = listHourly.size, key = { listHourly[it].timeStamp }, ) { index -> WeatherHour( hour = listHourly[index].time, weather = listHourly[index].weatherIcon, ) } } } } @Composable fun NowWeather( modifier: Modifier, currentWeather: CurrentWeatherViewData, ) { Box( modifier = modifier, contentAlignment = Alignment.TopCenter ) { Image( modifier = Modifier .fillMaxSize() .background(Color.Transparent), painter = painterResource(id = currentWeather.background), contentDescription = null, contentScale = ContentScale.FillBounds, ) Row ( modifier = Modifier .fillMaxWidth() .padding(top = 50.dp) .align(Alignment.TopCenter) .background(Color.Transparent), ){ Column( modifier = Modifier .padding(16.dp) .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top ) { Degrees( currentWeather = currentWeather.weather, currentTemp = currentWeather.temp, ) } } } } @Composable fun DetailWeather( modifier: Modifier = Modifier, @DrawableRes iconId: Int, title: String, description: String, ) { Column( modifier = modifier, horizontalAlignment = Alignment.End, ) { Image( modifier = Modifier.size(30.dp), painter = painterResource(id = iconId), contentDescription = null, colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSurface) ) Text( text = title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(top = 5.dp), ) Text( text = description, style = MaterialTheme.typography.headlineSmall, ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun CurrentWeatherAppBar( modifier: Modifier = Modifier, title: String = "", city: String? = null, onDrawer: () -> Unit = {}, onNavigateSearch: () -> Unit = {}, ) { TopAppBar( modifier = modifier, title = { if (title.isNotBlank()) { Text(text = title, maxLines = 1, overflow = TextOverflow.Visible) } }, navigationIcon = { IconButton(onClick = onDrawer) { Icon( imageVector = Icons.Outlined.Menu, contentDescription = null, ) } }, actions = { Card( onClick = onNavigateSearch, shape = RoundedCornerShape(10.dp), elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), colors = CardDefaults.cardColors(containerColor = Color.Transparent), ) { Row( modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.Sharp.LocationOn, contentDescription = null, modifier = Modifier.padding(end = 5.dp), ) Text( text = city ?: stringResource(id = R.string.unknown_address), style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } } }, ) } @Composable fun Degrees( modifier: Modifier = Modifier, currentTemp: String, currentWeather: String, isBold: Boolean = false, ) { Column( modifier = modifier, horizontalAlignment = Alignment.End, ) { Row(verticalAlignment = Alignment.CenterVertically) { Text( text = currentTemp, style = MaterialTheme.typography.displayLarge.copy( fontWeight = if (isBold) FontWeight.Bold else FontWeight.Normal ), modifier = Modifier.alignBy(LastBaseline), ) Column(modifier = Modifier.alignBy(LastBaseline)) { Text(text = "o", modifier = Modifier.padding(bottom = 10.dp)) Text(text = "c") } } Text( text = currentWeather, style = MaterialTheme.typography.labelMedium.copy(fontSize = 22.sp), ) } } @Composable fun WeatherHour( modifier: Modifier = Modifier, hour: String, @DrawableRes weather: Int, ) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = hour, style = MaterialTheme.typography.titleMedium, ) Image( painter = painterResource(id = weather), contentDescription = null, modifier = Modifier .size(40.dp) .padding(top = 15.dp), ) } } @Preview(name = "Light") @Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun NowWeatherPreview() { WeaposeTheme { NowWeather( modifier = Modifier.size(500.dp), currentWeather = previewCurrentWeatherViewData(), ) } } @Preview(name = "Light", showBackground = true) @Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun DegreesPreview() { WeaposeTheme { Degrees( currentWeather = previewCurrentWeatherViewData().weather, currentTemp = previewCurrentWeatherViewData().temp, ) } } @Preview(name = "Light", showBackground = true) @Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun AppBarPreview() { WeaposeTheme { CurrentWeatherAppBar(city = previewCurrentWeatherViewData().city) } } @OptIn(ExperimentalMaterialApi::class) @Preview(name = "Light", showBackground = true, device = NEXUS_5) @Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = PIXEL_4_XL) @Composable private fun ScreenPreview() { WeaposeTheme { CurrentWeatherScreen( state = CurrentWeatherViewState(), pullRefreshState = rememberPullRefreshState(refreshing = true, onRefresh = {}) ) } } @Preview(name = "Light") @Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun WeatherHourPreview() { WeaposeTheme { WeatherHour( hour = "10:00", weather = R.drawable.ic_clear_sky, ) } }
23
Kotlin
0
1
fbaa548efe3d25b8d54a74e2bf70086d82a59809
17,822
Weather-Compose
Apache License 2.0
src/main/kotlin/io/propa/framework/external/Extra.kt
PropaFramework
91,819,919
false
null
package io.propa.framework.external /** * Created by gbaldeck on 5/9/2017. */ external fun require(module: String): dynamic external val Math: dynamic
0
Kotlin
0
5
57f7e742540e16af6fd4272c539261e55c593d16
154
Propa
MIT License
module/bukkit/bukkit-util/src/main/kotlin/taboolib/platform/util/ItemStack.kt
TabooLib
120,413,612
false
{"Kotlin": 1478208, "Java": 1130022}
package taboolib.platform.util import org.bukkit.inventory.ItemStack import taboolib.library.xseries.XMaterial /** * 判定材质是否为空气 */ val XMaterial.isAir get() = this == XMaterial.AIR || this == XMaterial.CAVE_AIR || this == XMaterial.VOID_AIR /** * 判定物品是否为空气 */ val ItemStack?.isAir get() = isAir()
4
Kotlin
101
307
41a840c2623b616607852c9e1343c662a4143216
302
taboolib
MIT License
search/presentation/src/main/kotlin/com/cedrickflocon/android/showcase/search/presentation/field/SearchFieldComponent.kt
CedrickFlocon
456,870,712
false
{"Kotlin": 95445}
package com.cedrickflocon.android.showcase.search.presentation.field import com.cedrickflocon.android.showcase.search.di.SearchComponent import com.cedrickflocon.android.showcase.core.presentation.ViewModelScope import dagger.BindsInstance import dagger.Component import kotlinx.coroutines.CoroutineScope @ViewModelScope @Component(dependencies = [SearchComponent::class]) interface SearchFieldComponent { fun provideViewModel(): SearchFieldViewModel @Component.Factory interface Factory { fun create( @BindsInstance scope: CoroutineScope, searchComponent: SearchComponent ): SearchFieldComponent } }
0
Kotlin
0
1
bf6b30bb900002e35022b897c61bfb8752534caf
662
android-showcase
MIT License
src/Day01.kt
mkulak
573,910,880
false
{"Kotlin": 14860}
fun main() { fun part1(input: List<String>): Int = input.fold(0 to 0) { (maximum, current), str -> if (str.isEmpty()) Math.max(maximum, current) to 0 else maximum to current + str.toInt() }.first fun part2(input: List<String>): Int = input.fold(listOf<Int>() to 0) { (list, acc), str -> if (str.isEmpty()) list + acc to 0 else list to acc + str.toInt() }.first.sortedBy { -it }.take(3).sum() val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3b4e9b32df24d8b379c60ddc3c007d4be3f17d28
547
AdventOfKo2022
Apache License 2.0
src/jvmMain/kotlin/matt/http/req/write/write.kt
mgroth0
532,378,353
false
null
package matt.http.req.write import matt.file.MFile import matt.http.req.HTTPRequestImpl import matt.prim.byte.efficientlyTransferTo import kotlin.concurrent.thread class BasicHTTPWriter( private val req: HTTPRequestImpl, private val bytes: ByteArray ): HTTPWriter() { override fun write() { req.writeBytesNow(bytes) } } class AsyncWriter( private val req: HTTPRequestImpl, private val file: MFile ): HTTPWriter() { override fun write() { thread { println("running async data transfer") file.readChannel().efficientlyTransferTo(req.outputStream) println("finished running async data transfer") } } }
0
Kotlin
0
0
6bc6bc1eef902af513b3ebba0992b29922ed04ef
630
http
MIT License
app/src/main/kotlin/com/nelkinda/template/app/item/ItemRepository.kt
SujitNirgude2813
538,449,863
false
null
package com.nelkinda.template.app.item interface ItemRepository { fun getItem(name: String, quantity: Int, price: Double): Item? }
5
Kotlin
0
0
94522d2ddcd7a69dd8488bc3722b5cf308e5f520
136
uropia-tax-calculator-assignment
FSF All Permissive License
app/src/main/java/net/skyscanner/backpack/demo/compose/Text.kt
Skyscanner
117,813,847
false
null
/** * Backpack for Android - Skyscanner's Design System * * Copyright 2018-2021 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.skyscanner.backpack.demo.compose import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import net.skyscanner.backpack.compose.theme.BpkTheme @Composable fun TypographyStylesStory() { val styles = listOf( BpkTheme.typography.hero1 to "Hero 1", BpkTheme.typography.hero2 to "Hero 2", BpkTheme.typography.hero3 to "Hero 3", BpkTheme.typography.hero4 to "Hero 4", BpkTheme.typography.hero5 to "Hero 5", BpkTheme.typography.heading1 to "Heading 1", BpkTheme.typography.heading2 to "Heading 2", BpkTheme.typography.heading3 to "Heading 3", BpkTheme.typography.heading4 to "Heading 4", BpkTheme.typography.heading5 to "Heading 5", BpkTheme.typography.subheading to "Subheading", BpkTheme.typography.bodyLongform to "Body Longform", BpkTheme.typography.bodyDefault to "Body Default", BpkTheme.typography.footnote to "Footnote", BpkTheme.typography.caption to "Caption", BpkTheme.typography.label1 to "Label 1", BpkTheme.typography.label2 to "Label 2", ) LazyColumn(modifier = Modifier.padding(16.dp)) { items(styles) { style -> Text( style = style.first, text = style.second ) } } }
5
Kotlin
23
55
811ec4c8dd1c4c0f380b13e43f96b3323361565d
2,105
backpack-android
Apache License 2.0
app/src/main/java/com/shashank/moviefindermvvm/ui/moviedetail/MovieDetailViewModelFactory.kt
Shashank02051997
255,571,550
false
null
package com.shashank.moviefindermvvm.ui.moviedetail import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.shashank.moviefindermvvm.data.repositories.MovieDetailRepository @Suppress("UNCHECKED_CAST") class MovieDetailViewModelFactory( private val repository: MovieDetailRepository ) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return MovieDetailViewModel(repository) as T } }
0
Kotlin
24
76
8f24b851dc1befaffe2163aa4e08c02daf76feaf
497
MovieFinderUsingMVVM-Android
MIT License
app/src/main/java/com/baseproject/ui/base/BaseViewModel.kt
shubham-soni9
362,546,242
false
null
package com.baseproject.ui.base import androidx.lifecycle.ViewModel /** * Base structure for defining ViewModel */ abstract class BaseViewModel : ViewModel()
0
Kotlin
0
0
f3f888d4c3797c88289c4b0c5554d2f9ebfb253b
161
MVVM-BaseProject
MIT License
operator/src/main/kotlin/org/acasictf/ctf/operator/persistence/ZipChallengeTemplate.kt
acasi-ctf
333,260,332
false
{"JavaScript": 113736, "Kotlin": 98138, "Python": 68991, "Java": 37916, "Go": 28263, "CSS": 14823, "Dockerfile": 11108, "Shell": 10068, "Makefile": 6618, "TypeScript": 6073, "HTML": 1323, "C++": 563, "Mako": 494}
package org.acasictf.ctf.operator.persistence import java.io.File import java.util.zip.ZipEntry import java.util.zip.ZipFile class ZipChallengeTemplate(file: File) : ChallengeTemplate() { private val zipFile = ZipFile(file) override fun readFile(path: String): ChallengeTemplateFile = ZipChallengeTemplateFile(zipFile, path) } private class ZipChallengeTemplateFile( private val zipFile: ZipFile, path: String ) : ChallengeTemplateFile { private val zipEntry: ZipEntry? = zipFile.getEntry(path) override fun exists() = zipEntry != null override fun getInputStream() = zipFile.getInputStream(zipEntry!!) }
18
JavaScript
2
4
582614352013ee95c757bfb7e4b7159a4a46e389
650
ctf
Apache License 2.0
app/src/main/java/com/example/mywaycompose/domain/usecase/task/UseInsertTask.kt
larkes-cyber
739,078,285
false
{"Kotlin": 573267}
package com.example.mywaycompose.domain.usecase.task import com.example.mywaycompose.domain.mapper.toTaskEntity import com.example.mywaycompose.domain.model.Task import com.example.mywaycompose.domain.repository.TaskRepository import javax.inject.Inject class UseInsertTask @Inject constructor(private val taskRepository: TaskRepository) { suspend fun execute(task:Task){ taskRepository.insertTask(task.toTaskEntity()) } }
0
Kotlin
0
1
b329374b9a5f459e75fb30b7a05a726fce065ceb
440
PlannerApp
Apache License 2.0
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimSelectionModel.kt
JetBrains
1,459,486
false
{"Kotlin": 5959132, "Java": 211095, "ANTLR": 84686, "HTML": 2184}
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.api interface VimSelectionModel { val selectionStart: Int val selectionEnd: Int fun hasSelection(): Boolean }
6
Kotlin
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
357
ideavim
MIT License
solar/src/main/java/com/chiksmedina/solar/bold/essentionalui/PinCircle.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.PinCircle: ImageVector get() { if (_pinCircle != null) { return _pinCircle!! } _pinCircle = Builder( name = "PinCircle", 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(21.9998f, 12.0f) curveTo(21.9998f, 17.5228f, 17.5226f, 22.0f, 11.9998f, 22.0f) curveTo(6.4769f, 22.0f, 1.9998f, 17.5228f, 1.9998f, 12.0f) curveTo(1.9998f, 6.4771f, 6.4769f, 2.0f, 11.9998f, 2.0f) curveTo(17.5226f, 2.0f, 21.9998f, 6.4771f, 21.9998f, 12.0f) close() moveTo(14.1094f, 8.4188f) lineTo(15.5918f, 9.9026f) curveTo(16.5977f, 10.9095f, 17.1007f, 11.413f, 16.9833f, 11.9557f) curveTo(16.866f, 12.4985f, 16.2f, 12.7487f, 14.8681f, 13.2491f) lineTo(13.9461f, 13.5955f) curveTo(13.5894f, 13.7295f, 13.411f, 13.7965f, 13.2734f, 13.9157f) curveTo(13.2131f, 13.9679f, 13.1592f, 14.027f, 13.1127f, 14.0918f) curveTo(13.0065f, 14.2397f, 12.9559f, 14.4236f, 12.8548f, 14.7913f) curveTo(12.6247f, 15.6276f, 12.5096f, 16.0457f, 12.2357f, 16.202f) curveTo(12.1202f, 16.2679f, 11.9896f, 16.3025f, 11.8567f, 16.3023f) curveTo(11.5413f, 16.3018f, 11.235f, 15.9951f, 10.6222f, 15.3818f) lineTo(10.1495f, 14.9086f) lineTo(8.5308f, 16.5299f) curveTo(8.2381f, 16.823f, 7.7632f, 16.8234f, 7.4701f, 16.5308f) curveTo(7.177f, 16.2381f, 7.1766f, 15.7632f, 7.4692f, 15.4701f) lineTo(9.0887f, 13.848f) curveTo(9.0885f, 13.8482f, 9.0889f, 13.8478f, 9.0887f, 13.848f) lineTo(8.6424f, 13.4f) curveTo(8.0335f, 12.7905f, 7.7291f, 12.4858f, 7.7271f, 12.1723f) curveTo(7.7262f, 12.0368f, 7.7614f, 11.9035f, 7.829f, 11.786f) curveTo(7.9854f, 11.5145f, 8.4005f, 11.4f, 9.2307f, 11.1711f) curveTo(9.5991f, 11.0696f, 9.7832f, 11.0188f, 9.9312f, 10.9123f) curveTo(9.9977f, 10.8644f, 10.0581f, 10.8088f, 10.1112f, 10.7465f) curveTo(10.2295f, 10.6076f, 10.2953f, 10.4281f, 10.4269f, 10.069f) lineTo(10.7608f, 9.1575f) curveTo(11.2543f, 7.8108f, 11.501f, 7.1374f, 12.0452f, 7.0173f) curveTo(12.5894f, 6.8973f, 13.0961f, 7.4044f, 14.1094f, 8.4188f) close() } } .build() return _pinCircle!! } private var _pinCircle: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
3,555
SolarIconSetAndroid
MIT License
database/src/main/java/es/littledavity/database/chorbo/ContactsTypeConverter.kt
Benderinos
260,322,264
false
null
/* * Copyright 2021 dalodev */ package es.littledavity.database.chorbo import androidx.room.ProvidedTypeConverter import androidx.room.TypeConverter import com.paulrybitskyi.hiltbinder.BindType import es.littledavity.core.JsonConverter import es.littledavity.database.chorbo.entities.CreationDate import es.littledavity.database.chorbo.entities.CreationDateCategory import es.littledavity.database.chorbo.entities.Image import es.littledavity.database.chorbo.entities.Info import es.littledavity.database.commons.RoomTypeConverter import javax.inject.Inject @ProvidedTypeConverter @BindType(contributesTo = BindType.Collection.SET) internal class ContactsTypeConverter @Inject constructor( private val jsonConverter: JsonConverter ) : RoomTypeConverter { @TypeConverter fun fromInfoList(infoList: List<Info>?): String = jsonConverter.toJson(infoList) @TypeConverter fun toInfoList(json: String): List<Info> = jsonConverter.fromJson(json) ?: emptyList() @TypeConverter fun fromImage(image: Image?): String = jsonConverter.toJson(image) @TypeConverter fun toImage(json: String): Image? = jsonConverter.fromJson(json) @TypeConverter fun fromImages(images: MutableList<Image>): String = jsonConverter.toJson(images) @TypeConverter fun toImages(json: String): MutableList<Image> = jsonConverter.fromJson(json) ?: mutableListOf() @TypeConverter fun fromCreationDate(creationDate: CreationDate): String = jsonConverter.toJson(creationDate) @TypeConverter fun toReleaseDates(json: String): CreationDate? = jsonConverter.fromJson(json) @TypeConverter fun fromCreationDateCategory(category: CreationDateCategory): String = jsonConverter.toJson(category) @TypeConverter fun toCreationDateCategory(json: String): CreationDateCategory = jsonConverter.fromJson(json) ?: CreationDateCategory.UNKNOWN }
0
Kotlin
0
1
4f7f9d251c4da8e130a9f2b64879867bfecb44e8
1,901
ChorboAgenda
Apache License 2.0
app/src/main/java/com/example/applaudochallenge/ui/navigation/screens/ProfileScreen.kt
mauriciolima1988
561,894,249
false
null
package com.example.applaudochallenge.ui.navigation.screens import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.example.applaudochallenge.R import com.example.applaudochallenge.data.database.FavoriteTvShow import com.example.applaudochallenge.ui.CustomAlertDialog import com.example.applaudochallenge.ui.navigation.components.ImageViewSection import com.example.applaudochallenge.ui.navigation.components.RatingViewSection import com.example.applaudochallenge.ui.navigation.components.TitleViewSection import com.example.applaudochallenge.ui.navigation.viewmodels.ProfileScreenViewModel import com.example.applaudochallenge.ui.theme.dimension @OptIn(ExperimentalLifecycleComposeApi::class) @Composable internal fun ProfileScreen( viewModel: ProfileScreenViewModel = hiltViewModel(), onBackPressed: () -> Unit ) { val favoritesList by viewModel.favoritesList.collectAsStateWithLifecycle() val showLeaveDialog = rememberSaveable { mutableStateOf(false) } if (showLeaveDialog.value) { CustomAlertDialog( message = stringResource(id = R.string.leave_dialog_message), positiveText = stringResource(id = R.string.stay_dialog_button_text), negativeText = stringResource(id = R.string.leave_dialog_button_text), showDialog = showLeaveDialog, onAction = { onBackPressed() }) } ProfileScreen(onBackPressed, favoritesList, showLeaveDialog) } @Composable private fun ProfileScreen( onBackPressed: () -> Unit, favoritesList: List<FavoriteTvShow>?, showLeaveDialog: MutableState<Boolean> ) { Scaffold( topBar = { ProfileTopBar(onBackPressed) } ) { LazyColumn( modifier = Modifier .fillMaxSize() .padding(it), verticalArrangement = Arrangement.Top ) { item { ProfileSection() FavoriteSection(favoritesList ?: emptyList()) LogOutButtonSection(showLeaveDialog) } } } } @Composable private fun ProfileTopBar( onBackPressed: () -> Unit ) { TopAppBar( modifier = Modifier .fillMaxWidth() .height(MaterialTheme.dimension.sizeDp48), title = { Text( text = stringResource(id = R.string.profile), color = Color.White ) }, navigationIcon = { IconButton( modifier = Modifier.size(MaterialTheme.dimension.sizeDp32), onClick = onBackPressed ) { Icon( modifier = Modifier.size(MaterialTheme.dimension.sizeDp24), imageVector = Icons.Default.ArrowBack, tint = Color.White, contentDescription = null ) } }, backgroundColor = MaterialTheme.colors.primary ) } @Composable internal fun LogOutButtonSection(showLeaveDialog: MutableState<Boolean>) { Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp8)) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Button( modifier = Modifier .fillMaxWidth() .padding(MaterialTheme.dimension.sizeDp16) .size(MaterialTheme.dimension.sizeDp48), onClick = { showLeaveDialog.value = true } ) { Text( text = stringResource(id = R.string.logout_button_text), color = Color.White ) } } } @Composable internal fun FavoriteSection(favoritesList: List<FavoriteTvShow>) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start ) { Text( modifier = Modifier.padding(horizontal = MaterialTheme.dimension.sizeDp16), text = stringResource(id = R.string.my_favorites), fontWeight = FontWeight.Bold ) if (favoritesList.isEmpty()) { Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp16)) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Text( text = stringResource(id = R.string.favorites_empty) ) } } else { Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp8)) LazyRow( modifier = Modifier.padding(horizontal = MaterialTheme.dimension.sizeDp8) ) { items(favoritesList) { favTvShow -> FavoritesListItem(favoriteTvShow = favTvShow) } } } } } @Composable internal fun FavoritesListItem( modifier: Modifier = Modifier, favoriteTvShow: FavoriteTvShow ) { Card( modifier = modifier .padding(MaterialTheme.dimension.sizeDp8) .size(width = MaterialTheme.dimension.sizeDp192, height = MaterialTheme.dimension.sizeDp244), shape = RoundedCornerShape(MaterialTheme.dimension.sizeDp8), elevation = MaterialTheme.dimension.sizeDp4 ) { Column { ImageViewSection(imageUrl = favoriteTvShow.poster_path ?: "") Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp8)) Column( modifier = Modifier.padding(MaterialTheme.dimension.sizeDp8) ) { TitleViewSection(tvShowName = favoriteTvShow.name) Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp8)) RatingViewSection(tvShowScoreRating = favoriteTvShow.vote_average) } } } } @Composable internal fun ProfileSection() { Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp32)) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Box( contentAlignment = Alignment.BottomEnd ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(MaterialTheme.dimension.sizeDp128) .border( MaterialTheme.dimension.sizeDp16, color = colorResource(id = R.color.primary_semitransparent_color), CircleShape ) .border(4.dp, color = Color.Transparent, CircleShape), ) { Icon( modifier = Modifier.size(MaterialTheme.dimension.sizeDp80), imageVector = Icons.Default.Person, contentDescription = null, tint = Color.Gray ) } /* FloatingActionButton( modifier = Modifier.size(MaterialTheme.dimension.sizeDp32), backgroundColor = MaterialTheme.colors.primary, onClick = {} ) { Icon( modifier = Modifier.size(MaterialTheme.dimension.sizeDp16), imageVector = Icons.Default.Edit, tint = Color.White, contentDescription = null ) }*/ } Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp16)) Text( text = stringResource(id = R.string.profile_mock_name), ) Text( text = stringResource(id = R.string.profile_mock_username), fontSize = 10.sp, ) Spacer(modifier = Modifier.height(MaterialTheme.dimension.sizeDp16)) } }
0
Kotlin
0
0
d4481d5e5fcfcaf0c953fd1fe806c1aedfcdca9c
9,229
Applaudo_s_Code_Challenge_Android
MIT License
core/common/src/main/java/com/core/common/ui/theme/Color.kt
7pak
764,350,162
false
{"Kotlin": 496880}
package com.core.common.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val Red = Color(0xFFff2e63) val PreWhite = Color(0xFFf6f6f6) val Cantaloupe = Color(0xFFf7d7c8) val Beige = Color(0xFFFFF0E5)
0
Kotlin
0
1
2fe106a4241dfd24ef63948ebb3095ce40c6f9d7
406
LonePaw-PetAdoption
MIT License
app/src/main/java/com/items/bim/entity/KVMapEntity.kt
losebai
800,799,665
false
{"Kotlin": 648062, "Java": 11455}
package com.items.bim.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "kv_map") data class KVMapEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(name = "first") val key: String, @ColumnInfo(name = "second") var value: String? )
0
Kotlin
0
0
325bd3c4d8d9c7717dafd3e8d346446f85e32b8a
351
B-Im
Apache License 2.0
app/src/main/java/com/example/buynow/data/local/room/category/CategoryRepo.kt
Shanan23
794,368,317
false
{"Kotlin": 220243}
package com.example.buynow.data.local.room.category import androidx.lifecycle.LiveData class CategoryRepo(private val categoryDao: CategoryDao) { val allItems: LiveData<List<CategoryEntity>> = categoryDao.getAll() val getByCategoryId: LiveData<CategoryEntity> = categoryDao.getByCategoryId() suspend fun insert(category: CategoryEntity) { categoryDao.insert(category) } suspend fun delete(category: CategoryEntity) { categoryDao.delete(category) } suspend fun update(category: CategoryEntity) { categoryDao.update(category) } }
0
Kotlin
0
0
072435120a602f1818e692ad95a58b0c887b496a
590
ToSerba
MIT License
src/main/kotlin/ffc/entity/healthcare/CommunityService.kt
ffc-nectec
137,706,528
false
{"Kotlin": 159504}
/* * Copyright 2019 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.entity.healthcare import ffc.entity.Entity import ffc.entity.Lookup open class CommunityService(val serviceType: ServiceType) : Entity() { class ServiceType(id: String, name: String) : Lookup(id, name) } class HomeVisit( serviceType: CommunityService.ServiceType, var detail: String? = null, var result: String? = null, var plan: String? = null ) : CommunityService(serviceType)
2
Kotlin
0
0
6ec51b8cd89c3f9a26548fd0d25e1f5583df1ce8
1,072
entities
Apache License 2.0
feature/home/presentation/src/test/java/com/tfandkusu/androidview/viewmodel/home/HomeViewModelTest.kt
tfandkusu
461,559,603
false
null
package com.tfandkusu.androidview.viewmodel.home import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.tfandkusu.androidview.catalog.GitHubRepoCatalog import com.tfandkusu.androidview.error.NetworkErrorException import com.tfandkusu.androidview.usecase.home.HomeLoadUseCase import com.tfandkusu.androidview.usecase.home.HomeOnCreateUseCase import com.tfandkusu.androidview.viewmodel.error.ApiErrorState import com.tfandkusu.androidview.viewmodel.mockStateObserver import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerifySequence import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.verifySequence import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule class HomeViewModelTest { @get:Rule val rule: TestRule = InstantTaskExecutorRule() @ExperimentalCoroutinesApi private val testDispatcher = UnconfinedTestDispatcher() @MockK(relaxed = true) private lateinit var loadUseCase: HomeLoadUseCase @MockK(relaxed = true) private lateinit var onCreateUseCase: HomeOnCreateUseCase private lateinit var viewModel: HomeViewModel @ExperimentalCoroutinesApi @Before fun setUp() { Dispatchers.setMain(testDispatcher) MockKAnnotations.init(this) viewModel = HomeViewModelImpl(loadUseCase, onCreateUseCase) } @ExperimentalCoroutinesApi @After fun tearDown() { Dispatchers.resetMain() } @ExperimentalCoroutinesApi @Test fun onCreate() = runTest { val repos = GitHubRepoCatalog.getList() every { onCreateUseCase.execute() } returns flow { emit(repos) } val mockStateObserver = viewModel.state.mockStateObserver() viewModel.event(HomeEvent.OnCreate) verifySequence { mockStateObserver.onChanged(HomeState()) onCreateUseCase.execute() mockStateObserver.onChanged(HomeState(repos = repos)) } } @ExperimentalCoroutinesApi @Test fun loadSuccess() = runTest { val stateMockObserver = viewModel.state.mockStateObserver() val errorStateMockObserver = viewModel.error.state.mockStateObserver() viewModel.event(HomeEvent.Load) coVerifySequence { stateMockObserver.onChanged(HomeState()) errorStateMockObserver.onChanged(ApiErrorState()) errorStateMockObserver.onChanged(ApiErrorState()) stateMockObserver.onChanged(HomeState(progress = true)) loadUseCase.execute() stateMockObserver.onChanged(HomeState(progress = false)) } } @ExperimentalCoroutinesApi @Test fun loadError() = runTest { coEvery { loadUseCase.execute() } throws NetworkErrorException() val stateMockObserver = viewModel.state.mockStateObserver() val errorMockStateObserver = viewModel.error.state.mockStateObserver() viewModel.event(HomeEvent.Load) coVerifySequence { stateMockObserver.onChanged(HomeState()) errorMockStateObserver.onChanged(ApiErrorState()) errorMockStateObserver.onChanged(ApiErrorState()) stateMockObserver.onChanged(HomeState(progress = true)) loadUseCase.execute() errorMockStateObserver.onChanged(ApiErrorState(network = true)) stateMockObserver.onChanged(HomeState(progress = false)) } } }
23
Kotlin
0
0
bb4e6f6159a893837029a904231e04c40452a850
3,842
try_android_view_in_compose
Apache License 2.0
navigation/src/main/java/dev/marcellogalhardo/staccato/navigation/StaccatoScope.kt
marcellogalhardo
421,596,917
false
null
package dev.marcellogalhardo.staccato.navigation import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import androidx.navigation.NavBackStackEntry import dev.marcellogalhardo.staccato.core.InternalStaccatoApi import dev.marcellogalhardo.staccato.core.StaccatoScope import dev.marcellogalhardo.staccato.navigation.internal.StaccatoViewModel @OptIn(InternalStaccatoApi::class) @Composable fun StaccatoScope(navBackStackEntry: NavBackStackEntry, content: @Composable () -> Unit) { val vmProvider = remember { ViewModelProvider(navBackStackEntry, navBackStackEntry.defaultViewModelProviderFactory) } val vm = vmProvider.get<StaccatoViewModel>() StaccatoScope( onClearedHandler = { _, clear -> SideEffect { vm.onClearedListeners += clear } }, content = content, ) }
0
Kotlin
1
5
7893ec3e1702348ecd1a4b235ff7976a5116a983
955
staccato
Apache License 2.0
x-decode/ForegroundService.kt
m32
740,193,708
false
{"Python": 47, "Shell": 2, "SQL": 1, "Text": 2, "Ignore List": 1, "Markdown": 3, "Java": 60, "Kotlin": 3, "XML": 1}
private fun updateEsp32(context: Context){ val dbHandler = MyDBHandler(context, null, null, 1) val user = dbHandler.getUser() updateUser(user, unit) val setPref = PreferenceManager.getDefaultSharedPreferences(this) update12hr(setPref.getBoolean(ST.PREF_12H, false)) updateHourly(hourly) val disp = byteArrayOfInts(0xAB, 0x00, 0x04, 0xFF, 0x23, 0x80, if (setPref.getBoolean(ST.PREF_DISPLAY_OFF, false)) 1 else 0) sendData(disp) val timeout = byteArrayOfInts(0xAB, 0x00, 0x04, 0xFF, 0x7B, 0x80, setPref.getInt(ST.PREF_TIMEOUT, 10)) sendData(timeout) val level = readBatteryLevel(context) updateBat(level) } private fun sendImage(pos: Int, context: Context){ val checkG = byteArrayOfInts(0xAD, 0x04, 0x00, 0x00, 0x00, 0x37, 0x9D, 0x00) val checkR = byteArrayOfInts(0xAD, 0x04, 0x00, 0x00, 0x00, 0xB5, 0x8C, 0x00) val datB = byteArrayOfInts(0xAE, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00) val datG = byteArrayOfInts(0xAE, 0x12, 0x00, 0x00, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0) val datR = byteArrayOfInts(0xAE, 0x12, 0x00, 0x00, 0xF8, 0x00, 0xF8, 0x00, 0xF8, 0x00, 0xF8, 0x00, 0xF8, 0x00, 0xF8, 0x00, 0xF8, 0x00, 0xF8, 0x00) when { pos == 112 -> { checkG[1] = 0x02.toByte() checkG[3] = (pos/256).toByte() checkG[4] = (pos%256).toByte() checkG[5] = 0x37.toByte() checkG[6] = 0xDF.toByte() checkG[7] = 1 transmitData(checkG, 100, context) for (x in 0x0E00 .. 0x0E1F){ datR[2] = (x/256).toByte() datR[3] = (x%256).toByte() sendData(datR) } } pos % 28 == 0 -> { for (x in pos * 64 until (pos + 1) * 64) { //0x1BFF checkR[3] = (pos / 256).toByte() checkR[4] = (pos % 256).toByte() if (x % 64 == 0) { transmitData(checkR, ((x.toFloat() / 0x1BFF) * 100).toInt(), context) } datR[2] = (x / 256).toByte() datR[3] = (x % 256).toByte() sendData(datR) } } else -> { for (x in pos * 64 until (pos + 1) * 64) { //0x1BFF checkG[3] = (pos / 256).toByte() checkG[4] = (pos % 256).toByte() if (x % 64 == 0) { transmitData(checkG, ((x.toFloat() / 0x1BFF) * 100).toInt(), context) } datG[2] = (x / 256).toByte() datG[3] = (x % 256).toByte() sendData(datG) } } } //cancelNotification(SERVICE_ID2, context) } fun uploadFile(pos: Int, context: Context){ val directory = context.cacheDir val upload = File(directory, "upload") val file = File(upload, "out$pos.hex") val check = File(upload, "check$pos.hex") if (file.exists() && check.exists()){ val sum = check.readBytes() transmitData(sum, ((pos.toFloat() / 0x70) * 100).toInt(), context) val pxls = file.readBytes() if (pos == 112){ val array = ByteArray(20) for (b in 0 until 32) { for (y in 0 until 20){ array[y] = pxls[(b*20)+y] } sendData(array) } } else { for (b in 0 until 64) { val array = ByteArray(20) for (y in 0 until 20){ array[y] = pxls[(b*20)+y] } sendData(array) } } } else { sendImage(pos, context) } } fun sendDat(byteArray: ByteArray, pos: Int, context: Context){ val checkSum = byteArrayOfInts(0xAD, 0x04, 0x00, 0x00, 0x00, 0x37, 0x9D, 0x00) val data = byteArrayOfInts(0xAE, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00) val crc = CRC16Modbus() for (b in byteArray){ crc.update(b.toInt()) } val sum = crc.crcBytes checkSum[3] = (pos / 256).toByte() checkSum[4] = (pos % 256).toByte() checkSum[5] = sum[1] checkSum[6] = sum[0] if (pos == 112){ checkSum[1] = 0x02 checkSum[7] = 0x01 } transmitData(checkSum, ((pos.toFloat() / 0x70) * 100).toInt(), context) val pxls = byteArray if (pos == 112){ for (b in 0 until 32) { for (x in 0 until 16) { data[x + 4] = pxls[x + (b * 16)] } data[2] = ((b + 0x0E00)/ 256).toByte() data[3] = ((b + 0x0E00) % 256).toByte() sendData(data) } } else { for (b in 0 until 64) { for (x in 0 until 16) { data[x + 4] = pxls[x + (b * 16)] } data[2] = ((b + pos) / 256).toByte() data[3] = ((b + pos) % 256).toByte() sendData(data) } } }
0
Java
1
2
8ee0052ddd1b7b08b7dbf32dfd88a6b46c9036ce
5,599
wearfit2
MIT License
filelogger/src/main/java/abbasi/android/filelogger/file/FileWriter.kt
burakocak
507,634,847
false
{"Java Properties": 2, "Text": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 3, "Proguard": 2, "Kotlin": 13, "XML": 12, "INI": 1, "Java": 6}
/* * * Copyright (c) 2022 <NAME> * * */ package abbasi.android.filelogger.file import abbasi.android.filelogger.config.Constance.Companion.DIRECTORY import abbasi.android.filelogger.time.FastDateFormat import android.util.Log import java.io.File import java.io.FileOutputStream import java.io.OutputStreamWriter import java.util.* internal class FileWriter( private val directory: String, dataFormatterPattern: String ) { private var streamWriter: OutputStreamWriter? = null private var dateFormat: FastDateFormat? = null private var logFile: File? = null init { dateFormat = FastDateFormat.getInstance(dataFormatterPattern, Locale.US) try { val file = File(directory) val logDir = File(file.absolutePath + DIRECTORY) if (logDir.exists().not()) { logDir.mkdirs() } logFile = File(logDir, "${dateFormat?.format(System.currentTimeMillis())}.txt") } catch (e: Exception) { e.printStackTrace() } try { logFile?.createNewFile() val stream = FileOutputStream(logFile) streamWriter = OutputStreamWriter(stream).apply { write("File logger initialized at ${dateFormat?.format(System.currentTimeMillis())} \n\n\n") flush() } } catch (e: Exception) { e.printStackTrace() } } fun write(message: String) { streamWriter.takeIf { dateFormat != null }?.let { writer -> try { writer.write("${dateFormat?.format(System.currentTimeMillis())} $message") writer.flush() } catch (e: Exception) { Log.e(javaClass.simpleName, "e:", e) } } } fun deleteLogsDir() { val currentFile = File(directory) val logDir = File(currentFile.absolutePath + DIRECTORY) logDir.listFiles()?.filter { it.absolutePath != logFile?.absolutePath }?.forEach { it.delete() } } }
1
null
1
1
58c83c75b4be1b4bbb7d69e1a598841c18a33a1e
2,078
FileLogger
MIT License
app/src/main/java/com/bpdevop/mediccontrol/ui/components/MainAppScaffold.kt
bpdevop
839,980,935
false
{"Kotlin": 693059}
package com.bpdevop.mediccontrol.ui.components import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.AlertDialog import androidx.compose.material3.DrawerState import androidx.compose.material3.DrawerValue import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.bpdevop.mediccontrol.R import com.bpdevop.mediccontrol.core.extensions.navigateToLoginActivity import com.bpdevop.mediccontrol.core.utils.UiState import com.bpdevop.mediccontrol.ui.navigation.AppNavGraph import com.bpdevop.mediccontrol.ui.navigation.NavigationItem import com.bpdevop.mediccontrol.ui.navigation.Screen import com.bpdevop.mediccontrol.ui.viewmodels.DoctorProfileViewModel import com.bpdevop.mediccontrol.ui.viewmodels.MainViewModel import com.bpdevop.mediccontrol.ui.viewmodels.UserSessionViewModel import kotlinx.coroutines.launch @Composable fun MainAppScaffold() { val navController = rememberNavController() val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val scope = rememberCoroutineScope() val mainViewModel: MainViewModel = hiltViewModel() val sessionViewModel: UserSessionViewModel = hiltViewModel() val doctorProfileViewModel: DoctorProfileViewModel = hiltViewModel() val selectedItem by mainViewModel.selectedItem.collectAsState() var showLogoutDialog by remember { mutableStateOf(false) } var showMenu by remember { mutableStateOf(false) } val context = LocalContext.current val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route // Cargar el perfil del médico LaunchedEffect(Unit) { doctorProfileViewModel.getDoctorProfile() } val doctorProfileState by doctorProfileViewModel.doctorProfileState.collectAsState() val doctorName = when (doctorProfileState) { is UiState.Success -> (doctorProfileState as UiState.Success).data?.name ?: "Usuario" else -> "Usuario" } val (showBackArrow, topBarTitle) = rememberTopBarState(currentRoute, selectedItem) LaunchedEffect(navBackStackEntry) { val currentMenuItem = mainViewModel.getMenuItemByRoute(currentRoute) mainViewModel.selectItem(currentMenuItem ?: return@LaunchedEffect) } HandleLogoutDialog( showLogoutDialog = showLogoutDialog, onLogout = { sessionViewModel.signOut() context.navigateToLoginActivity() showLogoutDialog = false }, onDismissLogoutDialog = { showLogoutDialog = false } ) ModalNavigationDrawer( drawerState = drawerState, drawerContent = { MainDrawer( selectedItem = selectedItem, onItemClicked = { item -> scope.launch { navigateToItem(navController, item.route, drawerState) } }, userName = doctorName ) } ) { Scaffold( topBar = { TopBar( showBackArrow = showBackArrow, topBarTitle = topBarTitle, onBackClick = { navController.popBackStack() }, onMenuClick = { scope.launch { drawerState.open() } }, showMenu = showMenu, onMenuToggle = { showMenu = !showMenu }, onLogoutClick = { showLogoutDialog = true } ) } ) { innerPadding -> AppNavGraph( navController = navController, modifier = Modifier.padding(innerPadding) ) } } } @Composable fun rememberTopBarState(currentRoute: String?, selectedItem: NavigationItem?): Pair<Boolean?, String> { val showBackArrow = when (currentRoute) { null -> null Screen.Patients.route, Screen.Agenda.route, Screen.Profile.route, Screen.Export.route, -> false else -> true } val topBarTitle = when { currentRoute == Screen.Patients.route -> stringResource(id = Screen.Patients.titleResId) currentRoute == Screen.AddPatient.route -> stringResource(id = Screen.AddPatient.titleResId) currentRoute?.startsWith(Screen.PatientDetail.route) == true -> stringResource(id = Screen.PatientDetail.titleResId) currentRoute == Screen.Agenda.route -> stringResource(id = Screen.Agenda.titleResId) currentRoute == Screen.Profile.route -> stringResource(id = Screen.Profile.titleResId) currentRoute == Screen.Export.route -> stringResource(id = Screen.Export.titleResId) currentRoute == Screen.Settings.route -> stringResource(id = Screen.Settings.titleResId) currentRoute == Screen.About.route -> stringResource(id = Screen.About.titleResId) currentRoute?.startsWith(Screen.MedicalHistory.route) == true -> stringResource(id = Screen.MedicalHistory.titleResId) currentRoute?.startsWith(Screen.Vaccination.route) == true -> stringResource(id = Screen.Vaccination.titleResId) currentRoute?.startsWith(Screen.EditVaccination.route) == true -> stringResource(id = Screen.EditVaccination.titleResId) currentRoute?.startsWith(Screen.Allergy.route) == true -> stringResource(id = Screen.Allergy.titleResId) currentRoute?.startsWith(Screen.EditAllergy.route) == true -> stringResource(id = Screen.EditAllergy.titleResId) currentRoute?.startsWith(Screen.BloodPressure.route) == true -> stringResource(id = Screen.BloodPressure.titleResId) currentRoute?.startsWith(Screen.EditBloodPressure.route) == true -> stringResource(id = Screen.EditBloodPressure.titleResId) currentRoute?.startsWith(Screen.BloodGlucose.route) == true -> stringResource(id = Screen.BloodGlucose.titleResId) currentRoute?.startsWith(Screen.EditBloodGlucose.route) == true -> stringResource(id = Screen.EditBloodGlucose.titleResId) currentRoute?.startsWith(Screen.OxygenSaturation.route) == true -> stringResource(id = Screen.OxygenSaturation.titleResId) currentRoute?.startsWith(Screen.EditOxygenSaturation.route) == true -> stringResource(id = Screen.EditOxygenSaturation.titleResId) currentRoute?.startsWith(Screen.Examination.route) == true -> stringResource(id = Screen.Examination.titleResId) currentRoute?.startsWith(Screen.EditExamination.route) == true -> stringResource(id = Screen.EditExamination.titleResId) currentRoute?.startsWith(Screen.Prescription.route) == true -> stringResource(id = Screen.Prescription.titleResId) currentRoute?.startsWith(Screen.EditPrescription.route) == true -> stringResource(id = Screen.EditPrescription.titleResId) currentRoute?.startsWith(Screen.Laboratory.route) == true -> stringResource(id = Screen.Laboratory.titleResId) currentRoute?.startsWith(Screen.EditLaboratory.route) == true -> stringResource(id = Screen.EditLaboratory.titleResId) currentRoute?.startsWith(Screen.Radiology.route) == true -> stringResource(id = Screen.Radiology.titleResId) currentRoute?.startsWith(Screen.EditRadiology.route) == true -> stringResource(id = Screen.EditRadiology.titleResId) currentRoute?.startsWith(Screen.Appointment.route) == true -> stringResource(id = Screen.Appointment.titleResId) currentRoute?.startsWith(Screen.EditAppointment.route) == true -> stringResource(id = Screen.EditAppointment.titleResId) else -> selectedItem?.let { stringResource(id = it.titleResId) } ?: "" } return showBackArrow to topBarTitle } @OptIn(ExperimentalMaterial3Api::class) @Composable fun TopBar( showBackArrow: Boolean?, topBarTitle: String, onBackClick: () -> Unit, onMenuClick: () -> Unit, showMenu: Boolean, onMenuToggle: () -> Unit, onLogoutClick: () -> Unit, ) { TopAppBar( title = { Text(text = topBarTitle) }, navigationIcon = { val (icon, description, onClickAction) = when (showBackArrow) { true -> Triple(Icons.AutoMirrored.Filled.ArrowBack, "Back", onBackClick) false, null -> Triple(Icons.Default.Menu, "Menu", onMenuClick) } IconButton(onClick = onClickAction) { Icon(icon, contentDescription = description) } }, actions = { IconButton(onClick = onMenuToggle) { Icon(imageVector = Icons.Default.MoreVert, contentDescription = "More") } DropdownMenu( expanded = showMenu, onDismissRequest = onMenuToggle ) { DropdownMenuItem( text = { Text(stringResource(id = R.string.action_logout)) }, onClick = { onMenuToggle() onLogoutClick() } ) } }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer ) ) } @Composable private fun HandleLogoutDialog(showLogoutDialog: Boolean, onLogout: () -> Unit, onDismissLogoutDialog: () -> Unit) { if (showLogoutDialog) { AlertDialog( onDismissRequest = onDismissLogoutDialog, title = { Text(stringResource(id = R.string.action_logout)) }, text = { Text(stringResource(id = R.string.global_message_logout)) }, confirmButton = { TextButton(onClick = onLogout) { Text(stringResource(id = android.R.string.ok)) } }, dismissButton = { TextButton(onClick = onDismissLogoutDialog) { Text(stringResource(id = android.R.string.cancel)) } } ) } } private suspend fun navigateToItem(navController: NavHostController, route: String, drawerState: DrawerState) { drawerState.close() navController.navigate(route) { popUpTo(navController.graph.startDestinationId) { saveState = true } launchSingleTop = true restoreState = true } }
0
Kotlin
0
0
68aa078786199aca908f03965c617f096d91a384
11,754
MedicControl
MIT License
app/src/main/java/one/empty3/feature/app/maxSdk29/pro/data/LoginDataSource.kt
manuelddahmen
414,484,291
false
{"Java": 3683719, "Kotlin": 339317, "MATLAB": 18918, "HTML": 15428, "C++": 10463, "CSS": 2875, "GLSL": 1197, "Batchfile": 80}
package one.empty3.feature.app.maxSdk29.pro.data import android.os.StrictMode import android.os.StrictMode.ThreadPolicy import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import one.empty3.feature.app.maxSdk29.pro.data.model.LoggedInUser import one.empty3.feature.app.maxSdk29.pro.data.model.URLContentTask import java.io.IOException /** * Class that handles authentication w/ login credentials and retrieves user information. */ class LoginDataSource { fun login(username: String, password: String): Result<LoggedInUser> = runBlocking { val policy = ThreadPolicy.Builder().permitAll().build() StrictMode.setThreadPolicy(policy) try { val url: String = "https://empty3.app/agenda/src/android/login.php?username=$username&password=$password" val sb = StringBuilder("") val urlContentTask = URLContentTask() val job = launch { // launch a new coroutine and keep a reference to its Job val contentFromURL = urlContentTask.loadUrlAsString(url) urlContentTask.ConvertToInt(contentFromURL) println("Get HTTPS") } println("Job launched") job.join() // wait until child coroutine completes println("Job Done") Result.Success(LoggedInUser.getCurrentUser()) } catch (ex: Throwable) { System.err.println("Error logging in" + ex.message) Result.Error(IOException("Error logging in" + ex.message)) } Result.Error(NullPointerException("Return null")) } fun logout() { // TODO: revoke authentication } }
1
Java
0
0
a94ba1f7f40c183a236454de67622876bef92950
1,667
featureApp
Apache License 2.0
decoder/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/context/TypeContext.kt
CharlieTap
743,980,037
false
{"Kotlin": 2038041, "WebAssembly": 45714}
package io.github.charlietap.chasm.decoder.context import io.github.charlietap.chasm.ast.module.Type import io.github.charlietap.chasm.ast.type.DefinedType import io.github.charlietap.chasm.type.factory.DefinedTypeFactory internal interface TypeContext { val types: MutableList<Type> val definedTypes: List<DefinedType> } internal data class TypeContextImpl( override val types: MutableList<Type> = mutableListOf(), ) : TypeContext { override val definedTypes: List<DefinedType> by lazy { DefinedTypeFactory(types.map(Type::recursiveType)) } }
5
Kotlin
3
67
a452ab9e37504517b43118f636a28f54e7bcb57c
575
chasm
Apache License 2.0
components/core/ui/decompose/src/commonMain/kotlin/com/flipperdevices/ui/decompose/internal/WindowDecorator.kt
flipperdevices
288,258,832
false
{"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.ui.decompose.internal internal interface WindowDecorator { fun decorate() }
21
Kotlin
174
1,528
8f293e596741a6c97409acbc8de10c7ae6e8d8b0
108
Flipper-Android-App
MIT License
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/persistence/entity/messages/ParentMessageDb.kt
sceyt
549,073,085
false
{"Kotlin": 2713714, "Java": 107920}
package com.sceyt.chatuikit.persistence.entity.messages import androidx.room.Embedded import androidx.room.Relation import com.sceyt.chatuikit.persistence.entity.user.UserDb import com.sceyt.chatuikit.persistence.entity.user.UserEntity data class ParentMessageDb( @Embedded val messageEntity: MessageEntity, @Relation(parentColumn = "fromId", entityColumn = "user_id", entity = UserEntity::class) val from: UserDb?, @Relation(parentColumn = "tid", entityColumn = "messageTid", entity = AttachmentEntity::class) val attachments: List<AttachmentDb>?, @Relation(parentColumn = "tid", entityColumn = "messageTid", entity = MentionUserMessageLink::class) val mentionedUsers: List<MentionUserDb>? )
0
Kotlin
1
2
92717e7a0201600396bacddaa279f8a07a298650
761
sceyt-chat-android-uikit
MIT License
playground/sandbox-compose/src/main/kotlin/com/sdds/playground/sandbox/checkbox/group/CheckBoxGroupScreen.kt
salute-developers
765,665,583
false
{"Kotlin": 1289649}
package com.sdds.playground.sandbox.checkbox.group import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.tooling.preview.Preview import androidx.lifecycle.viewmodel.compose.viewModel import com.sdds.playground.sandbox.SandboxTheme import com.sdds.playground.sandbox.core.ComponentScaffold /** * Экран с [SandboxCheckBoxGroup] */ @Composable internal fun CheckBoxGroupScreen() { val checkboxGroupViewModel: CheckBoxGroupParametersViewModel = viewModel(CheckBoxGroupParametersViewModel::class.java) val checkboxGroupState by checkboxGroupViewModel.checkboxGroupState.collectAsState() ComponentScaffold( component = { SandboxCheckBoxGroup( items = checkboxGroupState.items, rootItem = checkboxGroupState.rootItem, size = checkboxGroupState.size, enabled = checkboxGroupState.enabled, ) }, propertiesOwner = checkboxGroupViewModel, ) } /** * Превью [CheckBoxGroupScreen] */ @Preview(showBackground = true) @Composable private fun ButtonsScreenPreview() { SandboxTheme { CheckBoxGroupScreen() } }
3
Kotlin
0
1
8a427b5746eb2e36e967fff4db32e86a27790ced
1,256
plasma-android
MIT License
generator/graphql-kotlin-schema-generator/src/test/kotlin/com/expediagroup/graphql/generator/internal/types/GenerateListTest.kt
ExpediaGroup
148,706,161
false
{"Kotlin": 2410561, "MDX": 720089, "HTML": 12165, "JavaScript": 10447, "CSS": 297, "Dockerfile": 147}
/* * Copyright 2022 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.generator.internal.types import graphql.schema.GraphQLList import graphql.schema.GraphQLNamedType import graphql.schema.GraphQLTypeUtil import org.junit.jupiter.api.Test import kotlin.test.assertEquals class GenerateListTest : TypeTestHelper() { private data class MyDataClass(val id: String) private class ClassWithList { val testList: List<Int> = listOf(1) val testListOfClass: List<MyDataClass> = listOf(MyDataClass("bar")) } @Test fun `verify a list of primitives for output`() { val listProp = ClassWithList::testList val result = generateList(generator, listProp.returnType, GraphQLKTypeMetadata()) assertEquals("Int", getListTypeName(result)) } @Test fun `verify a list of objects for ouput`() { val listProp = ClassWithList::testListOfClass val result = generateList(generator, listProp.returnType, GraphQLKTypeMetadata()) assertEquals("MyDataClass", getListTypeName(result)) } @Test fun `verify a list of primitives for input`() { val listProp = ClassWithList::testList val result = generateList(generator, listProp.returnType, GraphQLKTypeMetadata(inputType = true)) assertEquals("Int", getListTypeName(result)) } @Test fun `verify a list of objects for input`() { val listProp = ClassWithList::testListOfClass val result = generateList(generator, listProp.returnType, GraphQLKTypeMetadata(inputType = true)) assertEquals("MyDataClassInput", getListTypeName(result)) } private fun getListTypeName(list: GraphQLList) = (GraphQLTypeUtil.unwrapNonNull(list.wrappedType) as? GraphQLNamedType)?.name }
68
Kotlin
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
2,327
graphql-kotlin
Apache License 2.0
ground/src/main/java/com/google/android/ground/system/GeocodingManager.kt
google
127,777,820
false
null
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.android.ground.system import android.content.res.Resources import android.location.Address import android.location.Geocoder import com.google.android.ground.R import com.google.android.ground.coroutines.IoDispatcher import com.google.android.ground.model.geometry.Coordinates import com.google.android.ground.ui.map.Bounds import com.google.android.ground.ui.map.gms.GmsExt.center import java.io.IOException import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import timber.log.Timber /** Abstracts native geocoding facilities. */ @Singleton class GeocodingManager @Inject constructor( private val geocoder: Geocoder, @IoDispatcher private val ioDispatcher: CoroutineDispatcher, resources: Resources ) { private val defaultAreaName: String = resources.getString(R.string.unnamed_area) private val multipleRegionsLabel: String = resources.getString(R.string.multiple_regions) /** * Retrieve a human readable name for the region bounded by the provided {@param bounds}. * * If no area name is found for the given area, returns a default value. */ @Throws(IOException::class) suspend fun getAreaName(bounds: Bounds): String { // Get potential addresses of five sample points: the centroid and the four vertices of the // bounding box. val samplePoints = bounds.corners + bounds.center() val samplePointAddresses = withContext(ioDispatcher) { samplePoints.map { fetchAddressesBlocking(it) } } val nameComponents = findCommonComponents( samplePointAddresses.filter { it.isNotEmpty() }, Address::getCountryName, Address::getAdminArea, Address::getSubAdminArea, Address::getLocality ) return when (nameComponents.size) { 0 -> defaultAreaName 1 -> "$multipleRegionsLabel, ${nameComponents.first()}" else -> nameComponents.joinToString(", ") } } /** * Calls getters in order on all [Address]es and returns names present in all other entries * present in [samplePointAddresses]. If a common name is not found, searching stops and further * getters are not called. This allows the caller to build an area name out of multiple addresses * by finding the largest common admin unit name among provided addresses. */ private fun findCommonComponents( samplePointAddresses: List<List<Address>>, vararg getters: (Address) -> String? ): MutableList<String> { val commonComponents = mutableListOf<String>() for (getter in getters) { val samplePointNames = samplePointAddresses.map { it.mapNotNull(getter::invoke) }.filter { it.isNotEmpty() } val commonElements = getCommonComponents(samplePointNames) if (commonElements.isNotEmpty()) { // Choose the shortest common name. If two names have the same length, use whichever comes // first alphabetically. val selectedName = commonElements.sortedWith(compareBy({ it.length }, { it })).first() commonComponents.add(0, selectedName) } } return commonComponents } /** * Returns the distinct list of Strings which appear at least once in all sub-lists, or an empty * list if none are found. */ private fun getCommonComponents(samplePointNames: List<List<String>>): List<String> = // Require at least two vertices with non-null area labels to identify a common name. if (samplePointNames.size < 2) listOf() else samplePointNames.first().distinct().filter { el -> samplePointNames.drop(0).all { it.contains(el) } } /** * Fetches potential addresses for the specified coordinates. Blocks the thread on I/O; do not * call on main thread. */ private fun fetchAddressesBlocking(coordinates: Coordinates): List<Address> = // TODO(#1762): Replace with non-blocking call with listener. try { geocoder.getFromLocation(coordinates.lat, coordinates.lng, 5) ?: listOf() } catch (e: Exception) { Timber.e(e, "Reverse geocode lookup failed") listOf() } }
235
null
115
245
bb5229149eb3687923a8391f30f7279e477562a8
4,709
ground-android
Apache License 2.0
ArTalkNotificationCore/src/main/java/ir/araditc/anc/service/FirebaseMessagingService.kt
araditc
732,369,415
false
{"Kotlin": 5794}
package ir.araditc.anc.service import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class FirebaseMessagingService : FirebaseMessagingService() { override fun onMessageReceived(remoteMessage: RemoteMessage) { val json = remoteMessage.data val notification = remoteMessage.notification?.title; } override fun onNewToken(token: String) { super.onNewToken(token) } }
0
Kotlin
0
0
82e8f0e4845e83044cde3c4ea4114ea63cecb4a7
468
Arad.Push.Android.SDK
MIT License
modules/api-local/src/main/kotlin/ru/astrainteractive/astratemplate/api/local/mapping/UserMapperImpl.kt
Astra-Interactive
378,620,934
false
null
package ru.astrainteractive.astratemplate.api.local.mapping import ru.astrainteractive.astratemplate.api.dto.UserDTO import ru.astrainteractive.astratemplate.api.local.entities.UserDAO import ru.astrainteractive.klibs.mikro.core.domain.Mapper interface UserMapper : Mapper<UserDAO, UserDTO> object UserMapperImpl : UserMapper { override fun fromDTO(it: UserDTO): UserDAO { throw NotImplementedError() } override fun toDTO(it: UserDAO): UserDTO = UserDTO( id = it.id, discordId = it.discordId, minecraftUUID = it.minecraftUuid ) }
0
Kotlin
0
13
593a4d31150d76439d1b386206e3f54b67abfff3
582
AstraTemplate
MIT License
app/src/main/java/com/hypertrack/android/ui/screens/add_place_info/AddPlaceInfoViewModel.kt
hypertrack
241,723,736
false
null
@file:Suppress("OPT_IN_USAGE") package com.hypertrack.android.ui.screens.add_place_info import android.annotation.SuppressLint import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.Circle import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import com.google.maps.android.SphericalUtil import com.hypertrack.android.interactors.GeocodingInteractor import com.hypertrack.android.interactors.PlacesInteractor import com.hypertrack.android.interactors.app.GeofencesForMapUpdatedEvent import com.hypertrack.android.interactors.app.state.UserLoggedIn import com.hypertrack.android.repository.IntegrationsRepository import com.hypertrack.android.ui.base.BaseViewModel import com.hypertrack.android.ui.base.BaseViewModelDependencies import com.hypertrack.android.ui.base.Consumable import com.hypertrack.android.ui.common.delegates.address.GooglePlaceAddressDelegate import com.hypertrack.android.ui.common.map.HypertrackMapItemsFactory import com.hypertrack.android.ui.common.map.HypertrackMapWrapper import com.hypertrack.android.ui.common.map.MapParams import com.hypertrack.android.ui.common.map_state.AddGeofencesMapUiAction import com.hypertrack.android.ui.common.map_state.MapUiEffectHandler import com.hypertrack.android.ui.common.map_state.MapUiReducer import com.hypertrack.android.ui.common.use_case.get_error_message.asError import com.hypertrack.android.ui.common.util.isNearZero import com.hypertrack.android.ui.common.util.postValue import com.hypertrack.android.use_case.error.LogExceptionToCrashlyticsUseCase import com.hypertrack.android.utils.* import com.hypertrack.android.utils.exception.IllegalActionException import com.hypertrack.android.utils.formatters.MetersDistanceFormatter import com.hypertrack.android.utils.state_machine.ReducerResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flatMapConcat import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext //todo persist address state in create geofence scope? class AddPlaceInfoViewModel( private val location: LatLng, private val initialAddress: String?, private val _name: String?, baseDependencies: BaseViewModelDependencies, private val userStateFlow: StateFlow<UserLoggedIn?>, private val placesInteractor: PlacesInteractor, private val geocodingInteractor: GeocodingInteractor, private val integrationsRepository: IntegrationsRepository, private val distanceFormatter: MetersDistanceFormatter, private val mapItemsFactory: HypertrackMapItemsFactory, private val mapUiReducer: MapUiReducer, private val mapUiEffectHandler: MapUiEffectHandler, private val logExceptionToCrashlyticsUseCase: LogExceptionToCrashlyticsUseCase, ) : BaseViewModel(baseDependencies) { val viewState = MutableLiveData<ViewState>() val adjacentGeofenceDialogEvent = MutableLiveData<Consumable<GeofenceCreationParams>>() private val addressDelegate = GooglePlaceAddressDelegate(osUtilsProvider) private val reducer = AddPlaceInfoReducer(distanceFormatter, mapUiReducer) private val stateMachine = StateMachine<Action, State, Effect>( javaClass.simpleName, crashReportsProvider, Initial(), actionsScope, this::reduce, this::applyEffects, this::stateChangeEffects ) private val effectsHandler = AddPlaceInfoEffectsHandler( appInteractor, location, this::init, this::handleAction, viewState, destination, adjacentGeofenceDialogEvent, placesInteractor, mapItemsFactory, mapUiEffectHandler, getErrorMessageUseCase, showErrorUseCase, logExceptionToCrashlyticsUseCase, userStateFlow.mapState(appInteractor.appScope.actionsScope) { it?.geofencesForMap } ) init { runInVmEffectsScope { appInteractor.appEvent.collect { when (it) { is GeofencesForMapUpdatedEvent -> { handleAction(MapUiAction(AddGeofencesMapUiAction(it.geofences))) } else -> { } } } } } fun handleAction(action: Action) { stateMachine.handleAction(action) } private fun reduce(state: State, action: Action): ReducerResult<out State, out Effect> { return userStateFlow.value?.let { reducer.reduce(action, state, it) } ?: IllegalActionException(action, state).let { exception -> state.withEffects( LogExceptionToCrashlyticsEffect(exception), ShowErrorMessageEffect(exception.asError()) ) } } @SuppressLint("MissingPermission") fun onMapReady(googleMap: GoogleMap) { HypertrackMapWrapper( googleMap, osUtilsProvider, crashReportsProvider, MapParams( enableScroll = false, enableZoomKeys = true, enableMyLocationButton = false, enableMyLocationIndicator = false ) ).apply { setOnCameraMovedListener { handleAction(MapMovedAction(it)) } setOnMarkerClickListener { //todo effect it.snippet?.let { destination.postValue( AddPlaceInfoFragmentDirections.actionGlobalPlaceDetailsFragment( geofenceId = it ) ) } } }.also { handleAction(MapReadyAction(it)) } } private fun applyEffects(effects: Set<Effect>) { effects.forEach { effect -> runInVmEffectsScope { effectsHandler.getEffectFlow(effect) .catchException { onError(it) } .collect { actions -> actions.forEach { handleAction(it) } } } } } private fun stateChangeEffects(newState: State): Set<Effect> { return setOf(UpdateViewStateEffect(newState)) } private suspend fun init(map: HypertrackMapWrapper) { suspend { integrationsRepository.hasIntegrations() }.asFlow().flatMapConcat { res -> when (res) { is Success -> { suspend { loadAddress() }.asFlow().map { address -> InitFinishedAction( map = map, hasIntegrations = res.data, address = address, geofenceName = _name, location = location ) } } is Failure -> { handleErrorFlow(res.exception) } } }.collect { handleAction(it) } } private fun handleErrorFlow(exception: Exception): Flow<OnErrorAction> { return logExceptionToCrashlyticsUseCase.execute(exception).map { OnErrorAction(exception.asError()) } } private suspend fun loadAddress(): String? { return initialAddress ?: withContext(Dispatchers.IO) { geocodingInteractor.getPlaceFromCoordinates(location)?.let { addressDelegate.strictAddress(it) } } } }
1
Kotlin
17
31
7a613e4b618043d95e101b819d903c3b1eda6773
7,884
visits-android
MIT License
src/main/kotlin/util/MoulConfigFragment.kt
nea89o
637,563,904
false
{"Kotlin": 661685, "Java": 144356, "GLSL": 2115, "Nix": 1217}
package moe.nea.firmament.util import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper import io.github.notenoughupdates.moulconfig.gui.GuiContext import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext import me.shedaniel.math.Point import net.minecraft.client.gui.DrawContext class MoulConfigFragment( context: GuiContext, val position: Point, val dismiss: () -> Unit ) : GuiComponentWrapper(context) { init { this.init(MC.instance, MC.screen!!.width, MC.screen!!.height) } override fun createContext(drawContext: DrawContext?): GuiImmediateContext { val oldContext = super.createContext(drawContext) return oldContext.translated( position.x, position.y, context.root.width, context.root.height, ) } override fun render(drawContext: DrawContext?, i: Int, j: Int, f: Float) { val ctx = createContext(drawContext) val m = drawContext!!.matrices m.push() m.translate(position.x.toFloat(), position.y.toFloat(), 0F) context.root.render(ctx) m.pop() ctx.renderContext.doDrawTooltip() } override fun close() { dismiss() } }
25
Kotlin
6
37
0357245e88be4b8cd3d0681340d9a7065361ea74
1,242
Firmament
Apache License 2.0
src/day07/Node.kt
Puju2496
576,611,911
false
null
package day07 typealias Visitor = (Node) -> Unit enum class NodeType { DIR, FILE } class Node(val name: String, var size: Long = 0L, val type: NodeType, val parent: Node? = null, var children: MutableList<Node> = mutableListOf()) { fun addNode(childNode: Node) = children.add(childNode) fun updateNode(size: Long) { this.size = size } fun depthSearch(visit: Visitor) { visit(this) children.forEach { it.depthSearch(visit) } } fun searchValue(value: String): Node? { var result: Node? = null depthSearch { if (it.name == value) { result = it } } return result } fun calculateSize(): Long { var size = this.size children.forEach { size += when (it.type) { NodeType.DIR -> it.calculateSize() else -> it.size } } if (this.type == NodeType.DIR) this.updateNode(size) return size } }
0
Kotlin
0
0
e3b88d0bd948aaf2c831071fb767f08348e30213
1,057
advent-of-code-2022
Apache License 2.0
app/src/main/java/com/longdo/api3/controller/Util.kt
MetamediaTechnology
435,746,992
false
null
package com.longdo.api3.controller import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.Snackbar import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.longdo.api3.viewModel.LongdoMapViewModel @Composable fun MenuItem( onClick: () -> Unit, text: String ) { TextButton( onClick = onClick, modifier = Modifier .fillMaxWidth() .height(64.dp) ) { Text( text = text, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } @OptIn(ExperimentalAnimationApi::class) @Composable fun Snackbar() { val vm = viewModel<LongdoMapViewModel>() val zoomLevel = vm.snackBar.observeAsState("") AnimatedVisibility(visible = zoomLevel.value != "") { Snackbar { Text(text = zoomLevel.value) } } }
0
Kotlin
0
0
0ddb9a218a59564a2a5fb4cd5f8e819787776661
1,356
longdo-map-sdk3-android
Apache License 2.0
shared/src/commonMain/kotlin/ui/screens/HomeMenu.kt
ShreyashKore
672,328,509
false
{"Kotlin": 798650, "Swift": 626, "Shell": 228, "Ruby": 101}
package ui.screens import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material3.Divider import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import models.Wonder import models.Wonders import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import ui.AppIcons import ui.composables.AppIconButton import ui.homeBtn import ui.theme.fgColor import ui.theme.offWhite import ui.theme.white @Composable fun HomeMenu( data: Wonder, onPressBack: () -> Unit, onChangeWonder: (Wonder) -> Unit, openTimeline: () -> Unit, openCollection: () -> Unit, modifier: Modifier = Modifier, ) = BoxWithConstraints { val btnSize = (maxWidth / 5).coerceIn(60.dp, 100.dp) var isAboutDialogOpen by remember { mutableStateOf(false) } if (isAboutDialogOpen) { AboutApp(onDismissRequest = { isAboutDialogOpen = false }) } Column(modifier) { // AppHeader AppHeader( onClickClose = onPressBack, onToggleLanguage = { /* TODO - localization */ }, ) // Content Box( modifier = Modifier.fillMaxSize().padding(horizontal = 48.dp), contentAlignment = Alignment.Center, ) { Column( modifier = Modifier.fillMaxWidth() .wrapContentHeight(align = Alignment.CenterVertically), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(modifier = Modifier.height(50.dp)) // Wonder Buttons Grid WonderBtnsGrid( currentWonder = data, onSelectWonder = onChangeWonder, btnSize = btnSize, ) Spacer(modifier = Modifier.height(24.dp)) // Bottom buttons Column( horizontalAlignment = Alignment.CenterHorizontally ) { BottomButton( onClick = openTimeline, icon = AppIcons.Timeline, text = "Explore the timeline" ) Divider(modifier = Modifier.height(1.dp), color = Color.Gray) BottomButton( onClick = openCollection, icon = AppIcons.Collection, text = "View your collections" ) Divider(modifier = Modifier.height(1.dp), color = Color.Gray) BottomButton( onClick = { isAboutDialogOpen = true }, icon = AppIcons.Info, text = "About this app" ) } Spacer(modifier = Modifier.height(16.dp)) } } } } @Composable fun AppHeader( onClickClose: () -> Unit, onToggleLanguage: () -> Unit, ) { Row(Modifier.fillMaxWidth().height(72.dp).padding(8.dp)) { AppIconButton( iconPath = AppIcons.Close, contentDescription = "Close", onClick = onClickClose, ) Spacer(Modifier.weight(1f)) AppIconButton( iconPath = AppIcons.Info, contentDescription = "Change Language", onClick = onToggleLanguage, ) } } val modifiedWondersList = Wonders.toMutableList<Wonder?>().apply { add(4, null) } @OptIn(ExperimentalResourceApi::class) @Composable fun WonderBtnsGrid( currentWonder: Wonder, onSelectWonder: (Wonder) -> Unit, btnSize: Dp ) = LazyVerticalGrid( modifier = Modifier.wrapContentWidth(), columns = GridCells.Fixed(3), userScrollEnabled = false, horizontalArrangement = Arrangement.Center ) { val shape = RoundedCornerShape(10.dp) items( modifiedWondersList ) { wonder -> if (wonder == null) Box( Modifier.padding(8.dp).size(btnSize), contentAlignment = Alignment.Center, ) { Image( painterResource("images/common/compass_full.xml"), contentDescription = null, modifier = Modifier.size(24.dp) ) } else IconButton( onClick = { onSelectWonder(wonder) } ) { Image( painterResource(wonder.homeBtn), contentDescription = wonder.title, modifier = Modifier .padding(8.dp) .size(btnSize) .clip(shape) .background(wonder.fgColor) .run { if (currentWonder == wonder) border( width = 6.dp, color = offWhite, shape = shape ) else this } ) } } } @OptIn(ExperimentalResourceApi::class) @Composable private fun BottomButton( onClick: () -> Unit, icon: String, text: String ) { TextButton( onClick = onClick, modifier = Modifier.padding(8.dp) ) { Row( verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(icon), contentDescription = null, tint = white, modifier = Modifier.size(32.dp) ) Spacer(modifier = Modifier.width(4.dp)) Text( text = text, style = TextStyle(fontWeight = FontWeight.Bold), color = white, ) } } }
0
Kotlin
0
2
eb224af728eff2087d5f6cb624c3a1b711b996ce
7,609
wonderous_compose
Apache License 2.0
build-logic/convention/src/main/kotlin/com/wei/teachlink/TlBuildType.kt
azrael8576
584,299,514
false
{"Kotlin": 520337}
package com.wei.teachlink /** * This is shared between :app module to provide configurations type safety. */ enum class TlBuildType(val applicationIdSuffix: String? = null) { DEBUG(".debug"), RELEASE, }
13
Kotlin
1
18
60c2f3adac40f1a4189cf1a01b2b59f529f8b662
214
teachlink
Apache License 2.0
plugins/kotlin/idea/tests/testData/inspectionsLocal/removeExplicitTypeArguments/removeTypeArgumentsFromProperty.kt
NielsDoucet
78,524,818
false
{"Text": 6274, "XML": 6297, "YAML": 418, "Ant Build System": 13, "Shell": 563, "Markdown": 560, "Ignore List": 94, "Git Attributes": 10, "EditorConfig": 233, "Batchfile": 27, "SVG": 2354, "Java": 74637, "C++": 34, "HTML": 2883, "Kotlin": 39545, "DTrace": 1, "Gradle": 448, "Java Properties": 205, "INI": 415, "JFlex": 31, "CSS": 56, "Groovy": 3452, "XSLT": 112, "JavaScript": 206, "JSON": 858, "desktop": 1, "Python": 12056, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 275, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 5, "C#": 37, "Smalltalk": 17, "Diff": 131, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "Objective-C": 22, "CoffeeScript": 3, "HTTP": 2, "JSON with Comments": 59, "GraphQL": 49, "OpenStep Property List": 46, "Tcl": 1, "fish": 1, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 86, "Vim Script": 7, "Vim Snippet": 3, "Vim Help File": 2, "Starlark": 2, "E-mail": 18, "Roff": 245, "Roff Manpage": 39, "Swift": 3, "Maven POM": 76, "C": 47, "TOML": 47, "Proguard": 2, "Checksums": 58, "Java Server Pages": 8, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 14, "VBScript": 1, "NSIS": 5, "PlantUML": 5, "Thrift": 3, "Cython": 14, "reStructuredText": 56, "Regular Expression": 3, "JSON5": 4}
// FIX: Remove explicit type arguments // WITH_RUNTIME val foo: MutableList<String> = mutableListOf<String<caret>>()
1
null
1
1
d14025504c582d922141343de97441b2fc226b29
116
intellij-community
Apache License 2.0
data/src/main/java/com/example/data/entity/specie/SpecieEntity.kt
Yang-Seungmin
417,730,494
false
{"Kotlin": 92702}
package com.example.data.entity.specie import com.google.gson.annotations.SerializedName import java.io.Serializable data class SpecieEntity( val name: String, val classification: String, val designation: String, @SerializedName("average_height") val averageHeight: String, @SerializedName("skin_colors") val skinColors: String, @SerializedName("hair_colors") val hairColors: String, @SerializedName("eye_colors") val eyeColors: String, @SerializedName("average_lifespan") val averageLifespan: String, val homeworld: String, val language: String, val people: List<String>, val films: List<String>, val created: String, val edited: String, val url: String ) : Serializable
1
Kotlin
2
3
c9325b4b1b81ca46c90f258f4b382ce49b50aec1
754
clean-architecture-sample-android
Apache License 2.0
chat-sdk/src/main/java/ru/usedesk/chat_sdk/data/repository/api/entity/CreateChatResponse.kt
usedesk
127,645,126
false
null
package ru.usedesk.chat_sdk.data.repository.api.entity class CreateChatResponse( val status: String, val chatId: Long, val token: String )
0
Kotlin
6
3
55ff54eb258bd586d71f7a0de755cae20105ce70
151
Android_SDK
MIT License
src/commonMain/kotlin/eu/vendeli/rethis/types/options/FunctionRestoreOption.kt
vendelieu
861,014,428
false
{"Kotlin": 213441, "Shell": 1248}
package eu.vendeli.rethis.types.options sealed class FunctionRestoreOption { data object FLUSH : FunctionRestoreOption() data object APPEND : FunctionRestoreOption() data object REPLACE : FunctionRestoreOption() }
5
Kotlin
0
7
8ae609b5430e9ca9255c5a1cba2bdfc70e316020
227
re.this
Apache License 2.0
kota-support-v4/src/dialogs/AlertsV4.kt
hendraanggrian
90,611,601
false
{"Kotlin": 304601}
@file:JvmMultifileClass @file:JvmName("DialogsV4Kt") @file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.app.AlertDialog import android.support.annotation.StringRes import android.support.v4.app.Fragment @JvmOverloads inline fun Fragment.alert( noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = context!!.alert(init) @JvmOverloads inline fun Fragment.alert( message: CharSequence, title: CharSequence? = null, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = context!!.alert(message, title, init) @JvmOverloads inline fun Fragment.alert( @StringRes message: Int, @StringRes title: Int? = null, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = context!!.alert(message, title, init)
0
Kotlin
0
6
df5c9f6add0c469d54e19ce2ff9b110563c92f33
810
kota
Apache License 2.0
src/test/kotlin/io/github/markgregg/common/api/utils/StubRequest.kt
markgregg
565,567,948
false
{"Kotlin": 35072}
package io.github.markgregg.common.api.utils import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import io.github.markgregg.common.api.Request class StubRequest( val parameters: Map<String,String>?, val body: String ) : io.github.markgregg.common.api.Request { private var json: ObjectNode? = null override fun getItem(name: String): Any { return when(name) { "text" -> body "body" -> json() "parameter" -> try { jacksonObjectMapper().valueToTree(parameters) } catch (e: Exception) { jacksonObjectMapper().createObjectNode() } else -> throw Exception("$name is not part of this request") } } private fun json(): ObjectNode { if( json == null ) { json = try { jacksonObjectMapper().readTree(body) as? ObjectNode ?: jacksonObjectMapper().createObjectNode() } catch (e: Exception) { jacksonObjectMapper().createObjectNode() } } return json!! } }
0
Kotlin
0
0
66fc5d6c7e659e696674727bac87bfb2ac9029e6
1,173
adaptable-common
Apache License 2.0
app/src/main/java/com/lanier/foxcomposepractice/model/PokemonListModel.kt
taxeric
398,469,729
false
null
package com.lanier.foxcomposepractice.model import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.cachedIn import com.lanier.foxcomposepractice.base.BaseViewModel import com.lanier.foxcomposepractice.data.PokeListDataSource import com.lanier.foxcomposepractice.repo.PokemonListRepo /** * Author: 芒硝 * Email : <EMAIL> * Date : 2021/8/18 14:26 * Desc : list model */ class PokemonListModel: BaseViewModel() { private val repo = PokemonListRepo() val pager = Pager( PagingConfig( pageSize = 20, //一次加载20条 prefetchDistance = 1, //距离结尾处几个时候开始加载下一页 enablePlaceholders = true ) ){ PokeListDataSource(repo) }.flow.cachedIn(viewModelScope) }
0
Kotlin
2
9
31ad9d7e2440c43d0380143ec01818c60fe8781c
795
PokeCompose
Apache License 2.0
app/src/main/java/com/robert/android/lostpets/domain/repository/SettingsRepository.kt
robertene1994
303,119,114
false
null
package com.robert.android.lostpets.domain.repository /** * Interfaz del respositorio para las preferencias (ajustes de la aplicación) que el usuario * puede establecer para la aplicación. * * @author Robert Ene */ interface SettingsRepository { /** * Método que devuelve la preferencia del usuario sobre el idioma de la aplicación. * * @return la preferencia del usuario sobre el idioma de la aplicación. */ fun getLanguage(): String? /** * Método que guarda la preferencia del usuario sobre el idioma de la aplicación. * * @param language la preferencia del usuario sobre el idioma de la aplicación. */ fun saveLanguage(language: String) }
0
Kotlin
0
0
a7af7de031d3ab4e2d14851a117d3729330cd875
706
lostpets-android
MIT License
api/src/main/kotlin/com/rolldebee/rolldebee/database/red/RedConstraintRouteBuilder.kt
kouprlabs
603,971,753
false
null
package com.rolldebee.rolldebee.database.red import com.rolldebee.rolldebee.core.ConstraintGraph import com.rolldebee.rolldebee.core.ConstraintRoute import com.rolldebee.rolldebee.core.ConstraintRouteBuilder import org.springframework.stereotype.Service @Service class RedConstraintRouteBuilder : ConstraintRouteBuilder { override fun build(constraintGraph: ConstraintGraph): ConstraintRoute { val nodes = ArrayList<ConstraintGraph.Node>() for (node in constraintGraph.nodes) { recurse(nodes, node) } return ConstraintRoute(constraints = nodes.map { it.constraint }) } private fun recurse(nodes: ArrayList<ConstraintGraph.Node>, node: ConstraintGraph.Node) { if (nodes.any { it.constraint.name == node.constraint.name }) { return } for (dependency in node.dependencies) { recurse(nodes, dependency) } nodes.add(node) } }
0
Kotlin
1
2
3c8366db6793516732d4a68096d4f3ba99716acb
948
rolldebee
MIT License
yaorm/src/main/java/org/roylance/yaorm/utilities/migration/PropertyModelComparisonUtil.kt
roylanceMichael
43,471,745
false
{"Markdown": 2, "Gradle": 14, "Ignore List": 2, "Text": 1, "XML": 6, "OpenStep Property List": 2, "Java Properties": 6, "Java": 19, "Kotlin": 112, "Shell": 6, "Batchfile": 2, "INI": 5, "Protocol Buffer": 9, "Swift": 2, "HTML": 1, "JavaScript": 3, "CSS": 1, "JSON": 2}
package org.roylance.yaorm.utilities.migration import org.roylance.yaorm.YaormModel object PropertyModelComparisonUtil { fun addDifferenceIfDifferent( name:String, currentProperty: YaormModel.ColumnDefinition?, otherProperty: YaormModel.ColumnDefinition?, differenceReports: MutableList<YaormModel.Difference>, tableDefinition: YaormModel.TableDefinition) { if (currentProperty == null && otherProperty != null) { val difference = YaormModel.Difference.newBuilder() .setEntityType(YaormModel.Difference.EntityType.COLUMN) .setOperation(YaormModel.Difference.Operation.DROP) .setName(name) .setPropertyDefinition(otherProperty) .setTableDefinition(tableDefinition) .build() differenceReports.add(difference) } if (currentProperty != null && otherProperty == null) { val difference = YaormModel.Difference.newBuilder() .setEntityType(YaormModel.Difference.EntityType.COLUMN) .setOperation(YaormModel.Difference.Operation.CREATE) .setName(name) .setPropertyDefinition(currentProperty) .setTableDefinition(tableDefinition) .build() differenceReports.add(difference) } if (currentProperty != null && otherProperty != null && (currentProperty.name != otherProperty.name || currentProperty.type != otherProperty.type)) { val dropDifference = YaormModel.Difference.newBuilder() .setEntityType(YaormModel.Difference.EntityType.COLUMN) .setOperation(YaormModel.Difference.Operation.DROP) .setName(name) .setPropertyDefinition(otherProperty) .setTableDefinition(tableDefinition) .build() differenceReports.add(dropDifference) val createDifference = YaormModel.Difference.newBuilder() .setEntityType(YaormModel.Difference.EntityType.COLUMN) .setOperation(YaormModel.Difference.Operation.CREATE) .setName(name) .setPropertyDefinition(currentProperty) .setTableDefinition(tableDefinition) .build() differenceReports.add(createDifference) } } }
1
null
1
1
df672db4e16d84885ec3aa84e74c57e1e9bc1ce3
2,570
yaorm
MIT License
src/main/kotlin/br/com/acmattos/hdc/person/port/rest/PersonControllerEndpointDefinition.kt
acmattos
225,613,144
false
{"Kotlin": 955728, "JavaScript": 151772, "HTML": 26378, "CSS": 4190}
package br.com.acmattos.hdc.person.port.rest import br.com.acmattos.hdc.common.context.port.rest.EndpointDefinition import br.com.acmattos.hdc.common.tool.loggable.Loggable import io.javalin.apibuilder.ApiBuilder.get import io.javalin.apibuilder.ApiBuilder.path import io.javalin.apibuilder.ApiBuilder.post import io.javalin.apibuilder.ApiBuilder.put private const val PERSONS = "persons" private const val CONTACT_TYPES = "contact_types" private const val GENDERS = "genders" private const val MARITAL_STATUSES = "marital_statuses" private const val PERSON_TYPES = "person_types" private const val STATES = "states" private const val STATUSES = "statuses" private const val DENTIST_ID = ":dentist_id" /** * @author ACMattos * @since 05/10/2021. */ class PersonControllerEndpointDefinition( private val command: PersonCommandController, private val query: PersonQueryController ): EndpointDefinition { override fun routes() { path(PERSONS) { //post(command::createADentist) post(command::createPatient) put(command::updatePatient) get(query::findAllPersons) path(CONTACT_TYPES){ get(query::findAllContactTypes) } path(GENDERS){ get(query::findAllGenders) } path(MARITAL_STATUSES){ get(query::findAllMaritalStatuses) } path(PERSON_TYPES){ get(query::findAllPersonTypes) } path(STATES){ get(query::findAllStates) } path(STATUSES){ get(query::findAllStatuses) } path(DENTIST_ID) { get(query::findTheDentist) } } logger.info("Route loaded: -> POST /$PERSONS <-") logger.info("Route loaded: -> PUT /$PERSONS <-") logger.info("Route loaded: -> GET /$PERSONS <-") logger.info("Route loaded: -> GET /$PERSONS/$CONTACT_TYPES <-") logger.info("Route loaded: -> GET /$PERSONS/$GENDERS <-") logger.info("Route loaded: -> GET /$PERSONS/$MARITAL_STATUSES <-") logger.info("Route loaded: -> GET /$PERSONS/$PERSON_TYPES <-") logger.info("Route loaded: -> GET /$PERSONS/$STATES <-") logger.info("Route loaded: -> GET /$PERSONS/$STATUSES <-") logger.info("Route loaded: -> GET /$PERSONS/$DENTIST_ID <-") logger.info("All routes loaded for: -> ${PersonControllerEndpointDefinition::class.java} <-") } companion object: Loggable() }
0
Kotlin
0
0
d6d713373ef0374b715cbeadec66c027a3dbd66b
2,580
hdc
MIT License
app/src/main/java/pl/bydgoszcz/guideme/podlewacz/utils/CoroutinesExt.kt
mniami
130,084,279
false
null
package pl.bydgoszcz.guideme.podlewacz.utils import kotlinx.coroutines.* fun launchUI(block: suspend CoroutineScope.() -> Unit) = GlobalScope.launch(Dispatchers.Main, block = block) fun launchIO(block: suspend CoroutineScope.() -> Unit) = GlobalScope.launch(Dispatchers.IO, block = block) fun <T> asyncIO(block: suspend CoroutineScope.() -> T) = GlobalScope.async(Dispatchers.IO, block = block) fun <T> CoroutineScope.asyncIO(block: suspend CoroutineScope.() -> T) = async(Dispatchers.IO, block = block) suspend fun <T> offload(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.IO, block = block)
0
Kotlin
0
0
8a822c127e13d2a8f5625e51cf3bae4fb9e33ac4
618
pourtheflowers
MIT License
src/test/kotlin/com/contentful/java/cma/e2e/SpacesE2E.kt
contentful
26,211,601
false
{"Batchfile": 1, "XML": 2, "Shell": 90, "Maven POM": 1, "Markdown": 2, "YAML": 4, "Ignore List": 1, "Text": 1, "INI": 1, "JSON": 155, "Kotlin": 48, "Java": 139, "CODEOWNERS": 1}
/* * Copyright (C) 2019 Contentful GmbH * * 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.contentful.java.cma.e2e import com.contentful.java.cma.assertTestCallback import com.contentful.java.cma.lib.TestCallback import com.contentful.java.cma.model.CMASpace import org.junit.AfterClass import kotlin.test.assertEquals import kotlin.test.assertTrue import org.junit.Test as test class SpacesE2E : Base() { companion object { private const val CREATED_SPACE_NAME = "created space name" private const val CREATED_SPACE_LOCALE = "en-US" private const val FIRST_NAME = "UPDATED" private const val FIRST_ID = "ckrcqx0r0ffc" private const val UPDATED_NAME = "UPDATED" @AfterClass @JvmStatic fun tearDownSpaces() { try { client.spaces().fetchAll().items.filter { it.name == CREATED_SPACE_NAME }.forEach { client.spaces().delete(it) } } catch (throwable: Throwable) { // nothing found so no problem } } } @test fun testFetchAll() { val result = assertTestCallback(client.spaces().async() .fetchAll(TestCallback()) as TestCallback)!! assertTrue(result.total > 0, "At least one space should have been found.") assertEquals(100, result.limit) assertEquals(0, result.skip) val first = result.items.first() assertEquals(FIRST_ID, first.id) assertEquals(FIRST_NAME, first.name) } @test fun testFetchOne() { val result = assertTestCallback(client.spaces().async() .fetchOne(FIRST_ID, TestCallback()) as TestCallback)!! assertEquals(FIRST_NAME, result.name) assertEquals(FIRST_ID, result.id) assertEquals(FIRST_NAME, result.name) } @test fun testUpdate() { val toBeUpdated = assertTestCallback(client.spaces().async() .fetchOne(SPACE_ID, TestCallback()) as TestCallback)!! toBeUpdated.name = UPDATED_NAME val result = assertTestCallback(client.spaces().async() .update(toBeUpdated, TestCallback()) as TestCallback)!! assertEquals(UPDATED_NAME, result.name) } @test fun testCreate() { val space = CMASpace() .setName(CREATED_SPACE_NAME) .setDefaultLocale(CREATED_SPACE_LOCALE) val result = assertTestCallback(client.spaces().async() .create(space, TestCallback()) as TestCallback)!! assertEquals(CREATED_SPACE_NAME, result.name) } }
2
Java
24
26
2eba1a38717757793fb48493313a60cb5f0cac75
3,141
contentful-management.java
Apache License 2.0
src/main/kotlin/io/kanro/idea/plugin/protobuf/lang/annotator/ScopeTracker.kt
chenyingchao
356,158,388
true
{"Kotlin": 153893, "Lex": 6288, "Java": 730}
package io.kanro.idea.plugin.protobuf.lang.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufReservedName import io.kanro.idea.plugin.protobuf.lang.psi.primitive.ProtobufDefinition import io.kanro.idea.plugin.protobuf.lang.psi.primitive.ProtobufMultiNameDefinition import io.kanro.idea.plugin.protobuf.lang.psi.primitive.ProtobufScope open class ScopeTracker(scope: ProtobufScope) { private val nameMap = mutableMapOf<String, MutableList<ProtobufDefinition>>() private val reservedNameMap = mutableMapOf<String, MutableList<ProtobufReservedName>>() init { scope.definitions().forEach { record(it) } scope.reservedNames().forEach { record(it) } } protected open fun record(definition: ProtobufDefinition) { if (definition is ProtobufMultiNameDefinition) { definition.names().forEach { nameMap.getOrPut(it) { mutableListOf() }.add(definition) } } else { val name = definition.name() ?: return nameMap.getOrPut(name) { mutableListOf() }.add(definition) } } protected open fun record(reserved: ProtobufReservedName) { val name = reserved.identifierLiteral?.text ?: return reservedNameMap.getOrPut(name) { mutableListOf() }.add(reserved) } open fun visit(definition: ProtobufDefinition, holder: AnnotationHolder) { val name = definition.name() ?: return createError(definition, buildMessage(name, definition) ?: return, holder) } open fun visit(reserved: ProtobufReservedName, holder: AnnotationHolder) { val name = reserved.identifierLiteral?.text ?: return createError(reserved, buildMessage(name, reserved) ?: return, holder) } protected open fun buildMessage( name: String, definition: ProtobufDefinition ): String? { val reserves = reservedNameMap[name] ?: listOf() if (reserves.isNotEmpty()) { return "Name reserved: \"$name\"" } val elements = nameMap[name] ?: listOf() if (elements.size > 1) { return "Conflicting declarations: \"$name\"" } return null } protected open fun buildMessage( name: String, reserved: ProtobufReservedName ): String? { val reserves = reservedNameMap[name] ?: listOf() if (reserves.size > 1) { return "Conflicting reserved declarations: \"$name\"" } return null } protected open fun createError(definition: ProtobufDefinition, message: String, holder: AnnotationHolder) { holder.newAnnotation( HighlightSeverity.ERROR, message ).range(definition.identifier()?.textRange ?: definition.textRange).create() } protected open fun createError(reserved: ProtobufReservedName, message: String, holder: AnnotationHolder) { holder.newAnnotation( HighlightSeverity.ERROR, message ).range(reserved.textRange).create() } companion object { fun tracker(scope: ProtobufScope): ScopeTracker { return CachedValuesManager.getCachedValue(scope) { CachedValueProvider.Result.create( ScopeTracker(scope), PsiModificationTracker.MODIFICATION_COUNT ) } } } }
0
null
0
0
6258f1d20f3f99cbcf0a169335f1a2ad4011f3df
3,708
intellij-protobuf-plugin
Apache License 2.0
internal-core/src/main/java/com/pandulapeter/beagle/core/list/cells/ExpandedItemTextCell.kt
pandulapeter
209,092,048
false
null
package com.pandulapeter.beagle.core.list.cells import android.text.TextUtils import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.pandulapeter.beagle.common.configuration.Text import com.pandulapeter.beagle.common.contracts.module.Cell import com.pandulapeter.beagle.common.contracts.module.ViewHolder import com.pandulapeter.beagle.core.R import com.pandulapeter.beagle.core.databinding.BeagleCellExpandedItemTextBinding import com.pandulapeter.beagle.core.util.extension.setText import com.pandulapeter.beagle.utils.extensions.inflater import com.pandulapeter.beagle.utils.extensions.tintedDrawable internal data class ExpandedItemTextCell( override val id: String, private val text: Text, private val isEnabled: Boolean, private val shouldEllipsize: Boolean, val onItemSelected: (() -> Unit)? ) : Cell<ExpandedItemTextCell> { override fun createViewHolderDelegate() = object : ViewHolder.Delegate<ExpandedItemTextCell>() { override fun createViewHolder(parent: ViewGroup) = ExpandedItemTextViewHolder( binding = BeagleCellExpandedItemTextBinding.inflate(parent.inflater, parent, false) ) } private class ExpandedItemTextViewHolder( private val binding: BeagleCellExpandedItemTextBinding ) : ViewHolder<ExpandedItemTextCell>(binding.root) { private val bulletPointDrawable by lazy { binding.root.context.tintedDrawable(R.drawable.beagle_ic_bullet_point, binding.beagleTextView.textColors.defaultColor) } override fun bind(model: ExpandedItemTextCell) = binding.beagleTextView.run { setText(model.text) maxLines = if (model.shouldEllipsize) 4 else Int.MAX_VALUE ellipsize = TextUtils.TruncateAt.END isEnabled = model.isEnabled alpha = if (model.isEnabled) 1f else 0.6f setCompoundDrawablesWithIntrinsicBounds(bulletPointDrawable, null, null, null) model.onItemSelected.let { onItemSelected -> if (onItemSelected == null) { setOnClickListener(null) } else { setOnClickListener { if (bindingAdapterPosition != RecyclerView.NO_POSITION) { onItemSelected() } } } isClickable = onItemSelected != null && model.isEnabled } } } }
14
null
27
491
f07df4647c91a36917d92cf9c128bcf44b03b732
2,464
beagle
Apache License 2.0
test/src/main/kotlin/sh/nino/towa/test/MyFirstApplicationCommand.kt
NinoDiscord
496,875,353
false
null
/* * 👾 Towa: Powerful and advanced command handling library made for Discord. * Copyright © 2022 Nino Team <https://nino.sh> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package sh.nino.towa.test import sh.nino.towa.slash.commands.annotations.SlashCommand import sh.nino.towa.slash.commands.application.AbstractApplicationCommand import sh.nino.towa.slash.commands.application.ApplicationCommandContext import sh.nino.towa.slash.commands.application.int import sh.nino.towa.slash.commands.application.user @SlashCommand("boop", "Boop command!") class MyFirstApplicationCommand: AbstractApplicationCommand() { private val user by user("user", "Which should should be booped?") private val boops by int("boops", "How many boops the end user should receive.") override suspend fun execute(context: ApplicationCommandContext) { val amountOfBoops = context.option(boops) val booper = context.option(user) context.reply("${context.author.tag} [${context.author.id}] gave ${booper.tag} [${booper.id}] $amountOfBoops boops!") } }
5
Kotlin
0
5
9856bd5a9995d9a4c4f26856f7967687edd5fa71
2,103
towa
MIT License
lib-chain-bitcoin/src/androidTest/java/com/smallraw/chain/bitcoin/BitcoinAccountUnitTest.kt
QuincySx
262,699,409
false
null
package com.smallraw.chain.bitcoin import android.util.Log import androidx.test.ext.junit.runners.AndroidJUnit4 import com.smallraw.chain.bitcoincore.PrivateKey import com.smallraw.chain.bitcoincore.network.MainNet import com.smallraw.crypto.core.extensions.toHex import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class BitcoinAccountUnitTest { private val TAG = "BitcoinAccountUnitTest" // @Test // fun useAppContext() { // // Context of the app under test. // val appContext = InstrumentationRegistry.getInstrumentation().targetContext // assertEquals("com.example.mylibrary.test", appContext.packageName) // } @Test fun create_bitcoin_account() { val bitcoinKit = BitcoinKit(MainNet()) val keyPair = bitcoinKit.generateKeyPair( PrivateKey.ofHex("74e5eb5e87a7eca6f3d9142fcbf26858fe75e57261df60208e97543222906b33") ) val wifPrivateKey = bitcoinKit.getWIFPrivate(keyPair) val publicKey = keyPair.getPublicKey().getKey().toHex() val p2pshAddress = bitcoinKit.getAddress(keyPair.getPublicKey()).toString() Log.e(TAG, wifPrivateKey) Log.e(TAG, publicKey) Log.e(TAG, p2pshAddress) assertEquals(wifPrivateKey, "L18wo72G3Y4tcp8BqJEa6uqDCH6VbsewmYGkx54nsZhs6kmt9h5F") assertEquals( publicKey, "02e696c8a8d35a1c5f0e6a1f345424c34ed39f0e50195d7183cdf45cd237b2b96f" ) assertEquals(p2pshAddress, "14nZeETvctxC6w3gdJMGL6ZtvDq79JtPhL") } }
1
C
6
26
0beea2170ea56e2dd224fe0e174d5ac2951632ca
1,735
ChainWallet
Apache License 2.0
data-onecall/src/main/java/de/niklasbednarczyk/nbweather/data/onecall/models/MinutelyForecastModelData.kt
NiklasBednarczyk
529,683,941
false
{"Kotlin": 1028822}
package de.niklasbednarczyk.nbweather.data.onecall.models import de.niklasbednarczyk.nbweather.core.common.datetime.NBDateTimeValue import de.niklasbednarczyk.nbweather.core.common.nullsafe.nbMap import de.niklasbednarczyk.nbweather.core.common.nullsafe.nbNullSafe import de.niklasbednarczyk.nbweather.data.onecall.local.models.MinutelyForecastEntityLocal import de.niklasbednarczyk.nbweather.data.onecall.remote.models.MinutelyForecastModelRemote import de.niklasbednarczyk.nbweather.data.onecall.values.units.PrecipitationUnitsValue data class MinutelyForecastModelData( val forecastTime: NBDateTimeValue?, val precipitation: PrecipitationUnitsValue? ) { internal companion object { fun remoteToLocal( remoteList: List<MinutelyForecastModelRemote>?, metadataId: Long, ): List<MinutelyForecastEntityLocal> { return remoteList.nbMap { remote -> MinutelyForecastEntityLocal( metadataId = metadataId, dt = remote.dt, precipitation = remote.precipitation ) } } fun localToData( localList: List<MinutelyForecastEntityLocal>? ): List<MinutelyForecastModelData> { return localList.nbMap { local -> val precipitation = local.precipitation val precipitationValue = nbNullSafe(precipitation) { p -> PrecipitationUnitsValue(p) } MinutelyForecastModelData( forecastTime = NBDateTimeValue.from(local.dt), precipitation = precipitationValue ) } } } }
15
Kotlin
0
1
bd8ac5bae4ed4461e2461b6d89dd67358fdfbdd8
1,689
NBWeather
MIT License
linkedinLogin/src/main/java/com/kusu/linkedinlogin/model/login/Localized.kt
koushikcse
199,318,792
false
null
package com.kusu.linkedinlogin.model.login import java.io.Serializable data class Localized( var en_US: String? ) : Serializable
6
Kotlin
1
5
0ac04f8b6fa9c7c77f2a80520f1bb57a62c97ef2
134
LinkedIn
MIT License
src/main/kotlin/org/fountainmc/api/event/Cancellable.kt
FountainMC
60,523,700
false
null
package org.fountainmc.api.event interface Cancellable { var isCancelled: Boolean }
9
Kotlin
5
6
edb137ab4a348ed5915b144554a7959f28415d72
91
FountainAPI
MIT License
testutils/src/main/kotlin/com/jurajbegovac/testutils/TestSchedulerRule.kt
JurajBegovac
93,555,661
false
null
package com.jurajbegovac.testutils import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import rx.Scheduler import rx.android.plugins.RxAndroidPlugins import rx.android.plugins.RxAndroidSchedulersHook import rx.internal.schedulers.ExecutorScheduler import rx.plugins.RxJavaHooks import rx.schedulers.TestScheduler /** Created by <NAME> on 09/06/2017. */ class TestSchedulerRule : TestRule { private val immediate = object : Scheduler() { override fun createWorker(): Worker = ExecutorScheduler(Runnable::run).createWorker() } val testScheduler = TestScheduler() override fun apply(base: Statement, d: Description): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { RxJavaHooks.reset() RxJavaHooks.setOnIOScheduler { testScheduler } RxJavaHooks.setOnComputationScheduler { testScheduler } RxJavaHooks.setOnNewThreadScheduler { testScheduler } RxAndroidPlugins.getInstance().reset() RxAndroidPlugins.getInstance().registerSchedulersHook(object : RxAndroidSchedulersHook() { override fun getMainThreadScheduler(): Scheduler = immediate }) base.evaluate() } } } }
2
null
1
1
d1d8e46976b62318c29b174631d13ce941569b6e
1,295
RxKotlinTraits
MIT License
app/src/androidTest/java/net/skyscanner/backpack/chip/BpkChipTest.kt
Skyscanner
117,813,847
false
null
/** * Backpack for Android - Skyscanner's Design System * * Copyright 2018 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.skyscanner.backpack.chip import androidx.appcompat.content.res.AppCompatResources import net.skyscanner.backpack.BpkSnapshotTest import net.skyscanner.backpack.BpkTestVariant import androidx.test.ext.junit.runners.AndroidJUnit4 import net.skyscanner.backpack.Variants import net.skyscanner.backpack.demo.R import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class BpkChipTest : BpkSnapshotTest() { @Test fun default() { val view = BpkChip(testContext) view.text = "Chip" snap(view) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) fun notSelected() { val view = BpkChip(testContext) view.text = "Chip" view.isSelected = false snap(view) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) fun selected() { val view = BpkChip(testContext) view.text = "Chip" view.isSelected = true snap(view) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) fun disabled() { val view = BpkChip(testContext) view.text = "Chip" view.disabled = true snap(view) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) fun notSelected_OnDark() { val view = BpkChip(testContext) view.text = "Chip" view.style = BpkChip.Style.OnDark view.isSelected = false snap(view, background = R.color.bpkTextOnLight) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) fun selected_OnDark() { val view = BpkChip(testContext) view.text = "Chip" view.style = BpkChip.Style.OnDark view.isSelected = true snap(view, R.color.bpkTextOnLight) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) fun disabled_OnDark() { val view = BpkChip(testContext) view.text = "Chip" view.style = BpkChip.Style.OnDark view.disabled = true snap(view) } @Test fun withIcon() { val view = BpkChip(testContext) view.text = "Chip" view.icon = AppCompatResources.getDrawable(testContext, R.drawable.bpk_account) snap(view) } @Test @Variants(BpkTestVariant.Default) fun typeSelect() { val view = BpkChip(testContext) view.text = "Chip" view.type = BpkChip.Type.Select snap(view) } @Test @Variants(BpkTestVariant.Default) fun typeDismiss() { val view = BpkChip(testContext) view.text = "Chip" view.type = BpkChip.Type.Dismiss snap(view) } @Test fun withIconAndType() { val view = BpkChip(testContext) view.text = "Chip" view.icon = AppCompatResources.getDrawable(testContext, R.drawable.bpk_account) view.type = BpkChip.Type.Dismiss snap(view) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode) fun withIconAndType_Selected() { val view = BpkChip(testContext) view.text = "Chip" view.icon = AppCompatResources.getDrawable(testContext, R.drawable.bpk_account) view.type = BpkChip.Type.Select view.isSelected = true snap(view) } @Test @Variants(BpkTestVariant.Default, BpkTestVariant.DarkMode) fun withIconAndType_Disabled() { val view = BpkChip(testContext) view.text = "Chip" view.icon = AppCompatResources.getDrawable(testContext, R.drawable.bpk_account) view.type = BpkChip.Type.Select view.disabled = true snap(view) } }
5
Kotlin
31
80
47cfa7ac90005c9680eebcddb96fb50fb4e35d78
4,152
backpack-android
Apache License 2.0
src/test/kotlin/io/InterdomainAdvertisementReaderTest.kt
ssbgp
108,266,875
false
{"Kotlin": 396337}
package io import bgp.BGPRoute import bgp.policies.interdomain.* import core.routing.Route import core.simulator.Advertisement import org.hamcrest.MatcherAssert.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.junit.jupiter.api.Assertions.assertThrows import testing.node import testing.then import java.io.StringReader import org.hamcrest.Matchers.`is` as Is object InterdomainAdvertisementReaderTest: Spek({ infix fun <R: Route> String.isParsedTo(advertisement: Advertisement<R>): Pair<String, Advertisement<R>> = Pair(this, advertisement) context("an interdomain advertisements file with a single entry") { listOf( "10 = 0 | c" isParsedTo Advertisement(node(10), customerRoute(), time = 0), "11 = 0 | c" isParsedTo Advertisement(node(11), customerRoute(), time = 0), "10 = 15 | c" isParsedTo Advertisement(node(10), customerRoute(), time = 15), "10 = 15 | r" isParsedTo Advertisement(node(10), peerRoute(), time = 15), "10 = 15 | p" isParsedTo Advertisement(node(10), providerRoute(), time = 15), "10 = 15 | r+" isParsedTo Advertisement(node(10), peerplusRoute(), time = 15), "10 = 15 | r*" isParsedTo Advertisement(node(10), peerstarRoute(), time = 15), "10 = | c" isParsedTo Advertisement(node(10), customerRoute(), time = 0), "10 = 15 | " isParsedTo Advertisement(node(10), BGPRoute.self(), time = 15), "10 = | " isParsedTo Advertisement(node(10), BGPRoute.self(), time = 0), "10 = " isParsedTo Advertisement(node(10), BGPRoute.self(), time = 0), "10 = 15" isParsedTo Advertisement(node(10), BGPRoute.self(), time = 15) ).forEach { (line, advertisement) -> given("entry is `$line`") { val advertisements = InterdomainAdvertisementReader(StringReader(line)).use { it.read() } then("it reads 1 advertisement") { assertThat(advertisements.size, Is(1)) } val info = advertisements[0] then("the advertiser has ID '${advertisement.advertiser.id}'") { assertThat(info.advertiserID, Is(advertisement.advertiser.id)) } then("the default route is '${advertisement.route}'") { assertThat(info.defaultRoute, Is(advertisement.route)) } then("the advertising time is '${advertisement.time}'") { assertThat(info.time, Is(advertisement.time)) } } } listOf( "a = 0 | c", "10 = 0 | c | 10", "10 = 0 | b ", // 'b' is not a valid interdomain cost label "10 = -1 | c ", // advertise time must be non-negative "10 = a | c ", "10 = 0 | c | " ).forEach { line -> given("invalid entry is `$line`") { var exception: ParseException? = null it("throws a ParseException") { InterdomainAdvertisementReader(StringReader(line)).use { exception = assertThrows(ParseException::class.java) { it.read() } } } it("indicates the error is in line 1") { assertThat(exception?.lineNumber, Is(1)) } } } } given("file with entries `10 = 0 | c` and `10 = 1 | r`") { val fileContent = lines( "10 = 0 | c", "10 = 1 | r" ) val advertisements = InterdomainAdvertisementReader(StringReader(fileContent)).use { it.read() } it("reads 2 advertisements") { assertThat(advertisements.size, Is(2)) } it("reads one advertisement with advertiser ID 10") { assertThat(advertisements[0].advertiserID, Is(10)) } it("reads one advertisement with a customer route") { assertThat(advertisements[0].defaultRoute, Is(customerRoute())) } it("reads one advertisement with advertising time 0") { assertThat(advertisements[0].time, Is(0)) } it("reads another advertisement with advertiser ID 10") { assertThat(advertisements[1].advertiserID, Is(10)) } it("reads another advertisement with a peer route") { assertThat(advertisements[1].defaultRoute, Is(peerRoute())) } it("reads another advertisement with advertising time 1") { assertThat(advertisements[1].time, Is(1)) } } })
3
Kotlin
0
9
f2b681afdbf9fec8e91a13e5c69b5559d692e9b1
4,952
simulator
MIT License
App-SmartConf/app/src/main/java/epitech/eip/smartconf/Fragments/MeetingDescFragment.kt
MatiCG
225,349,463
false
null
package epitech.eip.smartconf.Fragments import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.app.Activity import android.content.Intent import android.speech.RecognizerIntent import android.text.TextUtils import android.widget.Toast import androidx.core.content.ContextCompat import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import epitech.eip.smartconf.BaseClass.BaseFragment import epitech.eip.smartconf.R import epitech.eip.smartconf.SpeechToText.SpeechRecognizerViewModel import kotlinx.android.synthetic.main.frag_meetingdesc_layout.* import kotlinx.android.synthetic.main.fragelem_readytostart_layout.* import tekproject.dev_epicture.epicture.ApiRequests.Requests import tekproject.dev_epicture.epicture.ApiRequests.UrlRequests class MeetingDescFragment(private val meetingID: String): BaseFragment() { override fun getLayout(): Int { return R.layout.frag_meetingdesc_layout } override fun setCustomActionBar(): Int { return R.layout.actionbar_return_layout } private lateinit var speechRecognizerViewModel: SpeechRecognizerViewModel var ref = FirebaseDatabase.getInstance().getReference("meetings") private var active = false private var test: String? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) frag_content.addView(loadInactive()) ref.addValueEventListener(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) {} @SuppressLint("SetTextI18n") override fun onDataChange(p0: DataSnapshot) { result?.text = "MEETING RESULT = " + p0 .child(meetingID) .child("speech") .value.toString() } }) button_start_recording?.setOnClickListener { if (speechRecognizerViewModel.isListening) { speechRecognizerViewModel.stopListening() } else { speechRecognizerViewModel.startListening() } } setupSpeechViewModel() } private fun setupSpeechViewModel() { speechRecognizerViewModel = ViewModelProviders.of(this).get(SpeechRecognizerViewModel::class.java) speechRecognizerViewModel.getViewState().observe(this, Observer<SpeechRecognizerViewModel.ViewState> { viewState -> render(viewState) }) } private fun render(uiOutput: SpeechRecognizerViewModel.ViewState?) { if (uiOutput == null) return textTV?.text = uiOutput.spokenText button_start_recording?.background = if (uiOutput.isListening) { context!!.resources.getDrawable(R.drawable.ic_mic_off, null) } else { if (!TextUtils.isEmpty(uiOutput.spokenText)) { saveData(uiOutput.spokenText) } context!!.resources.getDrawable(R.drawable.ic_mic, null) } } private fun saveData(spokenText: String) { Requests().makePostRequest(UrlRequests().adefinir(meetingID, spokenText), context!!) } private fun loadInactive(): View{ val view: View = LayoutInflater.from(context).inflate(R.layout.fragelem_readytostart_layout, frag_content, false) return view } private fun loadActive(): View{ val view: View = LayoutInflater.from(context).inflate(R.layout.fragelem_synthese_layout, frag_content, false) return view } private fun startRecording() { try { mediaRecorder?.prepare() mediaRecorder?.start() IS_RECORDING = true } catch (e: IllegalStateException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } private fun stopRecording(){ if(IS_RECORDING){ try { mediaRecorder?.stop() mediaRecorder?.release() IS_RECORDING = false storage = FirebaseStorage.getInstance() val storageRef = storage.reference.child("Meetings/Sounds/${meetingsId}/" + "recording.wav") val stream = FileInputStream(File(output)) storageRef.putStream(stream) } catch (e: IOException) { } } else{ Toast.makeText(context, "You are not recording right now!", Toast.LENGTH_SHORT).show() } } fun createToken(): String { val chars = ('0'..'9').toList().toTypedArray() + ('a'..'z').toList().toTypedArray() return (1..32).map { chars.random() }.joinToString { "" } } }
3
Kotlin
0
0
f4611d7e59cbc9f97d5b937f0d9037386678ca4a
5,024
SmartConf
MIT License
app/src/test/java/cz/dmn/cpska/testutil/TestExtensions.kt
kletzander
141,282,285
false
{"Kotlin": 138837}
package cz.dmn.cpska.testutil import org.hamcrest.CoreMatchers import org.junit.Assert infix fun Any?.shouldEqual(that: Any?) { that?.let { Assert.assertThat(this, CoreMatchers.equalTo(that)) } ?: Assert.assertThat(this, CoreMatchers.nullValue()) }
0
Kotlin
0
0
17a0b9e855458b73ac014bb7aab9698f89b741d2
266
cpska-android
MIT License
android/src/main/java/com/justifireactnativesdk/JustifiReactNativeSdkPackage.kt
justifi-tech
647,314,631
false
null
package com.justifireactnativesdk import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import com.justifireactnativesdk.ui.BankAccountManager import com.justifireactnativesdk.ui.CardViewManager import com.justifireactnativesdk.ui.ProviderModule class JustifiReactNativeSdkPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return listOf( CardViewManager(), ProviderModule(reactContext), BankAccountManager() ) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return listOf<ViewManager<*, *>>( BankAccountManager(), CardViewManager() ) } }
1
Kotlin
0
1
e249d5e8efcd8a7777ec8351b647ef06e40ebd2d
853
justifi-react-native-sdk
MIT License
app/src/main/java/io/github/bry1337/noted/activities/main/RefreshMainDataWork.kt
Bry1337
156,647,984
false
null
package io.github.bry1337.noted.activities.main import android.content.Context import android.support.annotation.WorkerThread import androidx.work.Worker import androidx.work.WorkerParameters /** * Created by Edward Bryan Abergas on 08/11/2018. * * @author [email protected] */ /** * Worker job to refresh titles from the network while the app is in the background. * * WorkManager is a library used to enqueue work that is guaranteed to execute after its * constraints are met. It can work even when the app is in the background, or not running. */ class RefreshMainDataWork(context: Context, params: WorkerParameters) : Worker(context, params) { /** * Do our actual processing for the worker. * * WorkManager will call this method from a background thread. It may be even after * the app has been terminated by the operating system, in which case [WorkManager] will start * just enough to run this [Worker] */ override fun doWork(): Result { return refreshTitle() } /** * Refresh the title from the network using [TItleRepository] */ // TODO: Implement refreshTitle using coroutines and runBlocking @WorkerThread private fun refreshTitle(): Result = Result.SUCCESS }
0
Kotlin
0
0
a8c8519fa25b96a3f2c2502318d6f5e24cd91cba
1,221
stunning-system
MIT License
app/src/main/java/io/github/bry1337/noted/activities/main/RefreshMainDataWork.kt
Bry1337
156,647,984
false
null
package io.github.bry1337.noted.activities.main import android.content.Context import android.support.annotation.WorkerThread import androidx.work.Worker import androidx.work.WorkerParameters /** * Created by Edward Bryan Abergas on 08/11/2018. * * @author [email protected] */ /** * Worker job to refresh titles from the network while the app is in the background. * * WorkManager is a library used to enqueue work that is guaranteed to execute after its * constraints are met. It can work even when the app is in the background, or not running. */ class RefreshMainDataWork(context: Context, params: WorkerParameters) : Worker(context, params) { /** * Do our actual processing for the worker. * * WorkManager will call this method from a background thread. It may be even after * the app has been terminated by the operating system, in which case [WorkManager] will start * just enough to run this [Worker] */ override fun doWork(): Result { return refreshTitle() } /** * Refresh the title from the network using [TItleRepository] */ // TODO: Implement refreshTitle using coroutines and runBlocking @WorkerThread private fun refreshTitle(): Result = Result.SUCCESS }
0
Kotlin
0
0
a8c8519fa25b96a3f2c2502318d6f5e24cd91cba
1,221
stunning-system
MIT License
backend/mandalore-express-domain/src/test/kotlin/com/beyondxscratch/mandaloreexpress/domain/search/spacetrain/Outbound.kt
davidaparicio
761,161,576
false
{"Kotlin": 198124, "JavaScript": 37294, "HTML": 1661, "CSS": 365}
package com.beyondxscratch.mandaloreexpress.domain.search.spacetrain @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.VALUE_PARAMETER) annotation class Inbound
8
Kotlin
0
0
05dc41e2a5a5ea47ef5d688177631ffa9923fe11
176
model-mitosis
Apache License 2.0
plugin/src/main/kotlin/dev/triumphteam/triumphchat/config/settings/Setting.kt
TriumphTeam
294,288,510
false
{"Kotlin": 128629}
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.triumphteam.triumphchat.config.settings import dev.triumphteam.triumphchat.config.bean.holders.ChatHolder import dev.triumphteam.triumphchat.config.bean.holders.MentionsHolder import dev.triumphteam.triumphchat.config.bean.holders.NotificationHolder import dev.triumphteam.triumphchat.config.bean.holders.PrivateMessageHolder import dev.triumphteam.triumphchat.func.MESSAGE_PLACEHOLDER import me.mattstudios.config.SettingsHolder import me.mattstudios.config.annotations.Comment import me.mattstudios.config.annotations.Path import me.mattstudios.config.properties.Property /** * Main setting holder for all the config related settings */ object Setting : SettingsHolder { @Comment( "" ) @Path("chat") val CHAT_FORMATS = Property.create(ChatHolder()) @Comment( "", "Format that will be sent to the console, use $MESSAGE_PLACEHOLDER to represent the message that'll be sent.", "Due to console limitations, formats and RGB are not supported here, only basic colors." ) @Path("console-format") val CONSOLE_FORMAT = Property.create("[%vault_prefix%] %player_name% > $MESSAGE_PLACEHOLDER") @Comment( "", "Base settings for all the notifications.", "Currently only sound." // TODO add more ) @Path("notification") val NOTIFICATION = Property.create(NotificationHolder()) @Comment( "", // TODO Better comment "Settings customizing the mentions." ) @Path("mentions") val MENTIONS = Property.create(MentionsHolder()) @Comment( "", "Customize your private messages." ) @Path("private-messages") val PRIVATE_MESSAGES = Property.create(PrivateMessageHolder()) }
0
Kotlin
2
2
fa22204ac59d5eff46f26089e4eae9e7f3593d29
2,885
triumph-chat
MIT License
dataforge-scripting/src/jvmMain/kotlin/space/kscience/dataforge/scripting/Builders.kt
SciProgCentre
148,831,678
false
{"Kotlin": 408170}
package space.kscience.dataforge.scripting import space.kscience.dataforge.context.* import space.kscience.dataforge.workspace.Workspace import space.kscience.dataforge.workspace.WorkspaceBuilder import java.io.File import kotlin.script.experimental.api.* import kotlin.script.experimental.host.toScriptSource import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration import kotlin.script.experimental.jvm.dependenciesFromCurrentContext import kotlin.script.experimental.jvm.jvm import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost public object Builders { private fun buildWorkspace(source: SourceCode, context: Context = Global): Workspace { val builder = WorkspaceBuilder(context) val workspaceScriptConfiguration = ScriptCompilationConfiguration { // baseClass(Any::class) implicitReceivers(WorkspaceBuilder::class) defaultImports( "space.kscience.dataforge.meta.*", "space.kscience.dataforge.workspace.*" ) jvm { dependenciesFromCurrentContext(wholeClasspath = true) } hostConfiguration(defaultJvmScriptingHostConfiguration) compilerOptions("-jvm-target", Runtime.version().feature().toString(),"-Xcontext-receivers") } val evaluationConfiguration = ScriptEvaluationConfiguration { implicitReceivers(builder) } BasicJvmScriptingHost().eval(source, workspaceScriptConfiguration, evaluationConfiguration).onFailure { it.reports.forEach { scriptDiagnostic -> when (scriptDiagnostic.severity) { ScriptDiagnostic.Severity.FATAL, ScriptDiagnostic.Severity.ERROR -> { context.logger.error(scriptDiagnostic.exception) { scriptDiagnostic.toString() } error(scriptDiagnostic.toString()) } ScriptDiagnostic.Severity.WARNING -> context.logger.warn { scriptDiagnostic.toString() } ScriptDiagnostic.Severity.INFO -> context.logger.info { scriptDiagnostic.toString() } ScriptDiagnostic.Severity.DEBUG -> context.logger.debug { scriptDiagnostic.toString() } } } } return builder.build() } public fun buildWorkspace(scriptFile: File): Workspace = buildWorkspace(scriptFile.toScriptSource()) public fun buildWorkspace(scriptString: String): Workspace = buildWorkspace(scriptString.toScriptSource()) }
14
Kotlin
3
25
d80846d5fbd4d232b7506f5b4124cddfdc61d17e
2,564
dataforge-core
Apache License 2.0
app/src/main/java/asia/fourtitude/recipe/utils/permission/PermissionUtils.kt
wafi89
639,276,475
false
null
package asia.fourtitude.recipe.utils.permission import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat fun checkIfPermissionGranted(context: Context, permission: String): Boolean { return (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) } fun shouldShowPermissionRationale(context: Context, permission: String): Boolean { val activity = context as Activity? if (activity == null) Log.d("Maps Util", "Activity is null") return ActivityCompat.shouldShowRequestPermissionRationale( activity!!, permission ) }
0
Kotlin
0
0
196163a4e59a2b91ead456264ff914dd4b8a56f5
741
Recipe-Book
Apache License 2.0
app/src/main/java/com/rifafauzi/basemvvm/ui/main/MainActivity.kt
Sinarmas-MSIG-Life
231,505,254
false
null
package com.rifafauzi.basemvvm.ui.main import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.rifafauzi.basemvvm.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
0
Kotlin
0
3
6a2f16cea05fab0804dfae26dbd708dc699ae65c
344
BaseMVVM
MIT License
imagepicker/src/main/java/com/esafirm/imagepicker/features/ReturnMode.kt
esafirm
70,986,819
false
null
package com.esafirm.imagepicker.features /** * Define the ImagePicker return behaviour * NONE -> When image is picked, [ImagePickerActivity] will not be dismissed even in [ImagePickerMode.SINGLE] * ALL -> When image is picked dismiss then deliver result * CAMERA_ONLY -> When image is picked with Camera, dismiss then deliver the result * GALLERY_ONLY -> Same as CAMERA_ONLY but with Gallery */ enum class ReturnMode { NONE, ALL, CAMERA_ONLY, GALLERY_ONLY }
85
Kotlin
299
976
ea079125ce69e0bcaab25260f2943ad6b0484d1b
468
android-image-picker
MIT License
src/commonMain/kotlin/org/angproj/crypt/c/BasicAgreement.kt
angelos-project
677,062,617
false
{"Kotlin": 18034168}
/** * Copyright (c) 2024 by <NAME> <<EMAIL>>. * * This software is available under the terms of the MIT license. Parts are licensed * under different terms if stated. The legal terms are attached to the LICENSE file * and are made available on: * * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT * * Contributors: * <NAME> - initial implementation */ package org.angproj.crypt.c import org.angproj.aux.num.BigInt public interface BasicAgreement { public fun setup(param: CipherParameters) public val fieldSize: Int public fun calculateAgreement(pubKey: CipherParameters): BigInt }
0
Kotlin
0
0
ed191fa0bc60aa5ed01fe8ef63a86c742890d243
643
angelos-project-crypt
MIT License
src/main/kotlin/org/rust/lang/core/completion/RsDeriveCompletionProvider.kt
Kobzol
174,706,351
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.patterns.ElementPattern import com.intellij.patterns.PlatformPatterns import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import org.rust.ide.icons.RsIcons import org.rust.ide.icons.multiple import org.rust.lang.RsLanguage import org.rust.lang.core.RsPsiPattern import org.rust.lang.core.psi.RsPath import org.rust.lang.core.psi.ext.RsStructOrEnumItemElement import org.rust.lang.core.psi.ext.ancestorStrict import org.rust.lang.core.psi.ext.withDefaultSubst import org.rust.lang.core.psiElement import org.rust.lang.core.resolve.ImplLookup import org.rust.lang.core.resolve.KnownDerivableTrait import org.rust.lang.core.resolve.knownItems import org.rust.lang.core.resolve.withDependencies import org.rust.lang.core.types.TraitRef import org.rust.lang.core.with object RsDeriveCompletionProvider : RsCompletionProvider() { private const val DEFAULT_PRIORITY = 5.0 private const val GROUP_PRIORITY = DEFAULT_PRIORITY + 0.1 override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { // TODO: use `processDeriveTraitResolveVariants` to share code between name resolution and completion val owner = parameters.position.ancestorStrict<RsStructOrEnumItemElement>() ?: return val ownerType = owner.declaredType val lookup = ImplLookup.relativeTo(owner) /** Filter unavailable and already derived */ fun Sequence<KnownDerivableTrait>.filterDerivables() = filter { val trait = it.findTrait(owner.knownItems) trait != null && !lookup.canSelect(TraitRef(ownerType, trait.withDefaultSubst())) } KnownDerivableTrait.values().asSequence() .filterDerivables() .forEach { derivable -> val traitWithDependencies = derivable.withDependencies.asSequence() .filterDerivables() .toList() // if 'traitWithDependencies' contains only one element // then all derivable dependencies are already satisfied // and 'traitWithDependencies' contains only 'derivable' element if (traitWithDependencies.size > 1) { val element = LookupElementBuilder.create(traitWithDependencies.joinToString(", ")) .withIcon(RsIcons.TRAIT.multiple()) result.addElement(element.withPriority(GROUP_PRIORITY)) } val element = LookupElementBuilder.create(derivable.name) .withIcon(RsIcons.TRAIT) result.addElement(element.withPriority(DEFAULT_PRIORITY)) } } override val elementPattern: ElementPattern<out PsiElement> get() { return PlatformPatterns.psiElement() .withLanguage(RsLanguage) // avoid completion in non primitive path like `derive[std::/*caret*/]` .withParent(psiElement<RsPath>() .with("PrimitivePath") { path -> path.path == null } .withParent(RsPsiPattern.derivedTraitMetaItem) ) } }
0
null
0
4
7d5f70bcf89dcc9c772efbeecf20fea7b0fb331e
3,602
intellij-rust
MIT License
authorization/src/main/java/com/example/alexeyglushkov/authorization/requestbuilder/OAuthEncoder.kt
soniccat
28,707,156
false
{"Gradle": 23, "INI": 3, "Shell": 1, "Text": 3, "Ignore List": 21, "Batchfile": 1, "Markdown": 1, "Proguard": 20, "Kotlin": 259, "XML": 122, "Java": 299, "Java Properties": 1, "Gherkin": 1, "Ruby": 5}
package com.example.alexeyglushkov.authorization.requestbuilder import org.junit.Assert import java.io.UnsupportedEncodingException import java.net.URLDecoder import java.net.URLEncoder import java.util.* import java.util.regex.Pattern import kotlin.collections.HashMap /** * @author <NAME> */ object OAuthEncoder { private const val CHARSET = "UTF-8" private var ENCODING_RULES: Map<String, String>? = null fun encode(plain: String?): String? { Assert.assertNotNull(plain, "Cannot encode null object") var encoded = "" encoded = try { URLEncoder.encode(plain, CHARSET) } catch (uee: UnsupportedEncodingException) { return null } for ((key, value) in ENCODING_RULES!!) { encoded = applyRule(encoded, key, value) } return encoded } private fun applyRule(encoded: String, toReplace: String, replacement: String): String { return encoded.replace(Pattern.quote(toReplace).toRegex(), replacement) } fun decode(encoded: String?): String? { Assert.assertNotNull(encoded, "Cannot decode null object") return try { URLDecoder.decode(encoded, CHARSET) } catch (uee: UnsupportedEncodingException) { null } } init { val rules = HashMap<String, String>() rules["*"] = "%2A" rules["+"] = "%20" rules["%7E"] = "~" ENCODING_RULES = Collections.unmodifiableMap(rules) } }
1
null
1
1
0e0fa442e16d5544f7694042cf40cafde3672173
1,506
android-taskmanager
MIT License
src/main/kotlin/io/usoamic/wallet/di/subcomponents/deposit/DepositSubcomponent.kt
usoamic
299,967,649
false
null
package io.usoamic.wallet.di.subcomponents.deposit import dagger.Subcomponent import io.usoamic.wallet.commons.di.scopes.WalletScope import io.usoamic.wallet.ui.main.deposit.DepositView @WalletScope @Subcomponent interface DepositSubcomponent { fun inject(depositView: DepositView) @Subcomponent.Factory interface Factory { fun create(): DepositSubcomponent } }
0
Kotlin
1
1
104257879f1b878930d1cf283385ffb70470b446
387
UsoamicWallet-Desktop
MIT License
src/test/kotlin/demo/BrokenTest.kt
hwellmann
201,079,348
false
null
package demo import org.junit.Test class BrokenTest { @Test fun blaTest() { Foo(); println("Output from test") } }
1
Kotlin
0
0
28f86fdca89e05f599cd8a5c5d0785083ed68838
148
kotlin-maven-classpath-bug
Apache License 2.0
src/test/kotlin/demo/BrokenTest.kt
hwellmann
201,079,348
false
null
package demo import org.junit.Test class BrokenTest { @Test fun blaTest() { Foo(); println("Output from test") } }
1
Kotlin
0
0
28f86fdca89e05f599cd8a5c5d0785083ed68838
148
kotlin-maven-classpath-bug
Apache License 2.0
src/main/kotlin/com/vengateshm/expensetracker/service/CategoryService.kt
vengateshm
398,829,324
false
null
package com.vengateshm.expensetracker.service import com.vengateshm.expensetracker.dto.CategoryDto interface CategoryService { fun create(categoryDto: CategoryDto): CategoryDto fun getAll(): List<CategoryDto> fun deleteAll() }
0
Kotlin
0
1
be2dbbd7c60b6ef9d8740c1e126fd42f18c2bc39
240
spring_boot_mongodb_REST_API
Apache License 2.0
module-book-reader/src/main/java/io/legado/app/service/AudioPlayService.kt
LinXueyuanStdio
332,099,365
false
null
package io.legado.app.service import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.BitmapFactory import android.media.AudioFocusRequest import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.Build import android.os.Handler import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.core.app.NotificationCompat import io.legado.app.App import io.legado.app.R import io.legado.app.base.BaseService import io.legado.app.constant.AppConst import io.legado.app.constant.EventBus import io.legado.app.constant.IntentAction import io.legado.app.constant.Status import io.legado.app.data.entities.BookChapter import io.legado.app.help.BookHelp import io.legado.app.help.IntentHelp import io.legado.app.help.MediaHelp import io.legado.app.model.analyzeRule.AnalyzeUrl import io.legado.app.receiver.MediaButtonReceiver import io.legado.app.service.help.AudioPlay import io.legado.app.ui.audio.AudioPlayActivity import io.legado.app.utils.postEvent import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.anko.toast class AudioPlayService : BaseService(), AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { companion object { var isRun = false var pause = false var timeMinute: Int = 0 } private val handler = Handler() private lateinit var audioManager: AudioManager private var mFocusRequest: AudioFocusRequest? = null private var title: String = "" private var subtitle: String = "" private val mediaPlayer = MediaPlayer() private var mediaSessionCompat: MediaSessionCompat? = null private var broadcastReceiver: BroadcastReceiver? = null private var url: String = "" private var position = 0 private val dsRunnable: Runnable = Runnable { doDs() } private var mpRunnable: Runnable = Runnable { upPlayProgress() } private var bookChapter: BookChapter? = null private var playSpeed: Float = 1f override fun onCreate() { super.onCreate() isRun = true audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager mFocusRequest = MediaHelp.getFocusRequest(this) mediaPlayer.setOnErrorListener(this) mediaPlayer.setOnPreparedListener(this) mediaPlayer.setOnCompletionListener(this) initMediaSession() initBroadcastReceiver() upNotification() upMediaSessionPlaybackState(PlaybackStateCompat.STATE_PLAYING) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { intent?.action?.let { action -> when (action) { IntentAction.play -> { AudioPlay.book?.let { title = it.name position = it.durChapterPos loadContent(it.durChapterIndex) } } IntentAction.pause -> pause(true) IntentAction.resume -> resume() IntentAction.prev -> moveToPrev() IntentAction.next -> moveToNext() IntentAction.adjustSpeed -> upSpeed(intent.getFloatExtra("adjust", 1f)) IntentAction.addTimer -> addTimer() IntentAction.setTimer -> setTimer(intent.getIntExtra("minute", 0)) IntentAction.adjustProgress -> { adjustProgress(intent.getIntExtra("position", position)) } else -> stopSelf() } } return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { super.onDestroy() isRun = false handler.removeCallbacks(dsRunnable) handler.removeCallbacks(mpRunnable) mediaPlayer.release() mediaSessionCompat?.release() unregisterReceiver(broadcastReceiver) upMediaSessionPlaybackState(PlaybackStateCompat.STATE_STOPPED) AudioPlay.status = Status.STOP postEvent(EventBus.AUDIO_STATE, Status.STOP) } private fun play() { upNotification() if (requestFocus()) { try { AudioPlay.status = Status.PLAY postEvent(EventBus.AUDIO_STATE, Status.PLAY) mediaPlayer.reset() val analyzeUrl = AnalyzeUrl(url, headerMapF = AudioPlay.headers(), useWebView = true) val uri = Uri.parse(analyzeUrl.url) mediaPlayer.setDataSource(this, uri, analyzeUrl.headerMap) mediaPlayer.prepareAsync() } catch (e: Exception) { launch { toast("$url ${e.localizedMessage}") stopSelf() } } } } private fun pause(pause: Boolean) { if (url.contains(".m3u8", false)) { stopSelf() } else { try { AudioPlayService.pause = pause handler.removeCallbacks(mpRunnable) position = mediaPlayer.currentPosition mediaPlayer.pause() upMediaSessionPlaybackState(PlaybackStateCompat.STATE_PAUSED) AudioPlay.status = Status.PAUSE postEvent(EventBus.AUDIO_STATE, Status.PAUSE) upNotification() } catch (e: Exception) { e.printStackTrace() } } } private fun resume() { pause = false mediaPlayer.start() mediaPlayer.seekTo(position) handler.removeCallbacks(mpRunnable) handler.postDelayed(mpRunnable, 1000) upMediaSessionPlaybackState(PlaybackStateCompat.STATE_PLAYING) AudioPlay.status = Status.PLAY postEvent(EventBus.AUDIO_STATE, Status.PLAY) upNotification() } private fun adjustProgress(position: Int) { if (mediaPlayer.isPlaying) { mediaPlayer.seekTo(position) } else { this.position = position } } private fun upSpeed(adjust: Float) { kotlin.runCatching { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { playSpeed += adjust if (mediaPlayer.isPlaying) { mediaPlayer.playbackParams = mediaPlayer.playbackParams.apply { speed = playSpeed } } postEvent(EventBus.AUDIO_SPEED, playSpeed) } } } /** * 加载完成 */ override fun onPrepared(mp: MediaPlayer?) { if (pause) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mediaPlayer.playbackParams = mediaPlayer.playbackParams.apply { speed = playSpeed } } else { mediaPlayer.start() } mediaPlayer.seekTo(position) postEvent(EventBus.AUDIO_SIZE, mediaPlayer.duration) bookChapter?.let { it.end = mediaPlayer.duration.toLong() } handler.removeCallbacks(mpRunnable) handler.post(mpRunnable) } /** * 播放出错 */ override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean { if (!mediaPlayer.isPlaying) { AudioPlay.status = Status.STOP postEvent(EventBus.AUDIO_STATE, Status.STOP) launch { toast("error: $what $extra $url") } } return true } /** * 播放结束 */ override fun onCompletion(mp: MediaPlayer?) { handler.removeCallbacks(mpRunnable) moveToNext() } private fun setTimer(minute: Int) { timeMinute = minute if (minute > 0) { handler.removeCallbacks(dsRunnable) handler.postDelayed(dsRunnable, 60000) } upNotification() } private fun addTimer() { if (timeMinute == 60) { timeMinute = 0 handler.removeCallbacks(dsRunnable) } else { timeMinute += 10 if (timeMinute > 60) timeMinute = 60 handler.removeCallbacks(dsRunnable) handler.postDelayed(dsRunnable, 60000) } postEvent(EventBus.TTS_DS, timeMinute) upNotification() } /** * 更新播放进度 */ private fun upPlayProgress() { saveProgress() postEvent(EventBus.AUDIO_PROGRESS, mediaPlayer.currentPosition) handler.postDelayed(mpRunnable, 1000) } private fun loadContent(index: Int) { AudioPlay.book?.let { book -> if (addLoading(index)) { launch(IO) { App.db.bookChapterDao().getChapter(book.bookUrl, index)?.let { chapter -> if (index == AudioPlay.durChapterIndex) { bookChapter = chapter subtitle = chapter.title postEvent(EventBus.AUDIO_SUB_TITLE, subtitle) postEvent(EventBus.AUDIO_SIZE, chapter.end?.toInt() ?: 0) postEvent(EventBus.AUDIO_PROGRESS, position) } loadContent(chapter) } ?: removeLoading(index) } } } } private fun loadContent(chapter: BookChapter) { AudioPlay.book?.let { book -> AudioPlay.webBook?.getContent(book, chapter, scope = this) ?.onSuccess(IO) { content -> if (content.isEmpty()) { withContext(Main) { toast("未获取到资源链接") } removeLoading(chapter.index) } else { BookHelp.saveContent(book, chapter, content) contentLoadFinish(chapter, content) removeLoading(chapter.index) } }?.onError { contentLoadFinish(chapter, it.localizedMessage ?: toString()) removeLoading(chapter.index) } } } private fun addLoading(index: Int): Boolean { synchronized(this) { if (AudioPlay.loadingChapters.contains(index)) return false AudioPlay.loadingChapters.add(index) return true } } private fun removeLoading(index: Int) { synchronized(this) { AudioPlay.loadingChapters.remove(index) } } /** * 加载完成 */ private fun contentLoadFinish(chapter: BookChapter, content: String) { if (chapter.index == AudioPlay.durChapterIndex) { subtitle = chapter.title url = content play() } } private fun moveToPrev() { if (AudioPlay.durChapterIndex > 0) { mediaPlayer.pause() AudioPlay.durChapterIndex-- AudioPlay.durPageIndex = 0 AudioPlay.book?.durChapterIndex = AudioPlay.durChapterIndex saveRead() position = 0 loadContent(AudioPlay.durChapterIndex) } } private fun moveToNext() { if (AudioPlay.durChapterIndex < AudioPlay.chapterSize - 1) { mediaPlayer.pause() AudioPlay.durChapterIndex++ AudioPlay.durPageIndex = 0 AudioPlay.book?.durChapterIndex = AudioPlay.durChapterIndex saveRead() position = 0 loadContent(AudioPlay.durChapterIndex) } else { stopSelf() } } private fun saveRead() { launch(IO) { AudioPlay.book?.let { book -> book.lastCheckCount = 0 book.durChapterTime = System.currentTimeMillis() book.durChapterIndex = AudioPlay.durChapterIndex book.durChapterPos = AudioPlay.durPageIndex book.durChapterTitle = subtitle App.db.bookDao().update(book) } } } private fun saveProgress() { launch(IO) { AudioPlay.book?.let { App.db.bookDao().upProgress(it.bookUrl, AudioPlay.durPageIndex) } } } /** * 定时 */ private fun doDs() { if (!pause) { timeMinute-- if (timeMinute == 0) { stopSelf() } else if (timeMinute > 0) { handler.postDelayed(dsRunnable, 60000) } } postEvent(EventBus.TTS_DS, timeMinute) upNotification() } /** * 更新媒体状态 */ private fun upMediaSessionPlaybackState(state: Int) { mediaSessionCompat?.setPlaybackState( PlaybackStateCompat.Builder() .setActions(MediaHelp.MEDIA_SESSION_ACTIONS) .setState(state, position.toLong(), 1f) .build() ) } /** * 初始化MediaSession, 注册多媒体按钮 */ private fun initMediaSession() { mediaSessionCompat = MediaSessionCompat(this, "readAloud") mediaSessionCompat?.setCallback(object : MediaSessionCompat.Callback() { override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean { return MediaButtonReceiver.handleIntent(this@AudioPlayService, mediaButtonEvent) } }) mediaSessionCompat?.setMediaButtonReceiver( PendingIntent.getBroadcast( this, 0, Intent( Intent.ACTION_MEDIA_BUTTON, null, App.INSTANCE, MediaButtonReceiver::class.java ), PendingIntent.FLAG_CANCEL_CURRENT ) ) mediaSessionCompat?.isActive = true } /** * 断开耳机监听 */ private fun initBroadcastReceiver() { broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent.action) { pause(true) } } } val intentFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) registerReceiver(broadcastReceiver, intentFilter) } /** * 音频焦点变化 */ override fun onAudioFocusChange(focusChange: Int) { when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { // 重新获得焦点, 可做恢复播放,恢复后台音量的操作 if (!pause) resume() } AudioManager.AUDIOFOCUS_LOSS -> { // 永久丢失焦点除非重新主动获取,这种情况是被其他播放器抢去了焦点, 为避免与其他播放器混音,可将音乐暂停 } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { // 暂时丢失焦点,这种情况是被其他应用申请了短暂的焦点,可压低后台音量 if (!pause) pause(false) } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { // 短暂丢失焦点,这种情况是被其他应用申请了短暂的焦点希望其他声音能压低音量(或者关闭声音)凸显这个声音(比如短信提示音), } } } /** * 更新通知 */ private fun upNotification() { var nTitle: String = when { pause -> getString(R.string.audio_pause) timeMinute in 1..60 -> getString( R.string.read_aloud_timer, timeMinute ) else -> getString(R.string.audio_play_t) } nTitle += ": $title" var nSubtitle = subtitle if (subtitle.isEmpty()) { nSubtitle = getString(R.string.audio_play_s) } val builder = NotificationCompat.Builder(this, AppConst.channelIdReadAloud) .setSmallIcon(R.drawable.novel_ic_volume_up) .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.novel_icon_read_book)) .setOngoing(true) .setContentTitle(nTitle) .setContentText(nSubtitle) .setContentIntent( IntentHelp.activityPendingIntent<AudioPlayActivity>(this, "activity") ) if (pause) { builder.addAction( R.drawable.novel_ic_play_24dp, getString(R.string.resume), thisPendingIntent(IntentAction.resume) ) } else { builder.addAction( R.drawable.novel_ic_pause_24dp, getString(R.string.pause), thisPendingIntent(IntentAction.pause) ) } builder.addAction( R.drawable.novel_ic_stop_black_24dp, getString(R.string.stop), thisPendingIntent(IntentAction.stop) ) builder.addAction( R.drawable.novel_ic_time_add_24dp, getString(R.string.set_timer), thisPendingIntent(IntentAction.addTimer) ) builder.setStyle( androidx.media.app.NotificationCompat.MediaStyle() .setShowActionsInCompactView(0, 1, 2) ) builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC) val notification = builder.build() startForeground(AppConst.notificationIdAudio, notification) } /** * @return 音频焦点 */ private fun requestFocus(): Boolean { return MediaHelp.requestFocus(audioManager, this, mFocusRequest) } private fun thisPendingIntent(action: String): PendingIntent? { return IntentHelp.servicePendingIntent<AudioPlayService>(this, action) } }
1
null
1
1
1131fe5d2c16c15adfa12111cfac0fda080a50dc
17,832
TimeCatModule-BookReader
Apache License 2.0
module-book-reader/src/main/java/io/legado/app/service/AudioPlayService.kt
LinXueyuanStdio
332,099,365
false
null
package io.legado.app.service import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.BitmapFactory import android.media.AudioFocusRequest import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.Build import android.os.Handler import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.core.app.NotificationCompat import io.legado.app.App import io.legado.app.R import io.legado.app.base.BaseService import io.legado.app.constant.AppConst import io.legado.app.constant.EventBus import io.legado.app.constant.IntentAction import io.legado.app.constant.Status import io.legado.app.data.entities.BookChapter import io.legado.app.help.BookHelp import io.legado.app.help.IntentHelp import io.legado.app.help.MediaHelp import io.legado.app.model.analyzeRule.AnalyzeUrl import io.legado.app.receiver.MediaButtonReceiver import io.legado.app.service.help.AudioPlay import io.legado.app.ui.audio.AudioPlayActivity import io.legado.app.utils.postEvent import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.anko.toast class AudioPlayService : BaseService(), AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { companion object { var isRun = false var pause = false var timeMinute: Int = 0 } private val handler = Handler() private lateinit var audioManager: AudioManager private var mFocusRequest: AudioFocusRequest? = null private var title: String = "" private var subtitle: String = "" private val mediaPlayer = MediaPlayer() private var mediaSessionCompat: MediaSessionCompat? = null private var broadcastReceiver: BroadcastReceiver? = null private var url: String = "" private var position = 0 private val dsRunnable: Runnable = Runnable { doDs() } private var mpRunnable: Runnable = Runnable { upPlayProgress() } private var bookChapter: BookChapter? = null private var playSpeed: Float = 1f override fun onCreate() { super.onCreate() isRun = true audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager mFocusRequest = MediaHelp.getFocusRequest(this) mediaPlayer.setOnErrorListener(this) mediaPlayer.setOnPreparedListener(this) mediaPlayer.setOnCompletionListener(this) initMediaSession() initBroadcastReceiver() upNotification() upMediaSessionPlaybackState(PlaybackStateCompat.STATE_PLAYING) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { intent?.action?.let { action -> when (action) { IntentAction.play -> { AudioPlay.book?.let { title = it.name position = it.durChapterPos loadContent(it.durChapterIndex) } } IntentAction.pause -> pause(true) IntentAction.resume -> resume() IntentAction.prev -> moveToPrev() IntentAction.next -> moveToNext() IntentAction.adjustSpeed -> upSpeed(intent.getFloatExtra("adjust", 1f)) IntentAction.addTimer -> addTimer() IntentAction.setTimer -> setTimer(intent.getIntExtra("minute", 0)) IntentAction.adjustProgress -> { adjustProgress(intent.getIntExtra("position", position)) } else -> stopSelf() } } return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { super.onDestroy() isRun = false handler.removeCallbacks(dsRunnable) handler.removeCallbacks(mpRunnable) mediaPlayer.release() mediaSessionCompat?.release() unregisterReceiver(broadcastReceiver) upMediaSessionPlaybackState(PlaybackStateCompat.STATE_STOPPED) AudioPlay.status = Status.STOP postEvent(EventBus.AUDIO_STATE, Status.STOP) } private fun play() { upNotification() if (requestFocus()) { try { AudioPlay.status = Status.PLAY postEvent(EventBus.AUDIO_STATE, Status.PLAY) mediaPlayer.reset() val analyzeUrl = AnalyzeUrl(url, headerMapF = AudioPlay.headers(), useWebView = true) val uri = Uri.parse(analyzeUrl.url) mediaPlayer.setDataSource(this, uri, analyzeUrl.headerMap) mediaPlayer.prepareAsync() } catch (e: Exception) { launch { toast("$url ${e.localizedMessage}") stopSelf() } } } } private fun pause(pause: Boolean) { if (url.contains(".m3u8", false)) { stopSelf() } else { try { AudioPlayService.pause = pause handler.removeCallbacks(mpRunnable) position = mediaPlayer.currentPosition mediaPlayer.pause() upMediaSessionPlaybackState(PlaybackStateCompat.STATE_PAUSED) AudioPlay.status = Status.PAUSE postEvent(EventBus.AUDIO_STATE, Status.PAUSE) upNotification() } catch (e: Exception) { e.printStackTrace() } } } private fun resume() { pause = false mediaPlayer.start() mediaPlayer.seekTo(position) handler.removeCallbacks(mpRunnable) handler.postDelayed(mpRunnable, 1000) upMediaSessionPlaybackState(PlaybackStateCompat.STATE_PLAYING) AudioPlay.status = Status.PLAY postEvent(EventBus.AUDIO_STATE, Status.PLAY) upNotification() } private fun adjustProgress(position: Int) { if (mediaPlayer.isPlaying) { mediaPlayer.seekTo(position) } else { this.position = position } } private fun upSpeed(adjust: Float) { kotlin.runCatching { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { playSpeed += adjust if (mediaPlayer.isPlaying) { mediaPlayer.playbackParams = mediaPlayer.playbackParams.apply { speed = playSpeed } } postEvent(EventBus.AUDIO_SPEED, playSpeed) } } } /** * 加载完成 */ override fun onPrepared(mp: MediaPlayer?) { if (pause) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mediaPlayer.playbackParams = mediaPlayer.playbackParams.apply { speed = playSpeed } } else { mediaPlayer.start() } mediaPlayer.seekTo(position) postEvent(EventBus.AUDIO_SIZE, mediaPlayer.duration) bookChapter?.let { it.end = mediaPlayer.duration.toLong() } handler.removeCallbacks(mpRunnable) handler.post(mpRunnable) } /** * 播放出错 */ override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean { if (!mediaPlayer.isPlaying) { AudioPlay.status = Status.STOP postEvent(EventBus.AUDIO_STATE, Status.STOP) launch { toast("error: $what $extra $url") } } return true } /** * 播放结束 */ override fun onCompletion(mp: MediaPlayer?) { handler.removeCallbacks(mpRunnable) moveToNext() } private fun setTimer(minute: Int) { timeMinute = minute if (minute > 0) { handler.removeCallbacks(dsRunnable) handler.postDelayed(dsRunnable, 60000) } upNotification() } private fun addTimer() { if (timeMinute == 60) { timeMinute = 0 handler.removeCallbacks(dsRunnable) } else { timeMinute += 10 if (timeMinute > 60) timeMinute = 60 handler.removeCallbacks(dsRunnable) handler.postDelayed(dsRunnable, 60000) } postEvent(EventBus.TTS_DS, timeMinute) upNotification() } /** * 更新播放进度 */ private fun upPlayProgress() { saveProgress() postEvent(EventBus.AUDIO_PROGRESS, mediaPlayer.currentPosition) handler.postDelayed(mpRunnable, 1000) } private fun loadContent(index: Int) { AudioPlay.book?.let { book -> if (addLoading(index)) { launch(IO) { App.db.bookChapterDao().getChapter(book.bookUrl, index)?.let { chapter -> if (index == AudioPlay.durChapterIndex) { bookChapter = chapter subtitle = chapter.title postEvent(EventBus.AUDIO_SUB_TITLE, subtitle) postEvent(EventBus.AUDIO_SIZE, chapter.end?.toInt() ?: 0) postEvent(EventBus.AUDIO_PROGRESS, position) } loadContent(chapter) } ?: removeLoading(index) } } } } private fun loadContent(chapter: BookChapter) { AudioPlay.book?.let { book -> AudioPlay.webBook?.getContent(book, chapter, scope = this) ?.onSuccess(IO) { content -> if (content.isEmpty()) { withContext(Main) { toast("未获取到资源链接") } removeLoading(chapter.index) } else { BookHelp.saveContent(book, chapter, content) contentLoadFinish(chapter, content) removeLoading(chapter.index) } }?.onError { contentLoadFinish(chapter, it.localizedMessage ?: toString()) removeLoading(chapter.index) } } } private fun addLoading(index: Int): Boolean { synchronized(this) { if (AudioPlay.loadingChapters.contains(index)) return false AudioPlay.loadingChapters.add(index) return true } } private fun removeLoading(index: Int) { synchronized(this) { AudioPlay.loadingChapters.remove(index) } } /** * 加载完成 */ private fun contentLoadFinish(chapter: BookChapter, content: String) { if (chapter.index == AudioPlay.durChapterIndex) { subtitle = chapter.title url = content play() } } private fun moveToPrev() { if (AudioPlay.durChapterIndex > 0) { mediaPlayer.pause() AudioPlay.durChapterIndex-- AudioPlay.durPageIndex = 0 AudioPlay.book?.durChapterIndex = AudioPlay.durChapterIndex saveRead() position = 0 loadContent(AudioPlay.durChapterIndex) } } private fun moveToNext() { if (AudioPlay.durChapterIndex < AudioPlay.chapterSize - 1) { mediaPlayer.pause() AudioPlay.durChapterIndex++ AudioPlay.durPageIndex = 0 AudioPlay.book?.durChapterIndex = AudioPlay.durChapterIndex saveRead() position = 0 loadContent(AudioPlay.durChapterIndex) } else { stopSelf() } } private fun saveRead() { launch(IO) { AudioPlay.book?.let { book -> book.lastCheckCount = 0 book.durChapterTime = System.currentTimeMillis() book.durChapterIndex = AudioPlay.durChapterIndex book.durChapterPos = AudioPlay.durPageIndex book.durChapterTitle = subtitle App.db.bookDao().update(book) } } } private fun saveProgress() { launch(IO) { AudioPlay.book?.let { App.db.bookDao().upProgress(it.bookUrl, AudioPlay.durPageIndex) } } } /** * 定时 */ private fun doDs() { if (!pause) { timeMinute-- if (timeMinute == 0) { stopSelf() } else if (timeMinute > 0) { handler.postDelayed(dsRunnable, 60000) } } postEvent(EventBus.TTS_DS, timeMinute) upNotification() } /** * 更新媒体状态 */ private fun upMediaSessionPlaybackState(state: Int) { mediaSessionCompat?.setPlaybackState( PlaybackStateCompat.Builder() .setActions(MediaHelp.MEDIA_SESSION_ACTIONS) .setState(state, position.toLong(), 1f) .build() ) } /** * 初始化MediaSession, 注册多媒体按钮 */ private fun initMediaSession() { mediaSessionCompat = MediaSessionCompat(this, "readAloud") mediaSessionCompat?.setCallback(object : MediaSessionCompat.Callback() { override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean { return MediaButtonReceiver.handleIntent(this@AudioPlayService, mediaButtonEvent) } }) mediaSessionCompat?.setMediaButtonReceiver( PendingIntent.getBroadcast( this, 0, Intent( Intent.ACTION_MEDIA_BUTTON, null, App.INSTANCE, MediaButtonReceiver::class.java ), PendingIntent.FLAG_CANCEL_CURRENT ) ) mediaSessionCompat?.isActive = true } /** * 断开耳机监听 */ private fun initBroadcastReceiver() { broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent.action) { pause(true) } } } val intentFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) registerReceiver(broadcastReceiver, intentFilter) } /** * 音频焦点变化 */ override fun onAudioFocusChange(focusChange: Int) { when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { // 重新获得焦点, 可做恢复播放,恢复后台音量的操作 if (!pause) resume() } AudioManager.AUDIOFOCUS_LOSS -> { // 永久丢失焦点除非重新主动获取,这种情况是被其他播放器抢去了焦点, 为避免与其他播放器混音,可将音乐暂停 } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { // 暂时丢失焦点,这种情况是被其他应用申请了短暂的焦点,可压低后台音量 if (!pause) pause(false) } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { // 短暂丢失焦点,这种情况是被其他应用申请了短暂的焦点希望其他声音能压低音量(或者关闭声音)凸显这个声音(比如短信提示音), } } } /** * 更新通知 */ private fun upNotification() { var nTitle: String = when { pause -> getString(R.string.audio_pause) timeMinute in 1..60 -> getString( R.string.read_aloud_timer, timeMinute ) else -> getString(R.string.audio_play_t) } nTitle += ": $title" var nSubtitle = subtitle if (subtitle.isEmpty()) { nSubtitle = getString(R.string.audio_play_s) } val builder = NotificationCompat.Builder(this, AppConst.channelIdReadAloud) .setSmallIcon(R.drawable.novel_ic_volume_up) .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.novel_icon_read_book)) .setOngoing(true) .setContentTitle(nTitle) .setContentText(nSubtitle) .setContentIntent( IntentHelp.activityPendingIntent<AudioPlayActivity>(this, "activity") ) if (pause) { builder.addAction( R.drawable.novel_ic_play_24dp, getString(R.string.resume), thisPendingIntent(IntentAction.resume) ) } else { builder.addAction( R.drawable.novel_ic_pause_24dp, getString(R.string.pause), thisPendingIntent(IntentAction.pause) ) } builder.addAction( R.drawable.novel_ic_stop_black_24dp, getString(R.string.stop), thisPendingIntent(IntentAction.stop) ) builder.addAction( R.drawable.novel_ic_time_add_24dp, getString(R.string.set_timer), thisPendingIntent(IntentAction.addTimer) ) builder.setStyle( androidx.media.app.NotificationCompat.MediaStyle() .setShowActionsInCompactView(0, 1, 2) ) builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC) val notification = builder.build() startForeground(AppConst.notificationIdAudio, notification) } /** * @return 音频焦点 */ private fun requestFocus(): Boolean { return MediaHelp.requestFocus(audioManager, this, mFocusRequest) } private fun thisPendingIntent(action: String): PendingIntent? { return IntentHelp.servicePendingIntent<AudioPlayService>(this, action) } }
1
null
1
1
1131fe5d2c16c15adfa12111cfac0fda080a50dc
17,832
TimeCatModule-BookReader
Apache License 2.0
src/main/kotlin/br/com/rafaelbiasi/doomfire/DoomFireApp.kt
rafaelbiasi
209,579,229
false
{"Kotlin": 9625}
package br.com.rafaelbiasi.doomfire fun main() { val fireWidth = 25 val fireHeight = 25 val render = ZirconRender(fireWidth, fireHeight) val doomFire = DoomFire(fireWidth, fireHeight) GameLoop(doomFire::start, doomFire::doFire, { doomFire.renderFire(render) }, render::isRunning).start() }
0
Kotlin
0
1
623620c3a786c2f1f945c4fef9f2211de94dc6f5
312
DoomFireKt
MIT License
next/kmp/pureHttp/src/desktopMain/kotlin/org/dweb_browser/pure/http/HttpPureServer.desktop.kt
BioforestChain
594,577,896
false
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
package org.dweb_browser.pure.http import io.ktor.server.engine.connector import io.ktor.server.engine.sslConnector import io.ktor.server.jetty.Jetty import io.ktor.server.jetty.JettyApplicationEngine import io.ktor.server.jetty.JettyApplicationEngineBase import kotlinx.coroutines.sync.withLock import org.dweb_browser.pure.http.ktor.KtorPureServer actual class HttpPureServer actual constructor(onRequest: HttpPureServerOnRequest) : KtorPureServer<JettyApplicationEngine, JettyApplicationEngineBase.Configuration>( Jetty, onRequest ) { init { allHttpPureServerInstances.add(this) } actual override suspend fun start(port: UShort): UShort { return start(port, true) } suspend fun start(port: UShort, https: Boolean) = serverLock.withLock { if (!serverDeferred.isCompleted) { createServer({ }) { if (https) { sslConnector( keyStore = SslSettings.keyStore, keyAlias = SslSettings.keyAlias, keyStorePassword = { SslSettings.keyStorePassword.toCharArray() }, privateKeyPassword = { SslSettings.privateKeyPassword.toCharArray() }) { this.port = port.toInt() this.keyStorePath = SslSettings.keyStoreFile } } else { connector { this.port = port.toInt() this.host = "0.0.0.0" } } }.also { it.start(wait = false) serverDeferred.complete(it) } } getPort() } }
66
Kotlin
5
20
6db1137257e38400c87279f4ccf46511752cd45a
1,501
dweb_browser
MIT License
library/src/main/java/com/github/mminng/banner/decoration/IndicatorDecoration.kt
mminng
336,510,575
false
null
package com.github.mminng.banner.decoration import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import com.github.mminng.banner.utils.dp2px /** * Created by zh on 2021/1/22. */ internal class IndicatorDecoration : ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { super.getItemOffsets(outRect, view, parent, state) val position = parent.getChildAdapterPosition(view) val reverseLayout = (parent.layoutManager as LinearLayoutManager).reverseLayout val orientation = (parent.layoutManager as LinearLayoutManager).orientation if (orientation == LinearLayoutManager.HORIZONTAL) { if (position > 0) { if (reverseLayout) { outRect.right = dp2px(3F, parent.context).toInt() } else { outRect.left = dp2px(3F, parent.context).toInt() } } } else { if (position > 0) { if (reverseLayout) { outRect.bottom = dp2px(3F, parent.context).toInt() } else { outRect.top = dp2px(3F, parent.context).toInt() } } } } }
0
Kotlin
0
5
9f8806a969b95c4ee9b166ff862986188f27e765
1,474
BannerView
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonperson/service/event/DomainEvent.kt
ministryofjustice
805,355,441
false
{"Kotlin": 647651, "Shell": 6374, "Dockerfile": 1365}
package uk.gov.justice.digital.hmpps.prisonperson.service.event import uk.gov.justice.digital.hmpps.prisonperson.enums.PrisonPersonField import uk.gov.justice.digital.hmpps.prisonperson.enums.Source import java.time.ZonedDateTime import java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME data class DomainEvent<T>( val eventType: String? = null, val additionalInformation: T?, val occurredAt: String, val description: String, val version: String, ) { constructor( eventType: String, additionalInformation: T?, occurredAt: ZonedDateTime, description: String, ) : this( eventType, additionalInformation, occurredAt.toOffsetDateFormat(), description, "1.0", ) } data class PrisonPersonAdditionalInformation( val url: String, val source: Source, val prisonerNumber: String, val fields: Collection<PrisonPersonField>, ) data class PrisonerMergedAdditionalInformation( val nomsNumber: String, val removedNomsNumber: String, val reason: String, ) fun ZonedDateTime.toOffsetDateFormat(): String = ISO_OFFSET_DATE_TIME.format(this)
2
Kotlin
0
1
c790d98025319a8a9af1c2f46d164e9eda2ff76a
1,099
hmpps-prison-person-api
MIT License
apps/androidApp/src/main/java/com/baptistecarlier/am24/ui/feature/list/screen/ListVM.kt
BapNesS
781,361,632
false
{"Kotlin": 58941}
package com.baptistecarlier.am24.ui.feature.list.screen import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.baptistecarlier.am24.shared.domain.interactor.list.GetGoatTeaserUc import com.baptistecarlier.am24.shared.domain.interactor.list.GetListModeUc import com.baptistecarlier.am24.shared.domain.interactor.list.UpdateListModeUc import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class ListVM( private val getGoatTeaserUc: GetGoatTeaserUc, private val getListModeUc: GetListModeUc, private val updateListModeUc: UpdateListModeUc, ) : ViewModel() { private val _state = MutableStateFlow<ListState>(ListState.Loading) val state: StateFlow<ListState> = _state init { retrieveData() } fun onRetry() { _state.update { ListState.Loading } retrieveData() } private fun retrieveData() { viewModelScope.launch { val listMode = getListModeUc() getGoatTeaserUc() .onSuccess { _state.value = ListState.Success(it.toImmutableList(), listMode) } .onFailure { _state.value = ListState.Error } } } fun onListModeChanged(isList: Boolean) { viewModelScope.launch { updateListModeUc(isList) } } }
0
Kotlin
0
3
8a07812369181db3a041fe7c9f78a99bbc8ab717
1,463
goat-multiplatform
Apache License 2.0
samples/src/main/java/tk/zielony/carbonsamples/widget/BottomNavigationViewActivity.kt
AshutoshChakraborty
219,755,130
true
{"Java Properties": 2, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Proguard": 3, "Java": 250, "Kotlin": 53}
package tk.zielony.carbonsamples.widget import android.os.Bundle import carbon.drawable.ColorStateListFactory import carbon.widget.BottomNavigationView import kotlinx.android.synthetic.main.activity_bottomnavigationview.* import tk.zielony.carbonsamples.ActivityAnnotation import tk.zielony.carbonsamples.R import tk.zielony.carbonsamples.ThemedActivity class BadgeItem : BottomNavigationView.Item() { var notificationCount: Int = 0 } @ActivityAnnotation(layout = R.layout.activity_bottomnavigationview, title = R.string.bottomNavigationViewActivity_title) class BottomNavigationViewActivity : ThemedActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() bottomBar.menuItems = arrayOf( BadgeItem().apply { icon = resources.getDrawable(R.drawable.ic_android_black_24dp) title = "Android" iconTintList = ColorStateListFactory.makeIconSecondary(this@BottomNavigationViewActivity) }, BadgeItem().apply { icon = resources.getDrawable(R.drawable.ic_calendar_black_24dp) title = "Calendar" iconTintList = ColorStateListFactory.makeIconSecondary(this@BottomNavigationViewActivity) notificationCount = 346 }, BadgeItem().apply { icon = resources.getDrawable(R.drawable.ic_comment_black_24dp) title = "Comment" iconTintList = ColorStateListFactory.makeIconSecondary(this@BottomNavigationViewActivity) notificationCount = 1 }) bottomBar3.menuItems = arrayOf( BottomNavigationView.Item().apply { icon = resources.getDrawable(R.drawable.ic_android_black_24dp) title = "Android" iconTintList = ColorStateListFactory.makeIconSecondary(this@BottomNavigationViewActivity) }, BottomNavigationView.Item().apply { icon = resources.getDrawable(R.drawable.ic_calendar_black_24dp) title = "Calendar" iconTintList = ColorStateListFactory.makeIconSecondary(this@BottomNavigationViewActivity) }, BottomNavigationView.Item().apply { icon = resources.getDrawable(R.drawable.ic_comment_black_24dp) title = "Comment" iconTintList = ColorStateListFactory.makeIconSecondary(this@BottomNavigationViewActivity) }) } }
0
null
0
0
87415e58f895af56310fc707c16935c7e0b37e46
2,686
Carbon
Apache License 2.0
app/src/main/java/org/watsi/uhp/views/DiagnosisListItem.kt
Meso-Health
227,514,539
false
{"Gradle": 7, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 4, "Markdown": 1, "Proguard": 2, "JSON": 25, "Kotlin": 419, "YAML": 3, "XML": 153, "Java": 1}
package org.watsi.uhp.views import android.content.Context import android.support.constraint.ConstraintLayout import android.util.AttributeSet import kotlinx.android.synthetic.main.view_diagnosis_list_item.view.diagnosis_name import org.watsi.domain.entities.Diagnosis class DiagnosisListItem @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { fun setDiagnosis(diagnosis: Diagnosis) { diagnosis_name.text = diagnosis.description } }
2
Kotlin
3
6
6e1da182073088f28230fe60a2e09d6f38aab957
558
meso-clinic
Apache License 2.0
app/src/main/java/com/clean/mvvm/domain/usecase/catsDetail/CheckFavouriteUseCaseImpl.kt
Prashant-Chandel
740,906,970
false
{"Kotlin": 141637, "Java": 15124, "CSS": 1131}
package com.clean.mvvm.domain.usecase.catsDetail import com.clean.mvvm.domain.repositories.CatDetailsRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class CheckFavouriteUseCaseImpl(private val catDetailsRepo: CatDetailsRepository) : CheckFavUseCase { override suspend fun execute(imageId: String): Flow<Int?> = flow { emit(catDetailsRepo.fetchIsFavouriteRelation(imageId)) } }
0
Kotlin
0
0
b65cb055296419305f513b4bfade893511eccd04
436
jetpack-compose-Single-Activity-MVVM-clean-Architect-Example-with-KOIN-
Apache License 2.0
libs/statemanager/src/main/kotlin/mono/state/command/mouse/LineInteractionMouseCommand.kt
tuanchauict
325,686,408
false
null
/* * Copyright (c) 2023, tuanchauict */ package mono.state.command.mouse import mono.common.MouseCursor import mono.common.exhaustive import mono.graphics.geo.DirectedPoint import mono.graphics.geo.MousePointer import mono.graphics.geo.Point import mono.shape.command.MoveLineAnchor import mono.shape.command.MoveLineEdge import mono.shape.connector.ShapeConnectorUseCase import mono.shape.shape.Line import mono.shapebound.LineInteractionPoint import mono.state.command.CommandEnvironment /** * A [MouseCommand] for moving anchor points or edges of Line shape. */ internal class LineInteractionMouseCommand( private val lineShape: Line, private val interactionPoint: LineInteractionPoint ) : MouseCommand { override val mouseCursor: MouseCursor? = null override fun execute( environment: CommandEnvironment, mousePointer: MousePointer ): MouseCommand.CommandResultType { when (mousePointer) { is MousePointer.Drag -> move( environment, mousePointer.boardCoordinate, isUpdateConfirmed = false, justMoveAnchor = !mousePointer.isWithShiftKey ) is MousePointer.Up -> move( environment, mousePointer.boardCoordinate, isUpdateConfirmed = true, justMoveAnchor = !mousePointer.isWithShiftKey ) is MousePointer.Down, is MousePointer.Click, is MousePointer.DoubleClick, is MousePointer.Move, MousePointer.Idle -> Unit }.exhaustive return if (mousePointer == MousePointer.Idle) { MouseCommand.CommandResultType.DONE } else { MouseCommand.CommandResultType.WORKING } } private fun move( environment: CommandEnvironment, point: Point, isUpdateConfirmed: Boolean, justMoveAnchor: Boolean ) { when (interactionPoint) { is LineInteractionPoint.Anchor -> moveAnchor(environment, interactionPoint, point, isUpdateConfirmed, justMoveAnchor) is LineInteractionPoint.Edge -> moveEdge(environment, interactionPoint, point, isUpdateConfirmed) } } private fun moveAnchor( environment: CommandEnvironment, interactionPoint: LineInteractionPoint.Anchor, point: Point, isUpdateConfirmed: Boolean, justMoveAnchor: Boolean ) { val edgeDirection = environment.getEdgeDirection(point) val direction = edgeDirection?.normalizedDirection ?: lineShape.getDirection(interactionPoint.anchor) val anchorPointUpdate = Line.AnchorPointUpdate( interactionPoint.anchor, DirectedPoint(direction, point) ) val connectShape = ShapeConnectorUseCase.getConnectableShape( anchorPointUpdate.point, environment.getShapes(point) ) environment.shapeManager.execute( MoveLineAnchor( lineShape, anchorPointUpdate, isUpdateConfirmed, justMoveAnchor = justMoveAnchor, connectShape = connectShape ) ) environment.updateInteractionBounds() } private fun moveEdge( environment: CommandEnvironment, interactionPoint: LineInteractionPoint.Edge, point: Point, isUpdateConfirmed: Boolean ) { environment.shapeManager.execute( MoveLineEdge( lineShape, interactionPoint.edgeId, point, isUpdateConfirmed ) ) environment.updateInteractionBounds() } }
12
Kotlin
1
144
f725b8890118f75c583eaf04d0de927103486744
3,801
MonoSketch
Apache License 2.0