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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/SiteBrowser.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.SiteBrowser: ImageVector
get() {
if (_siteBrowser != null) {
return _siteBrowser!!
}
_siteBrowser = Builder(name = "SiteBrowser", 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(15.363f, 16.221f)
lineToRelative(-0.314f, -3.659f)
curveToRelative(-0.026f, -0.302f, 0.212f, -0.562f, 0.515f, -0.562f)
curveToRelative(0.27f, 0.0f, 0.494f, 0.207f, 0.516f, 0.477f)
lineToRelative(0.212f, 2.681f)
lineToRelative(0.75f, -1.443f)
curveToRelative(0.193f, -0.372f, 0.725f, -0.372f, 0.918f, 0.0f)
lineToRelative(0.75f, 1.443f)
lineToRelative(0.21f, -2.681f)
curveToRelative(0.021f, -0.269f, 0.246f, -0.477f, 0.516f, -0.477f)
horizontalLineToRelative(0.002f)
curveToRelative(0.303f, 0.0f, 0.541f, 0.26f, 0.515f, 0.562f)
lineToRelative(-0.314f, 3.659f)
curveToRelative(-0.031f, 0.44f, -0.337f, 0.779f, -0.706f, 0.779f)
curveToRelative(-0.244f, 0.0f, -0.471f, -0.151f, -0.601f, -0.4f)
lineToRelative(-0.831f, -1.6f)
lineToRelative(-0.831f, 1.6f)
curveToRelative(-0.129f, 0.249f, -0.356f, 0.4f, -0.601f, 0.4f)
curveToRelative(-0.368f, 0.0f, -0.675f, -0.339f, -0.706f, -0.779f)
close()
moveTo(24.0f, 6.5f)
verticalLineToRelative(11.0f)
curveToRelative(0.0f, 3.033f, -2.468f, 5.5f, -5.5f, 5.5f)
lineTo(5.5f, 23.0f)
curveToRelative(-3.033f, 0.0f, -5.5f, -2.467f, -5.5f, -5.5f)
lineTo(0.0f, 6.5f)
curveTo(0.0f, 3.467f, 2.467f, 1.0f, 5.5f, 1.0f)
horizontalLineToRelative(13.0f)
curveToRelative(3.032f, 0.0f, 5.5f, 2.467f, 5.5f, 5.5f)
close()
moveTo(8.0f, 4.5f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
close()
moveTo(3.0f, 4.5f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
close()
moveTo(21.0f, 8.0f)
lineTo(3.0f, 8.0f)
verticalLineToRelative(9.5f)
curveToRelative(0.0f, 1.378f, 1.122f, 2.5f, 2.5f, 2.5f)
horizontalLineToRelative(13.0f)
curveToRelative(1.379f, 0.0f, 2.5f, -1.122f, 2.5f, -2.5f)
verticalLineToRelative(-9.5f)
close()
moveTo(5.068f, 17.0f)
curveToRelative(0.244f, 0.0f, 0.471f, -0.151f, 0.601f, -0.4f)
lineToRelative(0.831f, -1.6f)
lineToRelative(0.831f, 1.6f)
curveToRelative(0.129f, 0.249f, 0.356f, 0.4f, 0.601f, 0.4f)
curveToRelative(0.368f, 0.0f, 0.675f, -0.339f, 0.706f, -0.779f)
lineToRelative(0.314f, -3.659f)
curveToRelative(0.026f, -0.302f, -0.212f, -0.562f, -0.515f, -0.562f)
horizontalLineToRelative(-0.002f)
curveToRelative(-0.27f, 0.0f, -0.495f, 0.208f, -0.516f, 0.477f)
lineToRelative(-0.21f, 2.681f)
lineToRelative(-0.75f, -1.443f)
curveToRelative(-0.193f, -0.372f, -0.725f, -0.372f, -0.918f, 0.0f)
lineToRelative(-0.75f, 1.443f)
lineToRelative(-0.212f, -2.681f)
curveToRelative(-0.021f, -0.269f, -0.246f, -0.477f, -0.516f, -0.477f)
curveToRelative(-0.303f, 0.0f, -0.541f, 0.26f, -0.515f, 0.562f)
lineToRelative(0.314f, 3.659f)
curveToRelative(0.031f, 0.44f, 0.337f, 0.779f, 0.706f, 0.779f)
close()
moveTo(10.568f, 17.0f)
curveToRelative(0.244f, 0.0f, 0.471f, -0.151f, 0.601f, -0.4f)
lineToRelative(0.831f, -1.6f)
lineToRelative(0.831f, 1.6f)
curveToRelative(0.129f, 0.249f, 0.356f, 0.4f, 0.601f, 0.4f)
curveToRelative(0.368f, 0.0f, 0.675f, -0.339f, 0.706f, -0.779f)
lineToRelative(0.314f, -3.659f)
curveToRelative(0.026f, -0.302f, -0.212f, -0.562f, -0.515f, -0.562f)
horizontalLineToRelative(-0.481f)
lineToRelative(-0.247f, 3.158f)
lineToRelative(-0.75f, -1.443f)
curveToRelative(-0.193f, -0.372f, -0.725f, -0.372f, -0.918f, 0.0f)
lineToRelative(-0.75f, 1.443f)
lineToRelative(-0.212f, -2.681f)
curveToRelative(-0.021f, -0.269f, -0.246f, -0.477f, -0.516f, -0.477f)
curveToRelative(-0.303f, 0.0f, -0.541f, 0.26f, -0.515f, 0.562f)
lineToRelative(0.314f, 3.659f)
curveToRelative(0.031f, 0.44f, 0.337f, 0.779f, 0.706f, 0.779f)
close()
}
}
.build()
return _siteBrowser!!
}
private var _siteBrowser: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 6,380 | icons | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/SiteBrowser.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.SiteBrowser: ImageVector
get() {
if (_siteBrowser != null) {
return _siteBrowser!!
}
_siteBrowser = Builder(name = "SiteBrowser", 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(15.363f, 16.221f)
lineToRelative(-0.314f, -3.659f)
curveToRelative(-0.026f, -0.302f, 0.212f, -0.562f, 0.515f, -0.562f)
curveToRelative(0.27f, 0.0f, 0.494f, 0.207f, 0.516f, 0.477f)
lineToRelative(0.212f, 2.681f)
lineToRelative(0.75f, -1.443f)
curveToRelative(0.193f, -0.372f, 0.725f, -0.372f, 0.918f, 0.0f)
lineToRelative(0.75f, 1.443f)
lineToRelative(0.21f, -2.681f)
curveToRelative(0.021f, -0.269f, 0.246f, -0.477f, 0.516f, -0.477f)
horizontalLineToRelative(0.002f)
curveToRelative(0.303f, 0.0f, 0.541f, 0.26f, 0.515f, 0.562f)
lineToRelative(-0.314f, 3.659f)
curveToRelative(-0.031f, 0.44f, -0.337f, 0.779f, -0.706f, 0.779f)
curveToRelative(-0.244f, 0.0f, -0.471f, -0.151f, -0.601f, -0.4f)
lineToRelative(-0.831f, -1.6f)
lineToRelative(-0.831f, 1.6f)
curveToRelative(-0.129f, 0.249f, -0.356f, 0.4f, -0.601f, 0.4f)
curveToRelative(-0.368f, 0.0f, -0.675f, -0.339f, -0.706f, -0.779f)
close()
moveTo(24.0f, 6.5f)
verticalLineToRelative(11.0f)
curveToRelative(0.0f, 3.033f, -2.468f, 5.5f, -5.5f, 5.5f)
lineTo(5.5f, 23.0f)
curveToRelative(-3.033f, 0.0f, -5.5f, -2.467f, -5.5f, -5.5f)
lineTo(0.0f, 6.5f)
curveTo(0.0f, 3.467f, 2.467f, 1.0f, 5.5f, 1.0f)
horizontalLineToRelative(13.0f)
curveToRelative(3.032f, 0.0f, 5.5f, 2.467f, 5.5f, 5.5f)
close()
moveTo(8.0f, 4.5f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
close()
moveTo(3.0f, 4.5f)
curveToRelative(0.0f, 0.828f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
close()
moveTo(21.0f, 8.0f)
lineTo(3.0f, 8.0f)
verticalLineToRelative(9.5f)
curveToRelative(0.0f, 1.378f, 1.122f, 2.5f, 2.5f, 2.5f)
horizontalLineToRelative(13.0f)
curveToRelative(1.379f, 0.0f, 2.5f, -1.122f, 2.5f, -2.5f)
verticalLineToRelative(-9.5f)
close()
moveTo(5.068f, 17.0f)
curveToRelative(0.244f, 0.0f, 0.471f, -0.151f, 0.601f, -0.4f)
lineToRelative(0.831f, -1.6f)
lineToRelative(0.831f, 1.6f)
curveToRelative(0.129f, 0.249f, 0.356f, 0.4f, 0.601f, 0.4f)
curveToRelative(0.368f, 0.0f, 0.675f, -0.339f, 0.706f, -0.779f)
lineToRelative(0.314f, -3.659f)
curveToRelative(0.026f, -0.302f, -0.212f, -0.562f, -0.515f, -0.562f)
horizontalLineToRelative(-0.002f)
curveToRelative(-0.27f, 0.0f, -0.495f, 0.208f, -0.516f, 0.477f)
lineToRelative(-0.21f, 2.681f)
lineToRelative(-0.75f, -1.443f)
curveToRelative(-0.193f, -0.372f, -0.725f, -0.372f, -0.918f, 0.0f)
lineToRelative(-0.75f, 1.443f)
lineToRelative(-0.212f, -2.681f)
curveToRelative(-0.021f, -0.269f, -0.246f, -0.477f, -0.516f, -0.477f)
curveToRelative(-0.303f, 0.0f, -0.541f, 0.26f, -0.515f, 0.562f)
lineToRelative(0.314f, 3.659f)
curveToRelative(0.031f, 0.44f, 0.337f, 0.779f, 0.706f, 0.779f)
close()
moveTo(10.568f, 17.0f)
curveToRelative(0.244f, 0.0f, 0.471f, -0.151f, 0.601f, -0.4f)
lineToRelative(0.831f, -1.6f)
lineToRelative(0.831f, 1.6f)
curveToRelative(0.129f, 0.249f, 0.356f, 0.4f, 0.601f, 0.4f)
curveToRelative(0.368f, 0.0f, 0.675f, -0.339f, 0.706f, -0.779f)
lineToRelative(0.314f, -3.659f)
curveToRelative(0.026f, -0.302f, -0.212f, -0.562f, -0.515f, -0.562f)
horizontalLineToRelative(-0.481f)
lineToRelative(-0.247f, 3.158f)
lineToRelative(-0.75f, -1.443f)
curveToRelative(-0.193f, -0.372f, -0.725f, -0.372f, -0.918f, 0.0f)
lineToRelative(-0.75f, 1.443f)
lineToRelative(-0.212f, -2.681f)
curveToRelative(-0.021f, -0.269f, -0.246f, -0.477f, -0.516f, -0.477f)
curveToRelative(-0.303f, 0.0f, -0.541f, 0.26f, -0.515f, 0.562f)
lineToRelative(0.314f, 3.659f)
curveToRelative(0.031f, 0.44f, 0.337f, 0.779f, 0.706f, 0.779f)
close()
}
}
.build()
return _siteBrowser!!
}
private var _siteBrowser: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 6,380 | icons | MIT License |
verify/src/main/java/com/twilio/verify/networking/AuthenticationProvider.kt | twilio | 232,428,508 | false | null | /*
* Copyright (c) 2020 Twilio Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twilio.verify.networking
import com.twilio.security.logger.Level
import com.twilio.security.logger.Logger
import com.twilio.verify.TwilioVerifyException
import com.twilio.verify.TwilioVerifyException.ErrorCode.AuthenticationTokenError
import com.twilio.verify.data.DateProvider
import com.twilio.verify.data.getSignerTemplate
import com.twilio.verify.data.jwt.JwtGenerator
import com.twilio.verify.domain.factor.models.PushFactor
import com.twilio.verify.models.Factor
import java.util.concurrent.TimeUnit
import org.json.JSONObject
internal const val ctyKey = "cty"
internal const val kidKey = "kid"
internal const val jwtValidFor = 10L
internal const val subKey = "sub"
internal const val expKey = "exp"
internal const val iatKey = "nbf"
internal const val contentType = "twilio-pba;v=1"
internal class AuthenticationProvider(
private val jwtGenerator: JwtGenerator,
private val dateProvider: DateProvider
) : Authentication {
override fun generateJWT(
factor: Factor
): String {
try {
return when (factor) {
is PushFactor -> generateJwt(factor)
else -> throw IllegalArgumentException("Not supported factor for JWT generation")
}
} catch (e: Exception) {
Logger.log(Level.Error, e.toString(), e)
throw TwilioVerifyException(e, AuthenticationTokenError)
}
}
private fun generateJwt(factor: PushFactor): String {
val header = generateHeader(factor)
val payload = generatePayload(factor)
val alias = factor.keyPairAlias ?: throw IllegalStateException("Key pair not set")
return jwtGenerator.generateJWT(getSignerTemplate(alias, true), header, payload)
}
private fun generateHeader(factor: PushFactor) = JSONObject().apply {
put(ctyKey, contentType)
put(kidKey, factor.config.credentialSid)
}
private fun generatePayload(factor: PushFactor) =
JSONObject().apply {
put(subKey, factor.accountSid)
put(
expKey,
dateProvider.getCurrentTime() + TimeUnit.MINUTES.toSeconds(
jwtValidFor
)
)
put(iatKey, dateProvider.getCurrentTime())
}
}
| 5 | null | 3 | 9 | 7599b76a8eff6ceff2d6c5eb05fe0d0ebe7fe172 | 2,714 | twilio-verify-android | Apache License 2.0 |
mobzy-pathfinding/src/main/kotlin/com/mineinabyss/mobzy/ecs/goals/mobzy/flying/IdleFlyAboveGroundGoal.kt | MineInAbyss | 142,800,887 | false | null | package com.mineinabyss.mobzy.ecs.goals.mobzy.flying
import com.mineinabyss.idofront.destructure.component1
import com.mineinabyss.idofront.destructure.component2
import com.mineinabyss.idofront.destructure.component3
import com.mineinabyss.idofront.nms.pathfindergoals.moveTo
import com.mineinabyss.mobzy.ecs.components.initialization.pathfinding.PathfinderComponent
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.bukkit.Location
import org.bukkit.entity.Mob
import kotlin.random.Random
@Serializable
@SerialName("mobzy:behavior.idle_fly_above_ground")
class IdleFlyAboveGroundBehavior(
private val maxHeight: Double = 4.0,
private val radius: Double = 5.0
) : PathfinderComponent() {
override fun build(mob: Mob) = IdleFlyAboveGroundGoal(
mob,
maxHeight,
radius
)
}
class IdleFlyAboveGroundGoal(
mob: Mob,
private val maxHeight: Double = 4.0,
private val radius: Double = 5.0
) : IdleFlyGoal(mob) {
override fun init() {
val (x, y, z) = mob.location
val dx = x + Random.nextDouble(-radius, radius)
val dy = y + Random.nextDouble(-radius, radius / 2) //make it more likely to fly down
val dz = z + Random.nextDouble(-radius, radius)
val loc = Location(mob.world, dx, dy, dz)
if (!loc.clone().add(0.0, -maxHeight, 0.0).block.type.isSolid) {
moveController.moveTo(dx, dy - 0.1, dz, speed = 1.0)
return
}
if (y > 16) { //keep mobs from going down and killing themselves
targetLoc = loc
//TODO make a wrapper for the controller and figure out the difference between it and navigation
moveController.moveTo(x, y, z, 1.0)
}
}
}
| 13 | Kotlin | 8 | 29 | 6fdf955a0bc906f297eb91340fcdcabf5031beef | 1,764 | Mobzy | MIT License |
server/src/test/kotlin/com/mtraina/webtables/WebTablesApplicationTests.kt | mtraina | 128,670,482 | false | {"JavaScript": 25877, "Vue": 7604, "Kotlin": 3970, "HTML": 264} | package com.mtraina.webtables
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class WebTablesApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | JavaScript | 0 | 0 | aa0b7dabea3c8add616bc9af7a53c16318b62315 | 322 | wed-tables | Apache License 2.0 |
src/commonMain/kotlin/com/ucasoft/kcron/parsers/DaysParser.kt | Scogun | 309,119,232 | false | {"Kotlin": 75093} | package com.ucasoft.kcron.parsers
import com.ucasoft.kcron.common.CronPart
import com.ucasoft.kcron.common.DayGroups
class DaysParser : AnySpecificEveryAtParser<DayGroups>("\\?", "[1-9]|[1-2][0-9]|3[0-1]") {
override val additionalParts: String
get() = super.additionalParts + "|(L)|(LW)|(L-(?:${specificNumberPattern}))|((?:${specificNumberPattern})W)"
override val unknownGroup = DayGroups.Unknown
override val groups = DayGroups.entries
override val part = CronPart.Days
} | 4 | Kotlin | 3 | 18 | 855ec7f7cfb611dddb8e46112221faf0ce21cf1b | 505 | kcron-common | Apache License 2.0 |
features/profile/src/main/java/com/chesire/nekome/app/profile/SeriesProgress.kt | Chesire | 223,272,337 | false | null | package com.chesire.nekome.app.profile
/**
* Container for the different states a series can be in, aids with displaying on the profile.
*/
data class SeriesProgress(
val total: String,
val current: String,
val completed: String,
val onHold: String,
val dropped: String,
val planned: String,
val unknown: String
)
| 24 | Kotlin | 31 | 269 | d9747aeb6ca7dab5fa3ed6925b5cb7715915c3e0 | 345 | Nekome | Apache License 2.0 |
src/main/kotlin/rally/montecarl/security/AuthHelper.kt | jaksah | 345,928,956 | false | null | package rally.montecarl.security
import com.nimbusds.jose.shaded.json.JSONArray
import io.micronaut.security.authentication.Authentication
import rally.montecarl.repositories.TeamRole
import java.util.*
object AuthHelper {
fun getTeamId(auth: Authentication): UUID {
return UUID.fromString((auth.attributes["teamId"] ?: error("Invalid token: teamId not found")) as String)
}
fun getAdminRole(auth: Authentication): TeamRole? {
return auth.attributes["roles"]
?.let { it as JSONArray }
?.let { it.map { r -> TeamRole.valueOf(r as String) } }
?.let { it.find { r -> TeamRole.ADMIN == r }}
}
} | 0 | Kotlin | 0 | 0 | 58b156fd13408cc65ac44920868b5c0b7fdc6e0e | 661 | rebus-rmc | MIT License |
app/src/main/java/org/simple/clinic/registration/RegistrationApi.kt | eco4ndly | 244,967,563 | false | {"Gradle": 9, "Shell": 4, "Markdown": 26, "Java Properties": 2, "Text": 1, "Ignore List": 8, "Batchfile": 1, "YAML": 3, "Kotlin": 1176, "XML": 237, "INI": 2, "Proguard": 2, "JSON": 62, "Java": 1, "SVG": 1} | package org.simple.clinic.registration
import io.reactivex.Single
import org.simple.clinic.user.LoggedInUserPayload
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
interface RegistrationApi {
@GET("users/find")
fun findUser(
@Query("phone_number") phoneNumber: String
): Single<LoggedInUserPayload>
@POST("users/register")
fun createUser(
@Body body: RegistrationRequest
): Single<RegistrationResponse>
}
| 1 | null | 1 | 1 | c0bb3139dada4f34206928ec81f1e5f6f056134b | 493 | simple-android | MIT License |
bbfgradle/tmp/results/diffABI/jdwpjgk_FILE.kt | DaniilStepanov | 346,008,310 | false | {"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1} | // Bug happens on JVM , JVM -Xuse-ir
// FILE: tmp0.kt
import kotlin.collections.AbstractList
enum class Test {
A, B, OTHER
}
fun peek():Test = TODO()
fun box(): String =TODO()
data public class A(val vv: Test): AbstractList <ULong>(){
override val size: kotlin.Int
get() = TODO()
override fun contains(element: kotlin.ULong): kotlin.Boolean = TODO()
override fun get(index: kotlin.Int): kotlin.ULong = TODO()
override fun isEmpty(): kotlin.Boolean = TODO()
override fun iterator(): kotlin.collections.Iterator<kotlin.ULong> = TODO()
override fun toArray(): kotlin.Array<kotlin.Any?> = TODO()
override fun <T> toArray(array: kotlin.Array<T>): kotlin.Array<T> = TODO()
inline public fun <T> rehid(a: T): List<Test> = TODO()
val xhovj: Int = TODO()
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 777 | kotlinWithFuzzer | Apache License 2.0 |
backend-spring/rest-api/src/main/kotlin/com/jacknie/sample/chat/handler/ChatRoomHandler.kt | jacknie84 | 443,538,016 | false | {"Kotlin": 21270, "TypeScript": 19953, "CSS": 1973, "JavaScript": 235} | package com.jacknie.sample.chat.handler
import com.jacknie.sample.chat.model.ChatRoom
import com.jacknie.sample.chat.model.ChatRoomFilter
import com.jacknie.sample.chat.repository.ChatCategoryRepository
import com.jacknie.sample.chat.repository.ChatRoomRepository
import org.springframework.stereotype.Component
import org.springframework.util.MultiValueMap
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import reactor.core.publisher.Mono
@Component
class ChatRoomHandler(
private val chatRoomRepository: ChatRoomRepository,
private val chatCategoryRepository: ChatCategoryRepository,
private val validation: Validation,
) {
fun postChatRoom(request: ServerRequest): Mono<ServerResponse> {
return validation.bodyToMono<CreateChatRoom>(request)
.map { ChatRoom(subject = it.subject, capacity = it.capacity, categoryId = it.categoryId) }
.flatMap { validateCategoryId(it) }
.flatMap { chatRoomRepository.save(it) }
.map { request.uriBuilder().path("/{id}").build(it.id) }
.flatMap { ServerResponse.created(it).build() }
}
fun getChatRoom(request: ServerRequest): Mono<ServerResponse> {
return request.pathVariable("id")
.let { validation.toLong(it, "id must be integer") }
.flatMap { chatRoomRepository.findById(it) }
.flatMap { ServerResponse.ok().bodyValue(it) }
.switchIfEmpty(ServerResponse.notFound().build())
}
fun getChatRooms(request: ServerRequest): Mono<ServerResponse> {
val queryParams = request.queryParams()
val filter = getChatRoomFilter(queryParams)
val pageable = getPageable(queryParams)
return chatRoomRepository.findAll(filter, pageable).flatMap { paginationServerResponse(it) }
}
private fun getChatRoomFilter(queryParams: MultiValueMap<String, String>): ChatRoomFilter {
val keyword = queryParams.getFirst("keyword")
return ChatRoomFilter(keyword)
}
private fun validateCategoryId(room: ChatRoom): Mono<ChatRoom> {
val roomMono = Mono.just(room)
val categoryId = room.categoryId
val booleanMono = chatCategoryRepository.existsById(categoryId)
val errorMessage = "categoryId(${categoryId})로 ChatCategory 를 찾을 수 없습니다."
return validation.assertTrue(booleanMono, errorMessage).then(roomMono)
}
}
| 2 | Kotlin | 0 | 2 | bf7d36d927e1aff98e9da1ae157ad414f68f6ed4 | 2,479 | sample-chat-app | MIT License |
app/src/main/java/com/example/birlik/data/repository/AuthRepo.kt | zaurh | 784,302,222 | false | {"Kotlin": 361823} | package com.example.birlik.data.repository
import android.content.Context
import android.util.Patterns
import android.widget.Toast
import androidx.compose.runtime.mutableStateOf
import com.example.birlik.R
import com.example.birlik.data.remote.CountryData
import com.example.birlik.data.remote.UserData
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
class AuthRepo @Inject constructor(
private val auth: FirebaseAuth,
private val userRepo: UserRepo
) {
val isAuthLoading = mutableStateOf(false)
val isSignedIn = mutableStateOf(false)
private val _currentUserId = MutableStateFlow<String?>(null)
val currentUserId: StateFlow<String?> = _currentUserId
init {
isSignedIn.value = auth.currentUser != null
auth.addAuthStateListener { firebaseAuth ->
val userId = firebaseAuth.currentUser?.uid
_currentUserId.value = userId
}
}
fun signUp(
username: String,
country: String,
password: String,
context: Context
) {
isAuthLoading.value = true
if (!checkValidEmail(username)) {
Toast.makeText(context, "Email is not valid.", Toast.LENGTH_SHORT).show()
isAuthLoading.value = false
} else if (password.length < 8) {
Toast.makeText(context, "Password should be at least 8 characters.", Toast.LENGTH_SHORT)
.show()
isAuthLoading.value = false
} else {
checkEmailExistence(email = username, context)
auth.createUserWithEmailAndPassword(username, password)
.addOnSuccessListener {
isAuthLoading.value = false
isSignedIn.value = true
userRepo.addUser(
UserData(
userId = auth.currentUser?.uid.toString(),
username = username,
country = CountryData(
name = country,
image = when (country) {
"Polşa" -> R.drawable.pl
"Azərbaycan" -> R.drawable.az
else -> {
1
}
}
)
)
)
}
.addOnFailureListener {
isAuthLoading.value = false
}
}
}
fun signIn(email: String, password: String, context: Context) {
isAuthLoading.value = true
auth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener {
auth.currentUser?.let {
isAuthLoading.value = false
isSignedIn.value = true
}
}
.addOnFailureListener {
isAuthLoading.value = false
Toast.makeText(context, "Email or password is incorrect", Toast.LENGTH_SHORT).show()
}
}
fun signOut() {
auth.signOut()
isSignedIn.value = false
}
fun forgotPassword(email: String, context: Context) {
auth.sendPasswordResetEmail(email).addOnSuccessListener {
Toast.makeText(context, "Sent. Please check your email.", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(
context,
"Problem occurred. Please enter valid email.",
Toast.LENGTH_SHORT
).show()
}
}
//***************** Firebase AUTH Catching errors *********************
private fun checkEmailExistence(email: String, context: Context) {
auth.fetchSignInMethodsForEmail(email)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val result = task.result
if (result?.signInMethods?.isEmpty() == true) {
// Email does not exist
} else {
Toast.makeText(context, "Email is already registered.", Toast.LENGTH_SHORT)
.show()
isAuthLoading.value = false
}
} else {
// Error occurred
}
}
}
private fun checkValidEmail(email: String): Boolean {
val emailPattern = Patterns.EMAIL_ADDRESS
return emailPattern.matcher(email).matches()
}
} | 0 | Kotlin | 3 | 4 | f5cf9f0a339ea3b638f11f3ce7bdb2988ae370bd | 4,734 | Durak | MIT License |
feature_onboarding/onboarding_presentation/src/main/java/tech/ericwathome/presentation/onboarding_screen/OnboardingViewModel.kt | ericwafula | 514,323,986 | false | null | package tech.ericwathome.presentation.onboarding_screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import tech.ericwathome.onboarding_domain.use_case.OnboardingUseCases
import javax.inject.Inject
@HiltViewModel
class OnboardingViewModel @Inject constructor(
private val useCases: OnboardingUseCases
) : ViewModel() {
fun updateOnboardingState(showOnboarding: Boolean) {
viewModelScope.launch(Dispatchers.IO) {
useCases.updateOnboardingStatus(showOnboarding)
}
}
} | 0 | Kotlin | 1 | 5 | 26b67ec6532411653402de461ab09931b6475df4 | 663 | CurrencyBudy | MIT License |
app/src/main/java/org/stepik/android/domain/course_content/interactor/CourseContentInteractor.kt | d1sc0d | 362,793,745 | true | {"Kotlin": 3409874, "Java": 1002611, "CSS": 5464, "Shell": 618, "Prolog": 98} | package org.stepik.android.domain.course_content.interactor
import com.google.firebase.perf.FirebasePerformance
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.Singles.zip
import io.reactivex.rxkotlin.toObservable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import ru.nobird.android.core.model.mapToLongArray
import org.stepic.droid.util.plus
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_content.model.SessionData
import org.stepik.android.domain.exam_session.model.ExamSession
import org.stepik.android.domain.exam_session.repository.ExamSessionRepository
import org.stepik.android.domain.lesson.repository.LessonRepository
import org.stepik.android.domain.proctor_session.model.ProctorSession
import org.stepik.android.domain.proctor_session.repository.ProctorSessionRepository
import org.stepik.android.domain.progress.mapper.getProgresses
import org.stepik.android.domain.progress.repository.ProgressRepository
import org.stepik.android.domain.section.repository.SectionRepository
import org.stepik.android.domain.unit.repository.UnitRepository
import org.stepik.android.model.Course
import org.stepik.android.model.Section
import org.stepik.android.model.Unit
import org.stepik.android.presentation.course_content.mapper.CourseContentItemMapper
import org.stepik.android.view.course_content.model.CourseContentItem
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
class CourseContentInteractor
@Inject
constructor(
private val courseObservableSource: Observable<Course>,
private val sectionRepository: SectionRepository,
private val unitRepository: UnitRepository,
private val lessonRepository: LessonRepository,
private val progressRepository: ProgressRepository,
private val examSessionRepository: ExamSessionRepository,
private val proctorSessionRepository: ProctorSessionRepository,
private val courseContentItemMapper: CourseContentItemMapper
) {
companion object {
private const val UNITS_CHUNK_SIZE = 10
}
fun getCourseContent(shouldSkipStoredValue: Boolean = false): Observable<Pair<Course, List<CourseContentItem>>> {
val count = AtomicInteger(0)
return courseObservableSource
.skip(if (shouldSkipStoredValue) 1 else 0)
.switchMap { course ->
val shouldUseCache = !shouldSkipStoredValue && count.getAndIncrement() < 1
val contentObservable =
if (shouldUseCache) {
val cacheSource = getContent(course, emptyList(), DataSourceType.CACHE)
.share()
val remoteSource = cacheSource
.lastOrError()
.flatMapObservable { (_, items) ->
getContent(course, items, DataSourceType.REMOTE)
}
Observable.concat(cacheSource, remoteSource)
} else {
getContent(course, emptyList(), DataSourceType.REMOTE)
}
Observable.concat(getEmptySections(course), contentObservable)
}
}
private fun getEmptySections(course: Course): Observable<Pair<Course, List<CourseContentItem>>> =
Observable.just(course to emptyList())
private fun getContent(course: Course, items: List<CourseContentItem>, dataSourceType: DataSourceType): Observable<Pair<Course, List<CourseContentItem>>> {
val courseContentLoadingTrace = FirebasePerformance.getInstance().newTrace(Analytic.Traces.COURSE_CONTENT_LOADING)
courseContentLoadingTrace.putAttribute(AmplitudeAnalytic.Course.Params.COURSE, course.id.toString())
courseContentLoadingTrace.putAttribute(AmplitudeAnalytic.Course.Params.SOURCE, dataSourceType.name)
courseContentLoadingTrace.start()
return getSectionsOfCourse(course, dataSourceType)
.flatMap { populateSections(course, it, items, dataSourceType) }
.flatMapObservable { populatedItems ->
Observable.just(course to populatedItems) + loadUnits(course, populatedItems, dataSourceType)
}
.doOnComplete {
courseContentLoadingTrace.stop()
}
}
private fun getSectionsOfCourse(course: Course, dataSourceType: DataSourceType): Single<List<Section>> =
sectionRepository
.getSections(course.sections ?: listOf(), primarySourceType = dataSourceType)
private fun populateSections(course: Course, sections: List<Section>, items: List<CourseContentItem>, dataSourceType: DataSourceType): Single<List<CourseContentItem>> =
zip(
if (dataSourceType == DataSourceType.CACHE) Single.just(emptyList()) else progressRepository.getProgresses(sections.getProgresses()),
getSessionData(sections, dataSourceType)
) { progresses, sessionData ->
courseContentItemMapper.mapSectionsWithEmptyUnits(course, sections, items.filterIsInstance<CourseContentItem.UnitItem>(), progresses, sessionData)
}
private fun loadUnits(course: Course, items: List<CourseContentItem>, dataSourceType: DataSourceType): Observable<Pair<Course, List<CourseContentItem>>> =
Observable
.fromCallable { courseContentItemMapper.getUnitPlaceholdersIds(items) }
.flatMap { unitIds ->
val subject = PublishSubject.create<List<String>>()
val unitsSource = unitIds
.chunked(UNITS_CHUNK_SIZE)
.toObservable()
.concatMapSingle { ids ->
getUnits(ids, dataSourceType)
.flatMap { units ->
lessonRepository
.getLessons(*units.mapToLongArray(Unit::lesson), primarySourceType = dataSourceType)
.map { units to it }
.doOnSuccess { subject.onNext(units.getProgresses()) }
}
}
val progressesSource =
if (dataSourceType == DataSourceType.CACHE) {
Observable.just(emptyList())
} else {
Observable.concat(
Observable.just(emptyList()),
subject
.observeOn(Schedulers.io())
.flatMapSingle { progressIds ->
progressRepository.getProgresses(progressIds)
}
)
}
Observables
.combineLatest(progressesSource, unitsSource) { progresses, (units, lessons) ->
Triple(units, lessons, progresses)
}
.scan(items) { newItems, (units, lessons, progresses) ->
val sectionItems = newItems
.filterIsInstance<CourseContentItem.SectionItem>()
val unitItems = courseContentItemMapper.mapUnits(course, sectionItems, units, lessons, progresses)
courseContentItemMapper.replaceUnits(newItems, unitItems, progresses)
}
}
.map { course to it }
private fun getUnits(unitIds: List<Long>, dataSourceType: DataSourceType): Single<List<Unit>> =
unitRepository
.getUnits(unitIds, primarySourceType = dataSourceType)
private fun getSessionData(sections: List<Section>, dataSourceType: DataSourceType): Single<List<SessionData>> =
zip(
examSessionRepository.getExamSessions(sections.mapNotNull(Section::examSession), dataSourceType).onErrorReturnItem(emptyList()),
proctorSessionRepository.getProctorSessions(sections.mapNotNull(Section::proctorSession), dataSourceType).onErrorReturnItem(emptyList())
) { examSessions, proctorSessions ->
val examSessionsMap = examSessions.associateBy(ExamSession::section)
val proctorSessionsMap = proctorSessions.associateBy(ProctorSession::section)
sections.map { section ->
SessionData(
sectionId = section.id,
examSession = examSessionsMap[section.id],
proctorSession = proctorSessionsMap[section.id]
)
}
}
} | 0 | null | 0 | 0 | 29711b252497178e3beabd75537bcb1c00ba64bf | 8,786 | stepik-android | Apache License 2.0 |
test/src/me/anno/tests/engine/material/AutoTilableMaterial.kt | AntonioNoack | 456,513,348 | false | null | package me.anno.tests.engine.material
import me.anno.ecs.components.mesh.material.AutoTileableMaterial
import me.anno.engine.ui.render.SceneView.Companion.testSceneWithUI
import me.anno.utils.OS.pictures
fun main() {
val material = AutoTileableMaterial()
material.diffuseMap = pictures.getChild("textures/grass.jpg")
testSceneWithUI("AutoTileable Material", material)
} | 0 | null | 3 | 24 | 63377c2e684adf187a31af0f4e5dd0bfde1d050e | 383 | RemsEngine | Apache License 2.0 |
ffc/src/main/kotlin/ffc/app/photo/asymmetric/item/ZeroImagePresent.kt | ffc-nectec | 125,313,191 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "JSON": 12, "Kotlin": 175, "XML": 216, "Java": 60, "HTML": 1, "JavaScript": 11} | package ffc.app.photo.asymmetric.item
import ffc.app.photo.asymmetric.ImageItem
class ZeroImagePresent : ImagePresent {
override val maxDisplayItem: Int
get() = 1
override val item: List<ImageItem>
get() = listOf()
override val requestColumns: Int
get() = 1
}
| 5 | JavaScript | 1 | 2 | f19e7ea2cb3f891d3786b0f66d7c0cdf1c114eab | 298 | android | Apache License 2.0 |
commands/src/main/kotlin/tech/carcadex/kotlinbukkitkit/commands/dsl/DSLCommandArguments.kt | CarcadeX | 681,093,300 | false | {"Kotlin": 301127, "Java": 26805} | package tech.carcadex.kotlinbukkitkit.commands.dsl
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.OfflinePlayer
import org.bukkit.World
import org.bukkit.entity.Player
import tech.carcadex.kotlinbukkitkit.commands.exceptions.ArgumentNotFoundException
import tech.carcadex.kotlinbukkitkit.commands.exceptions.TypeParseException
import tech.carcadex.kotlinbukkitkit.commands.service.MessagesService
fun ExecutorContext.string(index: Int): String = argument(index) ?: throw ArgumentNotFoundException(index)
fun ExecutorContext.stringOrNull(index: Int): String? = argument(index)
fun ExecutorContext.integer(index: Int): Int = try {
argument(index)?.toInt()
} catch (e: NumberFormatException) {
MessagesService.byTag("#not-a-number")(sender)
throw TypeParseException()
} ?: throw ArgumentNotFoundException(index)
fun ExecutorContext.integerOrNull(index: Int): Int? = argument(index)?.toIntOrNull()
fun ExecutorContext.double(index: Int): Double = try {
argument(index)?.toDouble()
} catch (e: NumberFormatException) {
MessagesService.byTag("#not-a-number")(sender)
throw TypeParseException()
} ?: throw ArgumentNotFoundException(index)
fun ExecutorContext.doubleOrNull(index: Int): Double? = argument(index)?.toDoubleOrNull()
fun ExecutorContext.materialOrNull(index: Int): Material? = Material.matchMaterial(string(index))
fun ExecutorContext.material(index: Int): Material =
materialOrNull(index) ?: run {
MessagesService.byTag("#no-such-material")(sender)
throw TypeParseException()
}
fun ExecutorContext.worldOrNull(index: Int): World? = Bukkit.getWorld(argument(index) ?: "")
fun ExecutorContext.world(index: Int): World =
worldOrNull(index) ?: run {
MessagesService.byTag("#no-such-world")(sender)
throw TypeParseException()
}
fun ExecutorContext.playerOrNull(index: Int): Player? = Bukkit.getPlayer(argument(index) ?: "")
fun ExecutorContext.player(index: Int): Player =
playerOrNull(index) ?: run {
MessagesService.byTag("#no-such-player")(sender)
throw TypeParseException()
}
fun ExecutorContext.offlinePlayer(index: Int): OfflinePlayer = Bukkit.getOfflinePlayer(argument(index) ?: "") | 0 | Kotlin | 1 | 2 | 95edc90da4b6d703e46ef589dbcfbc58b16bff46 | 2,215 | KotlinBukkitKIT | MIT License |
app/src/main/java/ch/admin/foitt/pilotwallet/app/MainActivity.kt | e-id-admin | 775,912,525 | false | {"Kotlin": 1521284} | package ch.admin.foitt.pilotwallet.app
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import ch.admin.foitt.pilotwallet.app.presentation.MainScreen
import ch.admin.foitt.pilotwallet.platform.userInteraction.domain.usecase.UserInteraction
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var userInteraction: UserInteraction
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
val timeStamp = SystemClock.elapsedRealtime()
splashScreen.setKeepOnScreenCondition {
SystemClock.elapsedRealtime() - timeStamp < SPLASH_SCREEN_DURATION
}
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
this.setRecentsScreenshotEnabled(false)
}
setContent {
MainScreen(this)
}
}
override fun onUserInteraction() {
super.onUserInteraction()
userInteraction()
}
companion object {
private const val SPLASH_SCREEN_DURATION = 2000
}
}
| 1 | Kotlin | 1 | 4 | 6572b418ec5abc5d94b18510ffa87a1e433a5c82 | 1,365 | eidch-pilot-android-wallet | MIT License |
app/src/main/java/ch/admin/foitt/pilotwallet/app/MainActivity.kt | e-id-admin | 775,912,525 | false | {"Kotlin": 1521284} | package ch.admin.foitt.pilotwallet.app
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import ch.admin.foitt.pilotwallet.app.presentation.MainScreen
import ch.admin.foitt.pilotwallet.platform.userInteraction.domain.usecase.UserInteraction
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var userInteraction: UserInteraction
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
val timeStamp = SystemClock.elapsedRealtime()
splashScreen.setKeepOnScreenCondition {
SystemClock.elapsedRealtime() - timeStamp < SPLASH_SCREEN_DURATION
}
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
this.setRecentsScreenshotEnabled(false)
}
setContent {
MainScreen(this)
}
}
override fun onUserInteraction() {
super.onUserInteraction()
userInteraction()
}
companion object {
private const val SPLASH_SCREEN_DURATION = 2000
}
}
| 1 | Kotlin | 1 | 4 | 6572b418ec5abc5d94b18510ffa87a1e433a5c82 | 1,365 | eidch-pilot-android-wallet | MIT License |
lcc-content/src/main/kotlin/com/joshmanisdabomb/lcc/entity/model/DiscipleEntityModel.kt | joshmanisdabomb | 537,458,013 | false | {"Kotlin": 2724329, "Java": 138822} | package com.joshmanisdabomb.lcc.entity.model
import com.joshmanisdabomb.lcc.entity.DiscipleEntity
import com.joshmanisdabomb.lcc.extensions.square
import com.joshmanisdabomb.lcc.extensions.transform
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.minecraft.client.MinecraftClient
import net.minecraft.client.model.*
import net.minecraft.client.render.VertexConsumer
import net.minecraft.client.render.entity.model.EntityModelPartNames
import net.minecraft.client.render.entity.model.ModelWithArms
import net.minecraft.client.render.entity.model.ModelWithHead
import net.minecraft.client.render.entity.model.SinglePartEntityModel
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.util.Arm
import net.minecraft.util.math.MathHelper
@Environment(EnvType.CLIENT)
class DiscipleEntityModel(private val root: ModelPart) : SinglePartEntityModel<DiscipleEntity>(), ModelWithArms, ModelWithHead {
private val head: ModelPart
private val nose: ModelPart
private val brain1: ModelPart
private val brain2: ModelPart
private val brain3: ModelPart
private val arms: ModelPart
private val leftLeg: ModelPart
private val rightLeg: ModelPart
private val rightArm: ModelPart
private val leftArm: ModelPart
private val rightWing: ModelPart
private val leftWing: ModelPart
private val rightWingGrounded: ModelPart
private val leftWingGrounded: ModelPart
init {
this.head = root.getChild(EntityModelPartNames.HEAD)
this.nose = head.getChild(EntityModelPartNames.NOSE)
this.brain1 = head.getChild("brain_1")
brain1.visible = false
this.brain2 = brain1.getChild("brain_2")
brain2.visible = false
this.brain3 = brain1.getChild("brain_3")
brain3.visible = false
this.arms = root.getChild(EntityModelPartNames.ARMS)
this.leftLeg = root.getChild(EntityModelPartNames.LEFT_LEG)
this.rightLeg = root.getChild(EntityModelPartNames.RIGHT_LEG)
this.leftArm = root.getChild(EntityModelPartNames.LEFT_ARM)
this.rightArm = root.getChild(EntityModelPartNames.RIGHT_ARM)
this.leftWing = root.getChild("left_wing")
this.rightWing = root.getChild("right_wing")
this.leftWingGrounded = root.getChild("left_wing_grounded")
this.rightWingGrounded = root.getChild("right_wing_grounded")
}
override fun animateModel(entity: DiscipleEntity, limbAngle: Float, limbDistance: Float, tickDelta: Float) {
super.animateModel(entity, limbAngle, limbDistance, tickDelta)
if (!MinecraftClient.getInstance().isPaused) {
if (entity.wingAnimation < 0f) entity.wingAnimation = entity.age.toFloat()
val vel = entity.velocity
entity.wingAnimation += tickDelta + ((vel.x.square() + vel.y.coerceAtLeast(0.0) + vel.y.coerceAtMost(0.0).square() + vel.z.square()).toFloat().times(20f) * tickDelta)
}
}
override fun setAngles(entity: DiscipleEntity, limbAngle: Float, limbDistance: Float, animationProgress: Float, headYaw: Float, headPitch: Float) {
head.yaw = headYaw * (Math.PI.toFloat() / 180)
head.pitch = headPitch * (Math.PI.toFloat() / 180)
if (entity.isOnGround) {
leftWing.visible = false
rightWing.visible = false
leftWingGrounded.visible = true
rightWingGrounded.visible = true
rightLeg.pitch = MathHelper.cos(limbAngle * 0.6662f) * 1.4f * limbDistance * 0.5f
leftLeg.pitch = MathHelper.cos(limbAngle * 0.6662f + Math.PI.toFloat()) * 1.4f * limbDistance * 0.5f
} else {
leftWing.visible = true
rightWing.visible = true
leftWingGrounded.visible = false
rightWingGrounded.visible = false
rightLeg.pitch = 0.1f
leftLeg.pitch = 0.3f
}
if (entity.target != null) {
arms.visible = false
leftArm.visible = true
rightArm.visible = true
} else {
arms.visible = true
leftArm.visible = false
rightArm.visible = false
}
this.leftWing.roll = (MathHelper.sin(entity.wingAnimation * 0.017453292f) * 3.1415927f * 0.035f)
this.leftWing.yaw = (MathHelper.cos(entity.wingAnimation * 0.017453292f) * 3.1415927f * 0.1f) + 0.5f
this.rightWing.roll = -this.leftWing.roll
this.rightWing.yaw = -this.leftWing.yaw
}
fun renderBrainBase(matrices: MatrixStack, vertices: VertexConsumer, light: Int, overlay: Int) {
brain1.visible = true
brain1.render(matrices, vertices, light, overlay)
brain1.visible = false
}
fun renderBrainTop(matrices: MatrixStack, vertices: VertexConsumer, light: Int, overlay: Int) {
brain2.visible = true
brain3.visible = true
brain2.render(matrices, vertices, light, overlay)
brain3.render(matrices, vertices, light, overlay)
brain2.visible = false
brain3.visible = false
}
override fun getPart() = root
override fun setArmAngle(arm: Arm, matrices: MatrixStack) = (arm == Arm.LEFT).transform(leftArm, rightArm).rotate(matrices)
override fun getHead() = head
companion object {
fun data(): TexturedModelData {
val modelData = ModelData()
val root = modelData.root
val head = root.addChild(EntityModelPartNames.HEAD, ModelPartBuilder.create().uv(0, 0).cuboid(-4.0f, -10.0f, -4.0f, 8.0f, 10.0f, 8.0f), ModelTransform.pivot(0.0f, 0.0f, 0.0f))
val brain1 = head.addChild("brain_1", ModelPartBuilder.create().uv(64, 0).cuboid(-5.0f, 0.0f, -5.0f, 10.0f, 3.0f, 10.0f), ModelTransform.NONE)
val brain2 = brain1.addChild("brain_2", ModelPartBuilder.create().uv(64, 13).cuboid(0.0f, -2.5f, 0.0f, 6.0f, 3.0f, 8.0f), ModelTransform.of(-0.1f, 1.0f, -4.0f, 0.0f, 0.0f, 0.12f))
val brain3 = brain1.addChild("brain_3", ModelPartBuilder.create().uv(92, 13).cuboid(-6.0f, -2.5f, 0.0f, 6.0f, 3.0f, 8.0f), ModelTransform.of(0.1f, 1.0f, -4.0f, 0.0f, 0.0f, -0.12f))
val nose = head.addChild(EntityModelPartNames.NOSE, ModelPartBuilder.create().uv(24, 0).cuboid(-1.0f, -1.0f, -6.0f, 2.0f, 4.0f, 2.0f), ModelTransform.pivot(0.0f, -2.0f, 0.0f))
val body = root.addChild(EntityModelPartNames.BODY, ModelPartBuilder.create().uv(16, 20).cuboid(-4.0f, 0.0f, -3.0f, 8.0f, 12.0f, 6.0f).uv(0, 38).cuboid(-4.0f, 0.0f, -3.0f, 8.0f, 18.0f, 6.0f, Dilation(0.5f)), ModelTransform.pivot(0.0f, 0.0f, 0.0f))
val arms = root.addChild(EntityModelPartNames.ARMS, ModelPartBuilder.create().uv(44, 22).cuboid(-8.0f, -2.0f, -2.0f, 4.0f, 8.0f, 4.0f).uv(40, 38).cuboid(-4.0f, 2.0f, -2.0f, 8.0f, 4.0f, 4.0f), ModelTransform.of(0.0f, 3.0f, -1.0f, -0.75f, 0.0f, 0.0f))
arms.addChild("left_shoulder", ModelPartBuilder.create().uv(44, 22).mirrored().cuboid(4.0f, -2.0f, -2.0f, 4.0f, 8.0f, 4.0f), ModelTransform.NONE)
val rightLeg = root.addChild(EntityModelPartNames.RIGHT_LEG, ModelPartBuilder.create().uv(0, 22).cuboid(-2.0f, 0.0f, -2.0f, 4.0f, 12.0f, 4.0f), ModelTransform.pivot(-2.0f, 12.0f, 0.0f))
val leftLeg = root.addChild(EntityModelPartNames.LEFT_LEG, ModelPartBuilder.create().uv(0, 22).mirrored().cuboid(-2.0f, 0.0f, -2.0f, 4.0f, 12.0f, 4.0f), ModelTransform.pivot(2.0f, 12.0f, 0.0f))
val rightArm = root.addChild(EntityModelPartNames.RIGHT_ARM, ModelPartBuilder.create().uv(40, 46).cuboid(-3.0f, -2.0f, -2.0f, 4.0f, 12.0f, 4.0f), ModelTransform.pivot(-5.0f, 2.0f, 0.0f))
val leftArm = root.addChild(EntityModelPartNames.LEFT_ARM, ModelPartBuilder.create().uv(40, 46).mirrored().cuboid(-1.0f, -2.0f, -2.0f, 4.0f, 12.0f, 4.0f), ModelTransform.pivot(5.0f, 2.0f, 0.0f))
val rightWingGrounded = root.addChild("right_wing_grounded", ModelPartBuilder.create().uv(0, 64).mirrored().cuboid(0.0f, -10.0f, 0.0f, 11.0f, 25.0f, 0.0f, Dilation(0.001f)), ModelTransform.of(0.0f, 4.0f, 3.5f, 0.0f, -0.2f, 0.0f))
val leftWingGrounded = root.addChild("left_wing_grounded", ModelPartBuilder.create().uv(0, 64).cuboid(-11.0f, -10.0f, 0.0f, 11.0f, 25.0f, 0.0f, Dilation(0.001f)), ModelTransform.of(0.0f, 4.0f, 3.5f, 0.0f, 0.2f, 0.0f))
val rightWing = root.addChild("right_wing", ModelPartBuilder.create().uv(0, 89).mirrored().cuboid(0.0f, -10.0f, 0.0f, 27.0f, 25.0f, 0.0f, Dilation(0.001f)), ModelTransform.of(0.0f, 4.0f, 3.5f, 0.0f, 0.0f, 0.0f))
val leftWing = root.addChild("left_wing", ModelPartBuilder.create().uv(0, 89).cuboid(-27.0f, -10.0f, 0.0f, 27.0f, 25.0f, 0.0f, Dilation(0.001f)), ModelTransform.of(0.0f, 4.0f, 3.5f, 0.0f, 0.0f, 0.0f))
return TexturedModelData.of(modelData, 128, 128)
}
}
} | 0 | Kotlin | 0 | 0 | a836162eaf64a75ca97daffa02c1f9e66bdde1b4 | 8,805 | loosely-connected-concepts | Creative Commons Zero v1.0 Universal |
annotations/src/commonMain/kotlin/com/bennyhuo/kotlin/deepcopy/annotations/DeepCopy.kt | bennyhuo | 156,778,105 | false | {"Kotlin": 157255, "Shell": 1038, "Java": 98} | package com.bennyhuo.kotlin.deepcopy.annotations
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
annotation class DeepCopy | 2 | Kotlin | 25 | 269 | f8f8d54920108f1faca6522bac6e1a1ef9243c02 | 147 | KotlinDeepCopy | MIT License |
app/src/main/java/com/dk/piley/Piley.kt | justdeko | 511,233,835 | false | {"Kotlin": 461062, "Shell": 2624} | package com.dk.piley
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber.DebugTree
import timber.log.Timber.Forest.plant
@HiltAndroidApp
class Piley : Application() {
override fun onCreate() {
super.onCreate()
// init timber
if (BuildConfig.DEBUG) {
plant(DebugTree())
}
}
} | 6 | Kotlin | 0 | 7 | a7b4c836557ec66f9af2bb46afbb72d8e89303bd | 375 | piley | Apache License 2.0 |
app/src/main/java/fr/jbouffard/japan2020/presenter/UpdateHolidayStatPresenter.kt | shinmen | 122,744,871 | false | null | package fr.jbouffard.japan2020.presenter
import fr.jbouffard.japan2020.Domain.EventStore
import fr.jbouffard.japan2020.Domain.Travel.Entity.Holiday
class UpdateHolidayStatPresenter(private val eventStore: EventStore) {
suspend fun updateHolidayStats(holiday: Holiday) {
eventStore.saveEvents(holiday.streamId, holiday.getUncommittedChanges(), holiday.getUncommittedChanges().size)
}
} | 0 | Kotlin | 0 | 0 | 38bd88b83865347b4b50203511918b302226dd00 | 403 | app-japan-2020 | MIT License |
src/main/kotlin/org/ilinykh/kotlin/logicjsonpath/StringFunctions.kt | divinenickname | 787,887,762 | false | {"Kotlin": 26293} | package org.ilinykh.kotlin.logicjsonpath
fun String.isBoolean(): Boolean = setOf("true", "false").contains(this.lowercase())
fun String.isLong() = toLongOrNull() != null
fun String.isInt() = toIntOrNull() != null
fun String.isDouble() = toDoubleOrNull() != null
fun String.isFloat() = toFloatOrNull() != null
fun String.isNumber() = setOf(
String::isLong,
String::isInt,
String::isFloat,
String::isDouble,
).map { it(this) }
.count { !it } != 4
| 0 | Kotlin | 0 | 0 | b7386e8b179260afe9eafeb85a7be28347f6ada3 | 467 | logic-json-path | Apache License 2.0 |
app/src/main/java/com/hollabrowser/meforce/adblock/repository/abp/AbpEntity.kt | thearsenaldevteam | 524,712,465 | false | {"Kotlin": 1081389, "HTML": 29524, "Java": 5690, "JavaScript": 2126} | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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.hollabrowser.meforce.adblock.repository.abp
import android.os.Parcelable
//import androidx.room.Entity
//import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
//@Entity(tableName = "abp")
@Parcelize
class AbpEntity(
// @PrimaryKey(autoGenerate = true)
var entityId: Int = 0,
var url: String = "",
// shown in adblock settings
var title: String? = null,
// same as last modified? read from header of the blocklist, but does not exist in easylist
var lastUpdate: String? = null,
// when the local files were last updated
var lastLocalUpdate: Long = 0,
// how long the list is valid
// check for updates if time since last local update longer than expires
var expires: Int = -1,
// actually not used, except in a not so useful way for the internal list -> maybe remove
var version: String? = null,
// in the header of the remote file, not actually used for anything -> maybe remove
// also, there seems to be some decoding problem. ends up as "https" for all entities
var homePage: String? = null,
// last modified from header of the list (i.e. when file on server was last updated)
var lastModified: String? = null,
var enabled: Boolean = false
) : Parcelable {
constructor() : this(0)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AbpEntity) return false
if (entityId != other.entityId) return false
return true
}
override fun hashCode(): Int {
return entityId
}
// not using the db because i have no idea how to get it to compile -> store as string
override fun toString(): String {
return "$entityId§§$url§§$title§§$lastUpdate§§$lastLocalUpdate§§$expires§§$version§§$homePage§§$lastModified§§$enabled"
}
}
// and read from string
fun abpEntityFromString(string: String): AbpEntity? {
val list = string.split("§§")
if (list.size != 10)
return null
if (list[0].toIntOrNull() == null || list[4].toLongOrNull() == null || list[5].toIntOrNull() == null || (list[9] != "true" && list[9] != "false"))
return null
return AbpEntity(
entityId = list[0].toInt(),
url = list[1],
title = if (list[2] == "null") null else list[2],
lastUpdate = if (list[3] == "null") null else list[3],
lastLocalUpdate = list[4].toLong(),
expires = list[5].toInt(),
version = if (list[6] == "null") null else list[6],
homePage = if (list[7] == "null") null else list[7],
lastModified = if (list[8] == "null") null else list[8],
enabled = list[9] == "true",
)
}
| 0 | null | 0 | 0 | 43bac79108cbd9074ab21ade96f1c12d30db4c9f | 3,373 | holla-android | MIT License |
feature-account-impl/src/main/java/com/edgeverse/wallet/feature_account_impl/presentation/exporting/seed/di/ExportSeedModule.kt | finn-exchange | 512,140,809 | false | {"Kotlin": 2956205, "Java": 14536, "JavaScript": 399} | package com.edgeverse.wallet.feature_account_impl.presentation.exporting.seed.di
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import com.edgeverse.wallet.common.di.viewmodel.ViewModelKey
import com.edgeverse.wallet.common.di.viewmodel.ViewModelModule
import com.edgeverse.wallet.feature_account_impl.domain.account.export.seed.ExportSeedInteractor
import com.edgeverse.wallet.feature_account_impl.presentation.AccountRouter
import com.edgeverse.wallet.feature_account_impl.presentation.AdvancedEncryptionCommunicator
import com.edgeverse.wallet.feature_account_impl.presentation.exporting.ExportPayload
import com.edgeverse.wallet.feature_account_impl.presentation.exporting.seed.ExportSeedViewModel
@Module(includes = [ViewModelModule::class])
class ExportSeedModule {
@Provides
@IntoMap
@ViewModelKey(ExportSeedViewModel::class)
fun provideViewModel(
router: AccountRouter,
advancedEncryptionCommunicator: AdvancedEncryptionCommunicator,
interactor: ExportSeedInteractor,
payload: ExportPayload,
): ViewModel {
return ExportSeedViewModel(
router,
interactor,
advancedEncryptionCommunicator,
payload
)
}
@Provides
fun provideViewModelCreator(fragment: Fragment, viewModelFactory: ViewModelProvider.Factory): ExportSeedViewModel {
return ViewModelProvider(fragment, viewModelFactory).get(ExportSeedViewModel::class.java)
}
}
| 0 | Kotlin | 1 | 0 | 03229c4188cb56b0fb0340e60d60184c7afa2c75 | 1,622 | edgeverse-wallet | Apache License 2.0 |
src/main/kotlin/co/moelten/splity/database/SyncDataExtensions.kt | ryanmoelter | 270,082,440 | false | null | package co.moelten.splity.database
import co.moelten.splity.AccountAndBudget
import com.ryanmoelter.ynab.SyncData
import com.ryanmoelter.ynab.SyncDataQueries
val SyncData.firstAccountAndBudget
get() = AccountAndBudget(firstAccountId, firstAccountPayeeId, firstBudgetId)
val SyncData.secondAccountAndBudget
get() = AccountAndBudget(secondAccountId, secondAccountPayeeId, secondBudgetId)
fun SyncDataQueries.replaceOnly(syncData: SyncData) {
transaction {
clear()
insert(syncData)
}
}
| 0 | Kotlin | 0 | 2 | 41aa57dd44a7c9d61c8eb6a5327655856aae9c52 | 503 | splity | Apache License 2.0 |
library/src/main/java/com/hankkin/library/mvp/contract/IBaseLoading.kt | yangkongming | 170,292,594 | false | null | package com.hankkin.library.mvp.contract
/**
* Created by wenxin on 2018/6/12.
*/
interface IBaseLoading : IBaseViewContract {
fun showLoading()
fun hideLoading()
} | 1 | null | 1 | 1 | abb84370bfb4fa71cce4b70d1a55d850a1b7fb11 | 175 | Reading-develop-1.0.0 | Apache License 2.0 |
solve/src/commonMain/kotlin/io/github/smaugfm/game2048/search/SearchStatsLogger.kt | smaugfm | 626,019,057 | false | {"Kotlin": 114422} | package io.github.smaugfm.game2048.search
import io.github.smaugfm.game2048.board.Direction
import kotlin.math.pow
import kotlin.math.round
import kotlin.time.Duration
object SearchStatsLogger {
private val elapsedRegex = "(\\d+)(?:\\.\\d+)?(\\w+)".toRegex()
fun logResults(
duration: Duration,
score: Float,
depthLimit: Int,
direction: Direction,
s: SearchStats,
) {
val m = elapsedRegex.matchEntire(duration.toString())!!
val elapsed = "${m.groupValues[1].padStart(3)}${m.groupValues[2].padEnd(2)}"
println(
"Move ${direction.toString().padEnd(6)}: " +
"score=${score.format(12)}, " +
"elapsed=${elapsed}, " +
"maxDepth=${s.maxDepthReached.toString().padStart(2)}, " +
"evals=${s.evaluations.format(6)}, " +
"moves=${s.moves.format(6)}, " +
"cacheHits=${s.cacheHits.format(6)}, " +
"cacheSize=${s.cacheSize.toLong().format(6)}, " +
"depthLimit=$depthLimit"
)
}
private fun Float.format(padStart: Int = 0): String =
this.roundDecimalPlaces(2).toString().padStart(padStart)
private fun Float.roundDecimalPlaces(places: Int): Float {
if (places < 0) return this
val placesFactor: Float = 10f.pow(places.toFloat())
return round(this * placesFactor) / placesFactor
}
private fun Double.roundDecimalPlaces(places: Int): Double {
if (places < 0) return this
val placesFactor: Double = 10.0.pow(places.toDouble())
return round(this * placesFactor) / placesFactor
}
private fun Long.format(padStart: Int = 0): String {
val result = if (this < 10_000)
this.toString()
else if (this < 1_000_000)
"${this / 1_000}k"
else if (this < 1_000_000_000)
"${(this / 1_000_000.0).roundDecimalPlaces(1)}M"
else
"${(this / 1_000_000_000.0).roundDecimalPlaces(2)}B"
return result.padStart(padStart)
}
}
| 0 | Kotlin | 0 | 0 | 60ed56244ef8ea8238f69f8e4d10bbcfe4f17a89 | 2,090 | korge-2048 | MIT License |
id/src/main/kotlin/ru/kyamshanov/mission/identification/IdentificationService.kt | KYamshanov | 672,550,797 | false | {"Kotlin": 159384, "Java": 32298, "CSS": 7503, "Shell": 2505, "FreeMarker": 1980, "Dockerfile": 1167} | package ru.kyamshanov.mission.identification
import java.util.*
sealed interface IdentificationService {
suspend fun identify(accessToken: String): UUID
suspend fun revoke(accessToken: String)
}
interface GithubIdentificationService : IdentificationService | 6 | Kotlin | 0 | 0 | 186fccbcdcfb06a9d3a56dc9c908c2666753425d | 269 | Mission-backend | Apache License 2.0 |
app/src/main/java/com/kai/base/activity/BaseMvpActivity.kt | pressureKai | 326,004,502 | false | null | package com.kai.base.activity
import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.classic.common.MultipleStatusView
import com.gyf.immersionbar.ImmersionBar
import com.kai.base.R
import com.kai.base.mvp.base.BasePresenter
import com.kai.base.mvp.base.IView
import com.kai.common.eventBusEntity.BaseEntity
import com.kai.common.listener.CustomAnimatorListener
import com.kai.common.utils.LogUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import skin.support.SkinCompatManager
abstract class BaseMvpActivity<V : IView, P : BasePresenter<V>> : AppCompatActivity(), IView {
private var enableEventBus = true
protected var mPresenter: P? = null
private var mEventBusTarget = this::class.java.name
private var mMultipleStatusView: MultipleStatusView? = null
private val DEFAULT_LAYOUT_PARAMS = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT,
ConstraintLayout.LayoutParams.MATCH_PARENT)
private var mActivityTag = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mEventBusTarget = resetEventBusTarget()
init()
initView()
}
open fun resetEventBusTarget(): String {
return this::class.java.name
}
open fun getStatusView(): MultipleStatusView? {
var statusView: MultipleStatusView? = null
try {
statusView = findViewById(R.id.status)
} catch (e: Exception) {
LogUtils.e("BaseMvpActivity", e.toString())
}
return statusView
}
private fun init() {
this.setContentView(setLayoutId())
bindView()
mMultipleStatusView = getStatusView()
if (enableEventBus) {
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this)
}
}
}
abstract fun initView()
/**
* 用户第一次触发事件流中的MotionEvent.ACTION_DOWN时,Activity源码中调用的方法
*/
override fun onUserInteraction() {
super.onUserInteraction()
}
abstract fun setLayoutId(): Int
open fun createPresenter(): P? {
return null
}
open fun enableEventBus(enable: Boolean) {
enableEventBus = enable
}
override fun onResume() {
super.onResume()
if (enableEventBus) {
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this)
}
}
}
override fun onDestroy() {
super.onDestroy()
if (enableEventBus) {
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this)
}
}
unBindView()
}
@Subscribe(threadMode = ThreadMode.ASYNC, sticky = true)
open fun <T> onMessageEvent(baseEntity: BaseEntity<T>) {
if (baseEntity.message == mEventBusTarget) {
EventBus.getDefault().removeStickyEvent(baseEntity)
onMessageReceiver(baseEntity)
}
}
/**
* des EventBus接收数据的方法通过基类EventBusEntity包装数据,
* 在项目中进行数据交换
* @param baseEntity 被传输的数据
*/
open fun <T> onMessageReceiver(baseEntity: BaseEntity<T>) {
}
fun <T> postStickyEvent(data: T, code: Int? = 0, message: String = "") {
val eventBusEntity = BaseEntity<T>()
eventBusEntity.data = data
eventBusEntity.code = code!!
if (message.isNotEmpty()) {
eventBusEntity.message = message
}
EventBus.getDefault().postSticky(eventBusEntity)
}
override fun onPause() {
super.onPause()
if (enableEventBus) {
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this)
}
}
}
override fun bindView() {
mPresenter = createPresenter()
mPresenter?.register(this as V)
}
override fun unBindView() {
mPresenter?.unRegister()
}
fun showErrorView(layoutId: Int? = R.layout.layout_error) {
mMultipleStatusView?.let {
runOnUiThread {
it.showError(layoutId!!,DEFAULT_LAYOUT_PARAMS)
}
}
}
fun showEmptyView() {
mMultipleStatusView?.showEmpty()
}
fun showLoadingView(layoutId: Int? = R.layout.layout_loading) {
mMultipleStatusView?.let {
runOnUiThread {
it.showLoading(layoutId!!,DEFAULT_LAYOUT_PARAMS)
}
}
}
fun showNoNetView() {
mMultipleStatusView?.showNoNetwork()
}
fun showContent(){
runOnUiThread {
mMultipleStatusView?.showContent()
}
}
fun initImmersionBar(
view: View? = null,
fitSystem: Boolean = false,
dark:Boolean = false,
color: Int? = 0
) {
var immersionColor = R.color.app_background
color?.let {
if (it != 0) {
immersionColor = it
}
}
var fontIsDark = true
try {
val curSkinName = SkinCompatManager.getInstance().curSkinName
if(curSkinName.isEmpty()){
fontIsDark = true
} else if(curSkinName == "night"){
fontIsDark = false
}
}catch (e :java.lang.Exception){
LogUtils.e("BaseMvpActivity","getCurrentSkinName error is $e")
}
if(dark){
fontIsDark = true
}
if (view != null) {
ImmersionBar
.with(this)
.statusBarDarkFont(fontIsDark, 0.7f)
.fitsSystemWindows(fitSystem)
.navigationBarColor(immersionColor)
.titleBar(view)
.autoNavigationBarDarkModeEnable(fontIsDark, 0.8f)
.init()
} else {
ImmersionBar
.with(this)
.statusBarDarkFont(fontIsDark, 0.7f)
.fitsSystemWindows(fitSystem)
.navigationBarColor(immersionColor)
.autoNavigationBarDarkModeEnable(fontIsDark, 0.8f)
.init()
}
}
fun beginAnimation(view: View, height: Float, customAnimatorListener: CustomAnimatorListener? = null){
val mAnimatorTranslateY: ObjectAnimator = ObjectAnimator.ofFloat(
view,
"translationY", view.translationY, height
)
mAnimatorTranslateY.duration = 200
mAnimatorTranslateY.interpolator = LinearInterpolator()
mAnimatorTranslateY.start()
customAnimatorListener?.let {
mAnimatorTranslateY.addListener(customAnimatorListener)
}
}
} | 0 | Kotlin | 1 | 1 | 73edc5e8b838f9ba89e5ac717051c15871120673 | 6,979 | FreeRead | Apache License 2.0 |
app/src/main/java/org/myspecialway/ui/agenda/AgendaModel.kt | myspecialway | 133,219,843 | false | null | package org.myspecialway.ui.agenda
import android.arch.persistence.room.*
import android.os.Parcelable
import android.support.annotation.NonNull
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import org.myspecialway.common.ViewType
import java.text.SimpleDateFormat
import java.util.*
private val serverDateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z")
@Entity()
data class ScheduleModel(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "sche_model_id") @NonNull val id: Int,
@Embedded(prefix = "data_") val data: Data)
@Entity()
data class Data(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "data_id") @NonNull val id: Int,
@SerializedName("student") @Embedded val student: Student)
@Entity()
data class Student(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "class_id") @NonNull val id: Int,
val name: String? = null,
val number: Int? = null,
val level: String? = null,
val schedule: List<Schedule>,
@SerializedName("reminders") val reminder: List<Reminder>?,
val nonActiveTimes: List<NonActiveTimes>
)
@Entity()
data class Schedule(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "schedule_id") @NonNull val id: Int,
val index: String,
val hours: String? = null,
@Embedded val lesson: Lesson,
@Embedded val location: Location? = null)
@Entity
@Parcelize
data class Location(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "location_id") @NonNull val id: Int,
@SerializedName("location_id") val locationId: String? = null,
val name: String? = null,
val disabled: Boolean? = null,
var pinned: Boolean = false,
@Embedded var position: Position? = null,
@SerializedName("icon") var locationIcon: String? = null,
var type: String? = null
) : Parcelable
@Entity
data class BlockedSection(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") @NonNull val id: Int,
val reason: String? = null,
val from: String? = null,
val to: String? = null
)
@Entity()
@Parcelize
data class Position(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "floor") @NonNull val floor: Int) : Parcelable
@Entity()
data class Lesson(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "lesson_id") @NonNull val id: Int,
val title: String,
val icon: String)
@Entity()
data class Reminder(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "reminder_id") @NonNull val id: Int,
val enabled: Boolean = false,
val type: String,
val schedule: List<ReminderTime>)
@Entity()
@Parcelize
data class ReminderTime(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "reminder_time_id") @NonNull val id: Int,
@SerializedName("daysindex") val daysindex: List<Int>,
val hours: List<String>) : Parcelable
@Entity()
data class LocationData(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "loc_data_id") @NonNull val id: Int,
@SerializedName("locations") val locations: List<Location>)
@Entity()
data class BlockedSectionsData(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "block_sec_model_id") @NonNull val id: Int,
@SerializedName("blockedSections") val blockedSections: List<BlockedSection>)
@Entity
data class LocationModel(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "loc_model_id") @NonNull val id: Int,
val data: LocationData)
@Entity()
data class NonActiveTimes(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "nonActiveTime_id") @NonNull val id: Int,
val title: String = "",
val startDateTime: String,
val endDateTime: String,
val isAllDayEvent: Boolean = false,
val isAllClassesEvent: Boolean = false)
@Entity
data class BlockedSectionsModel(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "block_sec_model_id") @NonNull val id: Int,
val data: BlockedSectionsData)
// UI Models
@Parcelize
data class ScheduleRenderModel(var index: String? = null,
var title: String? = null,
var image: String? = null,
var hours: String? = null,
var time: Time? = null,
var isNow: Boolean = false,
var isLast: Boolean = false,
var unityDest: Location? =null) : Parcelable, ViewType {
override fun getViewType(): Int = AgendaTypes.ITEM_TYPE
}
@Parcelize
data class ReminderRenderModel(var enabled: Boolean = false,
var type: ReminderType = ReminderType.REHAB, // TODO: consider default
var reminderTime: List<ReminderTime> = listOf()) : Parcelable, ViewType {
override fun getViewType(): Int = AgendaTypes.ITEM_TYPE
}
@Parcelize
data class NonActiveTimeRenderModel(
var title: String = "",
var startDateTime: Date? = null,
var endDateTime: Date? = null,
var isAllDayEvent: Boolean = false,
var isAllClassesEvent: Boolean = false) : Parcelable, ViewType {
override fun getViewType(): Int = AgendaTypes.ITEM_TYPE
}
data class SingleImageRes(val image: Int) : ViewType {
override fun getViewType(): Int = AgendaTypes.SINGLE_IMAGE
}
enum class ReminderType(name: String) {
MEDICINE("MEDICINE"),
REHAB("REHAB"),
SCHEDULE("SCHEDULE"); // added to distinguish between alerts
companion object {
fun byName(name: String): ReminderType {
return when (name) {
ReminderType.MEDICINE.name -> ReminderType.MEDICINE
ReminderType.REHAB.name -> ReminderType.REHAB
ReminderType.SCHEDULE.name -> ReminderType.SCHEDULE
else -> ReminderType.REHAB // TODO
}
}
}
}
object AgendaTypes {
const val ITEM_TYPE = 0
const val SINGLE_IMAGE = 1
}
enum class DestinationType {
MEDICINE, TOILET, REGULAR;
}
fun mapScheduleRenderModel(schedule: Schedule) = ScheduleRenderModel()
.apply {
val display = schedule.hours ?: "7:30 - 08:00"
val currentTime = Calendar.getInstance(TimeZone.getDefault()).time
index = schedule.index
title = schedule.lesson.title
this.hours = schedule.hours
unityDest = schedule.location
image = schedule.lesson.icon
time = schedule.index.let { AgendaIndex.convertTimeFromIndex(it, display) }
isNow = currentTime.after(time?.date) && currentTime.before(createHour(hour(display), min(display)))
}
fun mapReminderRenderModel(reminder: Reminder) = ReminderRenderModel()
.apply {
enabled = reminder.enabled
type = ReminderType.byName(reminder.type)
reminderTime = reminder.schedule
}
fun mapNonActiveTimeRenderModel(nonActiveTime: NonActiveTimes) = NonActiveTimeRenderModel()
.apply {
title = nonActiveTime.title
isAllDayEvent = nonActiveTime.isAllDayEvent
startDateTime = parseDate(nonActiveTime.startDateTime)
endDateTime = parseDate(nonActiveTime.endDateTime)
isAllClassesEvent = nonActiveTime.isAllClassesEvent
}
private fun parseDate(dateStr: String): Date? {
try {
return serverDateFormat.parse(dateStr)
} catch (e: Throwable) {
return null
}
}
private fun min(h: String): Int = h.substringAfter("-")
.trim()
.split(":")[1]
.toInt()
private fun hour(h: String): Int = h.substringAfter("-")
.trim()
.split(":")[0]
.toInt() | 20 | Kotlin | 6 | 3 | 9914c25016a1fb19b535c8fe47a1642f791b5d44 | 7,984 | my-special-way-android | MIT License |
common/src/main/kotlin/com/codeviking/kxg/util/Buffer.kt | dwbullok | 153,008,678 | true | {"Kotlin": 925045} | package com.codeviking.kxg.util
/**
* Super class for platform-dependent buffers. In the JVM these buffers directly map to the corresponding NIO buffers.
* However, not all operations of NIO buffers are supported.
*
* @author fabmax
*/
interface Buffer {
var limit: Int
var position: Int
val remaining: Int
val capacity: Int
fun flip()
fun clear()
}
/**
* Represents a buffer for bytes.
*
* @author fabmax
*/
interface Uint8Buffer : Buffer {
operator fun get(i: Int): Byte
operator fun set(i: Int, value: Byte)
operator fun plusAssign(value: Byte) { put(value) }
fun put(value: Byte): Uint8Buffer
fun put(data: ByteArray): Uint8Buffer = put(data, 0, data.size)
fun put(data: ByteArray, offset: Int, len: Int): Uint8Buffer
fun put(data: Uint8Buffer): Uint8Buffer
}
/**
* Represents a buffer for shorts.
*
* @author fabmax
*/
interface Uint16Buffer : Buffer {
operator fun get(i: Int): Short
operator fun set(i: Int, value: Short)
operator fun plusAssign(value: Short) { put(value) }
fun put(value: Short): Uint16Buffer
fun put(data: ShortArray): Uint16Buffer = put(data, 0, data.size)
fun put(data: ShortArray, offset: Int, len: Int): Uint16Buffer
fun put(data: Uint16Buffer): Uint16Buffer
}
/**
* Represents a buffer for ints.
*
* @author fabmax
*/
interface Uint32Buffer : Buffer {
operator fun get(i: Int): Int
operator fun set(i: Int, value: Int)
operator fun plusAssign(value: Int) { put(value) }
fun put(value: Int): Uint32Buffer
fun put(data: IntArray): Uint32Buffer = put(data, 0, data.size)
fun put(data: IntArray, offset: Int, len: Int): Uint32Buffer
fun put(data: Uint32Buffer): Uint32Buffer
}
/**
* Represents a buffer for floats.
*
* @author fabmax
*/
interface Float32Buffer : Buffer {
operator fun get(i: Int): Float
operator fun set(i: Int, value: Float)
operator fun plusAssign(value: Float) { put(value) }
fun put(value: Float): Float32Buffer
fun put(data: FloatArray): Float32Buffer = put(data, 0, data.size)
fun put(data: FloatArray, offset: Int, len: Int): Float32Buffer
fun put(data: Float32Buffer): Float32Buffer
}
expect fun createUint8Buffer(capacity: Int): Uint8Buffer
expect fun createUint16Buffer(capacity: Int): Uint16Buffer
expect fun createUint32Buffer(capacity: Int): Uint32Buffer
expect fun createFloat32Buffer(capacity: Int): Float32Buffer
| 0 | Kotlin | 0 | 0 | 5121acb8d80480bf60624ae9ef87a39b97428e27 | 2,444 | kool | Apache License 2.0 |
UndoRedo/src/main/java/com/abada/undoredo/StateProvider.kt | aabadaa | 643,202,835 | false | {"Kotlin": 18935} | package com.abada.undoredo
interface StateProvider {
operator fun <T> get(key: String): T?
operator fun <T> set(key: String, value: T)
fun remove(key: String)
fun getAll(observedKeys: Set<String>): Map<String, Any>
}
| 0 | Kotlin | 0 | 0 | 81aa32ac2417c4f57e136988752f36dc5c051e3f | 236 | UndoRedoManager | Apache License 2.0 |
core/surfaceduoscreenmanager-sample/src/main/java/com/microsoft/device/dualscreen/sample_surfaceduoscreenmanager/MainActivity.kt | alcere | 262,999,476 | true | {"Kotlin": 92617} | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
package com.microsoft.device.dualscreen.sample_surfaceduoscreenmanager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.microsoft.device.dualscreen.core.manager.ScreenModeListener
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as SampleApp).surfaceDuoScreenManager.addScreenModeListener(
this,
object : ScreenModeListener {
override fun onSwitchToSingleScreen() {
Toast.makeText(
this@MainActivity,
"Single Screen Mode",
Toast.LENGTH_SHORT
).show()
}
override fun onSwitchToDualScreen() {
Toast.makeText(
this@MainActivity,
"Dual Screen Mode",
Toast.LENGTH_SHORT
).show()
}
}
)
}
}
| 0 | Kotlin | 0 | 0 | 6e6895d7b568fd27bca563a76f2d40e78dac9f71 | 1,256 | surface-duo-sdk | MIT License |
analysis/analysis-api-fe10/src/org/jetbrains/kotlin/analysis/api/descriptors/symbols/pointers/KtFe10DescEnumEntrySymbolPointer.kt | JetBrains | 3,432,266 | false | {"Kotlin": 78346118, "Java": 6692370, "Swift": 4062767, "C": 2609482, "C++": 1962762, "Objective-C++": 169966, "JavaScript": 138328, "Python": 59488, "Shell": 35024, "TypeScript": 22800, "Lex": 18369, "Groovy": 17400, "Objective-C": 15578, "Batchfile": 11746, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.descriptors.symbols.pointers
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.descriptors.KtFe10AnalysisSession
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.KtFe10DescEnumEntrySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtEnumEntrySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.findClassAcrossModuleDependencies
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.Name
class KtFe10DescEnumEntrySymbolPointer(private val classId: ClassId, private val entryName: Name) : KtSymbolPointer<KtEnumEntrySymbol>() {
@Deprecated("Consider using org.jetbrains.kotlin.analysis.api.KtAnalysisSession.restoreSymbol")
override fun restoreSymbol(analysisSession: KtAnalysisSession): KtEnumEntrySymbol? {
check(analysisSession is KtFe10AnalysisSession)
val analysisContext = analysisSession.analysisContext
val entryDescriptor = analysisContext.resolveSession.moduleDescriptor.findClassAcrossModuleDependencies(classId)
?.unsubstitutedMemberScope
?.getContributedClassifier(entryName, NoLookupLocation.FROM_IDE)
if (entryDescriptor is ClassDescriptor && entryDescriptor.kind == ClassKind.ENUM_ENTRY) {
return KtFe10DescEnumEntrySymbol(entryDescriptor, analysisContext)
}
return null
}
override fun pointsToTheSameSymbolAs(other: KtSymbolPointer<KtSymbol>): Boolean = this === other ||
other is KtFe10DescEnumEntrySymbolPointer &&
other.classId == classId &&
other.entryName == entryName
}
| 182 | Kotlin | 5617 | 47,637 | d257153a50bdaa761d54bbc9fd1c5d78a3769f0f | 2,190 | kotlin | Apache License 2.0 |
plugin/src/main/kotlin/ir/taher7/melodymine/services/Websocket.kt | Vallerian | 700,695,551 | false | {"Kotlin": 203762, "TypeScript": 151429, "CSS": 4018, "Shell": 2145, "JavaScript": 1577, "Dockerfile": 367} | package ir.taher7.melodymine.services
import io.socket.client.IO
import io.socket.client.Socket
import io.socket.client.SocketIOException
import ir.taher7.melodymine.MelodyMine
import ir.taher7.melodymine.database.Database
import ir.taher7.melodymine.listeners.SocketListener
import ir.taher7.melodymine.storage.Messages
import ir.taher7.melodymine.storage.Settings
import ir.taher7.melodymine.utils.Utils
import java.net.URI
object Websocket {
lateinit var socket: Socket
fun connect() {
try {
val auth = mapOf(
"from" to "plugin",
"server" to Settings.server,
"key" to Settings.pluginKey
)
val uri = URI.create(Utils.serverURL())
val options = IO.Options.builder()
.setAuth(auth)
.setTransports(arrayOf("websocket"))
.build()
socket = IO.socket(uri, options)
socket.connect()
SocketListener(socket)
socket.on(Socket.EVENT_CONNECT) {
MelodyMine.instance.logger.info(Messages.getMessageString("success.websocket"))
Database.updateSocketPlayer()
}
socket.on(Socket.EVENT_DISCONNECT) {
MelodyMine.instance.logger.severe(Messages.getMessageString("errors.websocket"))
Database.updateSocketPlayer()
if (!socket.isActive) connect()
}
} catch (ex: SocketIOException) {
MelodyMine.instance.logger.info(Messages.getMessageString("errors.websocket_failed"))
if (!socket.isActive) connect()
ex.printStackTrace()
}
}
}
| 0 | Kotlin | 8 | 33 | 1cd98f3aa07e4f75ec9e6876832d18fde52ffec3 | 1,711 | MelodyMine | Apache License 2.0 |
app/src/main/java/ren/imyan/kirby/ui/video/VideoFragment.kt | KirbyAssistant | 316,526,859 | false | null | package ren.imyan.kirby.ui.video
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import ren.imyan.base.BaseFragment
import ren.imyan.kirby.databinding.ViewpagerResBinding
import ren.imyan.kirby.util.showErrorMessage
import ren.imyan.kirby.util.showListData
/**
* @author EndureBlaze/炎忍 https://github.com.EndureBlaze
* @data 2021-02-19 19:27
* @website https://imyan.ren
*/
class VideoFragment : BaseFragment<ViewpagerResBinding, VideoViewModel>() {
override fun initViewModel(): VideoViewModel =
ViewModelProvider(this)[VideoViewModel::class.java]
override fun initBinding(
inflater: LayoutInflater,
container: ViewGroup?
): ViewpagerResBinding = ViewpagerResBinding.inflate(inflater, container, false)
override fun initView() {
}
override fun loadDate() {
viewModel.videoListData.data.observe(this) {
binding.showListData(VideoListAdapter(it), 2)
}
viewModel.videoListData.state.observe(this) {
binding.showErrorMessage(it, "video", viewModel)
}
}
} | 0 | Kotlin | 0 | 2 | d2bfb15d59373646ab360d09dd8a16d22c9ca571 | 1,129 | Kirby_Assistant_New | MIT License |
libnavigation-base/src/main/java/com/mapbox/navigation/base/route/model/StepManeuverType.kt | gajdzik | 234,039,995 | false | null | package com.mapbox.navigation.base.route.model
import androidx.annotation.StringDef
const val TURN = "turn"
const val NEW_NAME = "new name"
const val DEPART = "depart"
const val ARRIVE = "arrive"
const val MERGE = "merge"
const val ON_RAMP = "on ramp"
const val OFF_RAMP = "off ramp"
const val FORK = "fork"
const val END_OF_ROAD = "end of road"
const val CONTINUE = "continue"
const val ROUNDABOUT = "roundabout"
const val ROTARY = "rotary"
const val ROUNDABOUT_TURN = "roundabout turn"
const val NOTIFICATION = "notification"
const val EXIT_ROUNDABOUT = "exit roundabout"
const val EXIT_ROTARY = "exit rotary"
@Retention(AnnotationRetention.SOURCE)
@StringDef(TURN,
NEW_NAME,
DEPART,
ARRIVE,
MERGE,
ON_RAMP,
OFF_RAMP,
FORK,
END_OF_ROAD,
CONTINUE,
ROUNDABOUT,
ROTARY,
ROUNDABOUT_TURN,
NOTIFICATION,
EXIT_ROUNDABOUT,
EXIT_ROTARY)
annotation class StepManeuverType
| 1 | null | 1 | 1 | 48836f8d7bd0c1c6846a76bfd5035b6d856e0b35 | 987 | mapbox-navigation-android | Apache License 2.0 |
instrumented/nightly-tests/src/main/kotlin/com/datadog/android/nightly/fragments/ViewTrackingMixedHomeFragment.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.nightly.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.datadog.android.nightly.R
import com.datadog.android.nightly.utils.measure
internal class ViewTrackingMixedHomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.tracking_strategy_fragment, container, false)
}
override fun onResume() {
measure(TEST_METHOD_NAME) {
super.onResume()
}
}
companion object {
private const val TEST_METHOD_NAME = "rum_fragment_view_tracking_strategy"
}
}
| 33 | Kotlin | 39 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 1,066 | dd-sdk-android | Apache License 2.0 |
app/src/main/java/com/example/nasaexampleapi/di/modules/presentation/PresentationComponent.kt | etishkova | 210,207,235 | false | null | package com.example.nasaexampleapi.di.modules.presentation
import com.example.nasaexampleapi.MainActivity
import dagger.Subcomponent
@Subcomponent(modules = [PresentationModule::class])
interface PresentationComponent {
fun inject(mainActivity: MainActivity)
} | 0 | Kotlin | 0 | 0 | 3af6bb7dda55f9ce7c8ccc54dab90ba26e5010ea | 266 | nasa-apod | Apache License 2.0 |
shared/src/commonMain/kotlin/com/devmikespb/simpleweather/data/network/WeatherApi.kt | devmikhail | 644,861,703 | false | null | package com.devmikespb.simpleweather.data.network
import co.touchlab.kermit.Logger
import com.devmikespb.simpleweather.data.dto.Weather
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
class WeatherApi(
private val apiKey: String,
) {
private val baseUrl = "https://api.openweathermap.org/data/2.5/weather"
private val httpClient = HttpClient {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
useAlternativeNames = false
}
)
}
}
@Throws(Throwable::class)
suspend fun fetchWeather(city: String): Weather? =
httpClient
.get(baseUrl) {
url {
parameters.append("appid", apiKey)
parameters.append("q", city)
parameters.append("units", "metric")
}
}
.let {
if (it.status == HttpStatusCode.NotFound) {
null
} else {
it.body()
}
}
}
| 0 | Kotlin | 0 | 0 | 3c90fa69eb82209633411a645cc16b73ec257039 | 1,344 | Simple-Weather | MIT License |
base/src/main/java/com/islamversity/base/widgets/CurveView.kt | islamversity | 282,670,969 | false | null | package com.islamversity.base.widgets
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.islamversity.base.R
private const val DEFAULT_BACKGROUND_COLOR = Color.WHITE
class CurveView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
style: Int = 0
) : View(context, attrs, style) {
private var bgColor = 0
private val paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
}
var radius = 0F
set(value) {
field = value
invalidate()
}
init {
val ta = context.obtainStyledAttributes(attrs, R.styleable.CurveView)
try {
bgColor = ta.getColor(R.styleable.CurveView_cv_background, DEFAULT_BACKGROUND_COLOR)
radius = ta.getDimensionPixelSize(R.styleable.CurveView_cv_radius, 0).toFloat()
} finally {
ta.recycle()
}
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
paint.apply {
color = bgColor
style = Paint.Style.FILL
}
canvas?.drawRoundRect(0F, 0F, width.toFloat(), height.toFloat(), radius, radius, paint)
}
} | 15 | Kotlin | 7 | 21 | ab825e4951facd7779e0c3fcb0e68720d68a0fa1 | 1,367 | Reyan | Apache License 2.0 |
src/test/kotlin/runtime/ContainerRuntimeTest.kt | steep-wms | 237,438,539 | false | {"Kotlin": 1539171, "JavaScript": 233382, "SCSS": 38483, "Shell": 1830, "Dockerfile": 1598, "PLpgSQL": 1198} | package runtime
import helper.DefaultOutputCollector
import helper.UniqueID
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.core.json.jsonObjectOf
import model.metadata.Service
import model.processchain.Argument
import model.processchain.ArgumentVariable
import model.processchain.Executable
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
import java.io.IOException
import java.nio.file.Path
/**
* Common code for all tests related to container runtimes
* @author <NAME>
*/
interface ContainerRuntimeTest {
companion object {
@JvmStatic
val EXPECTED = "Elvis"
}
/**
* Create a configuration object to pass to the container runtime
*/
fun createConfig(tempDir: Path, additional: JsonObject = jsonObjectOf()): JsonObject
/**
* Create the container runtime
*/
fun createRuntime(config: JsonObject): Runtime
/**
* Test that a simple container can be executed and that its output can be
* collected
*/
@Test
fun executeEcho(@TempDir tempDir: Path) {
val exec = Executable(path = "alpine", serviceId = "echo", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "echo"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), EXPECTED),
type = Argument.Type.INPUT)
))
val runtime = createRuntime(createConfig(tempDir))
val collector = DefaultOutputCollector()
runtime.execute(exec, collector)
assertThat(collector.output()).isEqualTo(EXPECTED)
}
/**
* Test that a simple container can be executed and that its output (multiple
* lines) can be collected
*/
@Test
fun executeEchoMultiline(@TempDir tempDir: Path) {
val exec = Executable(path = "alpine", serviceId = "myservice", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "sh"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "-c"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "echo Hello && sleep 0.1 && echo World"),
type = Argument.Type.INPUT)
))
val runtime = createRuntime(createConfig(tempDir))
val collector = DefaultOutputCollector()
runtime.execute(exec, collector)
assertThat(collector.output()).isEqualTo("Hello\nWorld")
}
/**
* Test that a failure is correctly detected
*/
@Test
fun failure(@TempDir tempDir: Path) {
val exec = Executable(path = "alpine", serviceId = "false", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "false"),
type = Argument.Type.INPUT),
))
val runtime = createRuntime(createConfig(tempDir))
val collector = DefaultOutputCollector()
assertThatThrownBy { runtime.execute(exec, collector) }
.isInstanceOf(IOException::class.java)
}
/**
* Return the runtime argument required for the [executeVolume] test
*/
fun getVolumeRuntimeArgs(tempDir: Path): List<Argument>
/**
* Test that a Docker container can be executed with a mounted volume
*/
@Test
fun executeVolume(@TempDir tempDir: Path, @TempDir tempDir2: Path) {
val f = File(tempDir2.toFile(), "test.txt")
f.writeText(EXPECTED)
val exec = Executable(path = "alpine", serviceId = "cat", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "cat"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "/tmp/test.txt"),
type = Argument.Type.INPUT)
), runtime = Service.RUNTIME_DOCKER, runtimeArgs = getVolumeRuntimeArgs(tempDir2))
val runtime = createRuntime(createConfig(tempDir))
val collector = DefaultOutputCollector()
runtime.execute(exec, collector)
assertThat(collector.output()).isEqualTo(EXPECTED)
}
fun doExecuteVolumeConf(@TempDir tempDir: Path, @TempDir tempDir2: Path,
additionalConfig: JsonObject) {
val f = File(tempDir2.toFile(), "test.txt")
f.writeText(EXPECTED)
val exec = Executable(path = "alpine", serviceId = "cat", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "cat"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "/tmp/test.txt"),
type = Argument.Type.INPUT)
), runtime = Service.RUNTIME_DOCKER)
val runtime = createRuntime(createConfig(tempDir, additionalConfig))
val collector = DefaultOutputCollector()
runtime.execute(exec, collector)
assertThat(collector.output()).isEqualTo(EXPECTED)
}
/**
* Test that a container can be executed with a mounted volume specified in
* the configuration object
*
* Should call [doExecuteVolumeConf]
*/
@Test
fun executeVolumeConf(@TempDir tempDir: Path, @TempDir tempDir2: Path)
/**
* Return the runtime argument required for the [executeEnv] test
*/
fun getEnvRuntimeArgs(): List<Argument>
/**
* Test that a container can be executed with an environment variable
*/
@Test
fun executeEnv(@TempDir tempDir: Path) {
val exec = Executable(path = "alpine", serviceId = "sh", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "sh"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "-c"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "echo \$MYVAR"),
type = Argument.Type.INPUT)
), runtime = Service.RUNTIME_DOCKER, runtimeArgs = getEnvRuntimeArgs())
val runtime = createRuntime(createConfig(tempDir))
val collector = DefaultOutputCollector()
runtime.execute(exec, collector)
assertThat(collector.output()).isEqualTo(EXPECTED)
}
fun doExecuteEnvConf(@TempDir tempDir: Path, additionalConfig: JsonObject) {
val exec = Executable(path = "alpine", serviceId = "sh", arguments = listOf(
Argument(variable = ArgumentVariable(UniqueID.next(), "sh"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "-c"),
type = Argument.Type.INPUT),
Argument(variable = ArgumentVariable(UniqueID.next(), "echo \$MYVAR"),
type = Argument.Type.INPUT)
), runtime = Service.RUNTIME_DOCKER)
val runtime = createRuntime(createConfig(tempDir, additionalConfig))
val collector = DefaultOutputCollector()
runtime.execute(exec, collector)
assertThat(collector.output()).isEqualTo(EXPECTED)
}
/**
* Test that a container can be executed with an environment variable
* specified in the configuration object
*
* Should call [doExecuteEnvConf]
*/
@Test
fun executeEnvConf(@TempDir tempDir: Path)
}
| 37 | Kotlin | 5 | 38 | 8270b146664463b962e0c7387cf4f80d44b95e7b | 6,962 | steep | Apache License 2.0 |
data/src/main/java/com/example/data/cache/mappers/BookDataToBookDbMapper.kt | yusuf0405 | 484,801,816 | false | null | package com.example.data.cache.mappers
import com.example.data.cache.models.BookCache
import com.example.data.cache.models.BookPdfCache
import com.example.data.cache.models.BookPosterCache
import com.example.data.models.BookData
import com.example.domain.Mapper
class BookDataToBookDbMapper : Mapper<BookData, BookCache> {
override fun map(from: BookData): BookCache = from.run {
BookCache(
id = id,
title = title,
author = author,
updatedAt = updatedAt,
page = page,
createdAt = createdAt,
chapterCount = chapterCount,
publicYear = publicYear,
poster = BookPosterCache(
name = poster.name,
url = poster.url
),
book = BookPdfCache(
name = book.name,
url = book.url,
type = book.type
),
genres = genres
)
}
} | 1 | Kotlin | 1 | 2 | c88c4acfe0c2f9cb988a017e3cf334aa792ccc95 | 970 | BookLoverFinalApp | Apache License 1.1 |
lite/src/main/java/com/ryan/github/koroutine/lite/Deferred<T>.kt | Ryan-Shz | 299,865,491 | false | null | package com.ryan.github.koroutine.lite
import com.ryan.github.koroutine.lite.core.Job
interface Deferred<T> : Job {
suspend fun await(): T
} | 0 | Kotlin | 0 | 1 | ae4d42235ee10f871ab51b2c5f6488946c11d0ea | 146 | KoroutineLite | MIT License |
app/src/main/java/pt/rvcoding/cvnotes/ui/section_details/SectionDetailsViewModel.kt | revs87 | 587,101,198 | false | {"Kotlin": 215238} | package pt.rvcoding.cvnotes.ui.section_details
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import pt.rvcoding.cvnotes.domain.model.Note
import pt.rvcoding.cvnotes.domain.model.Section
import pt.rvcoding.cvnotes.domain.use_case.NoteUseCases
import pt.rvcoding.cvnotes.domain.use_case.SectionUseCases
import pt.rvcoding.cvnotes.ui.util.L
import javax.inject.Inject
@HiltViewModel
class SectionDetailsViewModel @Inject constructor(
private val sectionUseCases: SectionUseCases,
private val noteUseCases: NoteUseCases
) : ViewModel() {
private val _state = mutableStateOf(SectionDetailsState())
val state: State<SectionDetailsState> = _state
private val _sectionNameEditState = mutableStateOf("")
val sectionNameEditState: State<String> = _sectionNameEditState
private var getSectionJob: Job? = null
fun getSection(sectionId: Int) {
L.i("SectionDetailsViewModel", "Entered sectionId: $sectionId, ${viewModelScope.isActive}")
getSectionJob?.let { if (it.isActive) { it.cancel() } }
getSectionJob = viewModelScope.launch(Dispatchers.Default) {
updateUI(sectionId)
}
}
fun updateSectionNewNameState(newName: String) {
_sectionNameEditState.value = newName
}
fun updateSection(sectionId: Int, newName: String) {
viewModelScope.launch(Dispatchers.Default) {
val section = sectionUseCases.getSectionById(sectionId)
section ?: return@launch
sectionUseCases.insertSection(section.apply { description = newName.trim() })
updateUI(sectionId)
}
}
private var toggleNoteJob: Job? = null
fun toggleNoteSelection(note: Note) {
toggleNoteJob?.let { if (it.isActive) { it.cancel() } }
toggleNoteJob = viewModelScope.launch(Dispatchers.Default) {
noteUseCases.insertNote(note.apply { isSelected = !isSelected })
updateUI(note.sectionId)
}
}
fun unselectAllSelectedNotes(sectionId: Int) {
viewModelScope.launch(Dispatchers.Default) {
noteUseCases.unselectAllNotes(sectionId)
updateUI(sectionId)
}
}
fun deleteSelectedNotes(sectionId: Int) {
viewModelScope.launch(Dispatchers.Default) {
noteUseCases.deleteSelectedNotes(sectionId)
updateUI(sectionId)
}
}
private suspend fun updateUI(sectionId: Int) {
withContext(Dispatchers.Main) { _state.value = _state.value.copy(isLoading = true) }
val section = sectionUseCases.getSectionById(sectionId)
val notes = noteUseCases.getNotesBySectionId(sectionId)
val hasSelectedNote = noteUseCases.hasSelectedNotes(sectionId)
withContext(Dispatchers.Main) {
_state.value = _state.value.copy(
section = section ?: Section.Default,
notes = notes,
hasSelectedNotes = hasSelectedNote,
isLoading = false,
errorMessage = section?.let { "" } ?: "Section not found"
)
}
}
} | 0 | Kotlin | 0 | 1 | 51c13021ee93d962d04da0200ee84e95dc0227a5 | 3,415 | cvnotes-and | Apache License 2.0 |
libs/web/web/src/main/kotlin/net/corda/web/api/Endpoint.kt | corda | 346,070,752 | false | null | package net.corda.web.api
import org.apache.commons.validator.routines.UrlValidator
/**
* Endpoint class that stores a http endpoint with its associated WebHandler. Also contains validation logic
*
* @property methodType Http method type
* @property path url path
* @property webHandler processing logic used to process request to this path
* @property isApi flag indicating if this path is an API endpoint (and hence should be versioned)
*/
data class Endpoint(val methodType: HTTPMethod, val path: String, val webHandler: WebHandler, val isApi: Boolean = false) {
init {
val error = StringBuilder()
if (path.isBlank()) error.appendLine("Endpoint must not be empty")
if (!path.startsWith("/")) error.appendLine("Endpoint $path must start with '/'")
if (!isValidEndpoint(path)) error.appendLine("Endpoint $path is not validly formed")
if (error.isNotEmpty()) {
throw IllegalArgumentException(error.toString())
}
}
private fun isValidEndpoint(endpoint: String): Boolean =
UrlValidator(UrlValidator.ALLOW_LOCAL_URLS).isValid("http://localhost$endpoint")
override fun toString(): String {
return "Endpoint(methodType=$methodType, path='$path', isApi=$isApi)"
}
} | 96 | null | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 1,268 | corda-runtime-os | Apache License 2.0 |
template-vertx-basic/src/main/kotlin/cc/chordflower/template/basic/application/security/AppAuthenticationProvider.kt | fossabot | 340,571,858 | false | null | package cc.chordflower.template.basic.application.security
import cc.chordflower.template.basic.application.config.Configuration
import io.vertx.core.AsyncResult
import io.vertx.core.Future
import io.vertx.core.Handler
import io.vertx.core.json.JsonObject
import io.vertx.ext.auth.User
import io.vertx.ext.auth.authentication.AuthenticationProvider
import io.vertx.ext.auth.authentication.UsernamePasswordCredentials
@Suppress("JoinDeclarationAndAssignment")
class AppAuthenticationProvider : AuthenticationProvider {
private val user : String
private val password : String
constructor(configuration: Configuration) {
this.user = configuration.management.username
this.password = configuration.management.password
}
/**
* Authenticate a user.
*
* If the user is successfully authenticated a [User] object is passed to the handler in an [AsyncResult].
* The user object can then be used for authorisation.
*
* @param credentials The credentials
* @param resultHandler The result handler
*/
override fun authenticate(credentials: JsonObject?, resultHandler: Handler<AsyncResult<User>>?) {
val passwordCredentials = UsernamePasswordCredentials(credentials)
when {
passwordCredentials.username.isNullOrEmpty() || passwordCredentials.password.isNullOrEmpty() -> {
resultHandler?.handle(Future.failedFuture("The given username or password is invalid"))
}
passwordCredentials.username != user -> {
resultHandler?.handle(Future.failedFuture("The given username or password is invalid"))
}
!Argon2.verify(this.password, passwordCredentials.password.toCharArray()) -> {
resultHandler?.handle(Future.failedFuture("The given username or password is invalid"))
}
else -> {
resultHandler?.handle(Future.succeededFuture(User.fromName(user)))
}
}
}
}
| 0 | Kotlin | 0 | 1 | 54a32cb686105265079f1b8d68a75993edffce4b | 1,878 | template-3 | Apache License 2.0 |
buildSrc/src/main/kotlin/korlibs/korge/gradle/texpacker/SimpleBitmap.kt | korlibs | 80,095,683 | false | {"Kotlin": 4210038, "C": 105670, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 1068, "Shell": 439, "CMake": 202, "Batchfile": 41, "CSS": 33} | package korlibs.korge.gradle.texpacker
import java.awt.*
import java.awt.image.*
import java.io.*
import javax.imageio.*
import kotlin.math.*
inline class SimpleRGBA(val data: Int) {
val r: Int get() = (data ushr 0) and 0xFF
val g: Int get() = (data ushr 8) and 0xFF
val b: Int get() = (data ushr 16) and 0xFF
val a: Int get() = (data ushr 24) and 0xFF
}
class SimpleBitmap(val width: Int, val height: Int, val data: IntArray = IntArray(width * height)) {
override fun toString(): String = "SimpleBitmap($width, $height)"
companion object {
operator fun invoke(image: BufferedImage): SimpleBitmap {
val width = image.width
val height = image.height
val out = IntArray(width * height)
image.getRGB(0, 0, width, height, out, 0, width)
return SimpleBitmap(width, height, out)
}
operator fun invoke(file: File): SimpleBitmap {
return invoke(ImageIO.read(file) ?: error("Couldn't read $file as an image"))
}
}
private fun index(x: Int, y: Int): Int = y * width + x
operator fun get(x: Int, y: Int): SimpleRGBA = SimpleRGBA(data[index(x, y)])
operator fun set(x: Int, y: Int, value: SimpleRGBA) { data[index(x, y)] = value.data }
fun toBufferedImage(): BufferedImage = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB).also {
it.setRGB(0, 0, width, height, this.data, 0, width)
}
fun writeTo(file: File) {
ImageIO.write(toBufferedImage(), file.extension, file)
}
fun put(px: Int, py: Int, other: SimpleBitmap) {
//println("put $other in $this at [$px, $py]")
for (y in 0 until other.height) {
System.arraycopy(other.data, other.index(0, y), this.data, this.index(px, py + y), other.width)
}
}
fun slice(rect: Rectangle): SimpleBitmap {
val out = SimpleBitmap(rect.width, rect.height)
for (y in 0 until rect.height) {
System.arraycopy(this.data, this.index(rect.x, rect.y + y), out.data, out.index(0, y), rect.width)
}
return out
}
fun trim(): Rectangle {
var minLeft = width
var minRight = width
var minTop = height
var minBottom = height
for (y in 0 until height) {
for (x in 0 until width) if (this[x, y].a != 0) { minLeft = min(minLeft, x); break }
for (x in 0 until width) if (this[width - x - 1, y].a != 0) { minRight = min(minRight, x); break }
}
for (x in 0 until width) {
for (y in 0 until height) if (this[x, y].a != 0) { minTop = min(minTop, y); break }
for (y in 0 until height) if (this[x, height - y - 1].a != 0) { minBottom = min(minBottom, y); break }
}
if (minLeft == width || minTop == height) {
return Rectangle(0, 0, 0, 0)
}
return Rectangle(minLeft, minTop, width - minRight - minLeft, height - minBottom - minTop)
}
fun transferRect(x: Int, y: Int, width: Int, height: Int, out: IntArray, write: Boolean) {
for (n in 0 until height) {
val tindex = this.index(x, y + n)
val oindex = width * n
when {
write -> System.arraycopy(out, oindex, this.data, tindex, width)
else -> System.arraycopy(this.data, tindex, out, oindex, width)
}
}
}
fun getRect(x: Int, y: Int, width: Int, height: Int, out: IntArray = IntArray(width * height)): IntArray {
transferRect(x, y, width, height, out, write = false)
return out
}
fun putRect(x: Int, y: Int, width: Int, height: Int, out: IntArray) {
transferRect(x, y, width, height, out, write = true)
}
fun flipY(): SimpleBitmap {
val out = SimpleBitmap(width, height)
val row = IntArray(width)
for (y in 0 until height) {
getRect(0, y, width, 1, row)
out.putRect(0, height - 1 - y, width, 1, row)
}
return out
}
fun rotate90(): SimpleBitmap {
val out = SimpleBitmap(height, width)
val row = IntArray(width)
for (y in 0 until height) {
getRect(0, y, width, 1, row)
out.putRect(y, 0, 1, width, row)
}
return out
}
fun extrude(border: Int): SimpleBitmap {
val nwidth = width + border * 2
val nheight = height + border * 2
val out = SimpleBitmap(nwidth, nheight)
out.put(border, border, this)
// left
run {
val part = out.slice(Rectangle(border, 0, 1, nheight))
for (n in 0 until border) out.put(n, 0, part)
}
// right
run {
val part = out.slice(Rectangle(nwidth - border - 1, 0, 1, nheight))
for (n in 0 until border) out.put(nwidth - n - 1, 0, part)
}
// top
run {
val part = out.slice(Rectangle(0, border, nwidth, 1))
for (n in 0 until border) out.put(0, n, part)
}
// bottom
run {
val part = out.slice(Rectangle(0, nheight - border - 1, nwidth, 1))
for (n in 0 until border) out.put(0, nheight - n - 1, part)
}
return out
}
}
| 464 | Kotlin | 123 | 2,497 | 1a565007ab748e00a4d602fcd78f7d4032afaf0b | 5,249 | korge | Apache License 2.0 |
Breaking/app/src/main/java/com/dope/breaking/model/response/ResponseLogin.kt | Breaking-Dope | 503,993,613 | false | {"Kotlin": 694298} | package com.dope.breaking.model.response
import com.google.gson.annotations.SerializedName
import org.json.JSONObject
import java.io.Serializable
data class ResponseLogin(
@SerializedName("fullname") var fullName: String, // 유저 성 이름
@SerializedName("username") var userName: String, // 회원번호
@SerializedName("email") var userEmail: String, // 유저 이메일
@SerializedName("profileImgURL") var profileImgUrl: String? // 프로필 이미지 Url
) : Serializable {
companion object {
fun convertJsonToObject(jsonObject: JSONObject): ResponseLogin {
return ResponseLogin(
jsonObject["fullname"] as String,
jsonObject["username"] as String,
jsonObject["email"] as String,
if (jsonObject.isNull("profileImgURL")) null else jsonObject["profileImgURL"] as String?
)
}
}
}
| 8 | Kotlin | 0 | 3 | 7184309b7be2f63a5d81cbdd3005d90e24e7eb41 | 877 | breaking-android | Apache License 2.0 |
instrumented/integration/src/main/kotlin/com/datadog/android/sdk/integration/rum/FragmentTrackingPlaygroundActivity.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
@file:Suppress("DEPRECATION")
package com.datadog.android.sdk.integration.rum
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.datadog.android.Datadog
import com.datadog.android.rum.Rum
import com.datadog.android.rum.tracking.FragmentViewTrackingStrategy
import com.datadog.android.sdk.integration.R
import com.datadog.android.sdk.integration.RuntimeConfig
import com.datadog.android.sdk.utils.getTrackingConsent
internal class FragmentTrackingPlaygroundActivity : AppCompatActivity() {
lateinit var viewPager: ViewPager
lateinit var btnNext: Button
lateinit var btnLast: Button
@Suppress("CheckInternal")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val config = RuntimeConfig.configBuilder()
.build()
val trackingConsent = intent.getTrackingConsent()
Datadog.setVerbosity(Log.VERBOSE)
val sdkCore = Datadog.initialize(this, config, trackingConsent)
checkNotNull(sdkCore)
val rumConfig = RuntimeConfig.rumConfigBuilder()
.trackUserInteractions()
.trackLongTasks(RuntimeConfig.LONG_TASK_LARGE_THRESHOLD)
.useViewTrackingStrategy(FragmentViewTrackingStrategy(true))
.build()
Rum.enable(rumConfig, sdkCore)
setContentView(R.layout.fragment_tracking_layout)
viewPager = findViewById(R.id.pager)
btnNext = findViewById(R.id.btn_next)
btnLast = findViewById(R.id.btn_last)
viewPager.apply {
adapter = ViewPagerAdapter(supportFragmentManager)
}
btnNext.setOnClickListener {
viewPager.setCurrentItem(viewPager.currentItem + 1, true)
}
btnLast.setOnClickListener {
viewPager.setCurrentItem(viewPager.currentItem - 1, true)
}
// attach the fragment view tracking strategy
}
internal inner class ViewPagerAdapter(fragmentManager: FragmentManager) :
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> FragmentA()
1 -> FragmentB()
else -> FragmentC()
}.apply {
val args = Bundle().apply {
putString("fragmentClassName", this::class.java.simpleName)
putInt("adapterPosition", position)
}
arguments = args
}
}
override fun getCount(): Int {
return 3
}
}
}
| 46 | null | 60 | 151 | d7e640cf6440ab150c2bbfbac261e09b27e258f4 | 3,120 | dd-sdk-android | Apache License 2.0 |
app/src/main/java/app/quakelist/earthquakes/dto/QuakeFeature.kt | faisalmohd83 | 170,335,524 | false | {"Gradle": 3, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 1, "Java": 2, "XML": 22, "Kotlin": 15} | package app.quakelist.earthquakes.dto
data class QuakeFeature(
val geometry: QuakeGeometry,
val id: String,
val properties: QuakeData,
val type: String
) | 2 | Kotlin | 0 | 0 | 91478f17c67065fe56b3c4ae06f1f844b4baf957 | 186 | QuakeList | MIT License |
soapui-transform-karate/src/main/kotlin/eu/k5/soapui/transform/karate/model/Expression.kt | denninger-eu | 244,302,123 | false | {"XML": 41, "Maven POM": 17, "Text": 13, "Ignore List": 1, "Markdown": 1, "Kotlin": 397, "YAML": 106, "Java": 5, "Batchfile": 3, "INI": 1, "Gherkin": 5} | package eu.k5.soapui.transform.karate.model
import eu.k5.soapui.transform.ModelWriter
import eu.k5.soapui.transform.karate.model.literals.VariableLiteral
interface Expression {
fun write(writer: ModelWriter): ModelWriter
companion object {
fun newInstance(variable: VariableLiteral): Expression {
return NewInstanceExpression(variable)
}
}
}
fun ModelWriter.write(expression: Expression): ModelWriter {
expression.write(this)
return this
} | 5 | Kotlin | 0 | 0 | 665e54e4ac65d6c7e9805bb1b44f30f9ec702ce3 | 491 | soapui-utils | Apache License 2.0 |
src/main/kotlin/net/phobot/parser/clause/Clause.kt | psfblair | 270,472,887 | false | {"Maven POM": 1, "Text": 3, "Ignore List": 1, "Markdown": 1, "Java": 1, "Assembly": 1, "Kotlin": 32} | /*
* //
* // This file is part of the pika parser implementation allowing whitespace-sensitive syntax. It is based
* // on the Java reference implementation at:
* //
* // https://github.com/lukehutch/pikaparser
* //
* // The pika parsing algorithm is described in the following paper:
* //
* // Pika parsing: reformulating packrat parsing as a dynamic programming algorithm solves the left recursion
* // and error recovery problems. <NAME>, May 2020.
* // https://arxiv.org/abs/2005.06444* //
* //
* // This software is provided under the MIT license:
* //
* // Copyright (c) 2020 <NAME>
* // Based on pikaparser by <NAME>, also licensed with the MIT license.
* //
* // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* // documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* // and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* //
* // The above copyright notice and this permission notice shall be included in all copies or substantial portions
* // of the Software.
* //
* // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* // DEALINGS IN THE SOFTWARE.
* //
*
*/
package net.phobot.parser.clause
import net.phobot.parser.clause.aux.ASTNodeLabel
import net.phobot.parser.clause.aux.LabeledClause
import net.phobot.parser.clause.nonterminal.Seq
import net.phobot.parser.clause.terminal.Nothing
import net.phobot.parser.grammar.GrammarPrecedenceLevels
import net.phobot.parser.grammar.Rule
import net.phobot.parser.memotable.Match
import net.phobot.parser.memotable.MemoKey
import net.phobot.parser.memotable.MemoTable
import java.util.*
import java.util.stream.Collectors.joining
import kotlin.streams.asStream
import kotlin.streams.toList
/** Abstract superclass of all PEG operators and terminals. */
abstract class Clause
// -------------------------------------------------------------------------------------------------------------
/** Clause constructor. */
protected constructor(vararg subClauses: Clause) {
/** Subclauses, paired with their AST node label (if there is one). */
val labeledSubClauses: Array<LabeledClause>
init {
require(subClauses.isEmpty() || subClauses[0] !is Nothing)
{ // Nothing can't be the first subclause, since we don't trigger upwards expansion of the DP wavefront
// by seeding the memo table by matching Nothing at every input position, to keep the memo table small
"${Nothing::class.simpleName} cannot be the first subclause of any clause"
}
this.labeledSubClauses =
subClauses
.asSequence()
.asStream()
.map { subClause ->
if (subClause is ASTNodeLabel) {
LabeledClause(
// We will skip over the ASTNodeLabel node when adding subClause to subClauses array
subClause.labeledSubClauses[0].clause,
// We will transfer ASTNodeLabel.astNodeLabel to LabeledClause.astNodeLabel field
subClause.astNodeLabel
)
} else {
LabeledClause(subClause, null)
}
}
.toList()
.toTypedArray()
}
/** Rules this clause is a toplevel clause of (used by [}][.toStringWithRuleNames] */
val rules: MutableList<Rule> = mutableListOf()
/** The parent clauses of this clause that should be matched in the same start position. */
val seedParentClauses: MutableList<Clause> = mutableListOf()
/** If true, the clause can match while consuming zero characters. */
var canMatchZeroChars: Boolean = false
/** Index in the topological sort order of clauses, bottom-up. */
var clauseIdx: Int = 0
/** The cached result of the [.toString] method. */
private var toStringCached: String? = null
/** The cached result of the [.toStringWithRuleNames] method. */
private var toStringWithRuleNameCached: String? = null
// -------------------------------------------------------------------------------------------------------------
/** Get the names of rules that this clause is the root clause of. */
val ruleNames: String
get() =
rules
.stream()
.map { rule -> rule.ruleName }
.sorted()
.collect(joining(", "))
/** Register this clause with a rule (used by [.toStringWithRuleNames]). */
fun registerRule(rule: Rule) {
rules.add(rule)
}
/** Unregister this clause from a rule. */
fun unregisterRule(rule: Rule) {
rules.remove(rule)
}
// -------------------------------------------------------------------------------------------------------------
/** Find which subclauses need to add this clause as a "seed parent clause". Overridden in [Seq]. */
open fun addAsSeedParentClause() {
// Default implementation: all subclauses will seed this parent clause.
val added = HashSet<Any>()
for (labeledSubClause in labeledSubClauses) {
// Don't duplicate seed parent clauses in the subclause
if (added.add(labeledSubClause.clause)) {
labeledSubClause.clause.seedParentClauses.add(this)
}
}
}
/**
* Sets [.canMatchZeroChars] to true if this clause can match zero characters, i.e. always matches at any
* input position. Called bottom-up. Implemented in subclasses.
*/
abstract fun determineWhetherCanMatchZeroChars()
// -------------------------------------------------------------------------------------------------------------
/**
* Match a clause by looking up its subclauses in the memotable (in the case of nonterminals), or by looking at
* the input string (in the case of terminals). Implemented in subclasses.
*/
abstract fun match(memoTable: MemoTable, memoKey: MemoKey, input: String): Match?
override fun toString(): String {
throw IllegalArgumentException("toString() needs to be overridden in subclasses")
}
/** Get the clause as a string, with rule names prepended if the clause is the toplevel clause of a rule. */
fun toStringWithRuleNames(): String {
return updateStringWithRuleNameCacheIfNecessary {
if (rules.isNotEmpty()) {
val buf = StringBuilder()
// Add rule names
buf.append(ruleNames)
buf.append(" <- ")
// Add any AST node labels
var addedASTNodeLabels = false
for (i in rules.indices) {
val rule = rules[i]
if (rule.labeledClause.astNodeLabel != null) {
buf.append(rule.labeledClause.astNodeLabel + ":")
addedASTNodeLabels = true
}
}
val addParens = addedASTNodeLabels && GrammarPrecedenceLevels.needToAddParensAroundASTNodeLabel(this)
if (addParens) {
buf.append('(')
}
buf.append(toString())
if (addParens) {
buf.append(')')
}
buf.toString()
} else {
toString()
}
}
}
fun updateStringCacheIfNecessary(stringGenerator: () -> String): String {
if (toStringCached == null) {
toStringCached = stringGenerator()
}
return toStringCached as String
}
private fun updateStringWithRuleNameCacheIfNecessary(stringGenerator: () -> String): String {
if (toStringWithRuleNameCached == null) {
toStringWithRuleNameCached = stringGenerator()
}
return toStringWithRuleNameCached as String
}
}
| 0 | Kotlin | 0 | 0 | 15b793af07d12b90d0e99ae3cb4ad2c5221d12f9 | 8,767 | pikaparser-kotlin | MIT License |
app/src/main/java/com/freshdigitable/udonroad2/di/ActivityBuilders.kt | akihito104 | 149,869,805 | false | null | /*
* Copyright (c) 2018. Matsuda, Akihit (akihito104)
*
* 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.freshdigitable.udonroad2.di
import com.freshdigitable.udonroad2.input.di.TweetInputViewModelComponentModule
import com.freshdigitable.udonroad2.main.MainActivity
import com.freshdigitable.udonroad2.media.MediaActivity
import com.freshdigitable.udonroad2.media.di.MediaActivityModule
import com.freshdigitable.udonroad2.model.app.di.ActivityScope
import com.freshdigitable.udonroad2.user.UserActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
interface ActivityBuilders {
@ActivityScope
@ContributesAndroidInjector(
modules = [
MainActivityModule::class,
ViewModelModule::class,
TweetInputViewModelComponentModule::class,
]
)
fun contributesMainActivity(): MainActivity
@ActivityScope
@ContributesAndroidInjector(
modules = [
UserActivityModule::class,
ViewModelModule::class
]
)
fun contributeUserActivity(): UserActivity
@ActivityScope
@ContributesAndroidInjector(
modules = [
MediaActivityModule::class,
ViewModelModule::class
]
)
fun contributeMediaActivity(): MediaActivity
}
| 21 | null | 1 | 1 | 7ec50f204fda79cf222b24623f22e80d05301555 | 1,830 | UdonRoad2 | Apache License 2.0 |
python/src/com/jetbrains/python/requirements/RequirementsIcons.kt | JetBrains | 2,489,216 | false | null | package com.jetbrains.python.requirements
import com.intellij.icons.AllIcons
import javax.swing.Icon
object RequirementsIcons {
val FILE: Icon = AllIcons.FileTypes.Text
} | 251 | null | 5079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 175 | intellij-community | Apache License 2.0 |
app/src/main/java/org/stepik/android/view/injection/course_list/visited/CourseListVisitedScope.kt | StepicOrg | 42,045,161 | false | {"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618} | package org.stepik.android.view.injection.course_list.visited
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class CourseListVisitedScope | 13 | Kotlin | 54 | 189 | dd12cb96811a6fc2a7addcd969381570e335aca7 | 176 | stepik-android | Apache License 2.0 |
src/main/kotlin/io/tree/LevelOrderTraversal.kt | jffiorillo | 138,075,067 | false | {"Gradle Kotlin DSL": 2, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "Java": 11, "Kotlin": 286, "Markdown": 3} | package io.tree
import io.models.TreeNode
import io.utils.runTests
// https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
class LevelOrderTraversal {
fun execute(root: TreeNode?): List<List<Int>> {
if (root == null) return emptyList()
var stack = listOf(root)
val result = mutableListOf<List<Int>>()
while (stack.isNotEmpty()) {
result.add(0, stack.map { it.`val` })
stack = stack.filter { it.right != null || it.left != null }.flatMap { listOfNotNull(it.left, it.right) }
}
return result
}
}
fun main() {
runTests(listOf(
TreeNode(3,
TreeNode(9),
TreeNode(20,
TreeNode(15),
TreeNode(17))) to
listOf(listOf(15, 17), listOf(9, 20), listOf(3))
)) { (input, value) -> value to LevelOrderTraversal().execute(input) }
} | 1 | null | 1 | 1 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 842 | coding | MIT License |
src/test/java/com/szymczak/livr/BaseFuncTest.kt | umotif-public | 291,671,780 | true | {"Gradle": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 5, "Java": 13, "JSON": 216, "XML": 4} | package com.szymczak.livr
import com.szymczak.livr.util.IterationMethods
import org.assertj.core.api.Assertions.assertThat
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import org.junit.Test
import org.skyscreamer.jsonassert.JSONAssert
class BaseFuncTest {
private val parser = JSONParser()
@Test
fun positive() {
IterationMethods.listFilesForFolder("positive")
.forEach { json ->
//given
val rules = parser.parseToJsonObject(json, "rules")
val input = parser.parseToJsonObject(json, "input")
val output = parser.parseToJsonObject(json, "output").toJSONString()
val validator = LIVR.validator().init(rules, false)
//when
val result = validator.validate(input).toJSONString()
//then
assertThat(validator.getErrors()).isNull()
JSONAssert.assertEquals(result, output, false)
}
}
@Test
fun negative() {
IterationMethods.listFilesForFolder("negative")
.forEach { json ->
//given
val rules = parser.parseToJsonObject(json, "rules")
val input = parser.parseToJsonObject(json, "input")
val errors = parser.parseToJsonObject(json, "errors").toJSONString()
val validator = LIVR.validator().init(rules, false)
//when
validator.validate(input)
val errorResult =
(parser.parse(JSONObject.toJSONString(validator.getErrors())) as JSONObject).toJSONString()
//then
JSONAssert.assertEquals(errorResult, errors, false)
}
}
@Test
fun `aliases positive`() {
IterationMethods.listFilesForFolder("aliases_positive")
.forEach { json ->
//given
val rules = parser.parseToJsonObject(json, "rules")
val input = parser.parseToJsonObject(json, "input")
val output = parser.parseToJsonObject(json, "output").toJSONString()
val aliases = parser.parseToJsonArray(json, "aliases")
val validator = LIVR.validator().init(rules, false)
aliases.forEach {
validator.registerAliasedRule(it as JSONObject)
}
//when
val result = validator.validate(input).toJSONString()
//then
assertThat(validator.getErrors()).isNull()
//output
JSONAssert.assertEquals(result, output, false)
}
}
@Test
fun `aliases negative`() {
IterationMethods.listFilesForFolder("aliases_negative")
.forEach { json ->
//given
val rules = parser.parseToJsonObject(json, "rules")
val input = parser.parseToJsonObject(json, "input")
val errors = parser.parseToJsonObject(json, "errors").toJSONString()
val aliases = parser.parseToJsonArray(json, "aliases")
val validator = LIVR.validator().init(rules, false)
aliases.forEach {
validator.registerAliasedRule(it as JSONObject)
}
//when
validator.validate(input)
val errorResult =
(parser.parse(JSONObject.toJSONString(validator.getErrors())) as JSONObject).toJSONString()
//then
JSONAssert.assertEquals(errorResult, errors, false)
}
}
@Test
fun `null check test`() {
//given
val validator = LIVR.validator().prepare()
//when
val result = validator.validate(null as Any?)
//then
assertThat(result).isNull()
JSONAssert.assertEquals(
validator.getErrors().toJSONString(),
"""{"base":"FORMAT_ERROR"}""",
false
)
}
private fun JSONParser.parseToJsonObject(json: JSONObject, value: String) =
parse(json.getValueAsString(value)) as JSONObject
private fun JSONParser.parseToJsonArray(json: JSONObject, value: String) =
parse(json.getValueAsString(value)) as JSONArray
private fun JSONObject.getValueAsString(value: String) = getValue(value) as String
}
| 1 | Java | 1 | 0 | 1a925b0630b60cfedf5619dbc8e7dbeefdc829fb | 4,458 | java-livr-lib | The Unlicense |
kotest-runner/kotest-runner-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/runner/junit5/mypackage/DummySpec.kt | kotest | 47,071,082 | false | {"Kotlin": 4736924, "CSS": 352, "Java": 145} | package com.sksamuel.kotest.runner.junit5.mypackage
import io.kotest.core.spec.style.FunSpec
// used for discovery filter tests
class DummySpec1 : FunSpec({
test("a") {}
})
class DummySpec2 : FunSpec({
test("b") {}
})
| 141 | Kotlin | 648 | 4,435 | 2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f | 227 | kotest | Apache License 2.0 |
module_hotspot/src/main/java/me/jessyan/armscomponent/hotspot/di/module/HotspotActivityModule.kt | willpyshan13 | 195,998,380 | false | {"Java": 2743467, "Kotlin": 75964} | package me.jessyan.armscomponent.hotspot.di.module
import dagger.Binds
import dagger.Module
import me.jessyan.armscomponent.hotspot.mvp.contract.HotspotContract
import me.jessyan.armscomponent.hotspot.mvp.model.HotspotActivityModel
/**
* ================================================
* Description:
*
*
* Created by MVPArmsTemplate on 08/16/2019 09:17
* [Contact me](mailto:<EMAIL>)
* [Follow me](https://github.com/JessYanCoding)
* [Star me](https://github.com/JessYanCoding/MVPArms)
* [See me](https://github.com/JessYanCoding/MVPArms/wiki)
* [模版请保持更新](https://github.com/JessYanCoding/MVPArmsTemplate)
* ================================================
*/
@Module
abstract class HotspotActivityModule {
@Binds
internal abstract fun bindHotspotActivityModel(model: HotspotActivityModel): HotspotContract.Model
} | 1 | null | 1 | 1 | 255512d989602194f6a252e61fc067fc80c1cf79 | 841 | hll-translate | Apache License 2.0 |
app/src/main/java/com/epitech/diabetips/holders/RecipeItemViewHolder.kt | Diabetips | 275,361,973 | false | {"Gradle": 3, "YAML": 3, "Dockerfile": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 143, "XML": 150, "Java": 3} | package com.epitech.diabetips.holders
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.epitech.diabetips.R
import com.epitech.diabetips.managers.FavoriteManager
import com.epitech.diabetips.services.RecipeService
import com.epitech.diabetips.storages.RecipeObject
import com.epitech.diabetips.utils.ImageHandler
import kotlinx.android.synthetic.main.item_recipe.view.*
class RecipeItemViewHolder(inflater: LayoutInflater, parent: ViewGroup)
: RecyclerView.ViewHolder(inflater.inflate(R.layout.item_recipe, parent, false)) {
private var recipeText: TextView? = null
private var recipeDescription: TextView? = null
private var recipeImage: ImageView? = null
private var recipeFavorite: ImageButton? = null
private var context: Context
init {
recipeText = itemView.recipeText
recipeDescription = itemView.recipeDescription
recipeImage = itemView.recipeImage
recipeFavorite = itemView.recipeFavoriteButton
context = inflater.context
}
fun bind(recipe: RecipeObject, onItemClickListener : ((RecipeObject) -> Unit)? = null) {
recipeText?.text = recipe.name
recipeDescription?.text = recipe.description
itemView.setOnClickListener {onItemClickListener?.invoke(recipe)}
if (recipeFavorite != null) {
FavoriteManager.instance.handleImageButton(recipe.id, recipeFavorite!!)
}
if (recipeImage != null) {
ImageHandler.instance.loadImage(recipeImage!!, context, RecipeService.instance.getPictureUrl(recipe.id), R.drawable.ic_unknown, false)
}
}
}
| 0 | Kotlin | 0 | 1 | 6a1b5be85ab0aec6064849b4b630dbc8c035e126 | 1,803 | diabetips-android | MIT License |
packages/cactus-plugin-ledger-connector-fabric/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/DeployContractV1Response.kt | RafaelAPB | 241,220,244 | false | null | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import org.openapitools.client.models.ChainCodeLifeCycleCommandResponses
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
*
*
* @param success
* @param packageIds
* @param lifecycle
*/
data class DeployContractV1Response (
@Json(name = "success")
val success: kotlin.Boolean,
@Json(name = "packageIds")
val packageIds: kotlin.collections.List<kotlin.String>,
@Json(name = "lifecycle")
val lifecycle: ChainCodeLifeCycleCommandResponses
)
| 50 | null | 3 | 6 | 4c94bf21ee570349995c61204fe60a2dc6a35766 | 814 | blockchain-integration-framework | Apache License 2.0 |
CommonCoreLegacy/src/main/java/skedgo/tripkit/routing/TripExtensions.kt | mbarringer | 206,001,194 | true | {"Java Properties": 1, "YAML": 1, "Markdown": 5, "Gradle": 16, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 13, "Kotlin": 177, "INI": 6, "XML": 48, "Java": 297, "Proguard": 3, "JSON": 20, "Checksums": 34, "Git Attributes": 1} | package skedgo.tripkit.routing
import android.content.Context
import com.skedgo.android.common.model.TransportMode
import com.skedgo.android.common.util.TripSegmentUtils
import org.joda.time.DateTime
import java.util.concurrent.TimeUnit
/**
* Gets a start date-time with time-zone.
*/
val Trip.startDateTime: DateTime
get() = DateTime(
TimeUnit.SECONDS.toMillis(startTimeInSecs),
from.dateTimeZone
)
/**
* Get an end date-time with time-zone.
*/
val Trip.endDateTime: DateTime
get() = DateTime(
TimeUnit.SECONDS.toMillis(endTimeInSecs),
to.dateTimeZone
)
/**
* Gets a list of [TripSegment]s visible on the summary area of a [Trip].
*/
fun Trip.getSummarySegments(): List<TripSegment> = segments
?.filter { it.type != SegmentType.ARRIVAL }
?.filter { it.isVisibleInContext(Visibilities.VISIBILITY_IN_SUMMARY) }
?: emptyList()
fun Trip.getModeIds(): List<String> =
segments.mapNotNull { it.transportModeId }
fun Trip.hasWalkOnly(): Boolean {
val modeIds = getModeIds()
return modeIds.size == 1 && modeIds.contains(TransportMode.ID_WALK)
}
fun Trip.getTripSegment(segmentId: Long): TripSegment? = segments?.find { it.id == segmentId }
fun Trip.constructPlainText(context: Context): String =
StringBuilder().apply {
segments?.forEach {
addAddress(it)
addSegmentAction(context, it)
addNotes(context, it)
addNewLine()
}
}.toString()
private fun StringBuilder.addAddress(segment: TripSegment) {
if (shouldAdAddress(segment)) {
append("${segment.from?.address}, ")
}
}
private fun shouldAdAddress(segment: TripSegment) =
!segment.from?.address.isNullOrEmpty() &&
segment.type != SegmentType.STATIONARY &&
!(segment.from?.isNear(segment.to) ?: false)
private fun StringBuilder.addSegmentAction(context: Context, segment: TripSegment) {
append("${TripSegmentUtils.getTripSegmentAction(context, segment)}\n")
}
private fun StringBuilder.addNotes(context: Context, segment: TripSegment) {
if (!segment.notes.isNullOrEmpty()) {
append("${segment.getDisplayNotes(context.resources)}\n")
}
}
private fun StringBuilder.addNewLine() {
append("\n")
} | 0 | Java | 0 | 0 | ed369f9017444ce8ea169db77657e43b9e91246d | 2,195 | tripkit-android | Apache License 2.0 |
app/src/main/java/org/liuyi/mifreeformx/xposed/base/ReflectStaticMethod.kt | LiuYiGL | 624,455,753 | false | null | package org.liuyi.mifreeformx.xposed.base
import java.lang.reflect.Method
/**
* @Author: Liuyi
* @Date: 2023/05/06/23:24:37
* @Description:
*/
class ReflectStaticMethod<T>(init: () -> Method) {
val method = init()
internal fun call(vararg args: Any?) = method.invoke(null, *args) as? T
internal operator fun invoke(vararg args: Any?) = call(null, args)
} | 1 | null | 2 | 34 | 5d96c5ea8dc50df85b3a74090e623b3bcb3a7ae5 | 375 | MiFreeFormX | Apache License 2.0 |
modules/core/src/main/kotlin/datamaintain/core/exception/DatamaintainBuilderMandatoryException.kt | 4sh | 207,514,876 | false | {"Kotlin": 336955, "Shell": 4776, "Dockerfile": 2630, "JavaScript": 1072} | package datamaintain.core.exception
class DatamaintainBuilderMandatoryException(builder: String, field: String) :
DatamaintainBaseException("Cannot build $builder : $field is mandatory")
| 34 | Kotlin | 6 | 26 | 0cb32924208b053b36cd49a892d6be5a603095fc | 192 | datamaintain | Apache License 2.0 |
org.librarysimplified.audiobook.manifest.api/src/main/java/org/librarysimplified/audiobook/manifest/api/PlayerManifestTOCItem.kt | ThePalaceProject | 379,956,255 | false | {"Kotlin": 773251, "Java": 2523, "Shell": 968} | package org.librarysimplified.audiobook.manifest.api
import org.joda.time.Duration
/**
* A TOC item in a manifest.
*/
data class PlayerManifestTOCItem(
val title: String,
val index: Int,
val chapter: Int,
/**
* The interval covered by this TOC item on the absolute timeline.
*/
val intervalAbsoluteMilliseconds: PlayerMillisecondsAbsoluteInterval
) : Comparable<PlayerManifestTOCItem> {
override fun compareTo(other: PlayerManifestTOCItem): Int {
return Comparator.comparing(PlayerManifestTOCItem::index)
.compare(this, other)
}
val duration: Duration
get() = Duration.millis(this.durationMilliseconds)
val durationMilliseconds: Long
get() {
val absUpper = this.intervalAbsoluteMilliseconds.upper.value
val absLower = this.intervalAbsoluteMilliseconds.lower.value
return (absUpper - absLower) + 1
}
}
| 1 | Kotlin | 1 | 1 | 51d708d0c078e221838fe8245543c3686de395a3 | 875 | android-audiobook | Apache License 2.0 |
src/main/kotlin/no/njoh/pulseengine/modules/physics/bodies/LineBody.kt | NiklasJohansen | 239,208,354 | false | {"Kotlin": 846455, "GLSL": 39054, "PostScript": 178} | package no.njoh.pulseengine.modules.physics.bodies
import no.njoh.pulseengine.core.PulseEngine
import no.njoh.pulseengine.core.asset.types.Texture
import no.njoh.pulseengine.core.graphics.surface.Surface
import no.njoh.pulseengine.core.scene.SceneEntity
import no.njoh.pulseengine.core.scene.SceneEntity.Companion.POSITION_UPDATED
import no.njoh.pulseengine.core.scene.SceneEntity.Companion.ROTATION_UPDATED
import no.njoh.pulseengine.core.scene.interfaces.Spatial
import no.njoh.pulseengine.core.shared.primitives.Color
import no.njoh.pulseengine.core.shared.utils.MathUtil.atan2
import no.njoh.pulseengine.modules.physics.*
import no.njoh.pulseengine.modules.physics.BodyType.STATIC
import no.njoh.pulseengine.modules.physics.shapes.LineShape
import kotlin.math.*
interface LineBody : PhysicsBody
{
override val shape: LineShape
override fun init(engine: PulseEngine)
{
if (this is Spatial)
{
shape.init(x, y, width, rotation)
}
}
override fun beginStep(engine: PulseEngine, timeStep: Float, gravity: Float)
{
if (bodyType == STATIC)
return
// Point 0
val drag = 1f - drag
val xNow0 = shape.x0
val yNow0 = shape.y0
val xVel0 = (xNow0 - shape.xLast0) * drag + shape.xAcc0 * timeStep * timeStep
val yVel0 = (yNow0 - shape.yLast0) * drag + shape.yAcc0 * timeStep * timeStep
shape.xLast0 = xNow0
shape.yLast0 = yNow0
shape.x0 = xNow0 + xVel0
shape.y0 = yNow0 + yVel0
shape.xAcc0 = 0f
shape.yAcc0 = gravity
// Point 1
val xNow1 = shape.x1
val yNow1 = shape.y1
val xVel1 = (xNow1 - shape.xLast1) * drag + shape.xAcc1 * timeStep * timeStep
val yVel1 = (yNow1 - shape.yLast1) * drag + shape.yAcc1 * timeStep * timeStep
shape.xLast1 = xNow1
shape.yLast1 = yNow1
shape.x1 = xNow1 + xVel1
shape.y1 = yNow1 + yVel1
shape.xAcc1 = 0f
shape.yAcc1 = gravity
}
override fun iterateStep(engine: PulseEngine, iteration: Int, totalIterations: Int, worldWidth: Int, worldHeight: Int)
{
if (bodyType == STATIC)
return
val x = (shape.x0 + shape.x1) * 0.5f
val y = (shape.y0 + shape.y1) * 0.5f
val xMin = min(shape.x0, shape.x1)
val xMax = max(shape.x0, shape.x1)
val yMin = min(shape.y0, shape.y1)
val yMax = max(shape.y0, shape.y1)
engine.scene.forEachEntityNearby(x, y, xMax - xMin, yMax - yMin)
{
if (it !== this &&
it is PhysicsBody &&
it.layerMask and this.collisionMask != 0 &&
it.hasOverlappingAABB(xMin, yMin, xMax, yMax)
) {
ContactSolver.solve(this, it)?.let { result ->
onCollision(engine, it, result)
it.onCollision(engine, this, result)
it.wakeUp()
}
}
}
// Update constrains
val stiffness = 1f
val xDelta = shape.x0 - shape.x1
val yDelta = shape.y0 - shape.y1
val actualLength = sqrt(xDelta * xDelta + yDelta * yDelta)
val targetLength = shape.length
val deltaLength = (targetLength - actualLength) * 0.5f * stiffness
val xChange = (xDelta / actualLength) * deltaLength
val yChange = (yDelta / actualLength) * deltaLength
shape.x0 += xChange
shape.y0 += yChange
shape.x1 -= xChange
shape.y1 -= yChange
// Update collisions
if (iteration == totalIterations - 1)
{
onBodyUpdated()
}
}
override fun render(engine: PulseEngine, surface: Surface)
{
surface.setDrawColor(Color.WHITE)
surface.drawLine(shape.x0, shape.y0, shape.x1, shape.y1)
surface.drawTexture(Texture.BLANK, shape.x0 - 5f, shape.y0 - 5f, 10f, 10f, cornerRadius = 5f)
surface.drawTexture(Texture.BLANK, shape.x1 - 5f, shape.y1 - 5f, 10f, 10f, cornerRadius = 5f)
}
fun onBodyUpdated()
{
if (this is SceneEntity && this is Spatial)
{
val xDelta = shape.x1 - shape.x0
val yDelta = shape.y1 - shape.y0
rotation = (-atan2(yDelta, xDelta) / PI.toFloat() + 1.0f) * 180f
x = (shape.x0 + shape.x1) * 0.5f
y = (shape.y0 + shape.y1) * 0.5f
set(POSITION_UPDATED and ROTATION_UPDATED)
}
}
override fun wakeUp() { /* Point bodies do not sleep */ }
override fun hasOverlappingAABB(xMin: Float, yMin: Float, xMax: Float, yMax: Float): Boolean
{
val xMinLine = min(shape.x0, shape.x1)
val xMaxLine = max(shape.x0, shape.x1)
val yMinLine = min(shape.y0, shape.y1)
val yMaxLine = max(shape.y0, shape.y1)
return xMin < xMaxLine && xMax > xMinLine && yMin < yMaxLine && yMax > yMinLine
}
override fun getMass() = shape.mass
override fun onCollision(engine: PulseEngine, otherBody: PhysicsBody, result: ContactResult) { }
} | 0 | Kotlin | 0 | 1 | 47f284ccc45799ccd6cffb55851dd98044321f49 | 5,085 | PulseEngine | MIT License |
reaktive/src/commonMain/kotlin/com/badoo/reaktive/completable/ThreadLocal.kt | kls1002 | 218,411,025 | true | {"Kotlin": 805740, "Swift": 3813, "HTML": 1108, "Ruby": 150} | package com.badoo.reaktive.completable
import com.badoo.reaktive.base.exceptions.CompositeException
import com.badoo.reaktive.base.subscribeSafe
import com.badoo.reaktive.disposable.CompositeDisposable
import com.badoo.reaktive.disposable.Disposable
import com.badoo.reaktive.utils.ThreadLocalStorage
import com.badoo.reaktive.utils.handleSourceError
fun Completable.threadLocal(): Completable =
completable {
val disposables = CompositeDisposable()
it.setDisposable(disposables)
val emitterStorage = ThreadLocalStorage(it)
disposables += emitterStorage
subscribeSafe(
object : CompletableObserver {
override fun onSubscribe(disposable: Disposable) {
disposables += disposable
}
override fun onComplete() {
getEmitter()?.onComplete()
}
override fun onError(error: Throwable) {
getEmitter(error)?.onError(error)
}
private fun getEmitter(existingError: Throwable? = null): CompletableEmitter? =
try {
requireNotNull(emitterStorage.get())
} catch (e: Throwable) {
handleSourceError(if (existingError == null) e else CompositeException(existingError, e))
null
}
}
)
}
| 0 | null | 0 | 0 | b17afce9fe267a91053a39bd57130e666abbd28c | 1,454 | Reaktive | Apache License 2.0 |
app/src/main/java/com/ali/filmrent/dataClass/Language.kt | Alibalvardi | 740,135,480 | false | {"Kotlin": 200312} | package com.ali.filmrent.dataClass
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(indices = [Index(value = ["name"] , unique = true) ])
data class Language(
@PrimaryKey(autoGenerate = true)
val language_id :Int? = null ,
val name : String
)
| 0 | Kotlin | 0 | 0 | e335ae184e3776a068d96f266da5bab0a2bc212f | 303 | FilmRent | MIT License |
app/src/main/java/com/mankart/mankgram/ui/mainmenu/setting/SettingFragment.kt | reskimulud | 478,623,288 | false | null | package com.mankart.mankgram.ui.mainmenu.setting
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.mankart.mankgram.ui.ViewModelFactory
import com.mankart.mankgram.ui.authentication.AuthenticationActivity
import com.mankart.mankgram.ui.authentication.AuthenticationViewModel
import com.mankart.mankgram.databinding.FragmentSettingBinding
import java.util.*
class SettingFragment : Fragment() {
private lateinit var factory: ViewModelFactory
private val settingViewModel: SettingViewModel by activityViewModels { factory }
private val authenticationViewModel: AuthenticationViewModel by activityViewModels { factory }
private var _binding: FragmentSettingBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSettingBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
factory = ViewModelFactory.getInstance(requireActivity())
initObserve()
initView()
}
private fun initView() {
binding.setLanguage.setOnClickListener {
startActivity(Intent(Settings.ACTION_LOCALE_SETTINGS))
}
binding.localName.text = Locale.getDefault().displayName
binding.btnLogout.setOnClickListener {
startActivity(Intent(activity, AuthenticationActivity::class.java))
activity?.finish()
}
binding.switchMode.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
settingViewModel.saveThemeMode(isChecked)
}
binding.btnLogout.setOnClickListener {
authenticationViewModel.logout()
settingViewModel.saveIsFirstTime(false)
startActivity(Intent(activity, AuthenticationActivity::class.java))
activity?.finish()
}
}
private fun initObserve() {
settingViewModel.getThemeMode().observe(viewLifecycleOwner) { isNightMode ->
if (isNightMode) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
binding.switchMode.isChecked = isNightMode
}
settingViewModel.getUserName().observe(viewLifecycleOwner) { userName ->
binding.tvName.text = userName
}
settingViewModel.getUserEmail().observe(viewLifecycleOwner) { userEmail ->
binding.tvEmail.text = userEmail
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 2 | 16 | 40a5279fe533ac4f7b88be8d28d613f5c9d7fa67 | 3,251 | Mankgram | MIT License |
data/src/main/java/nam/tran/data/controller/IPlayerController.kt | Dev-Learn | 179,638,602 | false | null | package nam.tran.data.controller
import androidx.lifecycle.LiveData
import nam.tran.data.model.PlayerData
interface IPlayerController {
val player : LiveData<PlayerData>
fun checkPlayerNotUpdateUI(id : Int) : Boolean
fun playSong(name: String, id: Int,pathFolder : String?)
fun pauseSong()
fun stopSong()
fun pauseId() : Int
fun release()
} | 0 | Kotlin | 0 | 1 | bc3f73162b2f1673cbe85c57ba50f9044b98058d | 370 | Android-SongChart | Apache License 2.0 |
sample/src/main/kotlin/com/example/kotlin/TodoCommentStyling.kt | hanggrian | 556,969,715 | false | {"Kotlin": 283484, "Python": 75510, "Java": 20710, "CSS": 1653, "Groovy": 323} | package com.example.kotlin
class TodoCommentStyling {
// TODO add tests
// FIXME memory leak
}
| 0 | Kotlin | 0 | 1 | 2a371bdb0b18b9b0024df0867b6aab8ba4bc0ced | 104 | rulebook | Apache License 2.0 |
travako-starter/travako-starter-processor-core/src/main/java/io/arkitik/travako/starter/processor/core/errors/TravakoCoreStartupErrors.kt | arkitik | 441,685,610 | false | {"Kotlin": 324533, "Shell": 91} | package io.arkitik.travako.starter.processor.core.errors
import io.arkitik.radix.develop.shared.error.ErrorResponse
/**
* Created By [*<NAME> *](https://www.linkedin.com/in/iloom/)
* Created At 31 12:29 AM, **Fri, December 2021**
* Project *travako* [arkitik.io](https://arkitik.io)
*/
enum class TravakoCoreStartupErrors(
override val code: String,
override val message: String,
) : ErrorResponse {
JOB_CLASS_NOT_FOUND("TRAVAKO-CORE-STARTUP-0000", "Job Class not found"),
NO_PROVIDER_TO_CREATE_JOB("TRAVAKO-CORE-STARTUP-1111", "No provider to create jobs"),
}
| 1 | Kotlin | 0 | 3 | 0ebfbf4ea9c5a945130b89ab037111c5f9f8cc53 | 584 | travako | Apache License 2.0 |
motmbrowser/src/main/java/com/bammellab/motm/search/SearchMatchesFragment.kt | bammellab | 314,793,120 | true | {"Kotlin": 944764, "Rich Text Format": 254772} | /*
* Copyright 2020 Bammellab / <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
@file:Suppress("UNUSED_PARAMETER", "CanBeParameter")
package com.bammellab.motm.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.bammellab.motm.R
class SearchMatchesFragment : Fragment() {
private lateinit var searchViewModel: SearchViewModel
private lateinit var searchResultsDisplay: FrameLayout
private lateinit var recyclerView: RecyclerView
private lateinit var searchAdapter: SearchAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_search_matches, container, false)
searchResultsDisplay = root.findViewById(R.id.search_results_matches_frame_layout)
recyclerView = root.findViewById(R.id.search_results_list)
searchAdapter = SearchAdapter(root.context)
with(recyclerView) {
layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
adapter = searchAdapter
}
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (callback != null && dy > 0) {
callback!!.clearKeyboard()
}
}
})
return root
}
fun setViewModel(viewModel: SearchViewModel) {
searchViewModel = viewModel
//adapterInUse.setViewModel(searchViewModel)
}
fun show() {
searchResultsDisplay.visibility = VISIBLE
}
fun hide() {
searchResultsDisplay.visibility = GONE
}
fun isShowing(): Boolean {
return searchResultsDisplay.visibility == VISIBLE
}
fun startSearch(searchTerm: String) {
searchAdapter.doSearchOn(searchTerm)
}
fun setCallback(callbackIn: Callback) {
callback = callbackIn
}
interface Callback {
fun clearKeyboard()
}
private var callback: Callback? = null
fun setCallbackInAdapter(callbackIn: SearchAdapter.Callback) {
searchAdapter.setCallback(callbackIn)
}
} | 0 | Kotlin | 0 | 2 | 95f040f0ce8f33c35f549fd5828690b7ba0f192d | 3,046 | MotmBrowser | Apache License 2.0 |
dogFunFacts/src/main/java/com/faaadi/apps/kotlindsl/dogfunfacts/ui/DogFunFactsFragment.kt | profahad | 416,692,173 | false | null | package com.faaadi.apps.kotlindsl.dogfunfacts.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.faaadi.apps.kotlindsl.dogfunfacts.R
import com.faaadi.apps.kotlindsl.dogfunfacts.models.DogFactsResModel
import com.faaadi.apps.networkcore.handlers.ResourceState
import com.faaadi.apps.networkcore.utils.CoreUtility
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_dog_fun_facts.*
@AndroidEntryPoint
class DogFunFactsFragment : Fragment() {
private val viewModel by viewModels<DogFactsViewModel>()
private lateinit var dogFunFactsAdapter: DogFunFactsAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_dog_fun_facts, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getDogFunFacts()
setUpObservers()
}
private fun getDogFunFacts() {
viewModel.getDogFunFacts("10")
}
private fun setUpObservers() {
viewModel.dogFunFactsResponse.observe(viewLifecycleOwner, Observer {
when (it) {
is ResourceState.Success -> {
CoreUtility.printLog(TAG, "Inside_dogFunFactsResponse_success ${Gson().toJson(it)}")
viewModel.loadingVisibility.value = View.GONE
it.data?.also { facts->
setUpDogFactsRecyclerView(facts)
}
}
is ResourceState.Error -> {
viewModel.loadingVisibility.value = View.GONE
CoreUtility.printLog(TAG, "Inside_dogFunFactsResponse_error ${it.message}")
Toast.makeText(context,it.message,Toast.LENGTH_LONG).show()
}
is ResourceState.Loading -> {
viewModel.loadingVisibility.value = View.VISIBLE
}
}
})
viewModel.loadingVisibility.observe(viewLifecycleOwner, Observer {
if (it == View.VISIBLE)
dogLoaderView.visibility = View.VISIBLE
else
dogLoaderView.visibility = View.GONE
})
}
private fun setUpDogFactsRecyclerView(facts: ArrayList<DogFactsResModel>) {
dogLoaderView.visibility = View.GONE
rvDogFunFacts.apply {
visibility = View.VISIBLE
adapter = DogFunFactsAdapter(facts)
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
}
}
companion object{
private const val TAG = "DogFunFactsFragment"
}
} | 0 | Kotlin | 0 | 0 | 83c59b1da4f11ecd322865c317a325cc2aa0edc1 | 3,093 | android-moduler-arc | MIT License |
intellij-plugin-structure/structure-teamcity-actions/src/main/kotlin/com/jetbrains/plugin/structure/teamcity/action/TeamCityActionSpec.kt | JetBrains | 3,686,654 | false | {"Kotlin": 2515626, "Java": 253600, "CSS": 1454, "JavaScript": 692} | package com.jetbrains.plugin.structure.teamcity.action
object TeamCityActionSpec {
object ActionSpecVersion {
const val NAME = "spec-version"
const val DESCRIPTION = "the version of action specification"
}
object ActionName {
const val NAME = "name"
const val DESCRIPTION = "action name"
const val MAX_LENGTH = 30
/**
* Regular expression pattern for the action name.
*
* The pattern enforces the following rules:
* - Name cannot be empty.
* – Name can only contain latin letters, dashes and underscores.
* - Name cannot start or end with a dash or underscore.
* - Name cannot contain several consecutive dashes or underscores.
*/
val nameRegex: Regex = Regex("^[a-zA-Z0-9]+([_-][a-zA-Z0-9]+)*\$")
}
object ActionVersion {
const val NAME = "version"
const val DESCRIPTION = "action version"
}
object ActionDescription {
const val NAME = "description"
const val DESCRIPTION = "action description"
const val MAX_LENGTH = 250
}
object ActionInputs {
const val NAME = "inputs"
}
object ActionInputName {
const val NAME = "name"
const val DESCRIPTION = "action input name"
const val MAX_LENGTH = 50
}
object ActionInputType {
const val NAME = "type"
const val DESCRIPTION = "action input type"
}
object ActionInputRequired {
const val NAME = "required"
const val DESCRIPTION = "indicates whether the input is required"
}
object ActionInputLabel {
const val NAME = "label"
const val DESCRIPTION = "action input label"
const val MAX_LENGTH = 100
}
object ActionInputDescription {
const val NAME = "description"
const val DESCRIPTION = "action input description"
const val MAX_LENGTH = 250
}
object ActionInputDefault {
const val NAME = "default"
const val DESCRIPTION = "action input default value"
}
object ActionInputOptions {
const val NAME = "options"
const val DESCRIPTION = "action input options"
}
object ActionRequirements {
const val NAME = "requirements"
}
object ActionRequirementName {
const val NAME = "name"
const val DESCRIPTION = "action requirement name"
const val MAX_LENGTH = 50
}
object ActionRequirementType {
const val NAME = "type"
const val DESCRIPTION = "action requirement type"
}
object ActionRequirementValue {
const val NAME = "value"
}
object ActionSteps {
const val NAME = "steps"
const val DESCRIPTION = "action steps"
}
object ActionStepName {
const val NAME = "name"
const val DESCRIPTION = "action step name"
const val MAX_LENGTH = 50
}
object ActionStepWith {
const val NAME = "with"
const val DESCRIPTION = "runner or action reference"
const val MAX_LENGTH = 100
val allowedPrefixes = listOf("runner/", "action/")
}
object ActionStepScript {
const val NAME = "script"
const val DESCRIPTION = "executable script content"
const val MAX_LENGTH = 50_000
}
object ActionStepParams {
const val NAME = "params"
}
} | 3 | Kotlin | 37 | 177 | 96364e9e62ce181875a5ac366fb30cc113a4cc88 | 3,083 | intellij-plugin-verifier | Apache License 2.0 |
src/main/kotlin/aoc2020/day10/Joltage.kt | arnab | 75,525,311 | false | null | package aoc2020.day10
object Joltage {
fun parse(data: String): List<Int> = data.split("\n").map { it.toInt() }
fun arrange(adapters: List<Int>): List<Int> {
val sorted = adapters.sorted()
return sorted + listOf(sorted.maxOrNull()!! + 3)
}
fun calculateDiffs(chain: List<Int>): List<Int> {
val base = listOf(0) + chain
val pairs: List<Pair<Int, Int>> = base.zip(chain)
return pairs.map { (prev, next) -> next - prev }
}
fun solvePart1(differences: List<Int>): Int =
differences.groupingBy { it }
.eachCount()
.let { diffsCount -> diffsCount[1]!! * diffsCount[3]!! }
/**
* Cache of known paths for the given adapter, to avoid re-calculation of trillions of possibilities.
*/
private val knownPaths: MutableMap<Int, Long> = mutableMapOf()
fun countPaths(adapters: Set<Int>): Long {
knownPaths.clear()
return countPathsRecursively(adapters, 0, adapters.maxOrNull()!!)
}
private fun countPathsRecursively(adapters: Set<Int>, currentAdapter: Int, maxAdapter: Int): Long {
// No more paths
if (currentAdapter == maxAdapter) return 1
// memoize the path-count for the current adapter
knownPaths.getOrPut(currentAdapter) {
countPathsForAdapter(adapters, currentAdapter, maxAdapter)
}
return knownPaths[currentAdapter]!!
}
private fun countPathsForAdapter(adapters: Set<Int>, adapter: Int, maxAdapter: Int): Long =
listOfNotNull(
(adapter + 1).let { if (it in adapters) countPathsRecursively(adapters, it, maxAdapter) else null },
(adapter + 2).let { if (it in adapters) countPathsRecursively(adapters, it, maxAdapter) else null },
(adapter + 3).let { if (it in adapters) countPathsRecursively(adapters, it, maxAdapter) else null }
).sum()
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,904 | adventofcode | MIT License |
varddb/src/main/java/com/vardemin/varddb/AsyncUtil.kt | vardemin | 227,146,148 | false | null | package com.vardemin.varddb
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
suspend fun <T> async(context: CoroutineContext = Dispatchers.IO, body: ()-> T) =
withContext(context) {
body.invoke()
} | 0 | Kotlin | 0 | 3 | 65fb08b5c3a4e2858d0532d93abf6b03645db4f9 | 236 | VardDB | MIT License |
src/main/kotlin/me/senseiwells/replay/ServerReplay.kt | senseiwells | 643,690,788 | false | {"Kotlin": 57961, "Java": 16020} | package me.senseiwells.replay
import me.senseiwells.replay.config.ReplayConfig
import me.senseiwells.replay.player.predicates.*
import net.fabricmc.api.ModInitializer
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class ServerReplay: ModInitializer {
override fun onInitialize() {
ReplayConfig.addPredicateFactories(
AllPredicate,
AndPredicate,
HasNamePredicate,
HasOpPredicate,
InTeamPredicate,
NonePredicate,
NotPredicate,
OrPredicate,
UUIDPredicate
)
}
companion object {
@JvmField
val logger: Logger = LoggerFactory.getLogger("ServerReplay")
@JvmField
val version = "1.0.0"
}
} | 2 | Kotlin | 0 | 9 | fd80e863fea7850ae329a265c4064e7455b276fa | 765 | ServerReplay | MIT License |
app/src/main/java/cz/budikpet/bachelorwork/di/AppComponent.kt | budikpet | 173,619,887 | false | null | package cz.budikpet.bachelorwork.di
import cz.budikpet.bachelorwork.data.Repository
import cz.budikpet.bachelorwork.screens.calendarListView.CalendarsListFragment
import cz.budikpet.bachelorwork.screens.ctuLogin.CTULoginActivity
import cz.budikpet.bachelorwork.screens.emailListView.EmailListFragment
import cz.budikpet.bachelorwork.screens.eventEditView.EventEditFragment
import cz.budikpet.bachelorwork.screens.eventView.EventViewFragment
import cz.budikpet.bachelorwork.screens.freeTimeView.FreeTimeFragment
import cz.budikpet.bachelorwork.screens.main.MainActivity
import cz.budikpet.bachelorwork.screens.main.MainViewModel
import cz.budikpet.bachelorwork.screens.multidayView.MultidayFragmentHolder
import cz.budikpet.bachelorwork.screens.multidayView.MultidayViewFragment
import cz.budikpet.bachelorwork.screens.settings.SettingsFragment
import dagger.Component
import javax.inject.Singleton
/**
* Component connects modules and annotations.
*/
@Singleton
@Component(modules = [AppModule::class, ViewModelFactoryModule::class, MainViewModelModule::class])
internal interface AppComponent {
fun inject(mainViewModel: MainViewModel)
fun inject(repository: Repository)
fun inject(ctuLoginActivity: CTULoginActivity)
fun inject(mainActivity: MainActivity)
fun inject(multidayViewFragment: MultidayViewFragment)
fun inject(freeTimeFragment: FreeTimeFragment)
fun inject(settingsFragment: SettingsFragment)
fun inject(multidayFragmentHolder: MultidayFragmentHolder)
fun inject(eventViewFragment: EventViewFragment)
fun inject(eventEditFragment: EventEditFragment)
fun inject(emailListFragment: EmailListFragment)
fun inject(calendarsListFragment: CalendarsListFragment)
} | 0 | Kotlin | 0 | 0 | df5c3d4720f7afe2d9217e03428ca0681d753f57 | 1,723 | BachelorWork | MIT License |
app/src/main/java/xyz/asnes/attention/MainActivity.kt | nicasnes | 321,897,380 | false | null | package xyz.asnes.attention
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
open class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
supportActionBar?.hide()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Explore preference settings to see if this is the first run.
val settings = this.getSharedPreferences("appInfo", Context.MODE_PRIVATE)
// If this is the first run, request a phone number from the user.
if (!settings.getBoolean("isPhoneNumber", false)) {
settings.edit().putBoolean("isPhoneNumber", true).apply()
startActivity(Intent(this, OnboardingActivity::class.java))
}
}
/**
* Called when the user presses the "emotional attention" button.
* **/
fun openEmotionalAttentionMenu(view: View) {
val intent = Intent(this, EmotionalPromptsActivity::class.java)
startActivity(intent)
}
/**
* Called when the user presses the "physical attention" button.
*/
fun openPhysicalAttentionMenu(view: View) {
val intent = Intent(this, PhysicalPromptsActivity::class.java)
startActivity(intent)
}
/**
* Called when the user presses the "settings" button.
*/
fun openSettingsMenu(view: View) {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
}
} | 2 | Kotlin | 0 | 0 | 279ce346a052792e4340753bd2b6abe3340f738f | 1,572 | Communicator | MIT License |
waltid-openid4vc/src/commonMain/kotlin/id/walt/oid4vc/util/ShortIdUtils.kt | walt-id | 701,058,624 | false | {"Kotlin": 2010420, "Vue": 327721, "TypeScript": 92744, "JavaScript": 20560, "Dockerfile": 7147, "Shell": 1651, "CSS": 404} | package id.walt.oid4vc.util
import kotlinx.uuid.SecureRandom
object ShortIdUtils {
private val squids = Sqids()
fun randomSessionId(): String {
return squids.encode(
listOf(
(SecureRandom.nextDouble(0.0, Double.MAX_VALUE) * SecureRandom.nextLong(0, Long.MAX_VALUE)).toLong()
)
)
}
}
| 28 | Kotlin | 33 | 94 | 7f165250bbf32379b49a8f6fd660782fe2d9ffab | 355 | waltid-identity | Apache License 2.0 |
HeroApp/app/src/main/java/com/sachin/heroapp/presentation/screens/splash/SplashScreen.kt | iamsachin22 | 512,240,988 | false | {"Kotlin": 141099} | package com.sachin.heroapp.presentation.screens.splash
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.sachin.heroapp.R
import com.sachin.heroapp.navigation.Screen
import com.sachin.heroapp.ui.theme.Purple500
import com.sachin.heroapp.ui.theme.Purple700
import com.sachin.heroapp.ui.theme.Red700
@Composable
fun SplashScreen(
navController: NavHostController,
splashViewModel: SplashViewModel = hiltViewModel()
) {
val onBoardingCompleted by splashViewModel.onBoardingCompleted.collectAsState()
val degrees = remember { Animatable(0f) }
LaunchedEffect(key1 = true) {
degrees.animateTo(
targetValue = 360f,
animationSpec = tween(
durationMillis = 1000,
delayMillis = 200
)
)
navController.popBackStack()
if (onBoardingCompleted) {
navController.navigate(Screen.Home.route)
} else {
navController.navigate(Screen.Welcome.route)
}
}
Splash(degrees = degrees.value)
}
@Composable
fun Splash(degrees: Float) {
val modifier = if (isSystemInDarkTheme()) {
Modifier.background(Color.Black)
} else {
Modifier.background(
Brush.verticalGradient(listOf(Red700, Purple500))
)
}
Box(
modifier = modifier
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier.rotate(degrees = degrees),
painter = painterResource(id = R.drawable.icon_logo),
contentDescription = stringResource(R.string.app_logo)
)
}
}
@Composable
@Preview
fun SplashScreenPreview() {
Splash(degrees = 0f)
}
@Composable
@Preview(uiMode = UI_MODE_NIGHT_YES)
fun SplashScreenDarkPreview() {
Splash(degrees = 0f)
} | 0 | Kotlin | 0 | 2 | d80169a1a81b6d37cfadf55461dccbd1e5a1b60d | 2,649 | heroapp | Apache License 2.0 |
common/src/main/java/ru/haroncode/wordlearn/common/util/Keyboard.kt | Hukumister | 182,296,995 | false | null | package ru.haroncode.wordlearn.common.util
import android.app.Dialog
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.core.content.getSystemService
object Keyboard {
/**
* Explicitly request that the current input method's soft input area be
* shown to the user, if needed. Call this if the user interacts with
* your view in such a way that they have expressed they would like to
* start performing input into it.
*
* @param v The currently focused view, which would like to receive
* soft keyboard input.
* @param forceShow Provides additional operating flags.
*/
@JvmStatic
@JvmOverloads
fun show(v: View?, forceShow: Boolean = false) {
if (v != null) {
val imm = getInputMethodManager(v.context)
if (imm != null) {
if (forceShow) {
v.requestFocus()
}
val flags = if (forceShow) InputMethodManager.SHOW_FORCED else InputMethodManager.SHOW_IMPLICIT
imm.showSoftInput(v, flags)
}
}
}
/**
* @see .hide
*/
@JvmStatic
fun hide(dialog: Dialog?): Boolean {
if (dialog != null) {
// Find the currently focused view, so we can grab the correct window token from it.
val view = dialog.currentFocus
return hide(view)
}
return false
}
/**
* Request to hide the soft input window from the context of the window
* that is currently accepting input. This should be called as a result
* of the user doing some actually than fairly explicitly requests to
* have the input window hidden.
*
* @param v The currently focused view, which would like to lost
* soft keyboard input.
* @return true if soft keyboard input was active, false otherwise.
*/
@JvmStatic
fun hide(v: View?): Boolean {
var isHided = false
if (v != null) {
val imm = getInputMethodManager(v.context)
if (imm != null) {
isHided = imm.hideSoftInputFromWindow(v.applicationWindowToken, 0)
}
}
return isHided
}
private fun getInputMethodManager(context: Context) = context.getSystemService<InputMethodManager>()
}
| 0 | Kotlin | 0 | 5 | 1b98049eace38ed832f1ff41ddccd50b37b0f611 | 2,381 | WordLearn | MIT License |
app/src/main/java/com/rcd27/playfm/extensions/CompositeDisosableKtx.kt | rcd27 | 226,152,817 | false | null | package com.rcd27.playfm.extensions
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/** Утилита, добавляющая возможность складывать [Disposable] в [CompositeDisposable]
* через оператор присвоения `+=`
*/
operator fun CompositeDisposable.plusAssign(d: Disposable) {
this.add(d)
} | 1 | Kotlin | 0 | 1 | dfcb9742746a1d3ec8756aa6c5706de8eb1c07a6 | 335 | playfm | MIT License |
applications/account-generator-streams-source/src/main/kotlin/com/vmware/tanzu/data/services/rabbitmq/streaming/account/AccountGeneratorRunner.kt | Tanzu-Solutions-Engineering | 400,235,533 | false | null | package com.vmware.tanzu.data.services.rabbitmq.streaming.account
import com.fasterxml.jackson.databind.ObjectMapper
import com.vmware.tanzu.data.services.rabbitmq.streaming.account.domain.Account
import nyla.solutions.core.patterns.creational.generator.JavaBeanGeneratorCreator
import nyla.solutions.core.patterns.workthread.ExecutorBoss
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.rabbit.stream.producer.RabbitStreamTemplate
import org.springframework.stereotype.Component
import java.text.DecimalFormat
import java.util.concurrent.Callable
import java.util.concurrent.Future
/**
* Generates accounts
* @author <NAME>
*/
@Component
class AccountGeneratorRunner(
private val template: RabbitStreamTemplate,
@Value("\${account.generate.count:100000}")
private val count: Long) : ApplicationRunner {
private var futures: Future<*>? = null
private var account : Account = JavaBeanGeneratorCreator.of(Account::class.java).create()
private val logger = LoggerFactory.getLogger(this.javaClass)
/**
* Generate and send given number of accounts streaming records
*/
override fun run(args: ApplicationArguments?) {
var startTime = System.currentTimeMillis()
for(id in 1.. count) {
var text =
"{\"id\":\"$id\",\"name\":\"Account $id\",\"accountType\":\"Billing\",\"status\":\"OPEN\",\"notes\":\"Generated $id\",\"location\":{\"id\":\"$id\",\"address\":\"$id VMware Street\",\"cityTown\":\"City $id\",\"stateProvince\":\"State $id\",\"zipPostalCode\":\"2020$id\",\"countryCode\":\"US\"}}"
template.send(
template
.messageBuilder()
.properties().contentType("application/json")
.messageBuilder()
.addData(text.toByteArray(Charsets.UTF_8))
.build()
)
}
var endTime = System.currentTimeMillis()
var totalTime = endTime - startTime
logger.info("Completed loading {} records",DecimalFormat("#,###.##").format(count))
}
} | 3 | Go | 2 | 3 | 987fd4b51289e7cdfe358227e0f7a58c40290213 | 2,321 | tanzu-rabbitmq-event-streaming-showcase | Apache License 2.0 |
history/data/src/test/java/com/mitteloupe/whoami/history/data/mapper/HistoryRecordDeletionToDataMapperTest.kt | EranBoudjnah | 662,551,018 | false | null | package com.mitteloupe.whoami.history.data.mapper
import com.mitteloupe.whoami.datasource.history.model.HistoryRecordDeletionIdentifierDataModel
import com.mitteloupe.whoami.history.domain.model.HistoryRecordDeletionDomainModel
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
@RunWith(Parameterized::class)
class HistoryRecordDeletionToDataMapperTest(
private val givenDeletionRequest: HistoryRecordDeletionDomainModel,
private val expectedDataRequest: HistoryRecordDeletionIdentifierDataModel
) {
companion object {
@JvmStatic
@Parameters(name = "Given {0} then returns {2}")
fun data(): Collection<Array<*>> = listOf(
testCase(ipAddress = "1.2.3.4"),
testCase(ipAddress = "4.3.2.1")
)
private fun testCase(ipAddress: String) = arrayOf(
HistoryRecordDeletionDomainModel(ipAddress = ipAddress),
HistoryRecordDeletionIdentifierDataModel(ipAddress = ipAddress)
)
}
private lateinit var classUnderTest: HistoryRecordDeletionToDataMapper
@Before
fun setUp() {
classUnderTest = HistoryRecordDeletionToDataMapper()
}
@Test
fun `When toData`() {
// When
val actualValue = classUnderTest.toData(givenDeletionRequest)
// Then
assertEquals(expectedDataRequest, actualValue)
}
}
| 2 | null | 60 | 509 | b975f649800b12619cbedc78fde69e9e275d943f | 1,511 | CleanArchitectureForAndroid | MIT License |
src/main/kotlin/com/dwolla/shared/Money.kt | Dwolla | 189,449,029 | false | null | package com.dwolla.shared
data class Money(
@JvmField val value: String,
@JvmField val currency: Currency = Currency.USD
)
| 7 | Kotlin | 5 | 9 | 013d9d5cbf963c85224c0fd9c68f84044046ed17 | 132 | dwolla-v2-kotlin | MIT License |
app/src/main/java/vn/loitp/a/cv/layout/autoLinear/AutoLinearLayoutActivityFont.kt | tplloi | 126,578,283 | false | null | package vn.loitp.a.cv.layout.autoLinear
import android.os.Bundle
import androidx.core.view.isVisible
import com.loitp.annotation.IsFullScreen
import com.loitp.annotation.LogTag
import com.loitp.core.base.BaseActivityFont
import com.loitp.core.ext.openUrlInBrowser
import com.loitp.core.ext.setSafeOnClickListenerElastic
import kotlinx.android.synthetic.main.a_auto_linear_layout.*
import vn.loitp.R
import vn.loitp.app.EmptyActivity
@LogTag("AutoLinearLayoutActivity")
@IsFullScreen(false)
class AutoLinearLayoutActivityFont : BaseActivityFont() {
override fun setLayoutResourceId(): Int {
return R.layout.a_auto_linear_layout
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupViews()
}
private fun setupViews() {
lActionBar.apply {
this.ivIconLeft.setSafeOnClickListenerElastic(
runnable = {
onBaseBackPressed()
}
)
this.ivIconRight?.let {
it.setSafeOnClickListenerElastic(
runnable = {
context.openUrlInBrowser(
url = "https://github.com/AlbertGrobas/AutoLinearLayout"
)
}
)
it.isVisible = true
it.setImageResource(R.drawable.ic_baseline_code_48)
}
this.tvTitle?.text = EmptyActivity::class.java.simpleName
}
}
}
| 0 | Kotlin | 0 | 10 | 333bebaf3287b1633f35d29b8adaf25b19c1859f | 1,522 | base | Apache License 2.0 |
app/src/main/java/com/kvl/cyclotrack/FeatureFlags.kt | kevinvanleer | 311,970,003 | false | null | package com.kvl.cyclotrack
class FeatureFlags {
companion object {
const val devBuild: Boolean =
BuildConfig.BUILD_TYPE == "dev" || BuildConfig.BUILD_TYPE == "debug"
const val productionBuild: Boolean = BuildConfig.BUILD_TYPE == "prod"
const val betaBuild: Boolean = !productionBuild
//FOR TESTING
//const val betaBuild: Boolean = devBuild
}
}
| 0 | Kotlin | 0 | 7 | e62bbb39eec10d2f3c327c024f1462e3a6736987 | 406 | cyclotrack | The Unlicense |
boat-core/src/main/kotlin/xyz/srclab/common/collect/CollectionCollects.kt | srclab-projects | 247,777,997 | false | null | @file:JvmName("Collects")
@file:JvmMultifileClass
package xyz.srclab.common.collect
import kotlin.collections.addAll as addAllKt
import kotlin.collections.count as countKt
import kotlin.collections.plus as plusKt
import kotlin.collections.removeAll as removeAllKt
import kotlin.collections.retainAll as retainAllKt
import kotlin.collections.toList as toListKt
import kotlin.collections.toMutableList as toMutableListKt
fun <T> Collection<T>.containsAll(elements: Array<out T>): Boolean {
return this.containsAll(elements.toListKt())
}
fun <T> Collection<T>.containsAll(elements: Iterable<T>): Boolean {
return this.containsAll(elements.asToList())
}
fun <T> Collection<T>.count(): Int {
return this.countKt()
}
fun <T> Collection<T>.toMutableList(): MutableList<T> {
return this.toMutableListKt()
}
fun <T> Collection<T>.plus(element: T): List<T> {
return this.plusKt(element)
}
fun <T> Collection<T>.plus(elements: Array<out T>): List<T> {
return this.plusKt(elements)
}
fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
return this.plusKt(elements)
}
fun <T> Collection<T>.plus(elements: Sequence<T>): List<T> {
return this.plusKt(elements)
}
fun <T> MutableCollection<T>.addAll(elements: Array<out T>): Boolean {
return this.addAllKt(elements)
}
fun <T> MutableCollection<T>.addAll(elements: Iterable<T>): Boolean {
return this.addAllKt(elements)
}
fun <T> MutableCollection<T>.addAll(elements: Sequence<T>): Boolean {
return this.addAllKt(elements)
}
fun <T> MutableCollection<T>.removeAll(elements: Array<out T>): Boolean {
return this.removeAllKt(elements)
}
fun <T> MutableCollection<T>.removeAll(elements: Iterable<T>): Boolean {
return this.removeAllKt(elements)
}
fun <T> MutableCollection<T>.removeAll(elements: Sequence<T>): Boolean {
return this.removeAllKt(elements)
}
fun <T> MutableCollection<T>.retainAll(elements: Array<out T>): Boolean {
return this.retainAllKt(elements)
}
fun <T> MutableCollection<T>.retainAll(elements: Iterable<T>): Boolean {
return this.retainAllKt(elements)
}
fun <T> MutableCollection<T>.retainAll(elements: Sequence<T>): Boolean {
return this.retainAllKt(elements)
} | 0 | Kotlin | 0 | 4 | 192aee01efccc76dcaf18d6d34ebac9726302a83 | 2,208 | boat | Apache License 2.0 |
src/commonMain/kotlin/data/gems/SeersChrysoprase.kt | marisa-ashkandi | 332,658,265 | false | null | package data.gems
import character.Buff
import character.Stats
import data.model.Color
import data.model.Gem
import data.model.Quality
import sim.SimParticipant
import kotlin.js.JsExport
@JsExport
class SeersChrysoprase : Gem(30586, "Seer's Chrysoprase", "inv_jewelcrafting_talasite_03.jpg", null, Color.GREEN, Quality.EPIC) {
override var phase: Int = 1
override var stats: Stats = Stats(
intellect = 4,
spirit = 5,
)
}
| 21 | Kotlin | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 451 | tbcsim | MIT License |
app/src/main/java/br/com/kituteprogramador/biblioteca/commons/mvp/BaseMvpPresenter.kt | brunoha-zz | 125,435,616 | false | null | package br.com.kituteprogramador.biblioteca.commons.mvp
/**
* Created by brunoalmeida on 14/03/18.
*/
interface BaseMvpPresenter<in V : BaseMvpView> {
fun attachView(view : V)
fun detachView()
} | 0 | Kotlin | 0 | 0 | 9eb451e8ff426e329bf70f3471917f308bb3d121 | 208 | libraryApp | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/linear/Zoom.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.crypto.linear
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.crypto.LinearGroup
public val LinearGroup.Zoom: ImageVector
get() {
if (_zoom != null) {
return _zoom!!
}
_zoom = Builder(name = "Zoom", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF17191C)),
strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(6.0f, 9.7001f)
verticalLineTo(12.5f)
curveTo(6.0f, 14.0f, 7.3f, 15.3f, 8.8f, 15.3f)
horizontalLineTo(12.5f)
curveTo(13.0f, 15.3f, 13.4f, 14.9f, 13.4f, 14.4f)
verticalLineTo(11.6f)
curveTo(13.4f, 10.1f, 12.2f, 8.8f, 10.6f, 8.8f)
horizontalLineTo(6.9f)
curveTo(6.4f, 8.8f, 6.0f, 9.2001f, 6.0f, 9.7001f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF17191C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(18.0f, 9.2f)
verticalLineTo(14.8f)
lineTo(15.2f, 12.9f)
verticalLineTo(11.1f)
lineTo(18.0f, 9.2f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF17191C)),
strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 22.0f)
curveTo(17.5228f, 22.0f, 22.0f, 17.5228f, 22.0f, 12.0f)
curveTo(22.0f, 6.4771f, 17.5228f, 2.0f, 12.0f, 2.0f)
curveTo(6.4771f, 2.0f, 2.0f, 6.4771f, 2.0f, 12.0f)
curveTo(2.0f, 17.5228f, 6.4771f, 22.0f, 12.0f, 22.0f)
close()
}
}
.build()
return _zoom!!
}
private var _zoom: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,103 | VuesaxIcons | MIT License |
src/main/kotlin/io/github/sgtsilvio/oci/registry/OciRegistryHandler.kt | SgtSilvio | 640,861,931 | false | {"Kotlin": 8872} | package io.github.sgtsilvio.oci.registry
import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.handler.codec.http.HttpHeaderValues
import io.netty.handler.codec.http.HttpMethod.*
import org.json.JSONObject
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono
import reactor.netty.http.server.HttpServerRequest
import reactor.netty.http.server.HttpServerResponse
import java.util.function.BiFunction
import kotlin.io.path.fileSize
import kotlin.io.path.readBytes
/*
https://github.com/opencontainers/distribution-spec/blob/main/spec.md
https://docs.docker.com/registry/spec/api/
end-1 GET /v2/ 200 ✔
end-2 GET /v2/<name>/blobs/<digest> 200/404 ✔
end-2 HEAD /v2/<name>/blobs/<digest> 200/404 ✔
end-10 DELETE /v2/<name>/blobs/<digest> 405 ✔
end-3 GET /v2/<name>/manifests/<reference> 200/404 ✔
end-3 HEAD /v2/<name>/manifests/<reference> 200/404 ✔
end-7 PUT /v2/<name>/manifests/<reference> 405 ✔
end-9 DELETE /v2/<name>/manifests/<reference> 405 ✔
end-4a POST /v2/<name>/blobs/uploads/ 405 ✔
end-4b POST /v2/<name>/blobs/uploads/?digest=<digest> 405 ✔
end-11 POST /v2/<name>/blobs/uploads/?mount=<digest>&from=<other_name> 405 ✔
end-13 GET /v2/<name>/blobs/uploads/<reference> 405 ✔
end-5 PATCH /v2/<name>/blobs/uploads/<reference> 405 ✔
DELETE /v2/<name>/blobs/uploads/<reference> 405 ✔
end-6 PUT /v2/<name>/blobs/uploads/<reference>?digest=<digest> 405 ✔
end-8a GET /v2/<name>/tags/list 405 ✔
end-8b GET /v2/<name>/tags/list?n=<integer>&last=<tag name> 405 ✔
end-12a GET /v2/<name>/referrers/<digest>
end-12b GET /v2/<name>/referrers/<digest>?artifactType=<artifactType>
GET /v2/_catalog 405 ✔
GET /v2/_catalog?n=<integer>&last=<repository name> 405 ✔
*/
/**
* @author <NAME>
*/
class OciRegistryHandler(private val storage: OciRegistryStorage) :
BiFunction<HttpServerRequest, HttpServerResponse, Publisher<Void>> {
override fun apply(request: HttpServerRequest, response: HttpServerResponse): Publisher<Void> {
val segments = request.fullPath().substring(1).split('/')
return when {
segments[0] == "v2" -> handleV2(request, segments.drop(1), response)
else -> response.sendNotFound()
}
}
private fun handleV2(
request: HttpServerRequest,
segments: List<String>,
response: HttpServerResponse,
): Publisher<Void> = when {
segments.isEmpty() || segments[0].isEmpty() -> when (request.method()) {
GET, HEAD -> response.header("Docker-Distribution-API-Version", "registry/2.0").send()
else -> response.status(405).send()
}
(segments.size == 1) && (segments[0] == "_catalog") -> when (request.method()) {
GET -> response.status(405).send()
else -> response.status(405).send()
}
segments.size < 3 -> response.sendNotFound()
else -> when (segments[segments.lastIndex - 1]) {
"tags" -> if (segments[segments.lastIndex] == "list") {
when (request.method()) {
GET -> response.status(405).send()
else -> response.status(405).send()
}
} else response.sendNotFound()
"manifests" -> when (request.method()) {
GET -> getOrHeadManifest(segments, true, response)
HEAD -> getOrHeadManifest(segments, false, response)
PUT, DELETE -> response.status(405).send()
else -> response.status(405).send()
}
"blobs" -> when (request.method()) {
GET -> getOrHeadBlob(segments, true, response)
HEAD -> getOrHeadBlob(segments, false, response)
DELETE -> response.status(405).send()
else -> response.status(405).send()
}
"uploads" -> when (request.method()) {
POST, GET, PATCH, PUT, DELETE -> response.status(405).send()
else -> response.status(405).send()
}
else -> response.sendNotFound()
}
}
private fun getOrHeadManifest(
segments: List<String>,
isGET: Boolean,
response: HttpServerResponse,
): Publisher<Void> {
val name = decodeName(segments, segments.lastIndex - 1)
val reference = segments[segments.lastIndex]
val manifestFile = if (':' in reference) {
storage.getManifest(name, reference.toOciDigest())
} else {
storage.getManifest(name, reference)
} ?: return response.sendNotFound()
val manifestBytes = manifestFile.readBytes()
response.header(HttpHeaderNames.CONTENT_TYPE, JSONObject(manifestBytes.decodeToString()).getString("mediaType"))
response.header(HttpHeaderNames.CONTENT_LENGTH, manifestBytes.size.toString())
return if (isGET) response.sendByteArray(Mono.just(manifestBytes)) else response.send()
}
private fun getOrHeadBlob(segments: List<String>, isGET: Boolean, response: HttpServerResponse): Publisher<Void> {
val name = decodeName(segments, segments.lastIndex - 1)
val digest = segments[segments.lastIndex].toOciDigest()
val blobFile = storage.getBlob(name, digest) ?: return response.sendNotFound()
response.header(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_OCTET_STREAM)
response.header(HttpHeaderNames.CONTENT_LENGTH, blobFile.fileSize().toString())
return if (isGET) response.sendFile(blobFile) else response.send()
}
private fun decodeName(segments: List<String>, toIndex: Int) = segments.subList(0, toIndex).joinToString("/")
}
| 0 | Kotlin | 0 | 2 | dd21091741eafa6a4b2f4dd9724e28b5ed9fd9fe | 6,308 | oci-registry | Apache License 2.0 |
src/main/kotlin/astminer/parse/antlr/AntlrParsingResult.kt | JetBrains-Research | 161,813,380 | false | {"Gradle Kotlin DSL": 2, "Shell": 2, "Dockerfile": 1, "INI": 3, "Kotlin": 157, "YAML": 6, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Markdown": 8, "Java": 22, "Python": 15, "JavaScript": 2, "C++": 9, "PHP": 2, "ANTLR": 7} | package astminer.parse.antlr
import astminer.common.model.*
import astminer.parse.antlr.java.JavaFunctionSplitter
import astminer.parse.antlr.java.JavaParser
import astminer.parse.antlr.javascript.JavaScriptFunctionSplitter
import astminer.parse.antlr.javascript.JavaScriptParser
import astminer.parse.antlr.php.PHPFunctionSplitter
import astminer.parse.antlr.php.PHPParser
import astminer.parse.antlr.python.PythonFunctionSplitter
import astminer.parse.antlr.python.PythonParser
import java.io.File
object AntlrJavaParsingResultFactory : ParsingResultFactory {
override fun parse(file: File, inputDirectoryPath: String?) =
AntlrJavaParsingResult(file, inputDirectoryPath)
class AntlrJavaParsingResult(file: File, inputDirectoryPath: String?) :
ParsingResult<AntlrNode>(file, inputDirectoryPath) {
override val root = JavaParser().parseFile(file)
override val splitter = JavaFunctionSplitter()
}
}
object AntlrPythonParsingResultFactory : ParsingResultFactory {
override fun parse(file: File, inputDirectoryPath: String?) =
AntlrPythonParsingResult(file, inputDirectoryPath)
class AntlrPythonParsingResult(file: File, inputDirectoryPath: String?) :
ParsingResult<AntlrNode>(file, inputDirectoryPath) {
override val root = PythonParser().parseFile(file)
override val splitter = PythonFunctionSplitter()
}
}
object AntlrJavascriptParsingResultFactory : ParsingResultFactory {
override fun parse(file: File, inputDirectoryPath: String?) =
AntlrJavascriptParsingResult(file, inputDirectoryPath)
class AntlrJavascriptParsingResult(file: File, inputDirectoryPath: String?) :
ParsingResult<AntlrNode>(file, inputDirectoryPath) {
override val root = JavaScriptParser().parseFile(file)
override val splitter = JavaScriptFunctionSplitter()
}
}
object AntlrPHPParsingResultFactory : ParsingResultFactory {
override fun parse(file: File, inputDirectoryPath: String?) =
AntlrPHPParsingResult(file, inputDirectoryPath)
class AntlrPHPParsingResult(file: File, inputDirectoryPath: String?) :
ParsingResult<AntlrNode>(file, inputDirectoryPath) {
override val root = PHPParser().parseFile(file)
override val splitter = PHPFunctionSplitter()
}
}
| 12 | Kotlin | 80 | 279 | 8e7872fa78983b3b9b4ff4b9f70d24cc4dfed280 | 2,312 | astminer | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsrestrictedpatientsapi/model/exceptions/NoResultsReturnedException.kt | ministryofjustice | 377,843,107 | false | null | package uk.gov.justice.digital.hmpps.hmppsrestrictedpatientsapi.model.exceptions
class NoResultsReturnedException(override val message: String) : RuntimeException(message)
| 0 | Kotlin | 0 | 1 | e3137e262ec2e8bd56131588479068b7733e5955 | 173 | hmpps-restricted-patients-api | MIT License |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/TranslateActivity.kt | arashilmg | 254,092,232 | true | {"Kotlin": 593482, "Java": 37879, "HTML": 16598, "CSS": 2184} | package ch.rmy.android.http_shortcuts.activities.settings
import android.content.Context
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.BaseActivity
import ch.rmy.android.http_shortcuts.extensions.attachTo
import ch.rmy.android.http_shortcuts.extensions.consume
import ch.rmy.android.http_shortcuts.extensions.mapIf
import ch.rmy.android.http_shortcuts.extensions.observeTextChanges
import ch.rmy.android.http_shortcuts.extensions.sendMail
import ch.rmy.android.http_shortcuts.utils.BaseIntentBuilder
import kotterknife.bindView
class TranslateActivity : BaseActivity() {
private val languageInput: EditText by bindView(R.id.input_language)
private val githubProfileInput: EditText by bindView(R.id.input_github_profile)
private var inputValid = false
set(value) {
if (field != value) {
field = value
invalidateOptionsMenu()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_translate)
languageInput.observeTextChanges()
.subscribe {
inputValid = languageInput.text.isNotEmpty()
}
.attachTo(destroyer)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.translate_activity_menu, menu)
menu.findItem(R.id.action_create_translate_mail).isVisible = inputValid
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_create_translate_mail -> consume {
createMailDraft()
finish()
}
else -> super.onOptionsItemSelected(item)
}
private fun createMailDraft() {
sendMail(
getString(R.string.developer_email_address),
getString(R.string.email_subject_translate),
getEmailText(),
getString(R.string.settings_help_translate)
)
}
private fun getEmailText(): String =
getString(R.string.email_text_translate, languageInput.text.toString())
.mapIf(githubProfileInput.text.isNotEmpty()) {
it.plus(
getString(R.string.email_text_translate_github_optional, githubProfileInput.text.toString())
)
}
class IntentBuilder(context: Context) : BaseIntentBuilder(context, TranslateActivity::class.java)
} | 0 | null | 0 | 0 | 1a9f08d5e1a2dc996b81237b3dc13f94d2ffcf08 | 2,640 | HTTP-Shortcuts | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.