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
gallery/src/main/java/io/pixel/gallery/adapter/SpaceItemDecoration.kt
mmobin789
249,466,100
false
null
package rx.kt.gallery.adapter import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView class SpaceItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { outRect.left = space outRect.right = space outRect.bottom = space // Add top margin only for the top items to avoid double space between items if (parent.getChildLayoutPosition(view) == 0 || parent.getChildLayoutPosition(view) == 1 || parent.getChildLayoutPosition(view) == 2) { outRect.top = space } else { outRect.top = 0 } } }
3
null
8
81
ac479625f153e022718cbf117635114253d9193b
777
pixel
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualScriptVariableSet.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE") package godot import godot.`annotation`.GodotBaseType import godot.core.TransferContext import godot.core.VariantType.NIL import godot.core.VariantType.STRING import kotlin.String import kotlin.Suppress import kotlin.Unit @GodotBaseType public open class VisualScriptVariableSet : VisualScriptNode() { public open var varName: String get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSCRIPTVARIABLESET_GET_VAR_NAME, STRING) return TransferContext.readReturnValue(STRING, false) as String } set(`value`) { TransferContext.writeArguments(STRING to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSCRIPTVARIABLESET_SET_VAR_NAME, NIL) } public override fun __new(): Unit { callConstructor(ENGINECLASS_VISUALSCRIPTVARIABLESET) } }
47
Kotlin
25
301
0d33ac361b354b26c31bb36c7f434e6455583738
1,165
godot-kotlin-jvm
MIT License
ktor-client/ktor-client-features/ktor-client-auth/common/src/io/ktor/client/features/auth/providers/BasicAuthProvider.kt
jakobkmar
323,173,348
false
null
package io.ktor.client.features.auth.providers import io.ktor.client.features.auth.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.util.* /** * Add [BasicAuthProvider] to client [Auth] providers. */ fun Auth.basic(block: BasicAuthConfig.() -> Unit) { with(BasicAuthConfig().apply(block)) { providers.add(BasicAuthProvider(username, password, realm)) } } /** * [BasicAuthProvider] configuration. */ class BasicAuthConfig { /** * Required: The username of the basic auth. */ lateinit var username: String /** * Required: The password of the basic auth. */ lateinit var password: String /** * Optional: current provider realm */ var realm: String? = null } /** * Client basic authentication provider. */ class BasicAuthProvider( private val username: String, private val password: String, private val realm: String? ) : AuthProvider { override fun isApplicable(auth: HttpAuthHeader): Boolean { if (auth.authScheme != AuthScheme.Basic) return false if (realm != null) { if (auth !is HttpAuthHeader.Parameterized) return false return auth.parameter("realm") == realm } return true } override suspend fun addRequestHeaders(request: HttpRequestBuilder) { request.headers[HttpHeaders.Authorization] = constructBasicAuthValue(username, password) } private fun constructBasicAuthValue(username: String, password: String): String { val authString = "$username:$password" val authBuf = encodeBase64(authString.toByteArray(Charsets.ISO_8859_1)) return "Basic $authBuf" } }
0
null
0
7
ea35658a05cc085b97297a303a7c0de37efe0024
1,722
ktor
Apache License 2.0
http4k-realtime-core/src/main/kotlin/org/http4k/lens/wsMessageLens.kt
http4k
86,003,479
false
null
package org.http4k.lens import org.http4k.asString import org.http4k.core.Body import org.http4k.websocket.WsMessage internal val meta = Meta(true, "websocket", ParamMeta.ObjectParam, "message") /** * Represents a extraction of an entity from a target WsMessage. */ open class WsMessageLensSpec<out OUT>(internal val get: LensGet<WsMessage, OUT>) { /** * Create a lens for this Spec */ open fun toLens(): WsMessageLens<OUT> = WsMessageLens { get("message")(it).firstOrNull() ?: throw LensFailure(Missing(meta)) } /** * Create another WsMessageLensSpec which applies the uni-directional transformation to the result. Any resultant Lens can only be used to extract the final type from a WsMessage. */ fun <NEXT> map(nextIn: (OUT) -> NEXT): WsMessageLensSpec<NEXT> = WsMessageLensSpec(get.map(nextIn)) } /** * Represents a bi-directional extraction of an entity from a target Body, or an insertion into a target WsMessage. */ open class BiDiWsMessageLensSpec<OUT>(get: LensGet<WsMessage, OUT>, private val set: LensSet<WsMessage, OUT>) : WsMessageLensSpec<OUT>(get) { /** * Create another BiDiWsMessageLensSpec which applies the bi-directional transformations to the result. Any resultant Lens can be * used to extract or insert the final type from/into a WsMessage. */ fun <NEXT> map(nextIn: (OUT) -> NEXT, nextOut: (NEXT) -> OUT) = BiDiWsMessageLensSpec(get.map(nextIn), set.map(nextOut)) /** * Create a lens for this Spec */ override fun toLens(): BiDiWsMessageLens<OUT> { val getLens = get("") val setLens = set("") return BiDiWsMessageLens( { getLens(it).let { if (it.isEmpty()) throw LensFailure(Missing(meta)) else it.first() } }, { out: OUT, target: WsMessage -> setLens(out?.let { listOf(it) } ?: emptyList(), target) } ) } } /** * A WsMessageLens provides the extraction of an entity from a target WsMessage. */ open class WsMessageLens<out FINAL>(private val getLens: (WsMessage) -> FINAL) : LensExtractor<WsMessage, FINAL> { override operator fun invoke(target: WsMessage): FINAL = try { getLens(target) } catch (e: LensFailure) { throw e } catch (e: Exception) { throw LensFailure(Invalid(meta), cause = e, target = target) } } /** * A BiDiWsMessageLens provides the bi-directional extraction of an entity from a target body, or the insertion of an entity * into a target WsMessage. */ class BiDiWsMessageLens<FINAL>(get: (WsMessage) -> FINAL, private val setLens: (FINAL, WsMessage) -> WsMessage) : WsMessageLens<FINAL>(get) { @Suppress("UNCHECKED_CAST") operator fun invoke(target: FINAL): WsMessage = setLens(target, WsMessage(Body.EMPTY)) fun create(value: FINAL): WsMessage = invoke(value) } private val wsRoot = BiDiWsMessageLensSpec<Body>( LensGet { _, target -> listOf(target.body) }, LensSet { _, values, target -> values.fold(target) { m, next -> m.body(next) } }) fun WsMessage.Companion.binary() = wsRoot.map(Body::payload) { Body(it) } fun WsMessage.Companion.string() = wsRoot.map({ it.payload.asString() }, { it: String -> Body(it) })
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
3,263
http4k
Apache License 2.0
type-system/src/commonMain/kotlin/io/github/charlietap/chasm/type/matching/PackedTypeMatcher.kt
CharlieTap
743,980,037
false
{"Kotlin": 2038087, "WebAssembly": 45714}
package io.github.charlietap.chasm.type.matching import io.github.charlietap.chasm.ast.type.PackedType @Suppress("UNUSED_PARAMETER") internal fun PackedTypeMatcher( type1: PackedType, type2: PackedType, context: TypeMatcherContext, ): Boolean = type1 == type2
5
Kotlin
3
67
dd6fa51262510ecc5ee5b03866b3fa5d1384433b
274
chasm
Apache License 2.0
app/src/main/java/io/github/wulkanowy/data/db/migrations/Migration38.kt
wulkanowy
87,721,285
false
{"Kotlin": 1617521, "HTML": 1949, "Shell": 220}
package io.github.wulkanowy.data.db.migrations import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase class Migration38 : Migration(37, 38) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL(""" CREATE TABLE IF NOT EXISTS `SchoolAnnouncements` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `student_id` INTEGER NOT NULL, `date` INTEGER NOT NULL, `subject` TEXT NOT NULL, `content` TEXT NOT NULL ) """) } }
89
Kotlin
27
228
b708c70ea25cdebc50cfa48163e8cd41c090146a
600
wulkanowy
Apache License 2.0
src/day19/Day19.kt
martin3398
572,166,179
false
null
package day19 import readInput import java.lang.Integer.max import java.lang.Integer.min import kotlin.math.ceil data class Price(val ore: Int, val clay: Int, val obsidian: Int) data class Blueprint(val orePrice: Price, val clayPrice: Price, val obsidianPrice: Price, val geodePrice: Price) { fun canBuyOreRobot(act: BfsEntry) = listOf( act.timeLeft > 0, orePrice.ore <= act.ore + act.oreRobots * act.timeLeft, act.oreRobots < listOf(orePrice.ore, clayPrice.ore, obsidianPrice.ore, geodePrice.ore).max(), act.oreRobots * act.timeLeft + act.ore < act.timeLeft * listOf(orePrice.ore, clayPrice.ore, obsidianPrice.ore, geodePrice.ore).max() ).all { it } fun canBuyClayRobot(act: BfsEntry) = listOf( act.timeLeft > 0, clayPrice.ore <= act.ore + act.oreRobots * act.timeLeft, act.clayRobots < obsidianPrice.clay, act.clayRobots * act.timeLeft + act.clay < act.timeLeft * obsidianPrice.clay ).all { it } fun canBuyObsidianRobot(act: BfsEntry) = listOf( act.timeLeft > 0, obsidianPrice.ore <= act.ore + act.oreRobots * act.timeLeft, obsidianPrice.clay <= act.clay + act.clayRobots * act.timeLeft, act.obsidianRobots < geodePrice.obsidian, act.obsidianRobots * act.timeLeft + act.obsidian < act.timeLeft * geodePrice.obsidian, ).all { it } fun canBuyGeodeRobot(act: BfsEntry) = listOf( act.timeLeft > 0, geodePrice.ore <= act.ore + act.oreRobots * act.timeLeft, geodePrice.obsidian <= act.obsidian + act.obsidianRobots * act.timeLeft ).all { it } fun buyOreRobot(act: BfsEntry): BfsEntry { val necessaryTime = max(ceil((orePrice.ore - act.ore).toDouble() / act.oreRobots).toInt() + 1, 1) return BfsEntry( act.timeLeft - necessaryTime, act.ore + necessaryTime * act.oreRobots - orePrice.ore, act.clay + necessaryTime * act.clayRobots, act.obsidian + necessaryTime * act.obsidianRobots, act.geode + necessaryTime * act.geodeRobots, act.oreRobots + 1, act.clayRobots, act.obsidianRobots, act.geodeRobots ) } fun buyClayRobot(act: BfsEntry): BfsEntry { val necessaryTime = max(ceil((clayPrice.ore - act.ore).toDouble() / act.oreRobots).toInt() + 1, 1) return BfsEntry( act.timeLeft - necessaryTime, act.ore + necessaryTime * act.oreRobots - clayPrice.ore, act.clay + necessaryTime * act.clayRobots, act.obsidian + necessaryTime * act.obsidianRobots, act.geode + necessaryTime * act.geodeRobots, act.oreRobots, act.clayRobots + 1, act.obsidianRobots, act.geodeRobots, ) } fun buyObsidianRobot(act: BfsEntry): BfsEntry { val necessaryTime = listOf( ceil((obsidianPrice.ore - act.ore).toDouble() / act.oreRobots).toInt() + 1, ceil((obsidianPrice.clay - act.clay).toDouble() / act.clayRobots).toInt() + 1, 1 ).max() return BfsEntry( act.timeLeft - necessaryTime, act.ore + necessaryTime * act.oreRobots - obsidianPrice.ore, act.clay + necessaryTime * act.clayRobots - obsidianPrice.clay, act.obsidian + necessaryTime * act.obsidianRobots, act.geode + necessaryTime * act.geodeRobots, act.oreRobots, act.clayRobots, act.obsidianRobots + 1, act.geodeRobots, ) } fun buyGeodeRobot(act: BfsEntry): BfsEntry { val necessaryTime = listOf( ceil((geodePrice.ore - act.ore).toDouble() / act.oreRobots).toInt() + 1, ceil((geodePrice.obsidian - act.obsidian).toDouble() / act.obsidianRobots).toInt() + 1, 1 ).max() return BfsEntry( act.timeLeft - necessaryTime, act.ore + necessaryTime * act.oreRobots - geodePrice.ore, act.clay + necessaryTime * act.clayRobots, act.obsidian + necessaryTime * act.obsidianRobots - geodePrice.obsidian, act.geode + necessaryTime * act.geodeRobots, act.oreRobots, act.clayRobots, act.obsidianRobots, act.geodeRobots + 1, ) } } data class BfsEntry( val timeLeft: Int = 24, val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0, val oreRobots: Int = 1, val clayRobots: Int = 0, val obsidianRobots: Int = 0, val geodeRobots: Int = 0, ) fun main() { fun getMaxMinedGeode(blueprint: Blueprint, maxTime: Int = 24): Int { val queue = mutableListOf(BfsEntry(maxTime)) var max = Int.MIN_VALUE while (queue.isNotEmpty()) { val act = queue.removeFirst() var build = false if (blueprint.canBuyGeodeRobot(act)) { queue.add(0, blueprint.buyGeodeRobot(act)) build = true } if (blueprint.canBuyOreRobot(act)) { queue.add(0, blueprint.buyOreRobot(act)) build = true } if (blueprint.canBuyClayRobot(act)) { queue.add(0, blueprint.buyClayRobot(act)) build = true } if (blueprint.canBuyObsidianRobot(act)) { queue.add(0, blueprint.buyObsidianRobot(act)) build = true } if (!build) { val geodeCount = act.geode + act.timeLeft * act.geodeRobots if (geodeCount > max) { max = geodeCount } } } return max } fun part1(input: List<Blueprint>): Int { return input.mapIndexed { index, blueprint -> (index + 1) * getMaxMinedGeode(blueprint) }.sum() } fun part2(input: List<Blueprint>): Int { return input.slice(0..min(2, input.size - 1)).map { getMaxMinedGeode(it, 32) }.reduce { acc, e -> acc * e } } fun preprocess(input: List<String>): List<Blueprint> = input.map { row -> val split = row.split(":")[1].split(".").map { it.split(" ") } Blueprint( Price(split[0][5].toInt(), 0, 0), Price(split[1][5].toInt(), 0, 0), Price(split[2][5].toInt(), split[2][8].toInt(), 0), Price(split[3][5].toInt(), 0, split[3][8].toInt()), ) } // test if implementation meets criteria from the description, like: val testInput = readInput(19, true) check(part1(preprocess(testInput)) == 33) val input = readInput(19) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 3472) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
6,824
advent-of-code-2022
Apache License 2.0
compose/constraint-layout/src/commonMain/kotlin/androidx/constraintlayout/core/widgets/ChainHead.kt
Woody230
388,189,330
false
{"Kotlin": 3122765}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.core.widgets import androidx.constraintlayout.core.widgets.ConstraintWidget.DimensionBehaviour /** * Class to represent a chain by its main elements. */ class ChainHead(var first: ConstraintWidget, private val mOrientation: Int, isRtl: Boolean) { var firstVisibleWidget: ConstraintWidget? = null protected set var last: ConstraintWidget? = null protected set var lastVisibleWidget: ConstraintWidget? = null protected set var head: ConstraintWidget? = null protected set var firstMatchConstraintWidget: ConstraintWidget? = null protected set var lastMatchConstraintWidget: ConstraintWidget? = null protected set var mWeightedMatchConstraintsWidgets: ArrayList<ConstraintWidget>? = null var mWidgetsCount = 0 var mWidgetsMatchCount = 0 var totalWeight = 0f protected set var mVisibleWidgets = 0 var mTotalSize = 0 var mTotalMargins = 0 var mOptimizable = false private var mIsRtl = false var mHasUndefinedWeights = false protected var mHasDefinedWeights = false var mHasComplexMatchWeights = false protected var mHasRatio = false private var mDefined = false private fun defineChainProperties() { val offset = mOrientation * 2 var lastVisited = first mOptimizable = true // TraverseChain var widget = first var next: ConstraintWidget? = first var done = false while (!done) { mWidgetsCount++ widget.mNextChainWidget[mOrientation] = null widget.mListNextMatchConstraintsWidget[mOrientation] = null if (widget.visibility != ConstraintWidget.GONE) { mVisibleWidgets++ if (widget.getDimensionBehaviour(mOrientation) != DimensionBehaviour.MATCH_CONSTRAINT) { mTotalSize += widget.getLength(mOrientation) } mTotalSize += widget.mListAnchors[offset]?.margin ?: 0 mTotalSize += widget.mListAnchors[offset + 1]?.margin ?: 0 mTotalMargins += widget.mListAnchors[offset]?.margin ?: 0 mTotalMargins += widget.mListAnchors[offset + 1]?.margin ?: 0 // Visible widgets linked list. if (firstVisibleWidget == null) { firstVisibleWidget = widget } lastVisibleWidget = widget // Match constraint linked list. if (widget.mListDimensionBehaviors[mOrientation] == DimensionBehaviour.MATCH_CONSTRAINT) { if (widget.mResolvedMatchConstraintDefault[mOrientation] == ConstraintWidget.MATCH_CONSTRAINT_SPREAD || widget.mResolvedMatchConstraintDefault[mOrientation] == ConstraintWidget.MATCH_CONSTRAINT_RATIO || widget.mResolvedMatchConstraintDefault[mOrientation] == ConstraintWidget.MATCH_CONSTRAINT_PERCENT) { mWidgetsMatchCount++ // Note: Might cause an issue if we support MATCH_CONSTRAINT_RATIO_RESOLVED in chain optimization. (we currently don't) val weight = widget.mWeight[mOrientation] if (weight > 0) { totalWeight += widget.mWeight[mOrientation] } if (isMatchConstraintEqualityCandidate(widget, mOrientation)) { if (weight < 0) { mHasUndefinedWeights = true } else { mHasDefinedWeights = true } if (mWeightedMatchConstraintsWidgets == null) { mWeightedMatchConstraintsWidgets = ArrayList() } mWeightedMatchConstraintsWidgets!!.add(widget) } if (firstMatchConstraintWidget == null) { firstMatchConstraintWidget = widget } if (lastMatchConstraintWidget != null) { lastMatchConstraintWidget!!.mListNextMatchConstraintsWidget[mOrientation] = widget } lastMatchConstraintWidget = widget } if (mOrientation == ConstraintWidget.HORIZONTAL) { if (widget.mMatchConstraintDefaultWidth != ConstraintWidget.MATCH_CONSTRAINT_SPREAD) { mOptimizable = false } else if (widget.mMatchConstraintMinWidth != 0 || widget.mMatchConstraintMaxWidth != 0) { mOptimizable = false } } else { if (widget.mMatchConstraintDefaultHeight != ConstraintWidget.MATCH_CONSTRAINT_SPREAD) { mOptimizable = false } else if (widget.mMatchConstraintMinHeight != 0 || widget.mMatchConstraintMaxHeight != 0) { mOptimizable = false } } if (widget.dimensionRatio != 0.0f) { //TODO: Improve (Could use ratio optimization). mOptimizable = false mHasRatio = true } } } if (lastVisited !== widget) { lastVisited.mNextChainWidget[mOrientation] = widget } lastVisited = widget // go to the next widget val nextAnchor = widget.mListAnchors[offset + 1]?.target if (nextAnchor != null) { next = nextAnchor.owner if (next.mListAnchors[offset]?.target == null || next.mListAnchors[offset]?.target?.owner !== widget ) { next = null } } else { next = null } if (next != null) { widget = next } else { done = true } } if (firstVisibleWidget != null) { mTotalSize -= firstVisibleWidget!!.mListAnchors[offset]?.margin ?: 0 } if (lastVisibleWidget != null) { mTotalSize -= lastVisibleWidget!!.mListAnchors[offset + 1]?.margin ?: 0 } last = widget if (mOrientation == ConstraintWidget.HORIZONTAL && mIsRtl) { head = last } else { head = first } mHasComplexMatchWeights = mHasDefinedWeights && mHasUndefinedWeights } fun define() { if (!mDefined) { defineChainProperties() } mDefined = true } companion object { /** * Returns true if the widget should be part of the match equality rules in the chain * * @param widget the widget to test * @param orientation current orientation, HORIZONTAL or VERTICAL * @return */ private fun isMatchConstraintEqualityCandidate(widget: ConstraintWidget, orientation: Int): Boolean { return widget.visibility != ConstraintWidget.GONE && widget.mListDimensionBehaviors[orientation] == DimensionBehaviour.MATCH_CONSTRAINT && (widget.mResolvedMatchConstraintDefault[orientation] == ConstraintWidget.MATCH_CONSTRAINT_SPREAD || widget.mResolvedMatchConstraintDefault[orientation] == ConstraintWidget.MATCH_CONSTRAINT_RATIO) } } /** * Initialize variables, then determine visible widgets, the head of chain and * matched constraint widgets. * * @param first first widget in a chain * @param orientation orientation of the chain (either Horizontal or Vertical) * @param isRtl Right-to-left layout flag to determine the actual head of the chain */ init { mIsRtl = isRtl } }
2
Kotlin
0
7
5ad55d66bbb58a12bf3a8b436ea1ea4d8e9737bc
8,657
KotlinExtensions
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Narwhal.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.Narwhal: ImageVector get() { if (_narwhal != null) { return _narwhal!! } _narwhal = Builder(name = "Narwhal", 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(16.0f, 16.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.385f, 10.091f) lineTo(24.0f, 0.53f) lineToRelative(-0.904f, -0.53f) lineToRelative(-4.895f, 8.31f) curveToRelative(-0.697f, -0.2f, -1.432f, -0.307f, -2.192f, -0.308f) lineToRelative(-1.507f, -0.002f) verticalLineToRelative(0.003f) lineToRelative(-0.002f, -0.003f) curveToRelative(-3.382f, 0.0f, -7.183f, 2.855f, -9.5f, 4.931f) verticalLineToRelative(3.993f) lineToRelative(0.102f, 0.094f) curveToRelative(1.549f, -1.674f, 6.255f, -6.018f, 9.398f, -6.018f) lineToRelative(1.506f, 0.002f) curveToRelative(2.754f, 0.002f, 4.994f, 2.245f, 4.994f, 4.999f) reflectiveCurveToRelative(-2.243f, 4.999f, -4.999f, 4.999f) lineTo(6.5f, 21.0f) curveToRelative(-1.93f, 0.0f, -3.5f, -1.57f, -3.5f, -3.5f) verticalLineToRelative(-3.973f) curveToRelative(0.0f, -1.684f, 0.494f, -3.313f, 1.428f, -4.715f) lineToRelative(2.281f, -3.421f) curveToRelative(2.456f, -0.556f, 4.292f, -2.769f, 4.292f, -5.391f) curveToRelative(-4.173f, 0.0f, -5.5f, 2.776f, -5.5f, 2.776f) curveToRelative(0.0f, 0.0f, -1.378f, -2.776f, -5.5f, -2.776f) curveToRelative(0.0f, 2.262f, 1.365f, 4.219f, 3.317f, 5.071f) lineToRelative(-1.385f, 2.077f) curveToRelative(-1.264f, 1.896f, -1.932f, 4.101f, -1.932f, 6.379f) verticalLineToRelative(3.973f) curveToRelative(0.0f, 3.584f, 2.916f, 6.5f, 6.5f, 6.5f) horizontalLineToRelative(9.501f) curveToRelative(4.411f, 0.0f, 7.999f, -3.588f, 7.999f, -7.999f) curveToRelative(0.0f, -2.338f, -1.009f, -4.446f, -2.615f, -5.91f) close() } } .build() return _narwhal!! } private var _narwhal: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,501
icons
MIT License
app/src/main/java/com/example/easymakeup/domain/model/Product.kt
milosursulovic
578,556,942
false
{"Kotlin": 41812}
package com.example.easymakeup.domain.model data class Product( val title: String, val price: Float, val discount: Int )
0
Kotlin
0
0
cca28d6bedd0b672a69c558293f7ea7b12f92da2
134
easy-makeup
MIT License
keel-ec2-plugin/src/main/kotlin/com/netflix/spinnaker/keel/ec2/jackson/mixins/SecurityGroupRuleMixin.kt
dmart
278,398,832
true
{"Kotlin": 1856517, "Java": 15301, "Shell": 1691}
package com.netflix.spinnaker.keel.ec2.jackson.mixins import com.fasterxml.jackson.annotation.JsonIgnore interface SecurityGroupRuleMixin { @get:JsonIgnore val isSelfReference: Boolean }
0
null
0
0
83e75f3fe9ab8f9dcd1c53d09f38b7a1b67360bf
193
keel
Apache License 2.0
bitcoincore/src/main/kotlin/io/horizontalsystems/bitcoincore/storage/CoreDatabase.kt
horizontalsystems
147,199,533
false
null
package io.horizontalsystems.bitcoincore.storage import androidx.sqlite.db.SupportSQLiteDatabase import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.room.migration.Migration import android.content.Context import io.horizontalsystems.bitcoincore.models.* import io.horizontalsystems.bitcoincore.storage.migrations.Migration_10_11 @Database(version = 11, exportSchema = false, entities = [ BlockchainState::class, PeerAddress::class, BlockHash::class, Block::class, SentTransaction::class, Transaction::class, TransactionInput::class, TransactionOutput::class, PublicKey::class, InvalidTransaction::class ]) @TypeConverters(ScriptTypeConverter::class) abstract class CoreDatabase : RoomDatabase() { abstract val blockchainState: BlockchainStateDao abstract val peerAddress: PeerAddressDao abstract val blockHash: BlockHashDao abstract val block: BlockDao abstract val sentTransaction: SentTransactionDao abstract val transaction: TransactionDao abstract val input: TransactionInputDao abstract val output: TransactionOutputDao abstract val publicKey: PublicKeyDao abstract val invalidTransaction: InvalidTransactionDao companion object { fun getInstance(context: Context, dbName: String): CoreDatabase { return Room.databaseBuilder(context, CoreDatabase::class.java, dbName) .allowMainThreadQueries() .addMigrations( Migration_10_11, add_rawTransaction_to_Transaction, add_conflictingTxHash_to_Transaction, add_table_InvalidTransaction, update_transaction_output, update_block_timestamp, add_hasTransaction_to_Block, add_connectionTime_to_PeerAddress ) .fallbackToDestructiveMigration() .build() } private val add_rawTransaction_to_Transaction = object : Migration(9, 10) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `Transaction` ADD COLUMN `rawTransaction` TEXT") database.execSQL("ALTER TABLE `InvalidTransaction` ADD COLUMN `rawTransaction` TEXT") } } private val add_conflictingTxHash_to_Transaction = object : Migration(8, 9) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `Transaction` ADD COLUMN `conflictingTxHash` BLOB") database.execSQL("ALTER TABLE `InvalidTransaction` ADD COLUMN `conflictingTxHash` BLOB") } } private val add_table_InvalidTransaction = object : Migration(7, 8) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS `InvalidTransaction` (`hash` BLOB NOT NULL, `blockHash` BLOB, `version` INTEGER NOT NULL, `lockTime` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `order` INTEGER NOT NULL, `isMine` INTEGER NOT NULL, `isOutgoing` INTEGER NOT NULL, `segwit` INTEGER NOT NULL, `status` INTEGER NOT NULL, `serializedTxInfo` TEXT NOT NULL, PRIMARY KEY(`hash`))") database.execSQL("ALTER TABLE SentTransaction ADD COLUMN sendSuccess INTEGER DEFAULT 0 NOT NULL") database.execSQL("ALTER TABLE `Transaction` ADD COLUMN serializedTxInfo TEXT DEFAULT '' NOT NULL") } } private val update_transaction_output = object : Migration(6, 7) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE TransactionOutput ADD COLUMN `pluginId` INTEGER") database.execSQL("ALTER TABLE TransactionOutput ADD COLUMN `pluginData` TEXT") } } private val update_block_timestamp = object : Migration(3, 4) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("UPDATE Block SET block_timestamp = 1559256184 WHERE height = 578592 AND block_timestamp = 1559277784") } } private val add_hasTransaction_to_Block = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE Block ADD COLUMN hasTransactions INTEGER DEFAULT 0 NOT NULL") database.execSQL("UPDATE Block SET hasTransactions = 1") } } private val add_connectionTime_to_PeerAddress = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE PeerAddress ADD COLUMN connectionTime INTEGER") } } } }
39
null
76
96
110018d54d82bb4e3c2a1d6b0ddd1bb9eeff9167
4,978
bitcoin-kit-android
MIT License
falkon-sql-builder-sqlite/src/test/kotlin/com/jayrave/falkon/sqlBuilders/sqlite/SqliteInsertSqlBuilderIntegrationTests.kt
jayrave
65,279,209
false
null
package com.jayrave.falkon.sqlBuilders.sqlite import com.jayrave.falkon.sqlBuilders.test.insert.TestInsert import org.junit.Test class SqliteInsertSqlBuilderIntegrationTests : BaseClassForIntegrationTests() { @Test fun `can insert both null & non null values`() { TestInsert(SqliteInsertSqlBuilder(), db).`can insert both null & non null values`() } }
6
Kotlin
2
12
ce42d553c578cd8e509bbfd7effc5d56bf3cdedd
374
falkon
Apache License 2.0
net/src/main/java/com/tans/tfiletransporter/ByteSizeUtils.kt
Tans5
329,625,887
false
null
package com.tans.tfiletransporter const val KB = 1024 const val MB = 1024 * 1024 const val GB = 1024 * 1024 * 1024 fun Long.toSizeString(): String { return when (this) { in 0 until KB -> String.format("%d B", this) in KB until MB -> String.format("%.2f KB", this.toDouble() / KB) in MB until GB -> String.format("%.2f MB", this.toDouble() / MB) in GB until Long.MAX_VALUE -> String.format("%.2f GB", this.toDouble() / GB) else -> "" } }
1
null
20
96
061bf75ba02b48693e61fbc15af670dc24a4c2cf
487
tFileTransporter
Apache License 2.0
core/src/commonTest/kotlin/ProgressTests.kt
aSoft-Ltd
801,498,293
false
{"Kotlin": 8608}
import kommander.expect import status.PercentProgress import status.Progress import status.StagedProgressTracker import kotlin.test.Test class ProgressTests { @Test fun should_show_accurate_progress() { val progress: Progress<Double> = PercentProgress(35) // Then expect(progress.percentage.done).toBe(35.0) } @Test fun should_show_accurate_progress_percentage_on_a_staged_progress() { val tracker = StagedProgressTracker<Double>() val progress = mutableListOf<Double>() val listener = tracker.onProgress { progress.add(it.overall.percentage.done) } val (reading, uploading) = tracker.stages("Reading", "Uploading") val total = 10_000 for (i in 1..total) { reading(Progress(i, total)) } for (i in 1..total) { uploading(Progress(i, total)) } tracker.removeProgressListener(listener) expect(progress.size).toBe(2 * total) expect(progress.any { it <= 100 }).toBe(true) } }
0
Kotlin
0
1
8275b7ccd63eaff43d6a2d4f3bb2afe02afcbd56
1,042
status
MIT License
src/main/kotlin/structures/DataStructuresForTesting.kt
borismilner
205,596,925
false
null
package structures import java.util.* data class EdgeDetails(var properties: String? = null, var connectionMethod: String? = null, var relationshipType: String? = null, var nodes: ArrayList<ArrayList<String>>? = null, var source: String? = null, var target: String? = null) data class NodeDetails( var mainLabel: String? = null, var howMany: Int = 0, var properties: Map<String, String>? = null, var additionalLabels: MutableList<String>? = null ) data class NodePropertiesDetails( var node: String? = null, var properties: HashMap<String, String>? = null ) data class GraphYamlTemplate( var name: String? = null, var comments: String? = null, var nodes: List<NodeDetails>? = null, var relationships: List<EdgeDetails>? = null, var customProperties: List<NodePropertiesDetails>? = null )
1
Kotlin
0
4
2486c37c7c9d236cb252055c1b408a62bfe998aa
997
neogoodies
The Unlicense
backend/server/src/main/kotlin/com/varabyte/kobweb/server/io/ApiJarFile.kt
varabyte
389,223,226
false
null
package com.varabyte.kobweb.server.io import com.varabyte.kobweb.api.Apis import com.varabyte.kobweb.api.ApisFactory import com.varabyte.kobweb.api.log.Logger import com.varabyte.kobweb.project.io.LiveFile import java.io.ByteArrayInputStream import java.io.File import java.io.IOException import java.io.InputStream import java.net.URL import java.net.URLConnection import java.net.URLStreamHandler import java.nio.file.Path import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipFile /** * Wrapper around a Kobweb API jar, which is expected (in dev mode at least) to occasionally be reloaded on the fly. * * @param path The path to the api.jar itself */ class ApiJarFile(path: Path, private val logger: Logger) { private class DynamicClassLoader(private val content: ByteArray) : ClassLoader(ApiJarFile::class.java.classLoader) { private val zipFile: ZipFile = run { val file = File.createTempFile("KobwebApiJar", ".jar").also { it.deleteOnExit() } ByteArrayInputStream(content).use { stream -> file.writeBytes(stream.readBytes()) } ZipFile(file) } override fun findClass(name: String): Class<*> { return findClassInZip(name) ?.use { stream -> stream.readBytes() } ?.let { bytes -> defineClass(name, bytes, 0, bytes.size) } ?: super.findClass(name) } // Code inspired by org.jetbrains.kotlin.codegen.GeneratedClassLoader and .BytesUrlUtils private fun InputStream.toInMemoryUrl(): URL { return this .use { readBytes() } .let { bytes -> URL( null, "bytes:${Base64.getEncoder().encodeToString(bytes)}", object : URLStreamHandler() { override fun openConnection(url: URL): URLConnection { return object : URLConnection(url) { override fun connect() {} override fun getInputStream(): InputStream { return ByteArrayInputStream(Base64.getDecoder().decode(url.path)) } } } } ) } } override fun findResource(name: String): URL { return findFileInZip(name) ?.toInMemoryUrl() ?: super.findResource(name) } override fun findResources(name: String): Enumeration<URL> { val ourResource = findFileInZip(name) ?.toInMemoryUrl() ?.let { listOf(it) } ?: emptyList() return Collections.enumeration(ourResource + super.findResources(name).toList()) } // Convert a class name (e.g. "com.example.Demo") to its path form ("com/example/Demo.class") private fun findClassInZip(name: String) = findFileInZip("${name.replace('.', '/')}.class") private fun findFileInZip(name: String): InputStream? { // Convert a class name (e.g. "com.example.Demo") to its path form ("com/example/Demo.class") val entry: ZipEntry? = zipFile.getEntry(name) return entry ?.let { try { zipFile.getInputStream(entry) } catch (e: IOException) { null } } } } private class Cache(val content: ByteArray, logger: Logger) { val apis: Apis = run { val classLoader = DynamicClassLoader(content) val factory = classLoader.loadClass("ApisFactoryImpl").getDeclaredConstructor().newInstance() as ApisFactory factory.create(logger) } } private val delegateFile = LiveFile(path) private var cache: Cache? = null val apis: Apis get() { val currContent = delegateFile.content ?: error { "No API jar found at: ${delegateFile.path}" } var cache = cache // Reassign temporarily so Kotlin knows it won't change underneath us if (cache == null || cache.content !== delegateFile.content) { cache = Cache(currContent, logger) this.cache = cache } return cache.apis } }
85
Kotlin
21
570
54bb2756f40fc119179aaa0f0ad2b358d78affff
4,497
kobweb
Apache License 2.0
android/src/main/java/com/example/flutterpluginwangfei/view/filepicker/views/SquareRelativeLayout.kt
luhenchang
247,438,779
false
null
package droidninja.filepicker.views import android.annotation.TargetApi import android.content.Context import android.os.Build import android.util.AttributeSet import android.widget.RelativeLayout /** A RelativeLayout that will always be square -- same width and height, * where the height is based off the width. */ class SquareRelativeLayout : RelativeLayout { constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {} @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // Set getBitmap square layout. super.onMeasure(widthMeasureSpec, widthMeasureSpec) } }
6
null
4
8
ec7fda17d3422e2cb7132b45a8b4c2c2fbfc6448
1,003
flutter_picker_plugin
MIT License
src/main/kotlin/g0401_0500/s0436_find_right_interval/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
package g0401_0500.s0436_find_right_interval // #Medium #Array #Sorting #Binary_Search #Binary_Search_II_Day_11 // #2022_12_22_Time_333_ms_(100.00%)_Space_49.7_MB_(90.00%) import java.util.function.Function class Solution { private fun findminmax(num: Array<IntArray>): IntArray { var min = num[0][0] var max = num[0][0] for (i in 1 until num.size) { min = Math.min(min, num[i][0]) max = Math.max(max, num[i][0]) } return intArrayOf(min, max) } fun findRightInterval(intervals: Array<IntArray>): IntArray { if (intervals.size <= 1) { return intArrayOf(-1) } val n = intervals.size val result = IntArray(n) val map: MutableMap<Int, Int?> = HashMap() for (i in 0 until n) { map[intervals[i][0]] = i } val minmax = findminmax(intervals) for (i in minmax[1] - 1 downTo minmax[0] + 1) { map.computeIfAbsent(i, Function { k: Int -> map[k + 1] }) } for (i in 0 until n) { result[i] = map.getOrDefault(intervals[i][1], -1)!! } return result } }
0
Kotlin
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
1,173
LeetCode-in-Kotlin
MIT License
kotlin-mui/src/main/generated/mui/material/ListItemButton.kt
Pandinosaurus
126,706,152
true
{"Kotlin": 1387147, "JavaScript": 528}
// Automatically generated - do not modify! @file:JsModule("@mui/material/ListItemButton") @file:JsNonModule package mui.material external interface ListItemButtonProps : react.Props /** * * Demos: * * - [Lists](https://mui.com/components/lists/) * * API: * * - [ListItemButton API](https://mui.com/api/list-item-button/) * - inherits [ButtonBase API](https://mui.com/api/button-base/) */ @JsName("default") external val ListItemButton: react.FC<ListItemButtonProps>
1
Kotlin
0
0
9baf2b5b00ccf944e847cbea3ab452faf746013c
481
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/alvayonara/outsched/core/ui/SelectScheduleAdapter.kt
alvayonara
274,112,368
false
null
package com.alvayonara.outsched.core.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import com.alvayonara.outsched.R import com.alvayonara.outsched.core.domain.model.item.DateItem import com.alvayonara.outsched.core.domain.model.item.ScheduleItem import com.alvayonara.outsched.core.domain.model.item.ScheduleListItem import com.alvayonara.outsched.core.domain.model.item.ScheduleListItem.Companion.TYPE_DATE import com.alvayonara.outsched.core.domain.model.item.ScheduleListItem.Companion.TYPE_GENERAL import com.alvayonara.outsched.core.utils.ConvertUtils.convertTemperatureRound import com.alvayonara.outsched.ui.schedule.ScheduleDetailDialogFragment.Companion.EXTRA_SCHEDULE_DETAIL import com.alvayonara.outsched.core.utils.ConvertUtils.dateTimeConvert import com.alvayonara.outsched.core.utils.DateFormat import com.alvayonara.outsched.databinding.ItemDateSectionBinding import com.alvayonara.outsched.databinding.ItemRowSelectScheduleBinding import com.alvayonara.outsched.ui.schedule.ScheduleDetailDialogFragment class SelectScheduleAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var listItem: MutableList<ScheduleListItem> = mutableListOf() fun setSchedules(schedules: List<ScheduleListItem>?) { if (schedules == null) return listItem.clear() listItem.addAll(schedules) notifyDataSetChanged() } override fun getItemViewType(position: Int): Int = listItem[position].getType() override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): RecyclerView.ViewHolder { return when (viewType) { TYPE_GENERAL -> { ScheduleViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_row_select_schedule, parent, false) ) } TYPE_DATE -> { DateViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_date_section, parent, false) ) } else -> throw IllegalArgumentException("Invalid view type") } } override fun getItemCount(): Int = listItem.size override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { when (viewHolder.itemViewType) { TYPE_GENERAL -> { val holder: ScheduleViewHolder = viewHolder as ScheduleViewHolder holder.bindItem(listItem[position] as ScheduleItem) } TYPE_DATE -> { val holder: DateViewHolder = viewHolder as DateViewHolder holder.bindItem(listItem[position] as DateItem) } } } class ScheduleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = ItemRowSelectScheduleBinding.bind(itemView) fun bindItem(schedule: ScheduleItem) { with(itemView) { schedule.schedule?.let { with(binding) { when { it.icon.startsWith("clear") -> ivWeather.setImageResource(R.drawable.ic_clear) it.icon.startsWith("cloudy") -> ivWeather.setImageResource(R.drawable.ic_clouds) it.icon.startsWith("partly-cloudy") -> ivWeather.setImageResource(R.drawable.ic_partly_cloudy) it.icon.contains("rain") -> ivWeather.setImageResource(R.drawable.ic_rain) } tvWeather.text = it.summary tvHour.text = it.time.dateTimeConvert(DateFormat.FORMAT_ONLY_TIME) tvTemperature.text = context.getString( R.string.temperature, it.temperature.convertTemperatureRound() ) itemView.setOnClickListener { val scheduleDetailDialogFragment = ScheduleDetailDialogFragment() val mBundle = Bundle() mBundle.putParcelable(EXTRA_SCHEDULE_DETAIL, schedule.schedule) scheduleDetailDialogFragment.arguments = mBundle scheduleDetailDialogFragment.show( (context as AppCompatActivity).supportFragmentManager, ScheduleDetailDialogFragment::class.java.simpleName ) } } } } } } class DateViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = ItemDateSectionBinding.bind(itemView) fun bindItem(date: DateItem) { with(itemView) { binding.tvSectionDate.text = date.dateList } } } }
0
Kotlin
0
0
5f662b26cf7d48dc1bc3ce7f4a89b3e53e25080d
5,128
OutSched
Apache License 2.0
project/common/src/main/kotlin/ink/ptms/artifex/script/ScriptFileCompiled.kt
TabooLib
492,563,163
false
null
package ink.ptms.artifex.script import java.io.File /** * Artifex * ink.ptms.artifex.script.ScriptFileCompiled * * 编译成功的脚本文件 * * @author 坏黑 * @since 2022/5/16 14:25 */ interface ScriptFileCompiled : ScriptCompiled { /** * 脚本源文件 */ fun sourceFile(): File /** * 脚本签名 */ fun digest(): Array<String> /** * 脚本参数数量 */ fun propsSize(): Int /** * 脚本参数描述 */ fun propsDescription(): String /** * 序列化类文件 */ fun toByteArray(): ByteArray }
1
null
7
24
eeb2e09552ad1d7bc67f82d56191be8693b329af
531
artifex
Creative Commons Zero v1.0 Universal
core/src/commonMain/kotlin/work/socialhub/kslack/entity/block/composition/PlainTextObject.kt
uakihir0
794,979,552
false
{"Kotlin": 945304, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package work.socialhub.kslack.entity.block.composition /** * https://api.slack.com/reference/messaging/composition-objects#text */ class PlainTextObject : TextObject() { companion object { const val TYPE: String = "plain_text" } val type: String = TYPE var text: String? = null /** * The documentation of the Slack API states that the verbatim field is optional. * The API examples always render the emoji field (as true, but that is its default value) -- so that is not helpful. * I picked the Boolean because basically you have 3 possible states: * - true * - false * - not present (and therefore not rendered in the resulting JSON sent to the Slack API) */ var emoji: Boolean? = null }
5
Kotlin
0
0
4d7fe4d7658ebe5e7daac29f727db96a09deaead
762
kslack
MIT License
Splitify/Splitify/src/main/kotlin/project/Splitify/http/userController/userDTOS/UserCreation.kt
RodrigoNevesWork
604,869,686
false
null
package project.splitify.domain import javax.validation.constraints.Email data class UserCreation( val name : String, @field:Email(message = "Email must be a valid email address.") val email : String, val phone : String, val password : String )
2
Kotlin
0
1
217e80d682c56b8a0212d996505fd8b1bcda337c
269
Splitify
MIT License
app/src/main/java/com/example/androiddevchallenge/data/TeaProvider.kt
himattm
344,254,889
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.data import androidx.compose.ui.graphics.Color import com.example.androiddevchallenge.ui.theme.greenTea import com.example.androiddevchallenge.ui.theme.herbal import com.example.androiddevchallenge.ui.theme.offWhite import com.example.androiddevchallenge.ui.theme.oolong import kotlin.time.ExperimentalTime import kotlin.time.minutes @ExperimentalTime object TeaProvider { val teas = listOf<Tea>( Tea( type = "Black", color = Color.Black, brewTime = 3.minutes..5.minutes, brewTemp = 200..212, ), Tea( type = "Green", color = greenTea, brewTime = 1.minutes..3.minutes, brewTemp = 160..180, ), Tea( type = "White", color = offWhite, brewTime = 2.minutes..5.minutes, brewTemp = 160..190 ), Tea( type = "Oolong", color = oolong, brewTime = 2.minutes..6.minutes, brewTemp = 185..205, ), Tea( type = "Herbal", color = herbal, brewTime = 5.minutes..7.minutes, brewTemp = 200..212 ), ) }
0
Kotlin
0
0
990872b7dda6eefeeafdae3281d125b5312fedf4
1,866
compose-tea-time
Apache License 2.0
cli/src/main/kotlin/uk/gov/justice/digital/cli/client/BlockingDomainClient.kt
ministryofjustice
620,391,775
false
null
package uk.gov.justice.digital.cli.client import io.micronaut.context.annotation.Factory import io.micronaut.context.annotation.Value import io.micronaut.http.HttpHeaders.* import io.micronaut.http.HttpStatus import io.micronaut.http.HttpStatus.* import io.micronaut.http.MediaType.APPLICATION_JSON import io.micronaut.http.hateoas.JsonError import io.micronaut.http.uri.UriBuilder import io.micronaut.serde.ObjectMapper import jakarta.inject.Inject import jakarta.inject.Singleton import uk.gov.justice.digital.headers.Header import uk.gov.justice.digital.headers.SessionIdHeader import uk.gov.justice.digital.headers.TraceIdHeader import uk.gov.justice.digital.model.Domain import uk.gov.justice.digital.model.Status import uk.gov.justice.digital.model.WriteableDomain import java.net.URI import java.net.http.HttpClient import java.net.http.HttpClient.Redirect import java.net.http.HttpClient.Version import java.net.http.HttpRequest import java.net.http.HttpResponse import java.time.Duration import java.util.* // TODO - trace and session ID header filter interface DomainClient { fun getDomains(): Array<Domain> fun getDomains(name: String, status: Status? = null): Array<Domain> fun createDomain(domain: WriteableDomain): String } /** * Blocking client, suitable for CLI use. */ @Singleton class BlockingDomainClient : DomainClient { @Inject private lateinit var objectMapper: ObjectMapper @Inject private lateinit var client: HttpClient @Value("\${http.client.url}") private lateinit var baseUrl: String private val domainResource by lazy { UriBuilder.of("$baseUrl/domain").build() } override fun getDomains(): Array<Domain> = client.get<Array<Domain>>(domainResource) override fun getDomains(name: String, status: Status?): Array<Domain> { val requestUri = UriBuilder.of(domainResource) .queryParam("name", name) .withOptionalParameter("status", status?.name) .build() return client.get<Array<Domain>>(requestUri) } // Only add the query parameter if the value is not null. private fun UriBuilder.withOptionalParameter(name: String, value: String?): UriBuilder { return value?.let { this.queryParam(name, it) } ?: this } private fun configuredRequestBuilder(uri: URI) = HttpRequest.newBuilder(uri) .header(ACCEPT, APPLICATION_JSON) .header(USER_AGENT, "domain-builder-cli/v0.0.1") .withCustomHeader(TraceIdHeader()) .withCustomHeader(SessionIdHeader.instance) .timeout(REQUEST_TIMEOUT) private fun HttpRequest.Builder.withCustomHeader(header: Header) = this.header(header.name, header.value) private inline fun <reified T> HttpClient.get(uri: URI): T { val request = configuredRequestBuilder(uri) .GET() .build() val response = this.send(request, HttpResponse.BodyHandlers.ofInputStream()) if (response.statusCode() in 200..299) return objectMapper.readValue(response.body(), T::class.java) ?: throw UnexpectedResponseException("No data in response") else throw UnexpectedResponseException("Server returned an unexpected response: HTTP ${response.statusCode()}") } override fun createDomain(domain: WriteableDomain): String { val request = configuredRequestBuilder(domainResource) .header(CONTENT_TYPE, APPLICATION_JSON) .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(domain))) .build() val response = client.send(request, HttpResponse.BodyHandlers.ofString()) return when(HttpStatus.valueOf(response.statusCode())) { CREATED -> response.headers() .firstValue(LOCATION) .orElseThrow { IllegalStateException("No $LOCATION header on response") } CONFLICT -> throw ConflictException("Domain with name: ${domain.name} and status: ${domain.status} already exists") BAD_REQUEST -> throw BadRequestException(createErrorMessageForBadRequest(response)) else -> throw UnexpectedResponseException("Got unexpected response from server: $response") } } private fun <T> createErrorMessageForBadRequest(response: HttpResponse<T>) = response.headers() .firstValue(CONTENT_TYPE) .filter { it.equals(APPLICATION_JSON) } .flatMap { _ -> try { val jsonError = objectMapper.readValue(response.body().toString(), JsonError::class.java) Optional.ofNullable<String>(jsonError?.message) } catch (ex: Exception) { Optional.empty() } } .map { "The server could not process your request because:\n$it" } .orElse("The server could not process your request") companion object { private val REQUEST_TIMEOUT = Duration.ofSeconds(30) private val CONNECT_TIMEOUT = Duration.ofSeconds(15) } @Factory private class HttpClientFactory { @Singleton fun configuredClient(): HttpClient = HttpClient.newBuilder() .version(Version.HTTP_1_1) .followRedirects(Redirect.NORMAL) .connectTimeout(CONNECT_TIMEOUT) .build() } } sealed class ClientException(message: String) : RuntimeException(message) class BadRequestException(message: String) : ClientException(message) class ConflictException(message: String) : ClientException(message) class UnexpectedResponseException(message: String) : ClientException(message)
1
null
1
2
11f4737c5b5f16fc80b52c9690874679dd6567ef
5,689
digital-prison-reporting-domain-builder
MIT License
mailserver/pop3-agent/src/commonMain/kotlin/Pop3CommandPipeline.kt
lost-illusi0n
563,231,184
false
{"Kotlin": 245200, "Astro": 3842, "Dockerfile": 404, "JavaScript": 109}
package dev.sitar.kmail.agents.pop3 import dev.sitar.keystone.Pipeline import dev.sitar.keystone.Stage import dev.sitar.kmail.pop3.commands.Pop3Command data class Pop3CommandContext(val command: Pop3Command, var wasProcessed: Boolean) class Pop3CommandPipeline: Pipeline<Pop3CommandContext>(setOf(Logging, Before, Processing, After)) { companion object { val Logging = Stage("Logging") val Before = Stage("Before") val Processing = Stage("Processing") val After = Stage("After") } operator fun invoke(block: Pop3CommandPipeline.() -> Unit) { block(this) } }
0
Kotlin
1
6
0e823e71d5bb55334602d669f4a6c8f8718e5347
617
kmail
MIT License
mailserver/pop3-agent/src/commonMain/kotlin/Pop3CommandPipeline.kt
lost-illusi0n
563,231,184
false
{"Kotlin": 245200, "Astro": 3842, "Dockerfile": 404, "JavaScript": 109}
package dev.sitar.kmail.agents.pop3 import dev.sitar.keystone.Pipeline import dev.sitar.keystone.Stage import dev.sitar.kmail.pop3.commands.Pop3Command data class Pop3CommandContext(val command: Pop3Command, var wasProcessed: Boolean) class Pop3CommandPipeline: Pipeline<Pop3CommandContext>(setOf(Logging, Before, Processing, After)) { companion object { val Logging = Stage("Logging") val Before = Stage("Before") val Processing = Stage("Processing") val After = Stage("After") } operator fun invoke(block: Pop3CommandPipeline.() -> Unit) { block(this) } }
0
Kotlin
1
6
0e823e71d5bb55334602d669f4a6c8f8718e5347
617
kmail
MIT License
VVFBLA-MATCHMAKER-KOTLIN/src/program.kts
FBLA-MATCHMAKER
146,522,523
false
null
import java.io.BufferedReader import java.io.File import java.io.FileReader import java.util.Scanner object Program { @JvmStatic fun main(args:Array<String>) { // CALL INGESTDATA CLASS ingestData.main() } } internal object ingestData { private val sc:Scanner fun main() { val f = File("FBLA.txt") try { sc = Scanner(f) // Determine the length of FBLA.txt val reader = BufferedReader(FileReader("FBLA.txt")) val lines = 0 while (reader.readLine() != null) lines++ reader.close() // Create 2-D Array val arrayOfArrays = Array<Array<String>>(lines, {arrayOfNulls<String>(3)}) val s = 0 while (sc.hasNextLine()) { // Declare val lineParse = sc.nextLine() // Split the values val parts = lineParse.split(("\t").toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray() val conName = (parts[0]) val gender = (parts[1]) val grade = (parts[2]) val answer = (parts[3]) val genGrade = gender + grade val ConString = arrayOf<String>(conName, genGrade, answer) // Put ConString into its respective files arrayOfArrays[s][0] = ConString[0] arrayOfArrays[s][1] = ConString[1] arrayOfArrays[s][2] = ConString[2] // Print Test s = s + 1 } val cF7 = 0 val cF8 = 0 val cF9 = 0 val cM7 = 0 val cM8 = 0 val cM9 = 0 for (n in 0 until lines) { if (arrayOfArrays[n][1] == "F7" == true) { cF7 = cF7 + 1 } else if (arrayOfArrays[n][1] == "F8" == true) { cF8 = cF8 + 1 } else if (arrayOfArrays[n][1] == "F9" == true) { cF9 = cF9 + 1 } else if (arrayOfArrays[n][1] == "M7" == true) { cM7 = cM7 + 1 } else if (arrayOfArrays[n][1] == "M8" == true) { cM8 = cM8 + 1 } else if (arrayOfArrays[n][1] == "M9" == true) { cM9 = cM9 + 1 } } // MASTER F7 to M7 MATCHER\\ println("BEGIN NEXT GROUP") println("") println("") val master = arrayOfNulls<String>(30) for (F7 in 0 until lines) { if (arrayOfArrays[F7][1] == "F7" == true) { val mName = arrayOfArrays[F7][0] for (e in 0..29) { master[e] = arrayOfArrays[F7][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { sName = arrayOfArrays[M7][0] for (k in 0..29) { second[k] = arrayOfArrays[M7][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER F8 to M8 MATCHER\\ for (F8 in 0 until lines) { if (arrayOfArrays[F8][1] == "F8" == true) { val mName = arrayOfArrays[F8][0] for (e in 0..29) { master[e] = arrayOfArrays[F8][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (M8 in 0 until lines) { if (arrayOfArrays[M8][1] == "M8" == true) { sName = arrayOfArrays[M8][0] for (k in 0..29) { second[k] = arrayOfArrays[M8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER F9 to M9 MATCHER\\ for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { val mName = arrayOfArrays[F9][0] for (e in 0..29) { master[e] = arrayOfArrays[F9][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (M9 in 0 until lines) { if (arrayOfArrays[M9][1] == "M9" == true) { sName = arrayOfArrays[M9][0] for (k in 0..29) { second[k] = arrayOfArrays[M9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER M7 to F7 MATCHER\\ for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { val mName = arrayOfArrays[M7][0] for (e in 0..29) { master[e] = arrayOfArrays[M7][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F7 in 0 until lines) { if (arrayOfArrays[F7][1] == "F7" == true) { sName = arrayOfArrays[F7][0] for (k in 0..29) { second[k] = arrayOfArrays[F7][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER M8 to F8 MATCHER\\ for (M8 in 0 until lines) { if (arrayOfArrays[M8][1] == "M8" == true) { val mName = arrayOfArrays[M8][0] for (e in 0..29) { master[e] = arrayOfArrays[M8][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { sName = arrayOfArrays[M7][0] for (k in 0..29) { second[k] = arrayOfArrays[M7][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER M9 to F9 MATCHER\\ for (M9 in 0 until lines) { if (arrayOfArrays[M9][1] == "M9" == true) { val mName = arrayOfArrays[M9][0] for (e in 0..29) { master[e] = arrayOfArrays[M9][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER F8 to M7, M8, M9 MATCHER\\ for (F8 in 0 until lines) { if (arrayOfArrays[F8][1] == "F8" == true) { val mName = arrayOfArrays[F8][0] for (e in 0..29) { master[e] = arrayOfArrays[F8][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (M8 in 0 until lines) { if (arrayOfArrays[M8][1] == "M8" == true) { sName = arrayOfArrays[M8][0] for (k in 0..29) { second[k] = arrayOfArrays[M8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { sName = arrayOfArrays[M7][0] for (k in 0..29) { second[k] = arrayOfArrays[M7][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER F9 to M7, M8, M9 MATCHER\\ for (F7 in 0 until lines) { if (arrayOfArrays[F7][1] == "F7" == true) { val mName = arrayOfArrays[F7][0] for (e in 0..29) { master[e] = arrayOfArrays[F7][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (M8 in 0 until lines) { if (arrayOfArrays[M8][1] == "M8" == true) { sName = arrayOfArrays[M8][0] for (k in 0..29) { second[k] = arrayOfArrays[M8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { sName = arrayOfArrays[M7][0] for (k in 0..29) { second[k] = arrayOfArrays[M7][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER F7 to M7, M8, M9 MATCHER\\ for (F7 in 0 until lines) { if (arrayOfArrays[F7][1] == "F7" == true) { val mName = arrayOfArrays[F7][0] for (e in 0..29) { master[e] = arrayOfArrays[F7][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (M8 in 0 until lines) { if (arrayOfArrays[M8][1] == "M8" == true) { sName = arrayOfArrays[M8][0] for (k in 0..29) { second[k] = arrayOfArrays[M8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { sName = arrayOfArrays[M7][0] for (k in 0..29) { second[k] = arrayOfArrays[M7][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER M7 to F7, F8, F9 MATCHER\\ for (M7 in 0 until lines) { if (arrayOfArrays[M7][1] == "M7" == true) { val mName = arrayOfArrays[M7][0] for (e in 0..29) { master[e] = arrayOfArrays[M7][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (F8 in 0 until lines) { if (arrayOfArrays[F8][1] == "F8" == true) { sName = arrayOfArrays[F8][0] for (k in 0..29) { second[k] = arrayOfArrays[F8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER M8 to F7, F8, F9 MATCHER\\ for (M8 in 0 until lines) { if (arrayOfArrays[M8][1] == "M8" == true) { val mName = arrayOfArrays[M8][0] for (e in 0..29) { master[e] = arrayOfArrays[M8][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (F8 in 0 until lines) { if (arrayOfArrays[F8][1] == "F8" == true) { sName = arrayOfArrays[F8][0] for (k in 0..29) { second[k] = arrayOfArrays[F8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } println("BEGIN NEXT GROUP") println("") println("") // MASTER M9 to F7, F8, F9 MATCHER\\ for (M9 in 0 until lines) { if (arrayOfArrays[M9][1] == "M9" == true) { val mName = arrayOfArrays[M9][0] for (e in 0..29) { master[e] = arrayOfArrays[M9][2].substring(e, e + 1) } // End masterInt {_for_} // Start second val second = arrayOfNulls<String>(30) val sName = arrayOfArrays[0][0] val percentMatch = 0.0 val box1 = 0.0 val box2 = 0.0 val box3 = 0.0 val box4 = 0.0 val box5 = 0.0 val box6 = 0.0 val box7 = 0.0 val box8 = 0.0 val box9 = 0.0 val box10 = 0.0 val holdName = "" val sBox1 = "" val sBox2 = "" val sBox3 = "" val sBox4 = "" val sBox5 = "" val sBox6 = "" val sBox7 = "" val sBox8 = "" val sBox9 = "" val sBox10 = "" for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (F8 in 0 until lines) { if (arrayOfArrays[F8][1] == "F8" == true) { sName = arrayOfArrays[F8][0] for (k in 0..29) { second[k] = arrayOfArrays[F8][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } for (F9 in 0 until lines) { if (arrayOfArrays[F9][1] == "F9" == true) { sName = arrayOfArrays[F9][0] for (k in 0..29) { second[k] = arrayOfArrays[F9][2] .substring(k, k + 1) } // End masterInt {_for_} // Declare Varibles val matchCount = 0.0 val pMatch = 0.0 // Do the Math for (c in 0..29) { if (master[c] == second[c] == true) { matchCount++ } // End of "m=s" {_if_} } // End for "pMatch" {_for_} pMatch = matchCount / 30 val rounded = Math.round(pMatch * 1000).toDouble() / 1000 percentMatch = rounded holdName = sName if (percentMatch > box1) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = box1 box1 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = sBox1 sBox1 = holdName } else if (percentMatch > box2) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = box2 box2 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = sBox2 sBox2 = holdName } else if (percentMatch > box3) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = box3 box3 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = sBox3 sBox3 = holdName } else if (percentMatch > box4) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = box4 box4 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = sBox4 sBox4 = holdName } else if (percentMatch > box5) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = box5 box5 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = sBox5 sBox5 = holdName } else if (percentMatch > box6) { box10 = box9 box9 = box8 box8 = box7 box7 = box6 box6 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = sBox6 sBox6 = holdName } else if (percentMatch > box7) { box10 = box9 box9 = box8 box8 = box7 box7 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = sBox7 sBox7 = holdName } else if (percentMatch > box8) { box9 = box8 box10 = box9 box8 = percentMatch sBox10 = sBox9 sBox9 = sBox8 sBox8 = holdName } else if (percentMatch > box9) { box10 = box9 box9 = percentMatch sBox10 = sBox9 sBox9 = holdName } else if (percentMatch > box10) { box10 = percentMatch sBox10 = holdName } } } println((mName + "," + sBox1 + "," + sBox2 + "," + sBox3 + "," + sBox3 + "," + sBox4 + "," + sBox5 + "," + sBox6 + "," + sBox7 + "," + sBox8 + "," + sBox9 + "," + sBox10)) } } } // End of the {_try_} catch (e:Exception) { println(" :( ") } // Catch {_file_f_} } }
0
Kotlin
0
0
289631801f9bb621f06da5dbe75df546de76fd71
137,389
matchmaker-Kotlin
MIT License
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorPortfolioOfPortfolios.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategoryService import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorPortfolioOfPortfolios import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorPortfolioService import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.schema.graphQLFieldContributions import net.nemerosa.ontrack.graphql.support.GraphqlUtils.stdList import org.springframework.stereotype.Component @Component class GQLTypeIndicatorPortfolioOfPortfolios( private val indicatorPortfolioService: IndicatorPortfolioService, private val indicatorPortfolio: GQLTypeIndicatorPortfolio, private val indicatorCategory: GQLTypeIndicatorCategory, private val indicatorCategoryService: IndicatorCategoryService, private val fieldContributors: List<GQLFieldContributor> ) : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("List of portfolios") // Categories .field { it.name(IndicatorPortfolioOfPortfolios::categories.name) .description("Global indicator categories") .type(stdList(indicatorCategory.typeRef)) .dataFetcher { env -> val pp = env.getSource<IndicatorPortfolioOfPortfolios>() pp.categories.mapNotNull { id -> indicatorCategoryService.findCategoryById(id) } } } // List of portfolios .field { it.name("portfolios") .description("List of portfolios") .type(stdList(indicatorPortfolio.typeRef)) .dataFetcher { indicatorPortfolioService.findAll() } } // Links .fields(IndicatorPortfolioOfPortfolios::class.java.graphQLFieldContributions(fieldContributors)) //OK .build() override fun getTypeName(): String = IndicatorPortfolioOfPortfolios::class.java.simpleName }
57
null
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
2,748
ontrack
MIT License
domain/src/main/java/org/oppia/android/domain/topic/PrimeTopicAssetsControllerImpl.kt
oppia
148,093,817
false
null
package org.oppia.android.domain.topic import android.annotation.SuppressLint import android.app.Activity import android.app.Application import android.graphics.Typeface import android.os.Bundle import android.os.SystemClock import android.text.Spannable import android.text.style.ImageSpan import android.util.TypedValue import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.text.HtmlCompat import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.oppia.android.app.model.AnswerGroup import org.oppia.android.app.model.ChapterSummary import org.oppia.android.app.model.ConceptCard import org.oppia.android.app.model.Exploration import org.oppia.android.app.model.Hint import org.oppia.android.app.model.Interaction import org.oppia.android.app.model.Outcome import org.oppia.android.app.model.Question import org.oppia.android.app.model.RevisionCard import org.oppia.android.app.model.SchemaObject import org.oppia.android.app.model.SchemaObject.ObjectTypeCase.SUBTITLED_HTML import org.oppia.android.app.model.SchemaObjectList import org.oppia.android.app.model.Solution import org.oppia.android.app.model.State import org.oppia.android.app.model.StorySummary import org.oppia.android.app.model.SubtitledHtml import org.oppia.android.app.model.Subtopic import org.oppia.android.app.model.Topic import org.oppia.android.domain.exploration.ExplorationRetriever import org.oppia.android.domain.oppialogger.OppiaLogger import org.oppia.android.domain.question.QuestionRetriever import org.oppia.android.domain.util.JsonAssetRetriever import org.oppia.android.util.caching.AssetRepository import org.oppia.android.util.caching.TopicListToCache import org.oppia.android.util.gcsresource.DefaultResourceBucketName import org.oppia.android.util.gcsresource.QuestionResourceBucketName import org.oppia.android.util.locale.OppiaLocale import org.oppia.android.util.parser.html.ConceptCardHtmlParserEntityType import org.oppia.android.util.parser.html.ExplorationHtmlParserEntityType import org.oppia.android.util.parser.html.StoryHtmlParserEntityType import org.oppia.android.util.parser.html.TopicHtmlParserEntityType import org.oppia.android.util.parser.image.DefaultGcsPrefix import org.oppia.android.util.parser.image.ImageDownloadUrlTemplate import org.oppia.android.util.parser.image.ThumbnailDownloadUrlTemplate import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject import javax.inject.Singleton private const val CUSTOM_IMG_TAG = "oppia-noninteractive-image" private const val REPLACE_IMG_TAG = "img" private const val CUSTOM_IMG_FILE_PATH_ATTRIBUTE = "filepath-with-value" private const val REPLACE_IMG_FILE_PATH_ATTRIBUTE = "src" /** * Implementation of [PrimeTopicAssetsController] which primes assets & shows UI affordances before * and after priming. */ @Singleton class PrimeTopicAssetsControllerImpl @Inject constructor( private val application: Application, private val oppiaLogger: OppiaLogger, private val assetRepository: AssetRepository, private val topicController: TopicController, private val jsonAssetRetriever: JsonAssetRetriever, private val explorationRetriever: ExplorationRetriever, private val questionRetriever: QuestionRetriever, private val conceptCardRetriever: ConceptCardRetriever, private val revisionCardRetriever: RevisionCardRetriever, private val machineLocale: OppiaLocale.MachineLocale, @DefaultGcsPrefix private val gcsPrefix: String, @DefaultResourceBucketName private val gcsResource: String, @QuestionResourceBucketName private val questionGcsResource: String, @ImageDownloadUrlTemplate private val imageDownloadUrlTemplate: String, @ThumbnailDownloadUrlTemplate private val thumbnailDownloadUrlTemplate: String, @TopicListToCache private val topicListToCache: List<String>, @ExplorationHtmlParserEntityType private val explorationEntityType: String, @ConceptCardHtmlParserEntityType private val conceptCardEntityType: String, @TopicHtmlParserEntityType private val topicEntityType: String, @StoryHtmlParserEntityType private val storyEntityType: String ) : PrimeTopicAssetsController { // NOTE TO DEVELOPERS: Don't ever do this. The application should use shared dispatchers to // control resources & coordinate tests. This custom dispatcher is needed since priming is a // dispatcher-intensive operation and using the shared background dispatcher ends up blocking the // app UI, potentially in a breaking way. private val extraDispatcher = Executors.newFixedThreadPool( /* nThreads= */ 4 ).asCoroutineDispatcher() // NOTE TO DEVELOPERS: Never do this. We should never hold activity references in singleton // objects, even as weak references. This is being done to keep priming code isolated so that it's // easier to remove after #169 is completed. private val extraDispatcherScope = CoroutineScope(extraDispatcher) private val primeDownloadStatus = MutableLiveData(PrimeAssetsStatus(0, 0)) private val currentDownloadCount = AtomicInteger() private val failedDownloadCount = AtomicInteger() private val dialogShown = AtomicBoolean() private val dialogDismissed = AtomicBoolean() override fun downloadAssets(dialogStyleResId: Int) { prepareUiForDownloadStatusChanges(dialogStyleResId) // Ensure all JSON files are available in memory for quick retrieval. val allFiles = mutableListOf<String>() allFiles.add("topics.json") val topicIdJsonArray = jsonAssetRetriever .loadJsonFromAsset("topics.json")!! .getJSONArray("topic_id_list") for (i in 0 until topicIdJsonArray.length()) { allFiles.addAll(topicController.getJsonAssetFileNameList(topicIdJsonArray.optString(i))) } val primeAssetJobs = allFiles.map { extraDispatcherScope.async { assetRepository.primeTextFileFromLocalAssets(it) } } // The following job encapsulates all startup loading. NB: We don't currently wait on this job // to complete because it's fine to try to load the assets at the same time as priming the // cache, and it's unlikely the user can get into an exploration fast enough to try to load an // asset that would trigger a strict mode crash. extraDispatcherScope.launch { primeAssetJobs.forEach { it.await() } // Only download binary assets for configured topics. The others can still be streamed. val topics = loadTopics(topicListToCache) val explorationIds = topics.flatMap(::extractExplorationIds).toSet() val skillIds = topics.flatMap(::extractSkillIds).toSet() val explorations = loadExplorations(explorationIds) val questions = loadQuestions(skillIds) val conceptCards = loadConceptCards(skillIds) val revisionCards = loadRevisionCards(topics) val thumbnailUrls = topics.flatMap(::collectThumbnailUrls) val explorationImageUrls = explorations.flatMap(::collectImageUrls) val questionImageUrls = questions.flatMap(::collectImageUrls) val conceptCardImageUrls = conceptCards.flatMap(::collectImageUrls) val revisionCardImageUrls = revisionCards.flatMap(::collectImageUrls) val imageUrls = ( thumbnailUrls + explorationImageUrls + questionImageUrls + conceptCardImageUrls + revisionCardImageUrls ).toSet() oppiaLogger.d("AssetRepo", "Downloading up to ${imageUrls.size} images") val startTime = SystemClock.elapsedRealtime() val downloadUrls = imageUrls.filterNot(assetRepository::isRemoteBinaryAssetDownloaded) val assetDownloadCount = downloadUrls.size primeDownloadStatus.postValue( PrimeAssetsStatus(currentDownloadCount.get(), assetDownloadCount) ) downloadUrls.map { url: String -> extraDispatcherScope.async { try { assetRepository.primeRemoteBinaryAsset(url) } catch (e: Exception) { failedDownloadCount.incrementAndGet() oppiaLogger.w("AssetRepo", "Failed to download $url because $e") } primeDownloadStatus.postValue( PrimeAssetsStatus( currentDownloadCount.incrementAndGet(), assetDownloadCount, failedDownloadCount.get() ) ) } }.forEach { it.await() } val endTime = SystemClock.elapsedRealtime() oppiaLogger.d( "AssetRepo", "Finished downloading voiceovers and images in ${endTime - startTime}ms" ) // Send the final count since everything should be done now. This is redundant, but it's meant // to make sure the dialog reaches a finalized state. primeDownloadStatus.postValue(PrimeAssetsStatus(assetDownloadCount, assetDownloadCount)) } } private fun prepareUiForDownloadStatusChanges(dialogStyleResId: Int) { // Reference: https://stackoverflow.com/a/37713320. application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityPaused(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityDestroyed(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityStopped(activity: Activity) {} override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (!dialogDismissed.get()) { activity?.let { val appCompatActivity = it as AppCompatActivity primeDownloadStatus.observe( appCompatActivity, Observer<PrimeAssetsStatus> { primeAssetsStatus -> primeAssetsStatus?.let { status -> if (status.totalDownloadCount > 0 && !dialogShown.get()) { showProgressDialog(appCompatActivity, dialogStyleResId) } } } ) } } } }) } @SuppressLint("SetTextI18n") // This is a temporary, alpha-release only feature. private fun showProgressDialog(activity: Activity, dialogStyleResId: Int) { // Programmatically create the layout to avoid resource deps and to keep priming isolated. val layout = LinearLayout(activity) layout.orientation = LinearLayout.VERTICAL val textView = TextView(activity) layout.addView(textView) textView.text = "Downloading assets for offline support." val resources = activity.resources val marginPx = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 16f, resources.displayMetrics ).toInt() (textView.layoutParams as LinearLayout.LayoutParams).setMargins( /* left= */ marginPx, /* top= */ marginPx, /* right= */ marginPx, /* bottom= */ marginPx ) textView.textSize = 14f textView.typeface = Typeface.create("sans-serif", Typeface.NORMAL) val progressBar = ProgressBar( activity, /* attrs= */ null, android.R.attr.progressBarStyleHorizontal ) layout.addView(progressBar) (progressBar.layoutParams as LinearLayout.LayoutParams).setMargins( /* left= */ marginPx, /* top= */ 0, /* right= */ marginPx, /* bottom= */ 0 ) val dialog = AlertDialog.Builder(activity, dialogStyleResId) .setView(layout) .setPositiveButton("Close") { dialog, _ -> dialogDismissed.set(true) dialog.dismiss() }.create() dialog.setCanceledOnTouchOutside(false) dialog.show() dialogShown.set(true) primeDownloadStatus.observeForever(object : Observer<PrimeAssetsStatus> { override fun onChanged(status: PrimeAssetsStatus?) { status?.let { progressBar.max = it.totalDownloadCount if (it.currentDownloadCount > progressBar.progress) { progressBar.progress = it.currentDownloadCount } if (it.currentDownloadCount == it.totalDownloadCount) { if (it.failedDownloadCount > 0) { textView.text = "Finished downloading, but some failed to download. Please try again." } else { textView.text = "Finished downloading assets for offline support." } primeDownloadStatus.removeObserver(this) } } } }) } private fun loadTopics(topicIds: Collection<String>): Collection<Topic> { // Ignore topics no longer on the device. return topicIds.mapNotNull(topicController::retrieveTopic) } private fun loadExplorations(explorationIds: Collection<String>): Collection<Exploration> { return explorationIds.map(explorationRetriever::loadExploration) } private fun loadQuestions(skillIds: Collection<String>): Collection<Question> { return questionRetriever.loadQuestions(skillIds.toList()) } private fun loadConceptCards(skillIds: Collection<String>): Collection<ConceptCard> { return skillIds.map(conceptCardRetriever::loadConceptCard) } private fun loadRevisionCards(topics: Collection<Topic>): List<Pair<String, RevisionCard>> { return topics.flatMap { loadRevisionCards(it.topicId to it.subtopicList.map(Subtopic::getSubtopicId)) } } private fun loadRevisionCards( topicIdToSubtopicIds: Pair<String, Iterable<Int>> ): Collection<Pair<String, RevisionCard>> { val topicId = topicIdToSubtopicIds.first return topicIdToSubtopicIds.second.map { topicId to revisionCardRetriever.loadRevisionCard(topicId, it) } } private fun extractExplorationIds(topic: Topic): List<String> { val chapters = topic.storyList.flatMap(StorySummary::getChapterList) return chapters.map(ChapterSummary::getExplorationId) } private fun extractSkillIds(topic: Topic): List<String> { return topic.subtopicList.flatMap(Subtopic::getSkillIdsList) } private fun collectThumbnailUrls(topic: Topic): Collection<String> { val thumbnailUrls = mutableListOf<String>() val topicThumbnail = topic.topicThumbnail if (topicThumbnail.thumbnailFilename.isNotBlank()) { thumbnailUrls += getUriForThumbnail( topic.topicId, topicEntityType, topicThumbnail.thumbnailFilename ) } for (storySummary in topic.storyList) { val storyThumbnail = storySummary.storyThumbnail if (storyThumbnail.thumbnailFilename.isNotBlank()) { thumbnailUrls += getUriForThumbnail( storySummary.storyId, storyEntityType, storyThumbnail.thumbnailFilename ) } for (chapterSummary in storySummary.chapterList) { val chapterThumbnail = chapterSummary.chapterThumbnail if (chapterThumbnail.thumbnailFilename.isNotBlank()) { thumbnailUrls += getUriForThumbnail( storySummary.storyId, storyEntityType, chapterThumbnail.thumbnailFilename ) } } } for (subtopic in topic.subtopicList) { val subtopicThumbnail = subtopic.subtopicThumbnail if (subtopicThumbnail.thumbnailFilename.isNotBlank()) { thumbnailUrls += getUriForThumbnail( topic.topicId, topicEntityType, subtopicThumbnail.thumbnailFilename ) } } return thumbnailUrls } private fun collectImageUrls(exploration: Exploration): Collection<String> { return collectImageUrls(exploration, exploration.id, explorationEntityType, ::getUriForImage) { collectSubtitledHtmls(it.statesMap.values) } } private fun collectImageUrls(question: Question): Collection<String> { // TODO(#497): Update this to properly link to question assets. val skillId = question.linkedSkillIdsList.firstOrNull() ?: "" return collectImageUrls(question, skillId, "skill", ::getUriForQuestionImage) { collectSubtitledHtmls(listOf(question.questionState)) } } private fun collectImageUrls(conceptCard: ConceptCard): Collection<String> { return collectImageUrls( conceptCard, conceptCard.skillId, conceptCardEntityType, ::getUriForImage, ::collectSubtitledHtmls ) } private fun collectImageUrls( topicIdToRevisionCard: Pair<String, RevisionCard> ): Collection<String> { return collectImageUrls( topicIdToRevisionCard.second, topicIdToRevisionCard.first, topicEntityType, ::getUriForImage, ::collectSubtitledHtmls ) } private fun <T> collectImageUrls( entity: T, entityId: String, entityType: String, computeUriForImage: (String, String, String) -> String, collectSubtitledHtmls: (T) -> Collection<SubtitledHtml> ): Collection<String> { val subtitledHtmls = collectSubtitledHtmls(entity) val imageSources = subtitledHtmls.flatMap(::getImageSourcesFromHtml) return imageSources.toSet().map { imageSource -> computeUriForImage(entityId, entityType, imageSource) } } private fun collectSubtitledHtmls(states: Iterable<State>): Collection<SubtitledHtml> { val stateContents = states.map(State::getContent) val stateInteractions = states.map(State::getInteraction) // Retrieve choice options for multiple choice, item selection, and drag & drop sort. val customizationArgsMapList = stateInteractions.map(Interaction::getCustomizationArgsMap) val argsMapValues = customizationArgsMapList.mapNotNull { it["choices"] } // Defaults to empty lists if the type of customization argument is not an object list. val schemaObjectLists = argsMapValues.map(SchemaObject::getSchemaObjectList) val schemaObjects = schemaObjectLists.flatMap(SchemaObjectList::getSchemaObjectList) val subtitledHtmlObjects = schemaObjects.filter { it.objectTypeCase == SUBTITLED_HTML } val customizationSubtitledHtmls = subtitledHtmlObjects.map(SchemaObject::getSubtitledHtml) val stateSolutions = stateInteractions.map(Interaction::getSolution).map(Solution::getExplanation) val stateHints = stateInteractions.flatMap( Interaction::getHintList ).map(Hint::getHintContent) val answerGroupOutcomes = stateInteractions.flatMap(Interaction::getAnswerGroupsList).map(AnswerGroup::getOutcome) val defaultOutcomes = stateInteractions.map(Interaction::getDefaultOutcome) val outcomeFeedbacks = (answerGroupOutcomes + defaultOutcomes) .map(Outcome::getFeedback) val allSubtitledHtmls = stateContents + customizationSubtitledHtmls + stateSolutions + stateHints + outcomeFeedbacks return allSubtitledHtmls.filter { it != SubtitledHtml.getDefaultInstance() } } private fun collectSubtitledHtmls(conceptCard: ConceptCard): Collection<SubtitledHtml> { return conceptCard.workedExampleList + conceptCard.explanation } private fun collectSubtitledHtmls(revisionCard: RevisionCard): Collection<SubtitledHtml> { return listOf(revisionCard.pageContents) } private fun getImageSourcesFromHtml(subtitledHtml: SubtitledHtml): Collection<String> { val parsedHtml = parseHtml(replaceCustomOppiaImageTag(subtitledHtml.html)) val imageSpans = parsedHtml.getSpans( 0, parsedHtml.length, ImageSpan::class.java ) return imageSpans.toList().mapNotNull(ImageSpan::getSource) } private fun parseHtml(html: String): Spannable { return HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY) as Spannable } private fun replaceCustomOppiaImageTag(html: String): String { return html.replace(CUSTOM_IMG_TAG, REPLACE_IMG_TAG) .replace(CUSTOM_IMG_FILE_PATH_ATTRIBUTE, REPLACE_IMG_FILE_PATH_ATTRIBUTE) .replace("&amp;quot;", "") } private fun getUriForImage(entityId: String, entityType: String, imageFileName: String): String { return computeUrlForImageDownloads( imageDownloadUrlTemplate, gcsResource, entityType, entityId, imageFileName ) } private fun getUriForQuestionImage( entityId: String, entityType: String, imageFileName: String ): String { return computeUrlForImageDownloads( imageDownloadUrlTemplate, questionGcsResource, entityType, entityId, imageFileName ) } private fun getUriForThumbnail( entityId: String, entityType: String, imageFileName: String ): String { return computeUrlForImageDownloads( thumbnailDownloadUrlTemplate, gcsResource, entityType, entityId, imageFileName ) } private fun computeUrlForImageDownloads( template: String, gcsBucket: String, entityType: String, entityId: String, imageFileName: String ): String { val downloadUrlFile = machineLocale.run { template.formatForMachines(entityType, entityId, imageFileName) } return "$gcsPrefix/$gcsBucket/$downloadUrlFile" } private data class PrimeAssetsStatus( val currentDownloadCount: Int, val totalDownloadCount: Int, val failedDownloadCount: Int = 0 ) }
595
null
497
296
98257dbad55c2a9a03f898a38fa7ec57b27713a5
21,170
oppia-android
Apache License 2.0
.teamcity/Buildship/Jdk.kt
eclipse
32,398,083
false
{"Java": 1942456, "Groovy": 793125, "HTML": 121400, "Shell": 1191, "CSS": 131}
package Buildship import java.util.EnumSet enum class Jdk(val majorVersion: String, val vendor: String, val availableOn: EnumSet<OS> = EnumSet.allOf(OS::class.java)) { ORACLE_JDK_8("8", "oracle"), ORACLE_JDK_9("9", "oracle", EnumSet.of(OS.LINUX)), OPEN_JDK_10("10", "oracle", EnumSet.of(OS.LINUX)), OPEN_JDK_11("11", "openjdk"), OPEN_JDK_12("12", "openjdk", EnumSet.of(OS.LINUX)), OPEN_JDK_13("13", "openjdk", EnumSet.of(OS.LINUX)), OPEN_JDK_14("14", "openjdk", EnumSet.of(OS.LINUX)), OPEN_JDK_15("15", "openjdk"), OPEN_JDK_16("16", "openjdk"), OPEN_JDK_17("17", "openjdk"), OPEN_JDK_18("18", "openjdk"); // TODO add java 19-ea fun getJavaHomePath(os: OS) = if (availableOn.contains(os)) "%${os.name.toLowerCase()}.java${majorVersion}.${vendor}.64bit%" else throw RuntimeException("$name not available on ${os.name}") companion object { fun javaInstallationPathsProperty(os: OS) = "\"-Porg.gradle.java.installations.paths=${ Jdk.values().filter { it.availableOn.contains(os) }.joinToString(",") { it.getJavaHomePath(os) } }\"" } }
294
Java
175
511
942a601b12e2da706ad3bbcbf3950cc29b5c86ab
1,102
buildship
Naumen Public License
src/commonTest/kotlin/io/github/optimumcode/json/schema/assertions/number/JsonSchemaMultipleOfValidationTest.kt
OptimumCode
665,024,908
false
null
package io.github.optimumcode.json.schema.assertions.number import io.github.optimumcode.json.pointer.JsonPointer import io.github.optimumcode.json.schema.JsonSchema import io.github.optimumcode.json.schema.ValidationError import io.github.optimumcode.json.schema.base.KEY import io.kotest.assertions.assertSoftly import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.JsonUnquotedLiteral import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject // JsonUnquotedLiteral is used to bypass the JS conversion to integer value @OptIn(ExperimentalSerializationApi::class) @Suppress("unused") class JsonSchemaMultipleOfValidationTest : FunSpec() { init { listOf( JsonPrimitive(7), JsonPrimitive(49), JsonUnquotedLiteral("49.0"), JsonPrimitive(-49), JsonUnquotedLiteral("-49.0"), ).forEach { val schema = JsonSchema.fromDefinition( """ { "${KEY}schema": "http://json-schema.org/draft-07/schema#", "multipleOf": 7 } """.trimIndent(), ) test("integer in multiple of: $it % 7") { val errors = mutableListOf<ValidationError>() val valid = schema.validate(it, errors::add) valid shouldBe true errors shouldHaveSize 0 } } listOf( JsonPrimitive(3), JsonUnquotedLiteral("3.0"), JsonPrimitive(4.5), JsonPrimitive(-3), JsonUnquotedLiteral("-3.0"), JsonPrimitive(-4.5), ).forEach { val schema = JsonSchema.fromDefinition( """ { "${KEY}schema": "http://json-schema.org/draft-07/schema#", "multipleOf": 1.5 } """.trimIndent(), ) test("double in multiple of: $it % 1.5") { val errors = mutableListOf<ValidationError>() val valid = schema.validate(it, errors::add) valid shouldBe true errors shouldHaveSize 0 } } listOf( JsonPrimitive(0), JsonUnquotedLiteral("0.0"), JsonPrimitive(-1), JsonUnquotedLiteral("-1.0"), JsonPrimitive(-Double.MAX_VALUE), JsonPrimitive(Long.MIN_VALUE), ).forEach { test("reports not positive value $it") { shouldThrow<IllegalArgumentException> { JsonSchema.fromDefinition( """ { "${KEY}schema": "http://json-schema.org/draft-07/schema#", "multipleOf": $it } """.trimIndent(), ) }.message shouldBe "multipleOf value $it must be greater than zero" } } val numberSchema = JsonSchema.fromDefinition( """ { "${KEY}schema": "http://json-schema.org/draft-07/schema#", "multipleOf": 5 } """.trimIndent(), ) listOf( JsonPrimitive(true), JsonPrimitive("42"), JsonNull, buildJsonObject { }, buildJsonArray { }, ).forEach { test("not a number $it passes the validation") { val errors = mutableListOf<ValidationError>() val valid = numberSchema.validate(it, errors::add) valid shouldBe true errors shouldHaveSize 0 } } JsonSchema.fromDefinition( """ { "${KEY}schema": "http://json-schema.org/draft-07/schema#", "multipleOf": 0.0001 } """.trimIndent(), ).apply { listOf( JsonUnquotedLiteral("0.0075"), JsonUnquotedLiteral("0.075"), JsonUnquotedLiteral("0.75"), JsonUnquotedLiteral("7.5"), JsonUnquotedLiteral("75"), JsonUnquotedLiteral("750"), JsonUnquotedLiteral("12391239123"), JsonUnquotedLiteral("-0.0075"), JsonUnquotedLiteral("-0.075"), JsonUnquotedLiteral("-0.75"), JsonUnquotedLiteral("-7.5"), JsonUnquotedLiteral("-75"), JsonUnquotedLiteral("-750"), JsonUnquotedLiteral("-12391239123"), ).forEach { test("small number $it is multiple of 0.0001") { val errors = mutableListOf<ValidationError>() validate(it, errors::add) shouldBe true errors shouldHaveSize 0 } } listOf( JsonUnquotedLiteral("0.00001"), JsonUnquotedLiteral("0.00011"), JsonUnquotedLiteral("0.00751"), JsonUnquotedLiteral("0.01751"), JsonUnquotedLiteral("0.71751"), JsonUnquotedLiteral("1.71751"), JsonUnquotedLiteral("-0.00001"), JsonUnquotedLiteral("-0.00011"), JsonUnquotedLiteral("-0.00751"), JsonUnquotedLiteral("-0.01751"), JsonUnquotedLiteral("-0.71751"), JsonUnquotedLiteral("-1.71751"), ).forEach { test("small number $it is not a multiple of 0.0001") { val errors = mutableListOf<ValidationError>() validate(it, errors::add) shouldBe false errors.shouldContainExactly( ValidationError( schemaPath = JsonPointer("/multipleOf"), objectPath = JsonPointer.ROOT, message = "$it is not a multiple of 0.0001", ), ) } } } test("BUG_70 rounding problem with some numbers because double does not behave as you expect") { val schema = JsonSchema.fromDefinition( """ { "multipleOf": 0.01 } """.trimIndent(), ) val errors = mutableListOf<ValidationError>() val valid = schema.validate(JsonPrimitive(19.99), errors::add) assertSoftly { valid shouldBe true errors shouldHaveSize 0 } } } }
9
null
3
9
61e36f29adaf6538fd38307296cc5dd1339e1ffa
6,029
json-schema-validator
MIT License
sms/src/main/kotlin/dev/atick/sms/di/SmsHelperModule.kt
atick-faisal
609,303,624
false
{"Kotlin": 207223}
package dev.atick.sms.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dev.atick.sms.utils.SmsHelper import dev.atick.sms.utils.SmsHelperImpl import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class SmsHelperModule { @Binds @Singleton abstract fun bindSmsHelper( smsHelperImpl: SmsHelperImpl ): SmsHelper }
1
Kotlin
0
1
6cdf5bad531cf85a9e4823079cf9921851c5dd9c
447
Safety-Android
Apache License 2.0
src/main/kotlin/dev/andante/audience/resource/server/ResourcePackRequestHandler.kt
mcbrawls
668,356,321
false
{"Kotlin": 20786, "Java": 19332}
package dev.andante.audience.resource import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpHandler import org.apache.http.HttpHeaders import org.apache.http.client.methods.HttpGet import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.IOException /** * Handles requests for a [ResourcePackServer]. */ class ResourcePackRequestHandler( /** * The resource pack to be sent/received. */ private val resourcePack: ResourcePack ) : HttpHandler { /** * The length of the bytes in [resourcePack]. */ private val responseLength = resourcePack.bytes.size.toLong() override fun handle(exchange: HttpExchange?) { // throw npe if null exchange ?: run { return } // check for get if (exchange.requestMethod != HttpGet.METHOD_NAME) { exchange.close() return } // handle request try { sendResourcePack(exchange) } catch (exception: Exception) { onException(exception) } finally { exchange.close() } } /** * Sends the resource pack as a response to the request. */ @Throws(IOException::class) private fun sendResourcePack(exchange: HttpExchange) { // write zip as response exchange.responseHeaders[HttpHeaders.CONTENT_TYPE] = "application/zip" exchange.sendResponseHeaders(200, responseLength) exchange.responseBody.write(resourcePack.bytes) } /** * Handles exceptions caught during the exchange. */ private fun onException(exception: Exception) { logger.error("Exception caught when serving a resource pack", exception) } companion object { private val logger: Logger = LoggerFactory.getLogger("Resource Pack Request Handler") } }
0
Kotlin
0
0
3ebc8b4a16b09b9a6c2bd4ced58bbbb9cd90d1aa
1,852
audience
Creative Commons Zero v1.0 Universal
app/src/main/java/com/applab/ktmvvm/util/AppConstants.kt
arunantoney
144,386,586
false
null
package com.applab.ktmvvm.util object AppConstants { val PREF_NAME="crackInterviewPref" }
0
Kotlin
0
1
e45f67d6aadbf68753bf265c12c48b32862a78c2
92
Android-Kotlin-MVVM
MIT License
lib/src/main/kotlin/it/scoppelletti/spaceship/gms/FirebaseExceptionLoggerHandler.kt
dscoppelletti
263,641,066
false
null
/* * Copyright (C) 2019 <NAME>, <http://www.scoppelletti.it/>. * * 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 it.scoppelletti.spaceship.gms import com.google.firebase.crashlytics.FirebaseCrashlytics import it.scoppelletti.spaceship.ExceptionLoggerHandler import javax.inject.Inject /** * Implementation of `ExceptionLoggerHandler` interface using Firebase * Crashlytics. * * * [Firebase Crashlytics](http://firebase.google.com/products/crashlytics) * * @since 1.0.0 */ public class FirebaseExceptionLoggerHandler @Inject constructor( ): ExceptionLoggerHandler<Throwable> { override fun log(ex: Throwable) { val crashlytics = FirebaseCrashlytics.getInstance() crashlytics.recordException(ex) } }
0
Kotlin
0
0
a5fbc87289d0bcd08e7f798943de199ca2fad995
1,254
spaceship-gms
Apache License 2.0
includeBuild/src/main/kotlin/com/idex/build/versions.kt
lhwdev
331,217,993
false
null
package com.idex.build const val idexVersion = "1.0.0-dev" const val idexPackageVersion = "1.0.10001"
0
Kotlin
0
0
44a69d9276bd2ea9fe8ac37115728456d1e0d64f
104
IDEx
Apache License 2.0
ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/GitChangeLogCache.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.extension.git import net.nemerosa.ontrack.extension.git.model.GitChangeLog /** * Service used to access the cache for the change logs, used by the Rest controller * _and_ the GraphQL root queries. */ interface GitChangeLogCache { /** * Puts the given change log into the cache. */ fun put(changeLog: GitChangeLog) /** * Gets a required cache entry using its UUID or throws an exception. */ fun getRequired(uuid: String): GitChangeLog } /** * Cache section */ const val CACHE_GIT_CHANGE_LOG = "gitChangeLog"
57
null
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
582
ontrack
MIT License
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/logging/Logger.kt
JetBrains
49,584,664
false
null
package jetbrains.buildServer.dotnet.logging import jetbrains.buildServer.dotnet.* import java.io.File private const val MSBuildLoggerAssemblyName = "TeamCity.MSBuild.Logger.dll" private const val MSBuildLoggerSubDir = "msbuild" private const val VSTestLoggerAssemblyName = "TeamCity.VSTest.TestAdapter.dll" private const val VSTestSubDir = "vstest" enum class Logger(val msbuildTool: Tool, val vstestTool: Tool, val msbuildLogger: File, val vstestLogger: File) { // MSBuild loggers DotnetCore(Tool.MSBuildCrossPlatform, Tool.VSTestCrossPlatform, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), Mono(Tool.MSBuildMono, Tool.VSTestCrossPlatform, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V10Windows(Tool.MSBuild4Windows, Tool.VSTest12Windows, File("${MSBuildLoggerSubDir}12", MSBuildLoggerAssemblyName), File("${VSTestSubDir}12", VSTestLoggerAssemblyName)), V10WindowsX64(Tool.MSBuild4WindowsX64, Tool.VSTest12Windows, File("${MSBuildLoggerSubDir}12", MSBuildLoggerAssemblyName), File("${VSTestSubDir}12", VSTestLoggerAssemblyName)), V10WindowsX86(Tool.MSBuild4WindowsX86, Tool.VSTest12Windows, File("${MSBuildLoggerSubDir}12", MSBuildLoggerAssemblyName), File("${VSTestSubDir}12", VSTestLoggerAssemblyName)), V12Windows(Tool.MSBuild12Windows, Tool.VSTest12Windows, File("${MSBuildLoggerSubDir}12", MSBuildLoggerAssemblyName), File("${VSTestSubDir}12", VSTestLoggerAssemblyName)), V12WindowsX64(Tool.MSBuild12WindowsX64, Tool.VSTest12Windows, File("${MSBuildLoggerSubDir}12", MSBuildLoggerAssemblyName), File("${VSTestSubDir}12", VSTestLoggerAssemblyName)), V12WindowsX86(Tool.MSBuild12WindowsX86, Tool.VSTest12Windows, File("${MSBuildLoggerSubDir}12", MSBuildLoggerAssemblyName), File("${VSTestSubDir}12", VSTestLoggerAssemblyName)), V14Windows(Tool.MSBuild14Windows, Tool.VSTest14Windows, File("${MSBuildLoggerSubDir}14", MSBuildLoggerAssemblyName), File("${VSTestSubDir}14", VSTestLoggerAssemblyName)), V14WindowsX64(Tool.MSBuild14WindowsX64, Tool.VSTest14Windows, File("${MSBuildLoggerSubDir}14", MSBuildLoggerAssemblyName), File("${VSTestSubDir}14", VSTestLoggerAssemblyName)), V14WindowsX86(Tool.MSBuild14WindowsX86, Tool.VSTest14Windows, File("${MSBuildLoggerSubDir}14", MSBuildLoggerAssemblyName), File("${VSTestSubDir}14", VSTestLoggerAssemblyName)), V15Windows(Tool.MSBuild15Windows, Tool.VSTest15Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V15WindowsX64(Tool.MSBuild15WindowsX64, Tool.VSTest15Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V15WindowsX86(Tool.MSBuild15WindowsX86, Tool.VSTest15Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V16Windows(Tool.MSBuild16Windows, Tool.VSTest16Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V16WindowsX64(Tool.MSBuild16WindowsX64, Tool.VSTest16Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V16WindowsX86(Tool.MSBuild16WindowsX86, Tool.VSTest16Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V17Windows(Tool.MSBuild17Windows, Tool.VSTest17Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V17WindowsX64(Tool.MSBuild17WindowsX64, Tool.VSTest17Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), V17WindowsX86(Tool.MSBuild17WindowsX86, Tool.VSTest17Windows, File("${MSBuildLoggerSubDir}15", MSBuildLoggerAssemblyName), File("${VSTestSubDir}15", VSTestLoggerAssemblyName)), }
3
null
25
94
5f444c22b3354955d1060e08478d543d2b0b99b0
4,070
teamcity-dotnet-plugin
Apache License 2.0
feature-timesheet/src/main/java/fr/o80/sample/timesheet/usecase/ListEntries.kt
olivierperez
98,867,027
false
null
package fr.o80.sample.timesheet.usecase import fr.o80.crapp.data.ProjectRepository import fr.o80.crapp.data.TimesheetRepository import fr.o80.sample.lib.dagger.FeatureScope import fr.o80.sample.timesheet.usecase.model.EntryViewModel import fr.o80.sample.lib.utils.today import io.reactivex.Single import io.reactivex.functions.BiFunction import java.util.Date import javax.inject.Inject /** * @author <NAME> */ @FeatureScope class ListEntries @Inject constructor(private val timesheetRepository: TimesheetRepository, private val projectRepository: ProjectRepository) { fun findByDate(after: Date, strictlyBefore: Date): Single<List<EntryViewModel>> { return Single .zip(timesheetRepository.findByDateRange(after, strictlyBefore), projectRepository.allActive(), BiFunction { entries, projects -> val vms = mutableListOf<EntryViewModel>() vms.addAll(entries.map { EntryViewModel(it.project!!.label!!, it.project!!.code!!, it.hours, it.date!!) }) vms.addAll(projects .filter { project -> entries.find { entry -> entry.project?.id == project.id } == null } .map { EntryViewModel(it.label!!, it.code!!, 0, today()) }) vms.sortBy { it.label } vms.toList() }) } }
0
Kotlin
1
1
01b780b604eb433f1829c63ce04f06da83f1f6fa
1,491
crapp
Apache License 2.0
rulebook-checkstyle/src/test/kotlin/com/hanggrian/rulebook/checkstyle/MemberLineSpacingCheckTest.kt
hanggrian
556,969,715
false
{"Kotlin": 276685, "Python": 71886, "Java": 18646, "CSS": 1653, "Groovy": 329}
package com.hanggrian.rulebook.checkstyle import kotlin.test.Test import kotlin.test.assertEquals class MemberLineSpacingCheckTest { private val checker = checkerOf<MemberLineSpacingCheck>() @Test fun `Rule properties`() = MemberLineSpacingCheck().assertProperties() @Test fun `Declarations with newline`() = assertEquals(0, checker.read("MemberLineSpacing1")) @Test fun `Declarations without newline`() = assertEquals(3, checker.read("MemberLineSpacing2")) @Test fun `Block comment and annotations in declarations`() = assertEquals(0, checker.read("MemberLineSpacing3")) @Test fun `Skip fields`() = assertEquals(0, checker.read("MemberLineSpacing4")) }
0
Kotlin
0
1
bd830a60e69645136c391e7f0853662a45b0b56c
713
rulebook
Apache License 2.0
hexagonal/src/main/kotlin/com/devdeolho/hexagonal/application/core/domain/Address.kt
carloshenriquefs
842,119,747
false
{"Kotlin": 30680}
package com.devdeolho.hexagonal.application.core.domain data class Address( val street: String, val city: String, val state: String )
0
Kotlin
0
0
52b701675272bf5691e0a30577e21a657b258c14
159
hexagonal
MIT License
src/test/kotlin/no/nav/eessi/pensjon/kravinitialisering/integrationtest/ListenerIntegrasjonsTest.kt
navikt
346,987,628
false
null
package no.nav.eessi.pensjon.kravinitialisering.integrationtest import IntegrasjonsTestConfig import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.AnonymousAWSCredentials import com.amazonaws.client.builder.AwsClientBuilder import com.amazonaws.services.s3.AmazonS3ClientBuilder import com.ninjasquad.springmockk.MockkBean import io.findify.s3mock.S3Mock import io.mockk.every import no.nav.eessi.pensjon.json.toJson import no.nav.eessi.pensjon.kravinitialisering.BehandleHendelseModel import no.nav.eessi.pensjon.kravinitialisering.HendelseKode import no.nav.eessi.pensjon.kravinitialisering.listener.Listener import no.nav.eessi.pensjon.s3.S3StorageService import no.nav.eessi.pensjon.security.sts.STSService import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockserver.integration.ClientAndServer import org.mockserver.model.Header import org.mockserver.model.HttpRequest import org.mockserver.model.HttpResponse import org.mockserver.model.HttpStatusCode import org.mockserver.verify.VerificationTimes import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Profile import org.springframework.http.HttpMethod import org.springframework.kafka.core.DefaultKafkaConsumerFactory import org.springframework.kafka.core.DefaultKafkaProducerFactory import org.springframework.kafka.core.KafkaTemplate import org.springframework.kafka.listener.ContainerProperties import org.springframework.kafka.listener.KafkaMessageListenerContainer import org.springframework.kafka.listener.MessageListener import org.springframework.kafka.test.EmbeddedKafkaBroker import org.springframework.kafka.test.context.EmbeddedKafka import org.springframework.kafka.test.utils.ContainerTestUtils import org.springframework.kafka.test.utils.KafkaTestUtils import org.springframework.test.annotation.DirtiesContext import org.springframework.test.context.ActiveProfiles import org.springframework.web.client.RestTemplate import java.net.ServerSocket import java.nio.file.Files import java.nio.file.Paths import java.time.LocalDateTime import java.util.* import java.util.concurrent.* private const val KRAV_INITIALISERING_TOPIC = "eessi-pensjon-krav-initialisering" private lateinit var mockServer: ClientAndServer @SpringBootTest(classes = [IntegrasjonsTestConfig::class], value = ["SPRING_PROFILES_ACTIVE", "integrationtest"]) @ActiveProfiles("integrationtest") @DirtiesContext @EmbeddedKafka( controlledShutdown = true, partitions = 1, topics = [KRAV_INITIALISERING_TOPIC], brokerProperties = ["log.dir=out/embedded-kafkamottatt"] ) class ListenerIntegrasjonsTest { @Suppress("SpringJavaInjectionPointsAutowiringInspection") @Autowired lateinit var embeddedKafka: EmbeddedKafkaBroker @MockkBean(name = "pensjonsinformasjonOidcRestTemplate") lateinit var restEuxTemplate: RestTemplate @MockkBean lateinit var stsService: STSService @Autowired private lateinit var s3StorageService: S3StorageService @Autowired lateinit var listener: Listener private lateinit var container: KafkaMessageListenerContainer<String, String> private lateinit var sedMottattProducerTemplate: KafkaTemplate<Int, String> @BeforeEach fun setup() { every { stsService.getSystemOidcToken() } returns "something" container = settOppUtitlityConsumer(KRAV_INITIALISERING_TOPIC) container.start() ContainerTestUtils.waitForAssignment(container, embeddedKafka.partitionsPerTopic) sedMottattProducerTemplate = settOppProducerTemplate() } @AfterEach fun after() { shutdown(container) embeddedKafka.kafkaServers.forEach { it.shutdown() } } @Test fun `En hendelse skal initalisere et krav`() { // -- alder val mockmodelAlder = BehandleHendelseModel( sakId = "12312312347", bucId = "1231231987", hendelsesKode = HendelseKode.SOKNAD_OM_ALDERSPENSJON, LocalDateTime.now(), "Test på beskrivelsen også" ) sendMelding(mockmodelAlder) // -- uføre val mockmodel = BehandleHendelseModel( sakId = "123123123", bucId = "1231231", hendelsesKode = HendelseKode.SOKNAD_OM_UFORE, beskrivelse = "Test på beskrivelsen også" ) val annenMockmodel = BehandleHendelseModel( sakId = "1231231234", bucId = "3231231", hendelsesKode = HendelseKode.SOKNAD_OM_UFORE, beskrivelse = "Test på beskrivelsen også" ) val mockModelUtenOpprettdato = """ { "sakId" : "1231231111", "bucId" : "3231231", "hendelsesKode" : "SOKNAD_OM_UFORE", "beskrivelse" : "Test på beskrivelsen også" } """.trimIndent() sendMelding(mockmodel) sendMelding(mockmodel) sendMelding(annenMockmodel) sendMeldingString(mockModelUtenOpprettdato) listener.getLatch().await(5000, TimeUnit.MILLISECONDS) verify() } private fun verify() { mockServer.verify( HttpRequest.request() .withMethod(HttpMethod.POST.name) .withPath("/"), VerificationTimes.exactly(4) ) } private fun sendMelding(melding: BehandleHendelseModel) { sedMottattProducerTemplate.sendDefault(melding.toJson()) } private fun sendMeldingString(melding: String) { sedMottattProducerTemplate.sendDefault(melding) } private fun shutdown(container: KafkaMessageListenerContainer<String, String>) { container.stop() embeddedKafka.kafkaServers.forEach { it.shutdown() } } private fun settOppProducerTemplate(): KafkaTemplate<Int, String> { val senderProps = KafkaTestUtils.producerProps(embeddedKafka.brokersAsString) val pf = DefaultKafkaProducerFactory<Int, String>(senderProps) val template = KafkaTemplate(pf) template.defaultTopic = KRAV_INITIALISERING_TOPIC return template } private fun settOppUtitlityConsumer(topicNavn: String): KafkaMessageListenerContainer<String, String> { val consumerProperties = KafkaTestUtils.consumerProps( "eessi-pensjon-group2", "false", embeddedKafka ) consumerProperties["auto.offset.reset"] = "earliest" val consumerFactory = DefaultKafkaConsumerFactory<String, String>(consumerProperties) val containerProperties = ContainerProperties(topicNavn) val container = KafkaMessageListenerContainer<String, String>(consumerFactory, containerProperties) val messageListener = MessageListener<String, String> { record -> println("Konsumerer melding: $record") } container.setupMessageListener(messageListener) return container } companion object { init { // Start Mockserver in memory val port = randomFrom() mockServer = ClientAndServer.startClientAndServer(port) System.setProperty("mockServerport", port.toString()) // Mocker STS mockServer.`when`( HttpRequest.request() .withMethod(HttpMethod.GET.name) .withQueryStringParameter("grant_type", "client_credentials") ) .respond( HttpResponse.response() .withHeader(Header("Content-Type", "application/json; charset=utf-8")) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(String(Files.readAllBytes(Paths.get("src/test/resources/STStoken.json")))) ) mockServer.`when`( HttpRequest.request() .withMethod(HttpMethod.POST.name) .withPath("/") ) .respond( HttpResponse.response() .withHeader(Header("Content-Type", "application/json; charset=utf-8")) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("{}") ) } private fun randomFrom(from: Int = 1024, to: Int = 65535): Int { val random = Random() return random.nextInt(to - from) + from } fun initMockS3(): S3StorageService { val s3Port = ServerSocket(0).use { it.localPort } val s3api = S3Mock.Builder().withPort(s3Port).withInMemoryBackend().build() s3api.start() val endpoint = AwsClientBuilder.EndpointConfiguration("http://localhost:$s3Port", "us-east-1") val s3MockClient = AmazonS3ClientBuilder.standard() .withPathStyleAccessEnabled(true) .withCredentials(AWSStaticCredentialsProvider(AnonymousAWSCredentials())) .withEndpointConfiguration(endpoint) .build() s3MockClient.createBucket("eessipensjon") //return s3MockClient val storageService = S3StorageService(s3MockClient) storageService.bucketname = "eessipensjon" storageService.env = "q1" storageService.init() return storageService } } // Mocks PDL-PersonService and EuxService @Suppress("unused") @Profile("integrationtest") @TestConfiguration class TestConfig { @Bean fun s3StorageService(): S3StorageService { println("InintMock S3") return initMockS3() } } }
1
Kotlin
0
1
ae7a031fb37ae0436de77f2816054a5658137bf5
9,952
eessi-pensjon-krav-initialisering
MIT License
src/main/kotlin/turtlestoffel/Scene.kt
TurtleStoffel
708,417,395
false
{"Kotlin": 34198, "GLSL": 697}
package turtlestoffel import org.joml.Vector3f import org.lwjgl.BufferUtils import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL20.glUniformMatrix4fv import turtlestoffel.mesh.Line import turtlestoffel.mesh.PlaneBuilder import kotlin.properties.Delegates class Scene { private val camera = Camera() private val objects = mutableListOf<GameObject>() private var shader by Delegates.notNull<Int>() /** * Generate the shader program */ fun init() { shader = Shader.createShader() objects.addAll( listOf( GameObject(PlaneBuilder.build()), GameObject(Line.build(Vector3f(0.0f, 0.0f, 0.0f), Vector3f(1.0f, 1.0f, 1.0f))), ), ) } fun render(time: Double) { camera.update() objects.forEach { it.update(time) } camera.setViewProjectionMatrix(shader) // --- Render val modelMatrixLocation = glGetUniformLocation(shader, "modelMatrix") objects.forEach { glUniformMatrix4fv(modelMatrixLocation, false, it.modelMatrix.get(BufferUtils.createFloatBuffer(16))) it.mesh.render() } } fun handleKeyInput( key: Int, action: Int, ) { camera.handleKeyInput(key, action) } fun handleMouseInput( positionX: Double, positionY: Double, ) { println("Mouse position: ($positionX, $positionY)") val invertedY = Engine.WINDOW_SIZE.second - positionY val viewport = IntArray(4) viewport[0] = 0 viewport[1] = 0 viewport[2] = Engine.WINDOW_SIZE.first viewport[3] = Engine.WINDOW_SIZE.second val origin = Vector3f() val direction = Vector3f() camera.getViewProjectionMatrix().unprojectRay( positionX.toFloat(), invertedY.toFloat(), viewport, origin, direction, ) println("Origin: (${origin.x()}, ${origin.y()}, ${origin.z()})") println("Direction: (${direction.x()}, ${direction.y()}, ${direction.z()})") val end = origin.add(direction.mul(10000.0f)) println("End: (${end.x()}, ${end.y()}, ${end.z()})") val endOpposite = origin.add(direction.mul(-1000.0f)) objects.add(GameObject(Line.build(origin, end))) objects.add(GameObject(Line.build(origin, endOpposite))) objects.add(GameObject(Line.build(Vector3f(0.0f, 0.0f, 0.0f), origin))) } fun handleRightMouseDrag( positionX: Double, positionY: Double, ) { println("Right mouse drag: ($positionX, $positionY)") camera.handleRightMouseDrag(positionX, positionY) } }
0
Kotlin
0
0
8ffab3a4a7ec00cb1ddc1cf1006deb1d24c2b954
2,739
lwjgl-kotlin
MIT License
src/main/kotlin/br/com/zup/orangetalents/rest/Application.kt
rsousaj
389,658,780
true
{"Kotlin": 7709}
package br.com.zup.orangetalents.rest import io.micronaut.runtime.Micronaut.* fun main(args: Array<String>) { build() .args(*args) .packages("br.com.zup.orangetalents.rest") .start() }
0
Kotlin
0
0
4fa4d22849111d1ec5e5472e4c6faa4535f51711
197
orange-talents-05-template-pix-keymanager-rest
Apache License 2.0
src/main/prac/TestCoRoutine.kt
mangaldev
97,454,279
false
{"Maven POM": 1, "Text": 2, "Markdown": 1, "Java": 1, "Kotlin": 20}
import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.runBlocking import java.util.concurrent.TimeUnit fun main(args: Array<String>) { // runBlocking { //(1) // println("Starting blocking...") // delay(1000, TimeUnit.MILLISECONDS) // println("starting job after 1 sec") // runBlocking { // val result = async { // suspendingFunction() // } runBlocking { print("The result:") delay(1000L) } // } println("done") } private suspend fun suspendingFunction(): String { delay(2000, TimeUnit.MILLISECONDS) return "completed after 2 secs" }
0
Kotlin
0
0
a2dd477768195d9df678713a358aba3898fac223
650
MyKotlin
MIT License
src/main/kotlin/org/move/lang/core/psi/ext/MvStructField.kt
pontem-network
279,299,159
false
null
package org.move.lang.core.psi.ext import org.move.lang.core.psi.MvStruct import org.move.lang.core.psi.MvStructBlock import org.move.lang.core.psi.MvStructField val MvStructField.fieldsDefBlock: MvStructBlock? get() = parent as? MvStructBlock val MvStructField.structItem: MvStruct get() = fieldsDefBlock?.parent as MvStruct
9
null
16
52
84d857f75fb471539ef092cc44024d7d4d424860
353
intellij-move
MIT License
app/src/main/kotlin/com/example/myapplication/DetailFragment.kt
Jinhoon-Cho
694,527,358
false
{"Kotlin": 13502}
package com.example.myapplication import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.example.myapplication.databinding.FragmentDetailBinding import viewBinding class DetailFragment: Fragment(R.layout.fragment_detail) { private val binding by viewBinding(FragmentDetailBinding::bind) private val viewModel by viewModels<MyViewModel>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val safeArgs: DetailFragmentArgs by navArgs() val context = safeArgs.context val data = safeArgs.selectedItemData var testMessage = context; if ( data != null) { testMessage = "$context \n${data.context}" } binding.detailTextView.text = testMessage } fun load(selectedItemModel:ItemModel) { } }
0
Kotlin
0
0
d14e8239a7c2c3ecb95b38a444db49b3a9bb0814
985
android_mvvm_example
The Unlicense
core/src/test/kotlin/de/mirkosertic/bytecoder/core/SimpleKotlinTest.kt
mirkosertic
88,152,958
false
{"Maven POM": 17, "Text": 16, "Ignore List": 1, "Markdown": 45, "XML": 5, "Java": 7809, "INI": 132, "Kotlin": 5, "JavaScript": 3, "JSON": 1, "YAML": 4, "HTML": 53, "SVG": 9, "Java Properties": 118, "CSS": 1, "TOML": 1, "Clojure": 1}
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.mirkosertic.bytecoder.core import de.mirkosertic.bytecoder.asm.test.UnitTestRunner import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith @RunWith(UnitTestRunner::class) class SimpleKotlinTest { @Test fun simpleTest() { val result : Float = 10f + 20f assertEquals(30f, result, 0f) } }
38
Java
61
873
9f44bd5488254a381e249e4296232d66565f3a25
954
Bytecoder
Apache License 2.0
platform/workspace/storage/src/com/intellij/platform/workspace/storage/impl/WorkspaceModelDumper.kt
ingokegel
72,937,917
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.platform.workspace.storage.impl import com.intellij.platform.workspace.storage.EntityStorage @Suppress("unused") object WorkspaceModelDumper { fun simpleEntities(store: EntityStorage): String { return buildString { store as AbstractEntityStorage val classToEntities = HashMap<String, String>() store.entitiesByType.entityFamilies.forEachIndexed { i, entities -> if (entities == null) return@forEachIndexed val entityClass = i.findWorkspaceEntity() val ent = buildString { entities.entities.filterNotNull().forEach { this.append(" - ${it.javaClass.simpleName}:${it.id}\n") } } classToEntities[entityClass.simpleName] = ent } classToEntities.keys.sorted().forEach { key -> this.append("$key:\n") this.append("${classToEntities[key]}\n") } } } }
236
null
4946
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
1,045
intellij-community
Apache License 2.0
kotlin-springwebmvc/src/test/kotlin/com/gyejoon/springwebmvc/IntegrationTests.kt
Gyejoon
141,891,522
false
null
package com.gyejoon.springwebmvc import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.boot.test.web.client.getForEntity import org.springframework.http.HttpStatus import org.springframework.test.context.junit.jupiter.SpringExtension /** * Created by <EMAIL> on 2019-03-31 * Blog : http://gyejoong.tistory.com * Github : http://github.com/Gyejoon */ @ExtendWith(SpringExtension::class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class IntegrationTests(@Autowired val restTemplate: TestRestTemplate) { @BeforeAll fun setUp() { println(">> Setup") } @Test fun `Assert blog page title, content and status code`() { val entity = restTemplate.getForEntity<String>("/blog") assertThat(entity.statusCode).isEqualTo(HttpStatus.OK) assertThat(entity.body).contains("<h1>Blog</h1>") } @Test fun `Assert article page title, content and status code`() { val entity = restTemplate.getForEntity<String>("/article/2") assertThat(entity.statusCode).isEqualTo(HttpStatus.OK) assertThat(entity.body).contains("Spring Framework 5 톺아보기") } @AfterAll fun teardown() { println(">> Tear down") } }
0
Kotlin
0
2
2118ea4ccfb857434cc5b22009e58a6126d2c6d9
1,665
kotlin-examples
MIT License
src/test/kotlin/not/a/portal/PinappTest.kt
dumptruckman
2,425,205
true
{"Kotlin": 40109, "Java": 23825}
/* * This file is part of Pinapp. * * Copyright (c) 2017 Jeremy Wood * * 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 not.a.portal import com.dumptruckman.bukkit.utils.PluginFactory import org.junit.Before import org.junit.Assert.* import org.junit.Test class PinappTest { lateinit var pinapp: Pinapp @Before fun setUp() { pinapp = PluginFactory.createPluginInstance() pinapp.onLoad() pinapp.onEnable() } @Test fun testDefaultConfig() { val worldList = pinapp.config.getList("worlds") assertTrue(worldList.isNotEmpty()) assertTrue(worldList[0] is WorldSettings) } }
2
Kotlin
1
1
aded280ae61b23ebfdab48b48ec2a45011927a00
1,688
Pinapp
MIT License
compiler/testData/codegen/box/multiplatform/k2/basic/localIntersectionOverrideWithDefaultParameterInCommonModule.kt
JetBrains
3,432,266
false
null
// LANGUAGE: +MultiPlatformProjects // ISSUE: KT-60850 // WITH_STDLIB // MODULE: common // FILE: common.kt expect class Expect { fun foo(): String } interface Base { fun cancel(s: Expect? = null): String } open class Derived : Base { override fun cancel(s: Expect?): String { return s?.foo() ?: "OK" } } open class AbstractImpl : Derived(), Base fun testCommon(): String { class LocalCommon : AbstractImpl() { fun test(): String { return cancel() } } return LocalCommon().test() } // MODULE: platform()()(common) // FILE: platform.kt class ActualTarget { fun foo(): String = "Fail" } fun testPlatform(): String { class LocalPlatform : AbstractImpl() { fun test(): String { return cancel() } } return LocalPlatform().test() } actual typealias Expect = ActualTarget fun box(): String { if (testCommon() != "OK") return "Fail" return testPlatform() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
975
kotlin
Apache License 2.0
compiler/fir/analysis-tests/testData/resolveWithStdlib/problems/qualifierPriority.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
class AHolder(val a: Int) class F { object foo { // (1) val a: Int = 42 } companion object { // (2) val foo: AHolder = AHolder(52) } } class FF { object foo {} // (1) companion object { // (2) val foo: AHolder = AHolder(52) } } fun main() { F.foo.a // (1) everywhere F.foo // (2) in old FE, (1) in FIR // Why companion? with(F.foo) { a // (2) in old FE, (1) in FIR } FF.foo.<!UNRESOLVED_REFERENCE!>a<!> // (1) everywhere // Why not companion }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
533
kotlin
Apache License 2.0
app/src/main/java/nerd/tuxmobil/fahrplan/congress/wiki/WikiSessionUtils.kt
johnjohndoe
12,616,092
true
{"Gradle": 10, "Markdown": 8, "Java Properties": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 2, "YAML": 4, "Kotlin": 314, "Java": 6, "INI": 1, "Proguard": 2, "XML": 208, "Gradle Kotlin DSL": 1, "SVG": 29}
@file:JvmName("WikiSessionUtils") package nerd.tuxmobil.fahrplan.congress.wiki private val WIKI_LINK_REGEX by lazy { // language=regex Regex("(.*)(https://events.ccc.de/congress/)(\\d{4})(/wiki/index.php/Session:)(.*)") } /** * Returns true if the [receiver][this] contains a link to the * corresponding wiki session; Otherwise false. * * Background information: Self-organized sessions are exported * from the CCC wiki. The export file then contains regular sessions * plus wiki sessions. For wiki sessions the valid link to the wiki * is contained in the links whereas for regular sessions the link * is generated based on the session id. * Export script: https://github.com/voc/schedule */ fun String.containsWikiLink(): Boolean = matches(WIKI_LINK_REGEX)
63
Kotlin
99
27
4b91d7dcdfbc8de965a928b3ebfbfe595ec06b3f
780
CampFahrplan
Apache License 2.0
src/main/kotlin/no/nav/arbeidsgiver/altinnrettigheter/proxy/klient/AltinnrettigheterProxyKlientConfig.kt
navikt
252,563,839
false
null
package no.nav.arbeidsgiver.altinnrettigheter.proxy.klient data class AltinnrettigheterProxyKlientConfig @JvmOverloads constructor ( val proxy: ProxyConfig, val altinn: AltinnConfig? = null, ) data class AltinnConfig( val url: String, val altinnApiKey: String, val altinnApiGwApiKey: String ) data class ProxyConfig( val consumerId: String?, val url: String )
2
Kotlin
0
1
c28f5aba9078605332fb231d08241b41d8d30057
418
altinn-rettigheter-proxy-klient
MIT License
app/src/main/java/com/tory/dmzj/ui/LoginActivity.kt
ToryCrox
126,707,444
false
{"Markdown": 1, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Kotlin": 44, "XML": 36, "Java": 9}
package com.tory.dmzj.ui import android.Manifest.permission.READ_CONTACTS import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.annotation.TargetApi import android.app.LoaderManager.LoaderCallbacks import android.content.CursorLoader import android.content.Loader import android.content.pm.PackageManager import android.database.Cursor import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.ContactsContract import android.support.design.widget.Snackbar import android.text.TextUtils import android.view.View import android.view.inputmethod.EditorInfo import android.widget.ArrayAdapter import android.widget.TextView import com.tory.dmzj.R import com.tory.dmzj.event.LoginSuccessEvent import com.tory.dmzj.ext.toast import com.tory.dmzj.helper.SpHelper import com.tory.dmzj.networks.RetrofitHelper import com.tory.dmzj.ui.base.BaseSliderActivity import com.tory.dmzj.utils.L import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_login.* import org.greenrobot.eventbus.EventBus import java.util.* /** * A login screen that offers login via email/password. */ class LoginActivity : BaseSliderActivity(), LoaderCallbacks<Cursor> { override fun bindLayout() = R.layout.activity_login override fun initView() { super.initView() email.setText("<EMAIL>") password.setText("<PASSWORD>") } override fun doBusiness(savedInstanceState: Bundle?) { populateAutoComplete() password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ -> if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) { checkLogin() return@OnEditorActionListener true } false }) email_sign_in_button.setOnClickListener { attemptLogin() } } private fun populateAutoComplete() { if (!mayRequestContacts()) { return } loaderManager.initLoader(0, null, this) } private fun mayRequestContacts(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true } if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { return true } if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { Snackbar.make(email, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, { requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS) }) } else { requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS) } return false } /** * Callback received when a permissions request has been completed. */ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { populateAutoComplete() } } } private fun checkLogin(): View? { // Reset errors. email.error = null password.error = null // Store values at the time of the login attempt. val emailStr = email.text.toString() val passwordStr = password.text.toString() var focusView: View? = null // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(passwordStr) && !isPasswordValid(passwordStr)) { password.error = getString(R.string.error_invalid_password) focusView = password } // Check for a valid email address. if (TextUtils.isEmpty(emailStr)) { email.error = getString(R.string.error_field_required) focusView = email } else if (!isEmailValid(emailStr)) { email.error = getString(R.string.error_invalid_email) focusView = email } focusView?.requestFocus() return focusView } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ private fun attemptLogin() { var focusView: View? = checkLogin() var cancel = focusView != null // Store values at the time of the login attempt. val emailStr = email.text.toString() val passwordStr = <PASSWORD>() if (!cancel) { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true) login(emailStr, passwordStr) } } private fun login(emailStr: String, passwordStr: String) { RetrofitHelper.userService.login(emailStr, passwordStr) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({userModel -> L.d("login onNext"+userModel) if(userModel != null){ toast("登陆成功! ${userModel.data?.nickname}") SpHelper.setUser(userModel) EventBus.getDefault().post(LoginSuccessEvent()) finish() } },{e->L.e("login", e)},{ L.d("login onCompleted") showProgress(false) }) } private fun isEmailValid(email: String): Boolean { return email.contains("@") } private fun isPasswordValid(password: String): Boolean { return password.length > 4 } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private fun showProgress(show: Boolean) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong() login_form.visibility = if (show) View.GONE else View.VISIBLE login_form.animate() .setDuration(shortAnimTime) .alpha((if (show) 0 else 1).toFloat()) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { login_form.visibility = if (show) View.GONE else View.VISIBLE } }) login_progress.visibility = if (show) View.VISIBLE else View.GONE login_progress.animate() .setDuration(shortAnimTime) .alpha((if (show) 1 else 0).toFloat()) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { login_progress.visibility = if (show) View.VISIBLE else View.GONE } }) } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. login_progress.visibility = if (show) View.VISIBLE else View.GONE login_form.visibility = if (show) View.GONE else View.VISIBLE } } /** * 读取手机中Email */ override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> { return CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact. Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses. ContactsContract.Contacts.Data.MIMETYPE + " = ?", arrayOf(ContactsContract.CommonDataKinds.Email .CONTENT_ITEM_TYPE), // Show primary email addresses first. Note that there won't be // a primary email address if the user hasn't specified one. ContactsContract.Contacts.Data.IS_PRIMARY + " DESC") } override fun onLoadFinished(cursorLoader: Loader<Cursor>, cursor: Cursor) { val emails = ArrayList<String>() cursor.moveToFirst() while (!cursor.isAfterLast) { emails.add(cursor.getString(ProfileQuery.ADDRESS)) cursor.moveToNext() } addEmailsToAutoComplete(emails) } override fun onLoaderReset(cursorLoader: Loader<Cursor>) { } private fun addEmailsToAutoComplete(emailAddressCollection: List<String>) { //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. val adapter = ArrayAdapter(this@LoginActivity, android.R.layout.simple_dropdown_item_1line, emailAddressCollection) email.setAdapter(adapter) } object ProfileQuery { val PROJECTION = arrayOf( ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY) val ADDRESS = 0 val IS_PRIMARY = 1 } companion object { /** * Id to identity READ_CONTACTS permission request. */ private val REQUEST_READ_CONTACTS = 0 /** * A dummy authentication store containing known user names and passwords. * TODO: remove after connecting to a real authentication system. */ private val DUMMY_CREDENTIALS = arrayOf("<EMAIL>:hello", "<EMAIL>:world") } }
0
Kotlin
0
0
757716bd6e93e0576a69cc6c12f304795e8ff272
10,140
Dmzj
Apache License 2.0
featureHome/src/main/java/com/tapptitude/featurehome/di/Modules.kt
tapptitude
462,275,098
false
null
package com.tapptitude.featurehome.di import com.tapptitude.featurehome.presentation.HomeViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val homeModules = module { viewModel { HomeViewModel(loadImageUseCase = get(), sessionManager = get()) } }
8
Kotlin
0
4
ca3dafc110fe2370eb088a73421d8045bdb89c91
287
AndroidKotlinMVVMTemplate
MIT License
Corona-Warn-App/src/deviceForTesters/java/de/rki/coronawarnapp/test/ccl/CclTestModule.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.test.ccl import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import de.rki.coronawarnapp.util.viewmodel.CWAViewModel import de.rki.coronawarnapp.util.viewmodel.CWAViewModelFactory import de.rki.coronawarnapp.util.viewmodel.CWAViewModelKey @Module abstract class CclTestModule { @Binds @IntoMap @CWAViewModelKey(CclTestViewModel::class) abstract fun dscTest(factory: CclTestViewModel.Factory): CWAViewModelFactory<out CWAViewModel> }
6
null
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
505
cwa-app-android
Apache License 2.0
app/src/main/java/org/p2p/wallet/swap/interactor/orca/OrcaRouteInteractor.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.wallet.swap.interactor.orca import org.p2p.solanaj.core.Account import org.p2p.solanaj.core.PublicKey import org.p2p.solanaj.core.TransactionInstruction import org.p2p.solanaj.kits.AccountInstructions import org.p2p.solanaj.programs.TokenProgram import org.p2p.solanaj.programs.TokenSwapProgram import org.p2p.wallet.swap.interactor.SwapInstructionsInteractor import org.p2p.wallet.swap.model.AccountBalance import org.p2p.wallet.swap.model.orca.OrcaPool import org.p2p.wallet.swap.model.orca.OrcaPools import org.p2p.wallet.swap.model.orca.OrcaPoolsPair import org.p2p.wallet.swap.model.orca.OrcaRoute import org.p2p.wallet.swap.model.orca.OrcaRoutes import org.p2p.wallet.swap.model.orca.OrcaSwapInfo import org.p2p.wallet.swap.model.orca.OrcaTokens import org.p2p.wallet.swap.repository.OrcaSwapRepository import org.p2p.wallet.utils.Constants.WRAPPED_SOL_MINT import org.p2p.wallet.utils.toLamports import org.p2p.wallet.utils.toPublicKey import java.math.BigDecimal import java.math.BigInteger class OrcaRouteInteractor( private val orcaSwapRepository: OrcaSwapRepository, private val instructionsInteractor: SwapInstructionsInteractor ) { companion object { private const val PATH_STABLE = "[stable]" } private val balancesCache = mutableMapOf<String, AccountBalance>() // Construct exchange suspend fun constructExchange( pool: OrcaPool, tokens: OrcaTokens, owner: Account, fromTokenPubkey: String, toTokenPubkey: String?, amount: BigInteger, slippage: Double, feeRelayerFeePayer: PublicKey?, minRenExemption: BigInteger ): AccountInstructions { val fromMint = tokens[pool.tokenAName]?.mint?.toPublicKey() val toMint = tokens[pool.tokenBName]?.mint?.toPublicKey() val fromTokenPubkey = fromTokenPubkey.toPublicKey() if (fromMint == null || toMint == null) { throw IllegalStateException("Pool mints are not found") } // Create fromTokenAccount when needed val sourceAccountInstructions = if (fromMint.toBase58() == WRAPPED_SOL_MINT && owner.publicKey.equals(fromTokenPubkey)) { instructionsInteractor.prepareCreatingWSOLAccountAndCloseWhenDone( from = owner.publicKey, amount = amount, payer = feeRelayerFeePayer ?: owner.publicKey ) } else { AccountInstructions(fromTokenPubkey) } // If necessary, create a TokenAccount for the output token // If destination token is Solana, create WSOL if needed val destinationAccountInstructions = if (toMint.toBase58() == WRAPPED_SOL_MINT) { val toTokenPublicKey = toTokenPubkey?.toPublicKey() if (toTokenPublicKey != null && !toTokenPublicKey.equals(owner.publicKey)) { // wrapped sol has already been created, just return it, then close later val cleanupInstructions = listOf( TokenProgram.closeAccountInstruction( TokenProgram.PROGRAM_ID, toTokenPublicKey, owner.publicKey, owner.publicKey ) ) AccountInstructions( account = toTokenPublicKey, cleanupInstructions = cleanupInstructions ) } else { // create wrapped sol instructionsInteractor.prepareCreatingWSOLAccountAndCloseWhenDone( from = owner.publicKey, amount = BigInteger.ZERO, payer = owner.publicKey ) } } else if (toTokenPubkey != null) { // If destination is another token and has already been created AccountInstructions(toTokenPubkey.toPublicKey()) } else { // create wrapped sol instructionsInteractor.prepareForCreatingAssociatedTokenAccount( owner = owner.publicKey, mint = toMint, feePayer = owner.publicKey, closeAfterward = false ) } // form instructions val instructions = mutableListOf<TransactionInstruction>() val cleanupInstructions = mutableListOf<TransactionInstruction>() var accountCreationFee: BigInteger = BigInteger.ZERO // source instructions += sourceAccountInstructions.instructions cleanupInstructions += sourceAccountInstructions.cleanupInstructions if (sourceAccountInstructions.instructions.isNotEmpty()) { accountCreationFee += minRenExemption } // destination instructions += destinationAccountInstructions.instructions cleanupInstructions += destinationAccountInstructions.cleanupInstructions if (destinationAccountInstructions.instructions.isNotEmpty()) { accountCreationFee += minRenExemption } // swap instructions val minAmountOut = pool.getMinimumAmountOut(amount, slippage) ?: throw IllegalStateException("Couldn't estimate minimum out amount") val swapInstruction = TokenSwapProgram.swapInstruction( pool.account, pool.authority, owner.publicKey, sourceAccountInstructions.account, pool.tokenAccountA, pool.tokenAccountB, destinationAccountInstructions.account, pool.poolTokenMint, pool.feeAccount, pool.hostFeeAccount, TokenProgram.PROGRAM_ID, pool.swapProgramId, amount, minAmountOut ) instructions += swapInstruction val signers = mutableListOf<Account>() signers += sourceAccountInstructions.signers signers += destinationAccountInstructions.signers return AccountInstructions( destinationAccountInstructions.account, instructions, cleanupInstructions, signers ) } suspend fun loadBalances(currentRoutes: List<OrcaRoute>, infoPools: OrcaPools?) { val balanceAccounts = currentRoutes .flatten() .flatMap { listOfNotNull( infoPools?.get(it)?.tokenAccountA?.toBase58(), infoPools?.get(it)?.tokenAccountB?.toBase58() ) } .distinct() .filterNot { balancesCache.containsKey(it) } if (balanceAccounts.isEmpty()) return orcaSwapRepository.loadTokenBalances(balanceAccounts).forEach { (publicKey, balance) -> balancesCache[publicKey] = balance } } suspend fun getPools( infoPools: OrcaPools?, route: OrcaRoute, fromTokenName: String, toTokenName: String ): List<OrcaPool> { if (route.isEmpty()) return emptyList() val pools = route.mapNotNull { fixedPool(infoPools, it) }.toMutableList() // modify orders if (pools.size == 2) { // reverse order of the 2 pools // Ex: Swap from SOCN -> BTC, but paths are // [ // "BTC/SOL[aquafarm]", // "SOCN/SOL[stable][aquafarm]" // ] // Need to change to // [ // "SOCN/SOL[stable][aquafarm]", // "BTC/SOL[aquafarm]" // ] if (pools[0].tokenAName != fromTokenName && pools[0].tokenBName != fromTokenName) { val temp = pools[0] pools[0] = pools[1] pools[1] = temp } } // reverse token A and token B in pool if needed for (i in 0 until pools.size) { if (i == 0) { var pool = pools[0] if (pool.tokenAName.fixedTokenName() != fromTokenName.fixedTokenName()) { pool = pool.reversed } pools[0] = pool } if (i == 1) { var pool = pools[1] if (pool.tokenBName.fixedTokenName() != toTokenName.fixedTokenName()) { pool = pool.reversed } pools[1] = pool } } return pools } private suspend fun fixedPool( infoPools: OrcaPools?, path: String // Ex. BTC/SOL[aquafarm][stable]){} ): OrcaPool? { val pool = infoPools?.get(path) ?: return null pool.isStable = path.contains(PATH_STABLE) // get balances var tokenABalance = pool.tokenABalance ?: balancesCache[pool.tokenAccountA.toBase58()] var tokenBBalance = pool.tokenBBalance ?: balancesCache[pool.tokenAccountB.toBase58()] if (tokenABalance == null || tokenBBalance == null) { tokenABalance = orcaSwapRepository.loadTokenBalance(pool.tokenAccountA) tokenBBalance = orcaSwapRepository.loadTokenBalance(pool.tokenAccountB) balancesCache[pool.tokenAccountA.toBase58()] = tokenABalance balancesCache[pool.tokenAccountB.toBase58()] = tokenBBalance } pool.tokenABalance = tokenABalance pool.tokenBBalance = tokenBBalance return pool } // Find possible destination token (symbol) // - Parameter fromTokenName: from token name (symbol) // - Returns: List of token symbols that can be swapped to fun findPossibleDestinations( info: OrcaSwapInfo, fromTokenName: String ): List<String> { return findRoutes(info, fromTokenName, null).keys .mapNotNull { key -> key.split("/").find { it != fromTokenName } } .distinct() .sorted() } fun calculateLiquidityProviderFees( poolsPair: OrcaPoolsPair, inputAmount: BigDecimal, slippage: Double ): List<BigInteger> { if (poolsPair.size < 1) return emptyList() val pool0 = poolsPair[0] val sourceDecimals = pool0.tokenABalance?.decimals ?: throw IllegalStateException("Token A balance is null") val inputAmount = inputAmount.toLamports(sourceDecimals) // 1 pool val result = mutableListOf<BigInteger>() val fee0 = pool0.calculatingFees(inputAmount) result.add(fee0) // 2 pool if (poolsPair.size == 2) { val pool1 = poolsPair[1] val inputAmount = pool0.getMinimumAmountOut(inputAmount, slippage) if (inputAmount != null) { val fee1 = pool1.calculatingFees(inputAmount) result.add(fee1) } } return result } // / Find routes for from and to token name, aka symbol fun findRoutes( info: OrcaSwapInfo, fromTokenName: String?, toTokenName: String? ): OrcaRoutes { // if fromToken isn't selected if (fromTokenName.isNullOrEmpty()) return mutableMapOf() // if toToken isn't selected if (toTokenName == null) { // get all routes that have token A return info.routes.filter { it.key.split("/").contains(fromTokenName) } as OrcaRoutes } // get routes with fromToken and toToken val pair = listOf(fromTokenName, toTokenName) val validRoutesNames = listOf( pair.joinToString("/"), pair.reversed().joinToString("/") ) return info.routes.filter { validRoutesNames.contains(it.key) } as OrcaRoutes } } private fun String.fixedTokenName(): String = this.split("[").first()
8
Kotlin
6
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
11,821
key-app-android
MIT License
ScaffoldApp/app/src/main/java/com/zymat/scaffoldapp/MainActivity.kt
Zymat-dk
581,147,430
false
null
package com.zymat.scaffoldapp import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import android.os.Bundle import android.provider.MediaStore import android.widget.ImageButton import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.zymat.scaffoldapp.ml.ScaffoldModel import org.tensorflow.lite.support.common.FileUtil import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.support.image.TensorImage import org.tensorflow.lite.support.image.ops.ResizeOp class MainActivity : AppCompatActivity() { private lateinit var button: ImageButton // Knap til at vælge billede lateinit var imageView: ImageView // ImageView viser billedet lateinit var bitmap: Bitmap // Bitmap af billedet lateinit var model: ScaffoldModel // TFLite model til at detektere objekter lateinit var labels: List<String> // Liste af labels til modellen ("Hjul") private val paint = Paint() // Paint objekt til at tegne på billedet private val imageProcessor: ImageProcessor = // Image processor til at ændre billedets størrelse ImageProcessor.Builder().add( ResizeOp( 300, // Billedets størrelse bliver 300x300 300, ResizeOp.ResizeMethod.BILINEAR ) ).build() override fun onCreate(savedInstanceState: Bundle?) { // Når appen startes super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Sætter layout til activity_main.xml val intent = Intent() // Intentionen om at vælge et billede intent.type = "image/*" // Det skal være et billede intent.action = Intent.ACTION_GET_CONTENT // Vi vil have et billede fra brugeren // Henter labels og model labels = FileUtil.loadLabels(this, "labels.txt") model = ScaffoldModel.newInstance(this) // Finder ImageView og knap imageView = findViewById(R.id.imageV) button = findViewById(R.id.btn) button.setOnClickListener {// Når der trykkes på knappen startActivityForResult(intent, 101) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // Når der er valgt et billede super.onActivityResult(requestCode, resultCode, data) if (requestCode == 101) { // Hvis det er den rigtige statuskode val uri = data?.data // Finder billedets URI // Læser billedet fra URI bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, uri) getPredictions() // Finder objekter i billedet } } override fun onDestroy() { // Når appen lukkes super.onDestroy() model.close() // Lukker modellen, så den ikke bruger mere hukommelse } private fun getPredictions() { // Finder objekter i billedet // Start med at ændre billedet til et TensorImage var image = TensorImage.fromBitmap(bitmap) image = imageProcessor.process(image) // Ændrer billedet til 300x300 // Finder objekter i billedet val outputs = model.process(image) // Finder resultaterne fra modellen val detectionResults = outputs.detectionResultList // Laver en kopi af billedet, så vi kan tegne på det val mutable = bitmap.copy(Bitmap.Config.ARGB_8888, true) val canvas = Canvas(mutable) // Man kan tegne på canvas val w = mutable.width // Finder billedets bredde val h = mutable.height // Finder billedets højde // Finder skaleringsfaktorerne for billedet val wScale = w / 300 val hScale = h / 300 // Sætter paint objektets egenskaber paint.textSize = h / 15f paint.strokeWidth = h / 85f for (result in detectionResults) { // For hvert resultat fra modellen // Finder resultatets lokation, kategori og score val location = result.locationAsRectF; val category = result.categoryAsString; val score = result.scoreAsFloat; if (score < 0.88) { // Hvis scoren er for lav, så spring over continue } println("Score: $score") // Udskriver scoren i loggen // Finder farven til firkanten, afhængig af kategorien paint.color = getRectColor(category) // Sætter paint objektet til at tegne en firkant paint.style = Paint.Style.STROKE // Tegner en firkant canvas.drawRect( RectF( location.left * wScale, location.top * hScale, location.right * wScale, location.bottom * hScale ), paint ) } imageView.setImageBitmap(mutable) // Viser billedet i ImageView } private fun getRectColor(category: String): Int { // Finder farven til firkanten, afhængig af kategorien val color: Int = when (category){ "Hjul" -> R.color.sea // Hvis kategorien er "Hjul", så bliver farven "sea" else -> R.color.white // Ellers bliver farven "white" } return ContextCompat.getColor(this, color) // Returnerer farven } }
0
Kotlin
0
1
fb79616c4c1e5cfc19bba53e7ed05c7824c79ec9
5,476
Scaffold-ML
MIT License
app/src/main/java/com/bpdevop/mediccontrol/ui/screens/vaccination/VaccinationScreen.kt
bpdevop
839,980,935
false
{"Kotlin": 693059}
package com.bpdevop.mediccontrol.ui.screens.vaccination import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.bpdevop.mediccontrol.R import com.bpdevop.mediccontrol.data.model.Vaccine @Composable fun VaccinationScreen( patientId: String, onSaveSuccess: () -> Unit, onEditVaccine: (Vaccine) -> Unit, ) { var selectedTab by remember { mutableIntStateOf(0) } val tabs = listOf( stringResource(id = R.string.vaccination_screen_new_vaccine), stringResource(id = R.string.vaccination_screen_vaccine_history) ) Column(modifier = Modifier.fillMaxSize()) { TabRow( selectedTabIndex = selectedTab, modifier = Modifier.fillMaxWidth(), ) { tabs.forEachIndexed { index, title -> Tab( text = { Text(text = title) }, selected = selectedTab == index, onClick = { selectedTab = index } ) } } when (selectedTab) { 0 -> NewVaccineScreen( patientId = patientId, onVaccineAdded = onSaveSuccess ) 1 -> VaccinationHistoryScreen(patientId, onEditVaccine = onEditVaccine) } } }
0
Kotlin
0
0
68aa078786199aca908f03965c617f096d91a384
1,785
MedicControl
MIT License
modules/library-remote-config/src/main/kotlin/com/leinardi/forlago/library/remoteconfig/interactor/GetKillSwitchStreamInteractorImpl.kt
leinardi
405,185,933
false
null
/* * Copyright 2024 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.leinardi.forlago.library.remoteconfig.interactor import android.app.Application import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.lifecycleScope import com.google.firebase.FirebaseApp import com.google.firebase.remoteconfig.ConfigUpdate import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.firebase.remoteconfig.configUpdates import com.leinardi.forlago.library.annotation.AutoBind import com.leinardi.forlago.library.remoteconfig.api.interactor.GetFeatureFlagInteractor import com.leinardi.forlago.library.remoteconfig.api.interactor.GetKillSwitchStreamInteractor import com.leinardi.forlago.library.remoteconfig.api.model.RemoteConfigValue import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.tasks.await import javax.inject.Inject import javax.inject.Singleton @AutoBind @Singleton internal class GetKillSwitchStreamInteractorImpl @Inject constructor( application: Application, private val getFeatureFlagInteractor: GetFeatureFlagInteractor, ) : GetKillSwitchStreamInteractor { private val isFirebaseInitialized = FirebaseApp.getApps(application).isNotEmpty() private var configUpdatesFlow: SharedFlow<ConfigUpdate> = MutableSharedFlow() init { if (isFirebaseInitialized) { val remoteConfig = FirebaseRemoteConfig.getInstance() configUpdatesFlow = remoteConfig.configUpdates .onEach { remoteConfig.activate().await() } .shareIn( scope = ProcessLifecycleOwner.get().lifecycleScope, started = SharingStarted.Eagerly, ) } } override fun getBoolean(key: String): Flow<RemoteConfigValue.Boolean> = getConfigUpdatesStream(key) { getFeatureFlagInteractor.getBoolean(key) } override fun getByteArray(key: String): Flow<RemoteConfigValue.ByteArray> = getConfigUpdatesStream(key) { getFeatureFlagInteractor.getByteArray(key) } override fun getDouble(key: String): Flow<RemoteConfigValue.Double> = getConfigUpdatesStream(key) { getFeatureFlagInteractor.getDouble(key) } override fun getLong(key: String): Flow<RemoteConfigValue.Long> = getConfigUpdatesStream(key) { getFeatureFlagInteractor.getLong(key) } override fun getString(key: String): Flow<RemoteConfigValue.String> = getConfigUpdatesStream(key) { getFeatureFlagInteractor.getString(key) } private fun <T> getConfigUpdatesStream(key: String, onActivated: () -> T): Flow<T> = configUpdatesFlow .onSubscription { emit(ConfigUpdate.create(setOf(key))) } // emit current local value on subscription .filter { it.updatedKeys.contains(key) } .map { onActivated() } }
3
null
3
9
abe5eb3017f3365bbb1b61e74f2ef8f34097d411
3,778
Forlago
Apache License 2.0
src/main/kotlin/io/foxcapades/lib/json4k/jackson/wrap/JacksonJsonString.kt
Foxcapades
447,448,916
false
{"Kotlin": 55139}
package io.foxcapades.lib.json4k.jackson.wrap import com.fasterxml.jackson.databind.node.TextNode import io.foxcapades.lib.json4k.JsonElementType import io.foxcapades.lib.json4k.JsonString internal class JacksonJsonString(raw: TextNode) : JsonBase<TextNode>(raw), JsonString { override val type = JsonElementType.String override val isBlank = raw.textValue().isBlank() override val isEmpty = raw.textValue().isEmpty() override val isNotBlank = raw.textValue().isNotBlank() override val isNotEmpty = raw.textValue().isNotEmpty() override val length = raw.textValue().length override fun binaryValue(): ByteArray { try { return raw.binaryValue() } catch (e: Exception) { throw JsonString.NonBinaryStringException() } } override fun stringValue(): String = raw.textValue() override fun ifString(action: JsonString.() -> Unit) { action(this) } }
0
Kotlin
0
0
c7ba690cbe0f2be795376e0931bb34773d7a4678
903
Json4k-Jackson
MIT License
biz/src/commonMain/kotlin/validation/ValidateIdProperFormat.kt
crowdproj
518,714,370
false
null
package com.crowdproj.rating.biz.validation import com.crowdproj.kotlin.cor.ICorAddExecDsl import com.crowdproj.kotlin.cor.handlers.worker import com.crowdproj.rating.common.CwpRatingContext import com.crowdproj.rating.common.helper.errorValidation import com.crowdproj.rating.common.helper.fail import com.crowdproj.rating.common.model.CwpRatingId fun ICorAddExecDsl<CwpRatingContext>.validateIdProperFormat(title: String) = worker { this.title = title val regExp = Regex("^[0-9]+$") on { ratingValidating.id != CwpRatingId.NONE && !ratingValidating.id.asString().matches(regExp) } handle { fail( errorValidation( field = "id", violationCode = "badFormat", description = "value must contain only numbers" ) ) } }
0
Kotlin
2
0
680c52b3be9161b699c635fc032a0289ce71a239
824
crowdproj-ratings
Apache License 2.0
src/main/kotlin/org/jetbrains/bio/genome/query/Query.kt
JetBrains-Research
173,494,429
false
{"Kotlin": 1231142}
package org.jetbrains.bio.genome.query import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import java.util.function.Function /** * Named [Function] implementation capable of caching the results. */ interface Query<I, O> : Function<I, O> { /** * Returns unique identifier suitable for use in a file name. */ val id: String /** * Returns a human-readable description for this query. */ val description: String get() = id } /** A query which caches the result of [apply]. */ abstract class CachingQuery<I : Any, O> : Query<I, O> { abstract fun getUncached(input: I): O private val cache: Cache<I, O> = CacheBuilder.newBuilder().build() override fun apply(t: I): O = cache.get(t) { getUncached(t) } }
1
Kotlin
3
31
7ac98c8a413bc163da91fa9263af0a32dc7ffac5
783
bioinf-commons
MIT License
core/src/main/kotlin/org/jetbrains/kotlinx/dataframe/api/ColumnsSelectionDsl.kt
Kotlin
259,256,617
false
null
package org.jetbrains.kotlinx.dataframe.api import org.jetbrains.kotlinx.dataframe.ColumnsSelector import org.jetbrains.kotlinx.dataframe.DataColumn import org.jetbrains.kotlinx.dataframe.DataFrame import org.jetbrains.kotlinx.dataframe.DataRow import org.jetbrains.kotlinx.dataframe.columns.ColumnPath import org.jetbrains.kotlinx.dataframe.columns.ColumnSet import org.jetbrains.kotlinx.dataframe.columns.ColumnsResolver import org.jetbrains.kotlinx.dataframe.columns.SingleColumn import org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl import org.jetbrains.kotlinx.dataframe.documentation.DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate import org.jetbrains.kotlinx.dataframe.documentation.Indent import org.jetbrains.kotlinx.dataframe.documentation.LineBreak import org.jetbrains.kotlinx.dataframe.documentation.SelectingColumns import org.jetbrains.kotlinx.dataframe.impl.DataFrameReceiver import org.jetbrains.kotlinx.dataframe.impl.columns.ColumnsList import org.jetbrains.kotlinx.dataframe.util.COL_SELECT_DSL_LIST_DATACOLUMN_GET import org.jetbrains.kotlinx.dataframe.util.COL_SELECT_DSL_LIST_DATACOLUMN_GET_REPLACE import kotlin.experimental.ExperimentalTypeInference import kotlin.reflect.KProperty /** [Columns Selection DSL][ColumnsSelectionDsl] */ internal interface ColumnsSelectionDslLink @Suppress("UNCHECKED_CAST") @PublishedApi internal fun <T> ColumnsSelectionDsl<T>.asSingleColumn(): SingleColumn<DataRow<T>> = this as SingleColumn<DataRow<T>> /** * [DslMarker] for [ColumnsSelectionDsl] to prevent accessors being used across scopes for nested * [ColumnsSelectionDsl.select] calls. */ @DslMarker @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION) public annotation class ColumnsSelectionDslMarker /** * ## Columns Selection DSL * {@include [SelectingColumns.Dsl.WithExample]} * {@set [SelectingColumns.OperationArg] [select][DataFrame.select]} * * @comment This interface be safely cast to [SingleColumn] across the library because it's always * implemented in combination with [DataFrameReceiver] which is a [SingleColumn] itself. * It does not directly implement [SingleColumn] for DSL purposes. */ @ColumnsSelectionDslMarker public interface ColumnsSelectionDsl<out T> : /* SingleColumn<DataRow<T>> */ ColumnSelectionDsl<T>, // first {}, firstCol() FirstColumnsSelectionDsl, // last {}, lastCol() LastColumnsSelectionDsl, // single {}, singleCol() SingleColumnsSelectionDsl, // col(name), col(5), [5] ColColumnsSelectionDsl, // valueCol(name), valueCol(5) ValueColColumnsSelectionDsl, // frameCol(name), frameCol(5) FrameColColumnsSelectionDsl, // colGroup(name), colGroup(5) ColGroupColumnsSelectionDsl, // cols {}, cols(), cols(colA, colB), cols(1, 5), cols(1..5), [{}] ColsColumnsSelectionDsl, // colA.."colB" ColumnRangeColumnsSelectionDsl, // valueCols {}, valueCols() ValueColsColumnsSelectionDsl, // frameCols {}, frameCols() FrameColsColumnsSelectionDsl, // colGroups {}, colGroups() ColGroupsColumnsSelectionDsl, // colsOfKind(Value, Frame) {}, colsOfKind(Value, Frame) ColsOfKindColumnsSelectionDsl, // all(Cols), allAfter(colA), allBefore(colA), allFrom(colA), allUpTo(colA) AllColumnsSelectionDsl, // colsAtAnyDepth {}, colsAtAnyDepth() ColsAtAnyDepthColumnsSelectionDsl, // colsInGroups {}, colsInGroups() ColsInGroupsColumnsSelectionDsl, // take(5), takeLastCols(2), takeLastWhile {}, takeColsWhile {} TakeColumnsSelectionDsl, // drop(5), dropLastCols(2), dropLastWhile {}, dropColsWhile {} DropColumnsSelectionDsl, // select {}, TODO due to String.invoke conflict this cannot be moved out of ColumnsSelectionDsl SelectColumnsSelectionDsl, // except(), allExcept {}, allColsExcept {} AllExceptColumnsSelectionDsl, // nameContains(""), colsNameContains(""), nameStartsWith(""), childrenNameEndsWith("") ColumnNameFiltersColumnsSelectionDsl, // withoutNulls(), colsWithoutNulls() WithoutNullsColumnsSelectionDsl, // distinct() DistinctColumnsSelectionDsl, // none() NoneColumnsSelectionDsl, // colsOf<>(), colsOf<> {} ColsOfColumnsSelectionDsl, // simplify() SimplifyColumnsSelectionDsl, // filter {} FilterColumnsSelectionDsl, // colSet and colB AndColumnsSelectionDsl, // colA named "colB", colA into "colB" RenameColumnsSelectionDsl, // expr {} ExprColumnsSelectionDsl { /** * ## {@include [ColumnsSelectionDslLink]} Grammar * * @include [DslGrammarTemplateColumnsSelectionDsl.DslGrammarTemplate] * * {@set [DslGrammarTemplate.DefinitionsArg] * {@include [DslGrammarTemplate.ColumnGroupNoSingleColumnDef]} * * {@include [DslGrammarTemplate.ColumnSelectorDef]} * * {@include [DslGrammarTemplate.ColumnsSelectorDef]} * * {@include [DslGrammarTemplate.ColumnDef]} * * {@include [DslGrammarTemplate.ColumnGroupDef]} * * {@include [DslGrammarTemplate.ColumnNoAccessorDef]} * * {@include [DslGrammarTemplate.ColumnOrColumnSetDef]} * * {@include [DslGrammarTemplate.ColumnSetDef]} * * {@include [DslGrammarTemplate.ColumnsResolverDef]} * * {@include [DslGrammarTemplate.ConditionDef]} * * {@include [DslGrammarTemplate.ColumnExpressionDef]} * * {@include [DslGrammarTemplate.IgnoreCaseDef]} * * {@include [DslGrammarTemplate.IndexDef]} * * {@include [DslGrammarTemplate.IndexRangeDef]} * * {@include [DslGrammarTemplate.InferDef]} * * {@include [DslGrammarTemplate.ColumnKindDef]} * * {@include [DslGrammarTemplate.KTypeDef]} * * {@include [DslGrammarTemplate.NameDef]} * * {@include [DslGrammarTemplate.NumberDef]} * * {@include [DslGrammarTemplate.RegexDef]} * * {@include [DslGrammarTemplate.SingleColumnDef]} * * {@include [DslGrammarTemplate.ColumnTypeDef]} * * {@include [DslGrammarTemplate.TextDef]} * } * {@comment Plain DSL: -------------------------------------------------------------------------------------------- } * {@set [DslGrammarTemplate.PlainDslFunctionsArg] * * {@include [DslGrammarTemplate.ColumnRef]} {@include [ColumnRangeColumnsSelectionDsl.Grammar.PlainDslName]} {@include [DslGrammarTemplate.ColumnRef]} * * `|` **`this`**`/`**`it`**[**`[`**][cols]{@include [DslGrammarTemplate.ColumnRef]}**`,`**` .. `[**`]`**][cols] * * `|` **`this`**`/`**`it`**[**`[`**][cols]**`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`**[**`]`**][cols] * * `|` {@include [AllColumnsSelectionDsl.Grammar.PlainDslName]}**`()`** * * `|` **`all`**`(`{@include [AllColumnsSelectionDsl.Grammar.Before]}`|`{@include [AllColumnsSelectionDsl.Grammar.After]}`|`{@include [AllColumnsSelectionDsl.Grammar.From]}`|`{@include [AllColumnsSelectionDsl.Grammar.UpTo]}`)` `(` **`(`**{@include [DslGrammarTemplate.ColumnRef]}**`)`** `|` **`{`** {@include [DslGrammarTemplate.ColumnSelectorRef]} **`\}`** `)` * * `|` {@include [AllExceptColumnsSelectionDsl.Grammar.PlainDslName]} **`{ `**{@include [DslGrammarTemplate.ColumnsSelectorRef]}**` \}`** * * `|` {@include [AllExceptColumnsSelectionDsl.Grammar.PlainDslName]}**`(`**{@include [DslGrammarTemplate.ColumnRef]}**`,`**` ..`**`)`** * * `|` {@include [DslGrammarTemplate.ColumnOrColumnSetRef]} {@include [AndColumnsSelectionDsl.Grammar.InfixName]}` [ `**`{`**` ] `{@include [DslGrammarTemplate.ColumnOrColumnSetRef]}` [ `**`\}`**` ] ` * * `|` {@include [DslGrammarTemplate.ColumnOrColumnSetRef]}{@include [AndColumnsSelectionDsl.Grammar.Name]} **`(`**`|`**`{ `**{@include [DslGrammarTemplate.ColumnOrColumnSetRef]}**` \}`**`|`**`)`** * * `|` `(` * {@include [ColColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [ValueColColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [FrameColColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [ColGroupColumnsSelectionDsl.Grammar.PlainDslName]} * `)[`**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**`]`**`(`**{@include [DslGrammarTemplate.ColumnRef]}` | `{@include [DslGrammarTemplate.IndexRef]}**`)`** * * `|` `(` * {@include [ColsColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [ValueColsColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [FrameColsColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [ColGroupsColumnsSelectionDsl.Grammar.PlainDslName]} * `) [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * `|` {@include [ColsColumnsSelectionDsl.Grammar.PlainDslName]}`[`**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**`]`**`(`**{@include [DslGrammarTemplate.ColumnRef]}**`,`**` .. | `{@include [DslGrammarTemplate.IndexRef]}**`,`**` .. | `{@include [DslGrammarTemplate.IndexRangeRef]}**`)`** * * `|` {@include [ColsAtAnyDepthColumnsSelectionDsl.Grammar.PlainDslName]}` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * `|` {@include [ColsInGroupsColumnsSelectionDsl.Grammar.PlainDslName]}` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `] * * `|` {@include [ColsOfColumnsSelectionDsl.Grammar.PlainDslName]}**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**` [` **`(`**{@include [DslGrammarTemplate.KTypeRef]}**`)`** `] [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * `|` {@include [ColsOfKindColumnsSelectionDsl.Grammar.PlainDslName]}**`(`**{@include [DslGrammarTemplate.ColumnKindRef]}**`,`**` ..`**`)`**` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * `|` {@include [DropColumnsSelectionDsl.Grammar.PlainDslName]}**`(`**{@include [DslGrammarTemplate.NumberRef]}**`)`** * * `|` {@include [DropColumnsSelectionDsl.Grammar.PlainDslWhileName]}**` { `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** * * `|` {@include [ExprColumnsSelectionDsl.Grammar.PlainDslName]}**`(`**`[`{@include [DslGrammarTemplate.NameRef]}**`,`**`][`{@include [DslGrammarTemplate.InferRef]}`]`**`)`** **`{ `**{@include [DslGrammarTemplate.ColumnExpressionRef]}**` \}`** * * `|` `(` * {@include [FirstColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [LastColumnsSelectionDsl.Grammar.PlainDslName]} * `|` {@include [SingleColumnsSelectionDsl.Grammar.PlainDslName]} * `) [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * `|` {@include [ColumnNameFiltersColumnsSelectionDsl.Grammar.PlainDslNameContains]}**`(`**{@include [DslGrammarTemplate.TextRef]}`[`**`,`** {@include [DslGrammarTemplate.IgnoreCaseRef]}`] | `{@include [DslGrammarTemplate.RegexRef]}**`)`** * * `|` {@include [ColumnNameFiltersColumnsSelectionDsl.Grammar.PlainDslNameStartsEndsWith]}**`(`**{@include [DslGrammarTemplate.TextRef]}`[`**`,`** {@include [DslGrammarTemplate.IgnoreCaseRef]}`]`**`)`** * * `|` {@include [DslGrammarTemplate.ColumnRef]} {@include [RenameColumnsSelectionDsl.Grammar.InfixNamedName]}`/`{@include [RenameColumnsSelectionDsl.Grammar.InfixIntoName]} {@include [DslGrammarTemplate.ColumnRef]} * * `|` {@include [DslGrammarTemplate.ColumnRef]}`(`{@include [RenameColumnsSelectionDsl.Grammar.NamedName]}`|`{@include [RenameColumnsSelectionDsl.Grammar.IntoName]}`)`**`(`**{@include [DslGrammarTemplate.ColumnRef]}**`)`** * * `|` {@include [NoneColumnsSelectionDsl.Grammar.PlainDslName]}**`()`** * * `|` {@include [TakeColumnsSelectionDsl.Grammar.PlainDslName]}**`(`**{@include [DslGrammarTemplate.NumberRef]}**`)`** * * `|` {@include [TakeColumnsSelectionDsl.Grammar.PlainDslWhileName]}**` { `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** * * `|` {@include [WithoutNullsColumnsSelectionDsl.Grammar.PlainDslName]}**`()`** * } * {@comment ColumnSet: -------------------------------------------------------------------------------------------- } * {@set [DslGrammarTemplate.ColumnSetFunctionsArg] * * {@include [Indent]}[**`[`**][ColumnsSelectionDsl.col]{@include [DslGrammarTemplate.IndexRef]}[**`]`**][ColumnsSelectionDsl.col] * * {@include [Indent]}`|` [**`[`**][cols]{@include [DslGrammarTemplate.IndexRef]}**`,`**` .. | `{@include [DslGrammarTemplate.IndexRangeRef]}[**`]`**][cols]` * * {@include [Indent]}`|` [**`[`**][cols]**`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`**[**`]`**][cols] * * {@include [Indent]}`|` {@include [AllColumnsSelectionDsl.Grammar.ColumnSetName]}**`()`** * * {@include [Indent]}`|` .**`all`**`(`{@include [AllColumnsSelectionDsl.Grammar.Before]}`|`{@include [AllColumnsSelectionDsl.Grammar.After]}`|`{@include [AllColumnsSelectionDsl.Grammar.From]}`|`{@include [AllColumnsSelectionDsl.Grammar.UpTo]}`)` `(` **`(`**{@include [DslGrammarTemplate.ColumnRef]}**`)`** `|` **`{`** {@include [DslGrammarTemplate.ConditionRef]} **`\}`** `)` * * {@include [Indent]}`|` {@include [AndColumnsSelectionDsl.Grammar.Name]} **`(`**`|`**`{ `**{@include [DslGrammarTemplate.ColumnOrColumnSetRef]}**` \}`**`|`**`)`** * * {@include [Indent]}`|` `(` * {@include [ColColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [ValueColColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [FrameColColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [ColGroupColumnsSelectionDsl.Grammar.ColumnSetName]} * `)`**`(`**{@include [DslGrammarTemplate.IndexRef]}**`)`** * * {@include [Indent]}`|` `(` * {@include [ColsColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [ValueColsColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [FrameColsColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [ColGroupsColumnsSelectionDsl.Grammar.ColumnSetName]} * `) [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColsColumnsSelectionDsl.Grammar.ColumnSetName]}**`(`**{@include [DslGrammarTemplate.IndexRef]}**`,`**` .. | `{@include [DslGrammarTemplate.IndexRangeRef]}**`)`** * * {@include [Indent]}`|` {@include [ColsAtAnyDepthColumnsSelectionDsl.Grammar.ColumnSetName]}` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColsInGroupsColumnsSelectionDsl.Grammar.ColumnSetName]}` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColsOfColumnsSelectionDsl.Grammar.ColumnSetName]}**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**` [` **`(`**{@include [DslGrammarTemplate.KTypeRef]}**`)`** `] [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColsOfKindColumnsSelectionDsl.Grammar.ColumnSetName]}**`(`**{@include [DslGrammarTemplate.ColumnKindRef]}**`,`**` ..`**`)`**` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [DistinctColumnsSelectionDsl.Grammar.ColumnSetName]}**`()`** * * {@include [Indent]}`|` {@include [DropColumnsSelectionDsl.Grammar.ColumnSetName]}**`(`**{@include [DslGrammarTemplate.NumberRef]}**`)`** * * {@include [Indent]}`|` {@include [DropColumnsSelectionDsl.Grammar.ColumnSetWhileName]}**` { `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** * * {@include [Indent]}`|` {@include [AllExceptColumnsSelectionDsl.Grammar.ColumnSetName]} `[`**` { `**`]` {@include [DslGrammarTemplate.ColumnsResolverRef]} `[`**` \} `**`]` * * {@include [Indent]}`|` {@include [AllExceptColumnsSelectionDsl.Grammar.ColumnSetName]} {@include [DslGrammarTemplate.ColumnRef]} * * {@include [Indent]}`|` .{@include [AllExceptColumnsSelectionDsl.Grammar.ColumnSetName]}**`(`**{@include [DslGrammarTemplate.ColumnRef]}**`,`**` ..`**`)`** * * {@include [Indent]}`|` {@include [FilterColumnsSelectionDsl.Grammar.ColumnSetName]}**` {`** {@include [DslGrammarTemplate.ConditionRef]} **`\}`** * * {@include [Indent]}`|` `(` * {@include [FirstColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [LastColumnsSelectionDsl.Grammar.ColumnSetName]} * `|` {@include [SingleColumnsSelectionDsl.Grammar.ColumnSetName]} * `) [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColumnNameFiltersColumnsSelectionDsl.Grammar.ColumnSetNameStartsEndsWith]}**`(`**{@include [DslGrammarTemplate.TextRef]}`[`**`,`** {@include [DslGrammarTemplate.IgnoreCaseRef]}`]`**`)`** * * {@include [Indent]}`|` {@include [ColumnNameFiltersColumnsSelectionDsl.Grammar.ColumnSetNameContains]}**`(`**{@include [DslGrammarTemplate.TextRef]}`[`**`,`** {@include [DslGrammarTemplate.IgnoreCaseRef]}`] | `{@include [DslGrammarTemplate.RegexRef]}**`)`** * * {@include [Indent]}`|` {@include [SimplifyColumnsSelectionDsl.Grammar.ColumnSetName]}**`()`** * * {@include [Indent]}`|` {@include [TakeColumnsSelectionDsl.Grammar.ColumnSetName]}**`(`**{@include [DslGrammarTemplate.NumberRef]}**`)`** * * {@include [Indent]}`|` {@include [TakeColumnsSelectionDsl.Grammar.ColumnSetWhileName]}**` { `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** * * {@include [Indent]}`|` {@include [WithoutNullsColumnsSelectionDsl.Grammar.ColumnSetName]}**`()`** * } * {@comment ColumnGroup: -------------------------------------------------------------------------------------------- } * {@set [DslGrammarTemplate.ColumnGroupFunctionsArg] * * {@include [Indent]}`|` [**`[`**][cols]{@include [DslGrammarTemplate.ColumnRef]}**`,`**` ..`[**`]`**][cols] * * {@include [Indent]}`|` [**`[`**][cols]**`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`**[**`]`**][cols] * * {@include [Indent]}`|`[**` {`**][ColumnsSelectionDsl.select] {@include [DslGrammarTemplate.ColumnsSelectorRef]} [**`\}`**][ColumnsSelectionDsl.select] * * {@include [Indent]}`|` {@include [AllColumnsSelectionDsl.Grammar.ColumnGroupName]}**`()`** * * {@include [Indent]}`|` .**`allCols`**`(`{@include [AllColumnsSelectionDsl.Grammar.Before]}`|`{@include [AllColumnsSelectionDsl.Grammar.After]}`|`{@include [AllColumnsSelectionDsl.Grammar.From]}`|`{@include [AllColumnsSelectionDsl.Grammar.UpTo]}`)` `(` **`(`**{@include [DslGrammarTemplate.ColumnRef]}**`)`** `|` **`{`** {@include [DslGrammarTemplate.ColumnSelectorRef]} **`\}`** `)` * * {@include [Indent]}`|` {@include [AllExceptColumnsSelectionDsl.Grammar.ColumnGroupName]} **` { `**{@include [DslGrammarTemplate.ColumnsSelectorRef]}**` \} `** * * {@include [Indent]}`|` {@include [AllExceptColumnsSelectionDsl.Grammar.ColumnGroupName]}**`(`**{@include [DslGrammarTemplate.ColumnNoAccessorRef]}**`,`**` ..`**`)`** * * {@include [Indent]}`|` {@include [AndColumnsSelectionDsl.Grammar.Name]} **`(`**`|`**`{ `**{@include [DslGrammarTemplate.ColumnOrColumnSetRef]}**` \}`**`|`**`)`** * * {@include [Indent]}`| (` * {@include [ColColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [ValueColColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [FrameColColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [ColGroupColumnsSelectionDsl.Grammar.ColumnGroupName]} * `)[`**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**`]`**`(`**{@include [DslGrammarTemplate.ColumnRef]}` | `{@include [DslGrammarTemplate.IndexRef]}**`)`** * * {@include [Indent]}`|` `(` * {@include [ColsColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [ValueColsColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [FrameColsColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [ColGroupsColumnsSelectionDsl.Grammar.ColumnGroupName]} * `) [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColsColumnsSelectionDsl.Grammar.ColumnGroupName]}`[`**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**`]`**`(`**{@include [DslGrammarTemplate.ColumnRef]}**`,`**` .. | `{@include [DslGrammarTemplate.IndexRef]}**`,`**` .. | `{@include [DslGrammarTemplate.IndexRangeRef]}**`)`** * * {@include [Indent]}`|` {@include [ColsAtAnyDepthColumnsSelectionDsl.Grammar.ColumnGroupName]}` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColsInGroupsColumnsSelectionDsl.Grammar.ColumnGroupName]}` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [ColumnNameFiltersColumnsSelectionDsl.Grammar.ColumnGroupNameStartsWith]}**`(`**{@include [DslGrammarTemplate.TextRef]}`[`**`,`** {@include [DslGrammarTemplate.IgnoreCaseRef]}`]`**`)`** * * {@include [Indent]}`|` {@include [ColumnNameFiltersColumnsSelectionDsl.Grammar.ColumnGroupNameContains]}**`(`**{@include [DslGrammarTemplate.TextRef]}`[`**`,`** {@include [DslGrammarTemplate.IgnoreCaseRef]}`] | `{@include [DslGrammarTemplate.RegexRef]}**`)`** * * {@include [Indent]}`|` {@include [ColsOfKindColumnsSelectionDsl.Grammar.ColumnGroupName]}**`(`**{@include [DslGrammarTemplate.ColumnKindRef]}**`,`**` ..`**`)`**` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [WithoutNullsColumnsSelectionDsl.Grammar.ColumnGroupName]}**`()`** * * {@include [Indent]}`|` {@include [DropColumnsSelectionDsl.Grammar.ColumnGroupName]}**`(`**{@include [DslGrammarTemplate.NumberRef]}**`)`** * * {@include [Indent]}`|` {@include [DropColumnsSelectionDsl.Grammar.ColumnGroupWhileName]}**` { `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** * * {@include [Indent]}`|` {@include [AllExceptColumnsSelectionDsl.Grammar.ColumnGroupExperimentalName]} **` { `**{@include [DslGrammarTemplate.ColumnsSelectorRef]}**` \} EXPERIMENTAL!`** * * {@include [Indent]}`|` {@include [AllExceptColumnsSelectionDsl.Grammar.ColumnGroupExperimentalName]}**`(`**{@include [DslGrammarTemplate.ColumnNoAccessorRef]}**`,`**` ..`**`) EXPERIMENTAL!`** * * {@include [Indent]}`|` `(` * {@include [FirstColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [LastColumnsSelectionDsl.Grammar.ColumnGroupName]} * `|` {@include [SingleColumnsSelectionDsl.Grammar.ColumnGroupName]} * `) [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [Indent]}`|` {@include [SelectColumnsSelectionDsl.Grammar.ColumnGroupName]}**` {`** {@include [DslGrammarTemplate.ColumnsSelectorRef]} **`\}`** * * {@include [Indent]}`|` {@include [TakeColumnsSelectionDsl.Grammar.ColumnGroupName]}**`(`**{@include [DslGrammarTemplate.NumberRef]}**`)`** * * {@include [Indent]}`|` {@include [TakeColumnsSelectionDsl.Grammar.ColumnGroupWhileName]}**` { `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** * * {@include [LineBreak]} * * {@include [DslGrammarTemplate.SingleColumnRef]} * * {@include [Indent]}{@include [ColsOfColumnsSelectionDsl.Grammar.ColumnGroupName]}**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>`**` [` **`(`**{@include [DslGrammarTemplate.KTypeRef]}**`)`** `] [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * * {@include [LineBreak]} * * {@include [DslGrammarTemplate.ColumnGroupNoSingleColumnRef]} * * {@include [Indent]}{@include [ColsOfColumnsSelectionDsl.Grammar.ColumnGroupName]}**`<`**{@include [DslGrammarTemplate.ColumnTypeRef]}**`>(`**{@include [DslGrammarTemplate.KTypeRef]}**`)`** ` [` **`{ `**{@include [DslGrammarTemplate.ConditionRef]}**` \}`** `]` * } */ public interface DslGrammar /** * Invokes the given [ColumnsSelector] using this [ColumnsSelectionDsl]. */ public operator fun <C> ColumnsSelector<T, C>.invoke(): ColumnsResolver<C> = this@invoke(this@ColumnsSelectionDsl, this@ColumnsSelectionDsl) /** * ## Deprecated: Columns by Index Range from List of Columns * Helper function to create a [ColumnSet] from a list of columns by specifying a range of indices. * * ### Deprecated * * Deprecated because it's too niche. Let us know if you have a good use for it! */ @Deprecated( message = COL_SELECT_DSL_LIST_DATACOLUMN_GET, replaceWith = ReplaceWith(COL_SELECT_DSL_LIST_DATACOLUMN_GET_REPLACE), level = DeprecationLevel.ERROR, ) public operator fun <C> List<DataColumn<C>>.get(range: IntRange): ColumnSet<C> = ColumnsList(subList(range.first, range.last + 1)) // region select // NOTE: due to invoke conflicts these cannot be moved out of the interface /** * @include [SelectColumnsSelectionDsl.CommonSelectDocs] * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg] * * `df.`[select][DataFrame.select]` { myColGroup.`[select][SingleColumn.select]` { someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() } }` * * `df.`[select][DataFrame.select]` { myColGroup `[{][SingleColumn.select]` colA `[and][ColumnsSelectionDsl.and]` colB `[}][SingleColumn.select]` }` */ public operator fun <C, R> SingleColumn<DataRow<C>>.invoke(selector: ColumnsSelector<C, R>): ColumnSet<R> = select(selector) /** * @include [SelectColumnsSelectionDsl.CommonSelectDocs] * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg] * * `df.`[select][DataFrame.select]` { Type::myColGroup.`[select][KProperty.select]` { someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() } }` * * `df.`[select][DataFrame.select]` { DataSchemaType::myColGroup `[`{`][KProperty.select]` colA `[and][ColumnsSelectionDsl.and]` colB `[`}`][KProperty.select]` }` * * ## NOTE: {@comment TODO fix warning} * If you get a warning `CANDIDATE_CHOSEN_USING_OVERLOAD_RESOLUTION_BY_LAMBDA_ANNOTATION`, you * can safely ignore this. It is caused by a workaround for a bug in the Kotlin compiler * ([KT-64092](https://youtrack.jetbrains.com/issue/KT-64092/OVERLOADRESOLUTIONAMBIGUITY-caused-by-lambda-argument)). */ @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("KPropertyDataRowInvoke") public operator fun <C, R> KProperty<DataRow<C>>.invoke(selector: ColumnsSelector<C, R>): ColumnSet<R> = select(selector) /** * @include [SelectColumnsSelectionDsl.CommonSelectDocs] * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg] * * `df.`[select][DataFrame.select]` { Type::myColGroup.`[select][KProperty.select]` { someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() } }` * * `df.`[select][DataFrame.select]` { DataSchemaType::myColGroup `[`{`][KProperty.select]` colA `[and][ColumnsSelectionDsl.and]` colB `[`}`][KProperty.select]` }` */ @OptIn(ExperimentalTypeInference::class) @OverloadResolutionByLambdaReturnType public operator fun <C, R> KProperty<C>.invoke(selector: ColumnsSelector<C, R>): ColumnSet<R> = columnGroup(this).select(selector) /** * @include [SelectColumnsSelectionDsl.CommonSelectDocs] * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg] * * `df.`[select][DataFrame.select]` { "myColGroup".`[select][String.select]` { someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() } }` * * `df.`[select][DataFrame.select]` { "myColGroup" `[{][String.select]` colA `[and][ColumnsSelectionDsl.and]` colB `[}][String.select]` }` */ public operator fun <R> String.invoke(selector: ColumnsSelector<*, R>): ColumnSet<R> = select(selector) /** * @include [SelectColumnsSelectionDsl.CommonSelectDocs] * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg] * * `df.`[select][DataFrame.select]` { "pathTo"["myColGroup"].`[select][ColumnPath.select]` { someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() } }` * * `df.`[select][DataFrame.select]` { "pathTo"["myColGroup"] `[{][ColumnPath.select]` colA `[and][ColumnsSelectionDsl.and]` colB `[}][ColumnPath.select]` }` * * `df.`[select][DataFrame.select]` { `[pathOf][pathOf]`("pathTo", "myColGroup").`[select][ColumnPath.select]` { someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() } }` * * `df.`[select][DataFrame.select]` { `[pathOf][pathOf]`("pathTo", "myColGroup")`[() {][ColumnPath.select]` someCol `[and][ColumnsSelectionDsl.and]` `[colsOf][SingleColumn.colsOf]`<`[String][String]`>() `[}][ColumnPath.select]` }` */ public operator fun <R> ColumnPath.invoke(selector: ColumnsSelector<*, R>): ColumnSet<R> = select(selector) // endregion }
235
null
60
833
54d00e69ae7c06ff254c6591242413eaf7894f01
29,612
dataframe
Apache License 2.0
app/src/main/java/com/system/moneycontrol/model/business/TypeBusiness.kt
enirsilvaferraz
138,302,967
false
{"Kotlin": 71910}
package com.system.moneycontrol.model.business import com.system.moneycontrol.data.repositories.TypeRepository import com.system.moneycontrol.model.entities.PaymentType class TypeBusiness(private val repository: TypeRepository) { fun getAll() = repository.getList() fun delete(model: PaymentType) = repository.delete(model) fun save(model: PaymentType) = if (model.key.isNullOrBlank()) { repository.save(model) } else { repository.update(model) } }
0
Kotlin
0
0
7087fde3fbd7433d294cb43e874939df4f10b7e1
489
Money-Control
Apache License 2.0
credentials/credentials/src/main/java/androidx/credentials/CreateCustomCredentialRequest.kt
androidx
256,589,781
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.credentials import android.os.Bundle /** * Base custom create request class for registering a credential. * * An application can construct a subtype custom request and call * [CredentialManager.createCredential] to launch framework UI flows to collect consent and any * other metadata needed from the user to register a new user credential. * * If you get a [CreateCustomCredentialRequest] instead of a type-safe request class such as * [CreatePasswordRequest], [CreatePublicKeyCredentialRequest], etc., then you should check if you * have any other library at interest that supports this custom [type] of credential request, and if * so use its parsing utilities to resolve to a type-safe class within that library. * * Note: The Bundle keys for [credentialData] and [candidateQueryData] should not be in the form of * androidx.credentials.*` as they are reserved for internal use by this androidx library. * * @param type the credential type determined by the credential-type-specific subclass for custom * use cases * @param credentialData the data of this [CreateCustomCredentialRequest] in the [Bundle] format * (note: bundle keys in the form of `androidx.credentials.*` and `android.credentials.*` are * reserved for internal library usage) * @param candidateQueryData the partial request data in the [Bundle] format that will be sent to * the provider during the initial candidate query stage, which should not contain sensitive user * credential information (note: bundle keys in the form of `androidx.credentials.*` and * `android.credentials.*` are reserved for internal library usage) * @param isSystemProviderRequired true if must only be fulfilled by a system provider and false * otherwise * @param isAutoSelectAllowed defines if a create entry will be automatically chosen if it is the * only one available option, false by default * @param displayInfo the information to be displayed on the screen * @param origin the origin of a different application if the request is being made on behalf of * that application (Note: for API level >=34, setting a non-null value for this parameter will * throw a SecurityException if android.permission.CREDENTIAL_MANAGER_SET_ORIGIN is not present) * @param preferImmediatelyAvailableCredentials true if you prefer the operation to return * immediately when there is no available passkey registration offering instead of falling back to * discovering remote options, and false (default) otherwise * @throws IllegalArgumentException If [type] is empty * @throws NullPointerException If [type], [credentialData], or [candidateQueryData] is null */ open class CreateCustomCredentialRequest @JvmOverloads constructor( type: String, credentialData: Bundle, candidateQueryData: Bundle, isSystemProviderRequired: Boolean, displayInfo: DisplayInfo, isAutoSelectAllowed: Boolean = false, origin: String? = null, preferImmediatelyAvailableCredentials: Boolean = false, ) : CreateCredentialRequest( type, credentialData, candidateQueryData, isSystemProviderRequired, isAutoSelectAllowed, displayInfo, origin, preferImmediatelyAvailableCredentials ) { init { require(type.isNotEmpty()) { "type should not be empty" } } }
29
null
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
3,978
androidx
Apache License 2.0
app/src/main/kotlin/com/asadmshah/livecolorpicker/colors/ColorizerModule.kt
asadmshah
90,253,982
false
null
package com.asadmshah.livecolorpicker.colors import com.asadmshah.livecolorpicker.storage.Storage import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ColorizerModule { @Provides @Singleton fun colorizer(storage: Storage): Colorizer { return ColorizerImpl(storage) } }
0
Kotlin
0
1
199b2f94e7a9dec6492cbef6dae33236c1d9eb53
331
LiveColorPicker
Apache License 2.0
hilt/hilt-app/src/main/java/org/fnives/test/showcase/hilt/ui/home/MainViewModel.kt
fknives
356,982,481
false
null
package org.fnives.test.showcase.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.fnives.test.showcase.core.content.AddContentToFavouriteUseCase import org.fnives.test.showcase.core.content.FetchContentUseCase import org.fnives.test.showcase.core.content.GetAllContentUseCase import org.fnives.test.showcase.core.content.RemoveContentFromFavouritesUseCase import org.fnives.test.showcase.core.login.LogoutUseCase import org.fnives.test.showcase.model.content.ContentId import org.fnives.test.showcase.model.content.FavouriteContent import org.fnives.test.showcase.model.shared.Resource import org.fnives.test.showcase.ui.shared.Event import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val getAllContentUseCase: GetAllContentUseCase, private val logoutUseCase: LogoutUseCase, private val fetchContentUseCase: FetchContentUseCase, private val addContentToFavouriteUseCase: AddContentToFavouriteUseCase, private val removeContentFromFavouritesUseCase: RemoveContentFromFavouritesUseCase ) : ViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> = _loading private val _content: LiveData<List<FavouriteContent>> = liveData { getAllContentUseCase.get().collect { when (it) { is Resource.Error -> { _errorMessage.value = true _loading.value = false emit(emptyList<FavouriteContent>()) } is Resource.Loading -> { _errorMessage.value = false _loading.value = true } is Resource.Success -> { _errorMessage.value = false _loading.value = false emit(it.data) } } } } val content: LiveData<List<FavouriteContent>> = _content private val _errorMessage = MutableLiveData<Boolean>(false) val errorMessage: LiveData<Boolean> = _errorMessage private val _navigateToAuth = MutableLiveData<Event<Unit>>() val navigateToAuth: LiveData<Event<Unit>> = _navigateToAuth fun onLogout() { viewModelScope.launch { logoutUseCase.invoke() _navigateToAuth.value = Event(Unit) } } fun onRefresh() { if (_loading.value == true) return _loading.value = true viewModelScope.launch { fetchContentUseCase.invoke() } } fun onFavouriteToggleClicked(contentId: ContentId) { viewModelScope.launch { val content = _content.value?.firstOrNull { it.content.id == contentId } ?: return@launch if (content.isFavourite) { removeContentFromFavouritesUseCase.invoke(contentId) } else { addContentToFavouriteUseCase.invoke(contentId) } } } }
9
null
2
5
5bf503d90e8a13daf5626afc0cdf8bff523d2b94
3,218
AndroidTest-ShowCase
Apache License 2.0
src/main/kotlin/xyz/galaxyy/lualink/lua/misc/LuaLogger.kt
LuaLink
689,718,962
false
{"Kotlin": 42182, "Java": 6980, "Lua": 6363, "Nix": 118}
package xyz.galaxyy.lualink.lua.misc import net.kyori.adventure.text.minimessage.MiniMessage import org.luaj.vm2.LuaTable import org.luaj.vm2.LuaValue import org.luaj.vm2.lib.OneArgFunction import xyz.galaxyy.lualink.LuaLink class LuaLogger(private val plugin: LuaLink) : LuaTable() { init { this.set("info", object : OneArgFunction() { override fun call(arg: LuaValue): LuaValue? { plugin.componentLogger.info(MiniMessage.miniMessage().deserialize(arg.tojstring())) return LuaValue.NIL } }) this.set("warning", object : OneArgFunction() { override fun call(arg: LuaValue): LuaValue? { plugin.componentLogger.warn(MiniMessage.miniMessage().deserialize(arg.tojstring())) return LuaValue.NIL } }) this.set("error", object : OneArgFunction() { override fun call(arg: LuaValue): LuaValue? { plugin.componentLogger.error(MiniMessage.miniMessage().deserialize(arg.tojstring())) return LuaValue.NIL } }) this.set("severe", object : OneArgFunction() { override fun call(arg: LuaValue): LuaValue? { plugin.componentLogger.error(MiniMessage.miniMessage().deserialize(arg.tojstring())) return LuaValue.NIL } }) } }
3
Kotlin
2
8
dfd54f4de792698b40e1e65afc05e2a8f915e74a
1,404
LuaLink
MIT License
conductor-kotlin-client/src/test/kotlin/org/conductoross/client/kotlin/sample/SampleWorker.kt
korolkevich7
791,502,936
false
{"Kotlin": 134256, "Java": 2091}
/* * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.conductoross.kotlin.client.sample import org.conductoross.kotlin.client.worker.Worker import com.netflix.conductor.common.metadata.tasks.Task import com.netflix.conductor.common.metadata.tasks.TaskResult class SampleWorker(override val taskDefName: String) : Worker { override suspend fun execute(task: Task): TaskResult { val result = TaskResult(task) result.status = TaskResult.Status.COMPLETED // Register the output of the task result.outputData["outputKey1"] = "value" result.outputData["oddEven"] = 1 result.outputData["mod"] = 4 return result } }
0
Kotlin
0
0
ca442aaeb96f9005afd6f29cb3ad4fedea79236b
1,198
conductor-kotlin
Apache License 2.0
app-1/app/src/main/java/com/example/app1/MainActivity.kt
VictorMany
290,905,329
false
null
package com.example.app1 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button //Este import import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //AQUI COMENZAMOS CON TODa LA LOGICA Eventos() } fun Eventos(){ //SE hace de esta manera en Java /*var boton = findViewById<Button>(R.id.btnAceptar) boton.setOnClickListener { } */ //citamos nuestro botón btnAceptar.setOnClickListener { var nombre = txtNombre.text lblDato.text = "éste es tu nombre: $nombre" } } }
0
Kotlin
0
0
ab213d4e322ceb1b3e651df0882664a11231213e
825
Curso-Kotlin
MIT License
app/src/main/java/dev/borisochieng/gitrack/ui/adapters/RepositoryAdapter.kt
slowburn-404
777,819,284
false
{"Kotlin": 74987}
package dev.borisochieng.gitrack.ui.adapters import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.RecyclerView import dev.borisochieng.gitrack.databinding.ItemRepositoryBinding import dev.borisochieng.gitrack.ui.models.Repository import androidx.recyclerview.widget.DiffUtil class RepositoryAdapter(private val onRepositoryClickListener: OnRepositoryClickListener) : RecyclerView.Adapter<RepositoryAdapter.ViewHolder>() { inner class ViewHolder(private val binding: ItemRepositoryBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Repository) { binding.apply { repositoryName.text = item.name repositoryDesc.text = item.desc issueCount.text = item.issueCount.toString() starsCount.text = item.starCount.toString() //lastUpdated.text = item.lastUpdated root.setOnClickListener { onRepositoryClickListener.onItemClick(item) } } } } private val asyncListDiffer = AsyncListDiffer(this, DIFF_CALLBACK) fun setList(list: List<Repository>) { asyncListDiffer.submitList(list) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemBinding = ItemRepositoryBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(itemBinding) } override fun getItemCount(): Int = asyncListDiffer.currentList.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = asyncListDiffer.currentList[position] holder.bind(item) } companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Repository>() { override fun areItemsTheSame(oldItem: Repository, newItem: Repository): Boolean = oldItem.databaseId == newItem.databaseId override fun areContentsTheSame(oldItem: Repository, newItem: Repository): Boolean = oldItem == newItem } } }
0
Kotlin
0
1
ab9fc17ce4779c98368658339546c4a55fdad697
2,224
GiTrack
MIT License
app/src/main/java/com/hashconcepts/buycart/presentation/components/IncrementDecrementContainer.kt
HenryUdorji
506,773,556
false
{"Kotlin": 207630}
package com.yasirabanuka.shopcart.presentation.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.yasirabanuka.shopcart.R import com.yasirabanuka.shopcart.ui.theme.backgroundColor @Composable fun IncrementDecrementContainer( quantity: Int, increment: () -> Unit, decrement: () -> Unit ) { Row(verticalAlignment = Alignment.CenterVertically) { IncrementDecrement(icon = R.drawable.ic_minus) { decrement() } Text(text = quantity.toString(), style = MaterialTheme.typography.h2, fontSize = 11.sp) IncrementDecrement(icon = R.drawable.ic_add) { increment() } } } @Composable fun IncrementDecrement( icon: Int, onClick: () -> Unit, ) { IconButton(onClick = { onClick() }) { Icon( painter = painterResource(id = icon), contentDescription = null, modifier = Modifier .size(22.dp) .clip(RoundedCornerShape(5.dp)) .background(backgroundColor) ) } }
1
Kotlin
0
9
560dee481dd5212a9f3237352c89e8898c9b2801
1,610
BuyCart
Apache License 2.0
src/main/kotlin/de/sambalmueslie/padlet/client/wishes/Attributes.kt
sambalmueslie
370,110,224
false
null
package de.sambalmueslie.padlet.client.wishes import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class Attributes( @JsonProperty("id") val id: Long, @JsonProperty("wall_id") val wallId: Long, @JsonProperty("published") val published: Boolean, // @JsonProperty("row_id") // val rowId: Any, // @JsonProperty("col_id") // val colId: Any, @JsonProperty("row_span") val rowSpan: Int, @JsonProperty("col_span") val colSpan: Int, @JsonProperty("is_content_hidden") val isContentHidden: Boolean, @JsonProperty("updated_at") val updatedAt: String, @JsonProperty("headline") val headline: String, @JsonProperty("subject") val subject: String, @JsonProperty("body") val body: String, @JsonProperty("attachment") val attachment: String, @JsonProperty("permalink") val permalink: String, @JsonProperty("author_id") val authorId: Long, @JsonProperty("created_at") val createdAt: String, @JsonProperty("content_updated_at") val contentUpdatedAt: String, @JsonProperty("color") val color: String?, @JsonProperty("location_point") val locationPoint: LocationPoint?, @JsonProperty("location_name") val locationName: String?, // @JsonProperty("top") // val top: Any, // @JsonProperty("left") // val left: Any, @JsonProperty("width") val width: Int, // @JsonProperty("position") // val position: Position? , @JsonProperty("sort_index") val sortIndex: Long, @JsonProperty("wall_section_id") val wallSectionId: Long, // @JsonProperty("rank") // val rank: Any, // @JsonProperty("label") // val label: Any, // @JsonProperty("attachment_caption") // val attachmentCaption: Any,) )
0
Kotlin
0
0
9db6d0c8049792027422160c65cbc2ba0b64fc6a
1,887
padlet-notifier
Apache License 2.0
src/test/kotlin/io/ashdavies/rx/extensions/QueryTest.kt
ashdavies
56,701,828
false
null
package io.ashdavies.rx.extensions import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.Query import com.google.firebase.database.ValueEventListener import com.nhaarman.mockito_kotlin.KArgumentCaptor import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.given import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.then import com.nhaarman.mockito_kotlin.verify import io.ashdavies.rx.rxfirebase.ChildEvent import io.ashdavies.rx.rxfirebase.ChildEvent.Type import io.reactivex.observers.TestObserver import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class QueryTest { private val snapshot: DataSnapshot = mock() private val query: Query = mock() private val child: KArgumentCaptor<ChildEventListener> = argumentCaptor() private val value: KArgumentCaptor<ValueEventListener> = argumentCaptor() @BeforeEach fun setUp() { verify(query).addChildEventListener(child.capture()) verify(query).addValueEventListener(value.capture()) } @Test fun `should emit child event`() { val observer: TestObserver<ChildEvent> = query .onChildEvent() .test() child .lastValue .onChildAdded(snapshot, null) observer.assertValue(ChildEvent(snapshot, Type.CHILD_ADDED)) } @Test fun `should remove event listener on child event dispose`() { query .onChildEvent() .test() .dispose() then(query) .should() .removeEventListener(child.lastValue) } @Test fun `should emit child event value`() { given(snapshot.getValue(String::class.java)).willReturn("Hello World") val observer: TestObserver<String> = query .onChildEventValue<String>() .test() child .lastValue .onChildAdded(snapshot, null) observer.assertValue("Hello World") } @Test fun `should emit single value event`() { val observer: TestObserver<DataSnapshot> = query .onSingleValueEvent() .test() value .lastValue .onDataChange(snapshot) observer.assertValue(snapshot) } @Test fun `should remove event listener on single value event dispose`() { query .onSingleValueEvent() .test() .dispose() then(query) .should() .removeEventListener(value.lastValue) } @Test fun `should emit value event`() { val observer: TestObserver<DataSnapshot> = query .onValueEvent() .test() value .lastValue .onDataChange(snapshot) observer.assertValue(snapshot) } @Test fun `should remove event listener on value event dispose`() { query .onValueEvent() .test() .dispose() then(query) .should() .removeEventListener(value.lastValue) } }
3
Kotlin
6
35
0935448ea99f626acbfc8b9fb0021a48576c849f
2,929
rx-firebase
Apache License 2.0
app/src/main/java/com/serapercel/trickle/data/entity/Currency.kt
SerapErcel
577,003,272
false
{"Kotlin": 147496}
package com.serapercel.trickle.data.entity import android.os.Parcelable import com.google.firebase.database.IgnoreExtraProperties import kotlinx.parcelize.Parcelize @Parcelize @IgnoreExtraProperties data class Currency( val Isim: String, val CurrencyName: String, val ForexBuying: String, val ForexSelling: String, val BanknoteBuying: String, val BanknoteSelling: String ) : Parcelable
0
Kotlin
0
2
2ecc1ece2b4aeb2ce22903d2a7232639583d1d75
416
Trickle
MIT License
src/main/kotlin/site/liangbai/lbapi/util/TagUtil.kt
Liangbai2333
846,688,168
false
{"Kotlin": 75909}
package site.liangbai.lbapi.util import com.google.gson.JsonElement import taboolib.module.nms.ItemTag import taboolib.module.nms.ItemTagSerializer fun ItemTag.toJsonElement(): JsonElement { return ItemTagSerializer.serializeData(this) } fun JsonElement.toItemTag(): ItemTag { return ItemTagSerializer.deserializeData(this).asCompound() }
0
Kotlin
0
0
39a7a8c2607e0763b7dc9957ba4456bd68ff00f2
349
LBAPI
Creative Commons Zero v1.0 Universal
src/main/kotlin/no/nav/helse/RedteamMediator.kt
navikt
537,054,818
false
{"Kotlin": 38561, "Dockerfile": 196}
package no.nav.helse import no.nav.helse.model.RedTeam import no.nav.helse.slack.SlackUpdater import org.slf4j.Logger import org.slf4j.LoggerFactory import java.time.LocalDate class RedteamMediator( private val slackUpdater: SlackUpdater, private val redTeam: RedTeam, private val bøtte: Bøtte = object : Bøtte {} ) { private val logger: Logger = LoggerFactory.getLogger("red-team-mediator") fun override(from: String, to: String, date: LocalDate) { logger.info("Override from $from to $to on date: {} started", date) redTeam.override(from, to, date) bøtte.lagreOverstyringer(redTeam.overstyringerSomJson()) slackUpdater.handleOverride(date) logger.info("Override from $from to $to on date: {} completed", date) } fun update() { slackUpdater.update() } fun teamFor(date: LocalDate) = redTeam.teamFor(date) fun redTeamCalendar(span: Pair<LocalDate, LocalDate>) = redTeam.redTeamCalendar(span) }
0
Kotlin
0
0
7df82bc61078ab3236e37eb1c7edc23ca838fd3b
989
helse-redteam
MIT License
ktx/src/main/java/permissions/dispatcher/ktx/PermissionsRequesterImpl.kt
ibisalan
325,533,075
false
null
package permissions.dispatcher.ktx import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import permissions.dispatcher.PermissionUtils internal class PermissionsRequesterImpl( private val permissions: Array<out String>, private val activity: FragmentActivity, private val onShowRationale: ShowRationaleFun?, private val onPermissionDenied: Fun?, private val requiresPermission: Fun, onNeverAskAgain: Fun?, private val permissionRequestType: PermissionRequestType ) : PermissionsRequester { init { val viewModel = ViewModelProvider(activity).get(PermissionRequestViewModel::class.java) viewModel.observe( activity, requiresPermission, onPermissionDenied, onNeverAskAgain ) } override fun launch() { if (permissionRequestType.checkPermissions(activity, permissions)) { requiresPermission() } else { val requestFun = { activity.supportFragmentManager .beginTransaction() .replace(android.R.id.content, permissionRequestType.fragment(permissions)) .commitNowAllowingStateLoss() } if (PermissionUtils.shouldShowRequestPermissionRationale(activity, *permissions)) { onShowRationale?.invoke(KtxPermissionRequest.create(onPermissionDenied, requestFun)) } else { requestFun.invoke() } } } }
29
null
1454
2
3a238dad5a27d90b0bf27f22be920a2d6ac968a8
1,541
PermissionsDispatcher
Apache License 2.0
app/src/main/java/com/duckduckgo/app/browser/model/Authentication.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.app.browser.model import android.webkit.HttpAuthHandler data class BasicAuthenticationRequest( val handler: HttpAuthHandler, val host: String, val realm: String, val site: String, ) data class BasicAuthenticationCredentials( val username: String, val password: String, )
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
323
DuckDuckGo
Apache License 2.0
src/main/kotlin/com/auth0/jwtValidation/configuration/SecurityConfiguration.kt
sirech
368,286,853
false
null
package com.auth0.jwtValidation.configuration import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.web.cors.CorsConfiguration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) class SecurityConfiguration : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http.let { it .cors() .configurationSource { CorsConfiguration().applyPermitDefaultValues() } .and() .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) } } }
1
Kotlin
1
0
a819b6784f78001fe8c28a14a6d347e28773189e
1,039
example-jwt-validation
MIT License
arrangement/src/main/java/com/fang/arrangement/definition/Employee.kt
7ANG2C
794,384,998
false
{"Kotlin": 425333}
package com.fang.arrangement.definition import com.fang.arrangement.definition.foundation.KeyValue import com.fang.arrangement.foundation.Bool import com.google.gson.annotations.SerializedName internal data class Employee( @SerializedName(EmployeeKey.ID) val id: Long, @SerializedName(EmployeeKey.NAME) val name: String, @SerializedName(EmployeeKey.SALARIES) val salaries: List<Salary>, @SerializedName(EmployeeKey.EXPIRED) val expiredMillis: Long?, @SerializedName(EmployeeKey.DELETE) val delete: Int, ) { val isExpire get() = expiredMillis != null val notExpire get() = !isExpire val isDelete get() = Bool(delete) val notDelete get() = !isDelete } internal data class Salary( @SerializedName(EmployeeKey.S_MILLIS) val millis: Long, @SerializedName(EmployeeKey.S_SALARY) val salary: Int, ) internal interface EmployeeKey { companion object { const val ID = "id" const val NAME = "name" const val SALARIES = "salaries" const val EXPIRED = "expired" const val DELETE = "delete" const val S_MILLIS = "millis" const val S_SALARY = "salary" fun fold( id: String, name: String, salaries: String, expire: String, delete: String, ) = listOf( KeyValue(ID, id), KeyValue(NAME, name), KeyValue(SALARIES, salaries), KeyValue(EXPIRED, expire), KeyValue(DELETE, delete), ) } }
0
Kotlin
0
0
d820ad78b7eea6142da8f94c68af7b16cc0e583c
1,549
FANG
Apache License 2.0
app/src/main/java/eu/kanade/presentation/library/anime/AnimeLibraryList.kt
aniyomiorg
358,887,741
false
null
package eu.kanade.presentation.library.anime import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastAny import eu.kanade.presentation.library.DownloadsBadge import eu.kanade.presentation.library.EntryListItem import eu.kanade.presentation.library.GlobalSearchItem import eu.kanade.presentation.library.LanguageBadge import eu.kanade.presentation.library.UnviewedBadge import eu.kanade.tachiyomi.ui.library.anime.AnimeLibraryItem import tachiyomi.domain.entries.anime.model.AnimeCover import tachiyomi.domain.library.anime.LibraryAnime import tachiyomi.presentation.core.components.FastScrollLazyColumn import tachiyomi.presentation.core.util.plus @Composable fun AnimeLibraryList( items: List<AnimeLibraryItem>, contentPadding: PaddingValues, selection: List<LibraryAnime>, onClick: (LibraryAnime) -> Unit, onLongClick: (LibraryAnime) -> Unit, onClickContinueWatching: ((LibraryAnime) -> Unit)?, searchQuery: String?, onGlobalSearchClicked: () -> Unit, ) { FastScrollLazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = contentPadding + PaddingValues(vertical = 8.dp), ) { item { if (!searchQuery.isNullOrEmpty()) { GlobalSearchItem( modifier = Modifier.fillMaxWidth(), searchQuery = searchQuery, onClick = onGlobalSearchClicked, ) } } items( items = items, contentType = { "anime_library_list_item" }, ) { libraryItem -> val anime = libraryItem.libraryAnime.anime EntryListItem( isSelected = selection.fastAny { it.id == libraryItem.libraryAnime.id }, title = anime.title, coverData = AnimeCover( animeId = anime.id, sourceId = anime.source, isAnimeFavorite = anime.favorite, url = anime.thumbnailUrl, lastModified = anime.coverLastModified, ), badge = { DownloadsBadge(count = libraryItem.downloadCount) UnviewedBadge(count = libraryItem.unseenCount) LanguageBadge( isLocal = libraryItem.isLocal, sourceLanguage = libraryItem.sourceLanguage, ) }, onLongClick = { onLongClick(libraryItem.libraryAnime) }, onClick = { onClick(libraryItem.libraryAnime) }, onClickContinueViewing = if (onClickContinueWatching != null && libraryItem.unseenCount > 0) { { onClickContinueWatching(libraryItem.libraryAnime) } } else { null }, ) } } }
24
null
8
4,992
823099f775ef608b7c11f096da1f50762dab82df
3,169
aniyomi
Apache License 2.0
src/main/kotlin/io/github/abdulroufsidhu/orgolink/core/ims/product/ProductLogic.kt
abdulroufsidhu
812,751,533
false
null
package io.github.abdulroufsidhu.ambaar.apis.product import org.springframework.stereotype.Service @Service class ProductLogic( private val productDao: ProductDao ) { @Throws(NoSuchElementException::class, IllegalArgumentException::class) fun getProductInclusiveId(product: Product): List<Product> = when { product.id != null -> listOf(productDao.getReferenceById(product.id!!)) else -> getProductExcluciveId(product) } @Throws(NoSuchElementException::class, IllegalArgumentException::class) fun getProductExcluciveId(product: Product): List<Product> = when { product.name != null -> productDao.findByName(product.name!!).orElseThrow() product.company != null -> productDao.findByCompany(product.company!!).orElseThrow() product.dimentions != null -> productDao.findByDimentions(product.dimentions!!).orElseThrow() product.createdAt != null -> productDao.findByCreatedAt(product.createdAt!!).orElseThrow() product.weight != null -> productDao.findByWeight(product.weight!!).orElseThrow() else -> throw IllegalArgumentException("Invalid product") } fun saveOrGetProduct(product: Product): Product = getProductExcluciveId(product).ifEmpty { listOf(saveProduct(product)) }.first() fun saveProduct(product: Product): Product = productDao.save(product) private fun deleteProduct(product: Product) = productDao.delete(product) }
2
null
1
3
23c9ccdc1462ce2f064f49569ba46e537288a33f
1,434
orgolink_core
MIT License
data/traktauth/src/commonMain/kotlin/app/tivi/data/traktauth/TraktAuthRepository.kt
chrisbanes
100,624,553
false
null
// Copyright 2017, Google LLC, Christopher Banes and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.data.traktauth import app.tivi.data.traktauth.store.AuthStore import app.tivi.inject.ApplicationCoroutineScope import app.tivi.inject.ApplicationScope import app.tivi.util.AppCoroutineDispatchers import co.touchlab.kermit.Logger import kotlin.time.Duration.Companion.hours import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.datetime.Clock import kotlinx.datetime.Instant import me.tatarka.inject.annotations.Inject @ApplicationScope @Inject class TraktAuthRepository( private val scope: ApplicationCoroutineScope, private val dispatchers: AppCoroutineDispatchers, private val authStore: AuthStore, private val loginAction: Lazy<TraktLoginAction>, private val refreshTokenAction: Lazy<TraktRefreshTokenAction>, private val traktClient: Lazy<TraktClient>, ) { private val authState = MutableStateFlow<AuthState?>(null) private var authStateExpiry: Instant = Instant.DISTANT_PAST val state: Flow<TraktAuthState> = authState.map { when (it?.isAuthorized) { true -> TraktAuthState.LOGGED_IN else -> TraktAuthState.LOGGED_OUT } } fun isLoggedIn(): Boolean { return authState.value?.isAuthorized == true } private val logger by lazy { Logger.withTag("TraktAuthRepository") } init { // Read the auth state from the AuthStore scope.launch { val state = getAuthState() ?: AuthState.Empty updateAuthState(authState = state, persist = false) } } suspend fun getAuthState(): AuthState? { val state = authState.value if (state != null && state.isAuthorized && Clock.System.now() < authStateExpiry) { logger.d { "getAuthState. Using cached tokens: $state" } return state } logger.d { "getAuthState. Retrieving tokens from AuthStore" } return withContext(dispatchers.io) { authStore.get() } ?.also { cacheAuthState(it) } } suspend fun login(): AuthState? { logger.d { "login()" } return loginAction.value().also { logger.d { "Login finished. Result: $it" } updateAuthState(authState = it ?: AuthState.Empty) } } suspend fun refreshTokens(): AuthState? { logger.d { "refreshTokens()" } return getAuthState() ?.let { currentState -> logger.d { "Calling refreshTokenAction with $currentState" } refreshTokenAction.value.invoke(currentState) } .also { logger.d { "refreshTokens finished. Result: $it" } updateAuthState(authState = it ?: AuthState.Empty) } } suspend fun logout() { updateAuthState(authState = AuthState.Empty) } private fun cacheAuthState(authState: AuthState) { this.authState.update { authState } authStateExpiry = when { authState.isAuthorized -> Clock.System.now() + 1.hours else -> Instant.DISTANT_PAST } } private suspend fun updateAuthState(authState: AuthState, persist: Boolean = true) { if (persist) { // Persist auth state withContext(dispatchers.io) { if (authState.isAuthorized) { authStore.save(authState) logger.d { "Saved state to AuthStore: $authState" } } else { authStore.clear() logger.d { "Cleared AuthStore" } } } } logger.d { "updateAuthState: $authState. Persist: $persist" } cacheAuthState(authState) logger.d { "updateAuthState: Clearing TraktClient auth tokens" } traktClient.value.invalidateAuthTokens() } } interface TraktClient { fun invalidateAuthTokens() }
23
null
876
6,626
e261ffbded01c1439b93c550cd6e714c13bb9192
3,797
tivi
Apache License 2.0
diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/AstNodeUtils.kt
fossabot
277,387,332
true
{"Kotlin": 210675, "Java": 2002, "Shell": 601}
package org.cqfn.diktat.ruleset.utils import com.pinterest.ktlint.core.ast.ElementType import com.pinterest.ktlint.core.ast.ElementType.CONST_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.FILE import com.pinterest.ktlint.core.ast.ElementType.INTERNAL_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST import com.pinterest.ktlint.core.ast.ElementType.PRIVATE_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.PROTECTED_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.PUBLIC_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE import com.pinterest.ktlint.core.ast.isLeaf import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.psi.psiUtil.siblings import org.slf4j.Logger import org.slf4j.LoggerFactory val log: Logger = LoggerFactory.getLogger(ASTNode::class.java) fun ASTNode.checkLength(range: IntRange): Boolean = this.textLength in range /** * getting first child name with IDENTIFIER type */ fun ASTNode.getIdentifierName(): ASTNode? = this.getChildren(null).find { it.elementType == ElementType.IDENTIFIER } /** * getting first child name with TYPE_PARAMETER_LIST type */ fun ASTNode.getTypeParameterList(): ASTNode? = this.getChildren(null).find { it.elementType == ElementType.TYPE_PARAMETER_LIST } /** * getting all children that have IDENTIFIER type */ fun ASTNode.getAllIdentifierChildren(): List<ASTNode> = this.getChildren(null).filter { it.elementType == ElementType.IDENTIFIER } /** * obviously returns list with children that match particular element type */ fun ASTNode.getAllChildrenWithType(elementType: IElementType): List<ASTNode> = this.getChildren(null).filter { it.elementType == elementType } /** * obviously returns first child that match particular element type */ fun ASTNode.getFirstChildWithType(elementType: IElementType): ASTNode? = this.getChildren(null).find { it.elementType == elementType } /** * checks if the node has corresponding child with elementTyp */ fun ASTNode.hasChildOfType(elementType: IElementType): Boolean = this.getFirstChildWithType(elementType) != null fun ASTNode.hasAnyChildOfTypes(vararg elementType: IElementType): Boolean = elementType.any { this.hasChildOfType(it) } /** * */ fun ASTNode.findChildBefore(beforeThisNodeType: IElementType, childNodeType: IElementType): ASTNode? { val anchorNode = getChildren(null).find { it.elementType == beforeThisNodeType } getChildren(null).toList().let { if (anchorNode != null) it.subList(0, it.indexOf(anchorNode)) else it }.reversed() .find { it.elementType == childNodeType } ?.let { return it } log.warn("Not able to find a node with type $childNodeType before $beforeThisNodeType") return null } /** * method that is trying to find and return FIRST node that matches these conditions: * 1) it is one of children of "this" * 2) it stands in the list of children AFTER the node with type @afterThisNodeType * 3) it has type @childNodeType */ fun ASTNode.findChildAfter(afterThisNodeType: IElementType, childNodeType: IElementType): ASTNode? { var foundAnchorNode = false getChildren(null).forEach { // if we have already found previous node and type matches - then can return child if (foundAnchorNode && it.elementType == childNodeType) return it // found the node that is used as anchor and we are trying to find // a node with IElementType that stands after this anchor node if (it.elementType == afterThisNodeType) { foundAnchorNode = true } } log.warn("Not able to find a node with type $childNodeType after $afterThisNodeType") return null } fun ASTNode.allSiblings(withSelf: Boolean = false): List<ASTNode> = siblings(false).toList() + (if (withSelf) listOf(this) else listOf()) + siblings(true) // applicable for PROPERTY element type only fun ASTNode.isNodeFromCompanionObject(): Boolean { val parent = this.treeParent if (parent.elementType == ElementType.CLASS_BODY) { if (parent.treeParent.elementType == ElementType.OBJECT_DECLARATION) { return true; } } return false } fun ASTNode.isNodeFromFileLevel(): Boolean = this.treeParent.elementType == FILE fun ASTNode.isValProperty() = this.getChildren(null) .any { it.elementType == ElementType.VAL_KEYWORD } fun ASTNode.isConst() = this.findLeafWithSpecificType(CONST_KEYWORD) != null fun ASTNode.isVarProperty() = this.getChildren(null) .any { it.elementType == ElementType.VAR_KEYWORD } fun ASTNode.toLower() { (this as LeafPsiElement).replaceWithText(this.text.toLowerCase()) } /** * This util method does tree traversal and stores to the result all tree leaf node of particular type (elementType). * Recursively will visit each and every node and will get leafs of specific type. Those nodes will be added to the result. */ fun ASTNode.getAllLLeafsWithSpecificType(elementType: IElementType, result: MutableList<ASTNode>) { // if statements here have the only right order - don't change it if (this.isLeaf()) { if (this.elementType == elementType) { result.add(this) } } else { this.getChildren(null).forEach { it.getAllLLeafsWithSpecificType(elementType, result) } } } /** * This util method does tree traversal and returns first node that matches specific type * This node isn't necessarily a leaf though method name implies it */ fun ASTNode.findLeafWithSpecificType(elementType: IElementType): ASTNode? { if (this.elementType == elementType) return this if (this.isLeaf()) return null this.getChildren(null).forEach { val result = it.findLeafWithSpecificType(elementType) if (result != null) return result } return null } /** * This method performs tree traversal and returns all nodes with specific element type */ fun ASTNode.findAllNodesWithSpecificType(elementType: IElementType): List<ASTNode> { val initialAcc = if (this.elementType == elementType) mutableListOf(this) else mutableListOf() return initialAcc + this.getChildren(null).flatMap { it.findAllNodesWithSpecificType(elementType) } } /** * Finds all children of optional type which match the predicate */ fun ASTNode.findChildrenMatching(elementType: IElementType? = null, predicate: (ASTNode) -> Boolean): List<ASTNode> = getChildren(elementType?.let { TokenSet.create(it) }) .filter(predicate) /** * Check if this node has any children of optional type matching the predicate */ fun ASTNode.hasChildMatching(elementType: IElementType? = null, predicate: (ASTNode) -> Boolean): Boolean = findChildrenMatching(elementType, predicate).isNotEmpty() /** * Converts this AST node and all its children to pretty string representation */ fun ASTNode.prettyPrint(level: Int = 0, maxLevel: Int = -1): String { val result = StringBuilder("${this.elementType}: \"${this.text}\"").appendln() if (maxLevel != 0) { this.getChildren(null).forEach { child -> result.append("${"-".repeat(level + 1)} " + child.prettyPrint(level + 1, maxLevel - 1)).appendln() } } return result.toString() } /** * Checks if this modifier list corresponds to accessible outside entity * @param modifierList ASTNode with ElementType.MODIFIER_LIST, can be null if entity has no modifier list */ fun ASTNode?.isAccessibleOutside(): Boolean = if (this != null) { assert(this.elementType == MODIFIER_LIST) this.hasAnyChildOfTypes(PUBLIC_KEYWORD, PROTECTED_KEYWORD, INTERNAL_KEYWORD) || !this.hasAnyChildOfTypes(PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD, PRIVATE_KEYWORD) } else { true } /** * removing all newlines in WHITE_SPACE node and replacing it to a one newline saving the initial indenting format */ fun ASTNode.leaveOnlyOneNewLine() { assert(this.elementType == WHITE_SPACE) (this as LeafPsiElement).replaceWithText("\n${this.text.replace("\n", "")}") }
0
Kotlin
0
0
23c3fc6f002fa3bdb86c93c2c1c3cac390ca3383
8,334
diKTat
MIT License
diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/AstNodeUtils.kt
fossabot
277,387,332
true
{"Kotlin": 210675, "Java": 2002, "Shell": 601}
package org.cqfn.diktat.ruleset.utils import com.pinterest.ktlint.core.ast.ElementType import com.pinterest.ktlint.core.ast.ElementType.CONST_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.FILE import com.pinterest.ktlint.core.ast.ElementType.INTERNAL_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST import com.pinterest.ktlint.core.ast.ElementType.PRIVATE_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.PROTECTED_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.PUBLIC_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE import com.pinterest.ktlint.core.ast.isLeaf import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.psi.psiUtil.siblings import org.slf4j.Logger import org.slf4j.LoggerFactory val log: Logger = LoggerFactory.getLogger(ASTNode::class.java) fun ASTNode.checkLength(range: IntRange): Boolean = this.textLength in range /** * getting first child name with IDENTIFIER type */ fun ASTNode.getIdentifierName(): ASTNode? = this.getChildren(null).find { it.elementType == ElementType.IDENTIFIER } /** * getting first child name with TYPE_PARAMETER_LIST type */ fun ASTNode.getTypeParameterList(): ASTNode? = this.getChildren(null).find { it.elementType == ElementType.TYPE_PARAMETER_LIST } /** * getting all children that have IDENTIFIER type */ fun ASTNode.getAllIdentifierChildren(): List<ASTNode> = this.getChildren(null).filter { it.elementType == ElementType.IDENTIFIER } /** * obviously returns list with children that match particular element type */ fun ASTNode.getAllChildrenWithType(elementType: IElementType): List<ASTNode> = this.getChildren(null).filter { it.elementType == elementType } /** * obviously returns first child that match particular element type */ fun ASTNode.getFirstChildWithType(elementType: IElementType): ASTNode? = this.getChildren(null).find { it.elementType == elementType } /** * checks if the node has corresponding child with elementTyp */ fun ASTNode.hasChildOfType(elementType: IElementType): Boolean = this.getFirstChildWithType(elementType) != null fun ASTNode.hasAnyChildOfTypes(vararg elementType: IElementType): Boolean = elementType.any { this.hasChildOfType(it) } /** * */ fun ASTNode.findChildBefore(beforeThisNodeType: IElementType, childNodeType: IElementType): ASTNode? { val anchorNode = getChildren(null).find { it.elementType == beforeThisNodeType } getChildren(null).toList().let { if (anchorNode != null) it.subList(0, it.indexOf(anchorNode)) else it }.reversed() .find { it.elementType == childNodeType } ?.let { return it } log.warn("Not able to find a node with type $childNodeType before $beforeThisNodeType") return null } /** * method that is trying to find and return FIRST node that matches these conditions: * 1) it is one of children of "this" * 2) it stands in the list of children AFTER the node with type @afterThisNodeType * 3) it has type @childNodeType */ fun ASTNode.findChildAfter(afterThisNodeType: IElementType, childNodeType: IElementType): ASTNode? { var foundAnchorNode = false getChildren(null).forEach { // if we have already found previous node and type matches - then can return child if (foundAnchorNode && it.elementType == childNodeType) return it // found the node that is used as anchor and we are trying to find // a node with IElementType that stands after this anchor node if (it.elementType == afterThisNodeType) { foundAnchorNode = true } } log.warn("Not able to find a node with type $childNodeType after $afterThisNodeType") return null } fun ASTNode.allSiblings(withSelf: Boolean = false): List<ASTNode> = siblings(false).toList() + (if (withSelf) listOf(this) else listOf()) + siblings(true) // applicable for PROPERTY element type only fun ASTNode.isNodeFromCompanionObject(): Boolean { val parent = this.treeParent if (parent.elementType == ElementType.CLASS_BODY) { if (parent.treeParent.elementType == ElementType.OBJECT_DECLARATION) { return true; } } return false } fun ASTNode.isNodeFromFileLevel(): Boolean = this.treeParent.elementType == FILE fun ASTNode.isValProperty() = this.getChildren(null) .any { it.elementType == ElementType.VAL_KEYWORD } fun ASTNode.isConst() = this.findLeafWithSpecificType(CONST_KEYWORD) != null fun ASTNode.isVarProperty() = this.getChildren(null) .any { it.elementType == ElementType.VAR_KEYWORD } fun ASTNode.toLower() { (this as LeafPsiElement).replaceWithText(this.text.toLowerCase()) } /** * This util method does tree traversal and stores to the result all tree leaf node of particular type (elementType). * Recursively will visit each and every node and will get leafs of specific type. Those nodes will be added to the result. */ fun ASTNode.getAllLLeafsWithSpecificType(elementType: IElementType, result: MutableList<ASTNode>) { // if statements here have the only right order - don't change it if (this.isLeaf()) { if (this.elementType == elementType) { result.add(this) } } else { this.getChildren(null).forEach { it.getAllLLeafsWithSpecificType(elementType, result) } } } /** * This util method does tree traversal and returns first node that matches specific type * This node isn't necessarily a leaf though method name implies it */ fun ASTNode.findLeafWithSpecificType(elementType: IElementType): ASTNode? { if (this.elementType == elementType) return this if (this.isLeaf()) return null this.getChildren(null).forEach { val result = it.findLeafWithSpecificType(elementType) if (result != null) return result } return null } /** * This method performs tree traversal and returns all nodes with specific element type */ fun ASTNode.findAllNodesWithSpecificType(elementType: IElementType): List<ASTNode> { val initialAcc = if (this.elementType == elementType) mutableListOf(this) else mutableListOf() return initialAcc + this.getChildren(null).flatMap { it.findAllNodesWithSpecificType(elementType) } } /** * Finds all children of optional type which match the predicate */ fun ASTNode.findChildrenMatching(elementType: IElementType? = null, predicate: (ASTNode) -> Boolean): List<ASTNode> = getChildren(elementType?.let { TokenSet.create(it) }) .filter(predicate) /** * Check if this node has any children of optional type matching the predicate */ fun ASTNode.hasChildMatching(elementType: IElementType? = null, predicate: (ASTNode) -> Boolean): Boolean = findChildrenMatching(elementType, predicate).isNotEmpty() /** * Converts this AST node and all its children to pretty string representation */ fun ASTNode.prettyPrint(level: Int = 0, maxLevel: Int = -1): String { val result = StringBuilder("${this.elementType}: \"${this.text}\"").appendln() if (maxLevel != 0) { this.getChildren(null).forEach { child -> result.append("${"-".repeat(level + 1)} " + child.prettyPrint(level + 1, maxLevel - 1)).appendln() } } return result.toString() } /** * Checks if this modifier list corresponds to accessible outside entity * @param modifierList ASTNode with ElementType.MODIFIER_LIST, can be null if entity has no modifier list */ fun ASTNode?.isAccessibleOutside(): Boolean = if (this != null) { assert(this.elementType == MODIFIER_LIST) this.hasAnyChildOfTypes(PUBLIC_KEYWORD, PROTECTED_KEYWORD, INTERNAL_KEYWORD) || !this.hasAnyChildOfTypes(PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD, PRIVATE_KEYWORD) } else { true } /** * removing all newlines in WHITE_SPACE node and replacing it to a one newline saving the initial indenting format */ fun ASTNode.leaveOnlyOneNewLine() { assert(this.elementType == WHITE_SPACE) (this as LeafPsiElement).replaceWithText("\n${this.text.replace("\n", "")}") }
0
Kotlin
0
0
23c3fc6f002fa3bdb86c93c2c1c3cac390ca3383
8,334
diKTat
MIT License
intellij-plugin-structure/structure-toolbox/src/main/kotlin/com/jetbrains/plugin/structure/toolbox/ToolboxPluginDescriptor.kt
JetBrains
3,686,654
false
null
package com.jetbrains.plugin.structure.fleet import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.jetbrains.plugin.structure.base.problems.PluginProblem import com.jetbrains.plugin.structure.base.problems.* import com.vdurmont.semver4j.Semver import com.vdurmont.semver4j.SemverException @JsonIgnoreProperties(ignoreUnknown = true) data class FleetPluginDescriptor( @JsonProperty("id") val id: String? = null, @JsonProperty("version") val version: String? = null, @JsonProperty("compatibleShipVersionRange") val compatibleShipVersionRange: FleetShipVersionRange? = null, @JsonProperty("meta") val meta: FleetMeta? = null, ) { companion object { private val NON_ID_SYMBOL_REGEX = "^[A-Za-z\\d_.]+$".toRegex() fun parse(serializedDescriptor: String): FleetPluginDescriptor { return jacksonObjectMapper().readValue(serializedDescriptor, FleetPluginDescriptor::class.java) } } fun validate(): List<PluginProblem> { val problems = mutableListOf<PluginProblem>() when { id.isNullOrBlank() -> { problems.add(PropertyNotSpecified("id")) } !NON_ID_SYMBOL_REGEX.matches(id) -> { problems.add(InvalidPluginIDProblem(id)) } } if (version.isNullOrBlank()) { problems.add(PropertyNotSpecified("version")) } if (meta?.description.isNullOrBlank()) { problems.add(PropertyNotSpecified("description")) } if (meta?.vendor.isNullOrBlank()) { problems.add(PropertyNotSpecified("vendor")) } if (id != SHIP_PLUGIN_ID) { when { compatibleShipVersionRange == null -> { problems.add(PropertyNotSpecified("compatibleShipVersionRange")) } compatibleShipVersionRange.from.isNullOrBlank() -> { problems.add(PropertyNotSpecified("compatibleShipVersionRange.from")) } compatibleShipVersionRange.to.isNullOrBlank() -> { problems.add(PropertyNotSpecified("compatibleShipVersionRange.to")) } else -> { val fromSemver = parseVersionOrNull(compatibleShipVersionRange.from) val toSemver = parseVersionOrNull(compatibleShipVersionRange.to) when { fromSemver == null -> { problems.add(FleetInvalidShipVersion("from", compatibleShipVersionRange.from)) } toSemver == null -> { problems.add(FleetInvalidShipVersion("to", compatibleShipVersionRange.to)) } fromSemver.isGreaterThan(toSemver) -> { problems.add(FleetInvalidShipVersionRange(compatibleShipVersionRange.from, compatibleShipVersionRange.to)) } else -> { val fromVersionProblems = validateVersion("from", fromSemver) problems.addAll(fromVersionProblems) if (fromVersionProblems.isEmpty()) { problems.addAll(validateVersion("to", toSemver)) } } } } } } val readableName = meta?.name when { readableName.isNullOrBlank() -> { problems.add(PropertyNotSpecified("name")) } else -> { validatePropertyLength(FleetPluginManager.DESCRIPTOR_NAME, "name", readableName, MAX_NAME_LENGTH, problems) } } return problems } private fun parseVersionOrNull(version: String): Semver? { return try { Semver(version) } catch (e: SemverException) { null } } private fun validateVersion(versionName: String, semver: Semver): Collection<PluginProblem> { val problems = mutableListOf<PluginProblem>() when { semver.major > VERSION_MAJOR_PART_MAX_VALUE -> problems.add(FleetErroneousShipVersion(versionName, "major", semver.originalValue, VERSION_MAJOR_PART_MAX_VALUE)) semver.minor > VERSION_MINOR_PART_MAX_VALUE -> problems.add(FleetErroneousShipVersion(versionName, "minor", semver.originalValue, VERSION_MINOR_PART_MAX_VALUE)) semver.patch > VERSION_PATCH_PART_MAX_VALUE -> problems.add(FleetErroneousShipVersion(versionName, "patch", semver.originalValue, VERSION_PATCH_PART_MAX_VALUE)) } return problems } } @JsonIgnoreProperties(ignoreUnknown = true) data class FleetMeta( @JsonProperty("readableName") val name: String? = null, @JsonProperty("description") val description: String? = null, @JsonProperty("vendor") val vendor: String? = null ) data class FleetShipVersionRange( @JsonProperty("from") val from: String? = null, @JsonProperty("to") val to: String? = null ) { companion object { fun fromStringToLong(version: String?): Long { return Semver(version).run { major.toLong().shl(VERSION_PATCH_LENGTH + VERSION_MINOR_LENGTH) + minor.toLong().shl(VERSION_PATCH_LENGTH) + patch } } } @Suppress("unused") fun asLongRange(): LongRange { val fromLong = fromStringToLong(from) val toLong = fromStringToLong(to) return fromLong..toLong } } private const val VERSION_PATCH_LENGTH = 14 private const val VERSION_MINOR_LENGTH = 13 const val VERSION_MAJOR_PART_MAX_VALUE = 7449 // 1110100011001 const val VERSION_MINOR_PART_MAX_VALUE = 1.shl(VERSION_MINOR_LENGTH) - 1 // 8191 const val VERSION_PATCH_PART_MAX_VALUE = 1.shl(VERSION_PATCH_LENGTH) - 1 // 16383 class FleetInvalidShipVersion( versionName: String, version: String ) : InvalidDescriptorProblem( descriptorPath = FleetPluginManager.DESCRIPTOR_NAME, detailedMessage = "The `compatibleShipVersionRange.$versionName` version should be formatted as semver [$version]." ) { override val level get() = Level.ERROR } class FleetInvalidShipVersionRange(from: String, to: String) : InvalidDescriptorProblem( descriptorPath = FleetPluginManager.DESCRIPTOR_NAME, detailedMessage = "The `compatibleShipVersionRange.from` build $from is greater than `compatibleShipVersionRange.to` build $to." ) { override val level get() = Level.ERROR } class FleetErroneousShipVersion( versionName: String, partName: String, version: String, limit: Int ) : InvalidDescriptorProblem( descriptorPath = FleetPluginManager.DESCRIPTOR_NAME, detailedMessage = "The $partName part of `compatibleShipVersionRange.$versionName` version is too big [$version]. Max value is $limit." ) { override val level: Level get() = Level.ERROR }
5
null
47
170
87f7a15fe0485314deac32184fd33cfe5133b0ee
6,447
intellij-plugin-verifier
Apache License 2.0
app/src/main/kotlin/br/com/khomdrake/zenet/date/DateActivity.kt
KhomDrake
776,191,044
false
{"Kotlin": 92853}
package br.com.khomdrake.zenet.date import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Scaffold import br.com.khomdrake.imperiya.ui.components.DefaultTopBar import br.com.khomdrake.imperiya.ui.theme.ImperiyaTheme class DateActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ImperiyaTheme { Scaffold( topBar = { DefaultTopBar(title = "Date Sample") { finish() } } ) { DateContent(paddingValues = it) } } } } }
0
Kotlin
0
0
cee648d765ca6c18a3be00160da00c1a73cb7545
830
Zenet
Apache License 2.0
app/src/main/java/com/rahuls/scribbleio/ui/components/Texts.kt
rahulsain
784,647,686
false
null
package com.rahuls.scribbleio.ui.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.rahuls.scribbleio.ui.theme.PrimaryColor @Composable fun TitleText( modifier: Modifier = Modifier, onClick: (() -> Unit)? = null, text: String, marginTop: Dp = 0.dp, marginBottom: Dp = 0.dp, marginLeft: Dp = 0.dp, marginRight: Dp = 0.dp ) { Text( text = text, modifier = modifier .clickable { onClick?.invoke() } .padding(top = marginTop, bottom = marginBottom, start = marginLeft, end = marginRight), fontSize = 32.sp, color = PrimaryColor, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ) } @Composable fun SubtitleText( modifier: Modifier = Modifier, onClick: (() -> Unit)? = null, text: String, marginTop: Dp = 0.dp, marginBottom: Dp = 0.dp, marginLeft: Dp = 0.dp, marginRight: Dp = 0.dp ) { Text( text = text, modifier = modifier .clickable { onClick?.invoke() } .padding(top = marginTop, bottom = marginBottom, start = marginLeft, end = marginRight), fontSize = 18.sp, color = PrimaryColor, fontWeight = FontWeight.Normal, textAlign = TextAlign.Center ) } @Composable fun NormalText( modifier: Modifier = Modifier, onClick: (() -> Unit)? = null, text: String, size: TextUnit, align: TextAlign = TextAlign.Left, color: Color = PrimaryColor, weight: FontWeight = FontWeight.Normal, marginTop: Dp = 0.dp, marginBottom: Dp = 0.dp, marginLeft: Dp = 0.dp, marginRight: Dp = 0.dp ) { Text( text = text, modifier = modifier .wrapContentWidth() .wrapContentHeight() .clickable { onClick?.invoke() } .padding(top = marginTop, bottom = marginBottom, start = marginLeft, end = marginRight), fontSize = size, color = color, fontWeight = weight, textAlign = align ) }
0
Kotlin
0
0
cd84bdaa4621be9ed52277437c28834228ed1440
2,609
Scribble.io-Kotlin
MIT License
app/src/main/java/com/joymower/bottomnav/BottomBarScreen.kt
Seif19022
759,335,457
false
{"Kotlin": 103800, "Java": 8822}
package com.joymower.bottomnav import com.joymower.R sealed class BottomBarScreen( val route: String, val title: String, val icon: Int, val icon_focused: Int ) { // for home object Home: BottomBarScreen( route = "home", title = "Home", icon = R.drawable.ic_bottom_home, icon_focused = R.drawable.ic_bottom_home_focused ) // for control object Report: BottomBarScreen( route = "report", title = "Control", icon = R.drawable.ic_bottom_control_filled, icon_focused = R.drawable.ic_bottom_control_filled ) // for scheduled Mowings object Mowing: BottomBarScreen( route = "Mowing", title = "Scheduled mowing", icon = R.drawable.ic_bottom_patrols_filled, icon_focused = R.drawable.ic_bottom_patrols_filled ) // for data log object Log: BottomBarScreen( route = "log", title = "Historical Data and Analytics", icon = R.drawable.ic_bottom_report, icon_focused = R.drawable.ic_bottom_report_focused ) // for report object Profile: BottomBarScreen( route = "profile", title = "Profile", icon = R.drawable.ic_bottom_profile, icon_focused = R.drawable.ic_bottom_profile_focused ) }
0
Kotlin
0
1
8b70d3df6ed5b6ca025ef123ac676cb87c0cabfd
1,313
JoyMower
Apache License 2.0
diktat-rules/src/test/resources/test/paragraph1/naming/identifiers/VariableNamingTest.kt
petertrr
284,037,259
false
null
package test.paragraph1.naming.identifiers private var PascalCase = "" private var UPPER = "" private var UPPER_SNAKE = "" private var lower_snake = "" private val I_AM_CONSTANT1 = "" private val STRANGE_name = "" private val loWer_VAlue = "" private val lower = "" private val ValN_x256 = "" private val VoiceIP_port = ""
2
Kotlin
0
1
45231eddab4e968db6f19a6ad82ae96f14223385
324
diktat-backup
MIT License
spring-bank-project/spring-bank-api/src/commonMain/kotlin/io/joel/springbank/api/Format.kt
jnfeinstein
347,686,329
false
null
package io.joel.springbank.api import io.joel.springbank.api.request.* import io.joel.springbank.api.response.AccountCreatedResponse import io.joel.springbank.api.response.AccountDeletedResponse import io.joel.springbank.api.response.AccountUpdatedResponse import kotlinx.serialization.* import kotlinx.serialization.modules.* import kotlinx.serialization.protobuf.ProtoBuf public object Format { public fun toProtobuf(obj: Message): ByteArray = format.encodeToByteArray(PolymorphicSerializer(Message::class), obj) public fun fromProtobuf(arr: ByteArray): Message = format.decodeFromByteArray(PolymorphicSerializer(Message::class), arr) private val format = ProtoBuf { serializersModule = SerializersModule { polymorphic(Message::class) { // Requests subclass(CreateAccountRequest::class) subclass(DeleteAccountRequest::class) subclass(EchoRequest::class) subclass(NullRequest::class) subclass(UnitRequest::class) subclass(UpdateAccountRequest::class) // Responses subclass(AccountCreatedResponse::class) subclass(AccountDeletedResponse::class) subclass(AccountUpdatedResponse::class) } } } }
0
Kotlin
0
1
5e9d9bcf47fcefb77c466990d2e7c4fce070711c
1,329
spring-bank
MIT License
api/src/main/kotlin/net/devslash/SessionManager.kt
devslash-paul
152,959,898
false
null
package net.devslash interface SessionManager { fun <T> call(call: Call<T>, session: Session, jar: CookieJar): Exception? fun <T> call(call: Call<T>, session: Session): Exception? }
7
Kotlin
2
9
9346d497282869958f913bb84459921f53e3288e
187
fetchDSL
MIT License
kalexa-model/src/main/kotlin/com/hp/kalexa/model/request/list/ListBody.kt
HPInc
164,478,295
false
null
/* * Copyright 2018 HP Development Company, L.P. * SPDX-License-Identifier: MIT */ package com.hp.kalexa.model.request.list class ListBody(val listId: String)
0
Kotlin
1
17
e6674eeb24c255aef1859a62a65b805effdc9676
164
kalexa-sdk
MIT License
libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/roomlist/RustRoomListService.kt
SchildiChat
698,978,200
false
{"Kotlin": 4687234, "Shell": 41988, "Java": 9607, "Python": 8683, "JavaScript": 8215, "Ruby": 44}
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.libraries.matrix.impl.roomlist import io.element.android.libraries.matrix.api.roomlist.RoomList import io.element.android.libraries.matrix.api.roomlist.RoomListService import io.element.android.libraries.matrix.api.roomlist.RoomSummary import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import org.matrix.rustcomponents.sdk.RoomListEntriesUpdate import org.matrix.rustcomponents.sdk.RoomListException import org.matrix.rustcomponents.sdk.RoomListInput import org.matrix.rustcomponents.sdk.RoomListLoadingState import org.matrix.rustcomponents.sdk.RoomListRange import org.matrix.rustcomponents.sdk.RoomListServiceState import org.matrix.rustcomponents.sdk.RoomListServiceSyncIndicator import timber.log.Timber import org.matrix.rustcomponents.sdk.RoomListService as InnerRustRoomListService class RustRoomListService( private val innerRoomListService: InnerRustRoomListService, private val sessionCoroutineScope: CoroutineScope, private val dispatcher: CoroutineDispatcher, roomSummaryDetailsFactory: RoomSummaryDetailsFactory = RoomSummaryDetailsFactory(), ) : RoomListService { private val allRooms = MutableStateFlow<List<RoomSummary>>(emptyList()) private val inviteRooms = MutableStateFlow<List<RoomSummary>>(emptyList()) private val allRoomsLoadingState: MutableStateFlow<RoomList.LoadingState> = MutableStateFlow(RoomList.LoadingState.NotLoaded) private val allRoomsListProcessor = RoomSummaryListProcessor(allRooms, innerRoomListService, dispatcher, roomSummaryDetailsFactory) private val invitesLoadingState: MutableStateFlow<RoomList.LoadingState> = MutableStateFlow(RoomList.LoadingState.NotLoaded) private val inviteRoomsListProcessor = RoomSummaryListProcessor(inviteRooms, innerRoomListService, dispatcher, roomSummaryDetailsFactory) init { sessionCoroutineScope.launch(dispatcher) { val allRooms = innerRoomListService.allRooms() allRooms .observeEntriesWithProcessor(allRoomsListProcessor) .launchIn(this) allRooms .observeLoadingState(allRoomsLoadingState) .launchIn(this) launch { // Wait until running, as invites is only available after that innerRoomListService.stateFlow().first { it == RoomListServiceState.RUNNING } val invites = innerRoomListService.invites() invites .observeEntriesWithProcessor(inviteRoomsListProcessor) .launchIn(this) invites .observeLoadingState(invitesLoadingState) .launchIn(this) } } } override fun allRooms(): RoomList { return RustRoomList(allRooms, allRoomsLoadingState) } override fun invites(): RoomList { return RustRoomList(inviteRooms, invitesLoadingState) } override fun updateAllRoomsVisibleRange(range: IntRange) { Timber.v("setVisibleRange=$range") sessionCoroutineScope.launch { try { val ranges = listOf(RoomListRange(range.first.toUInt(), range.last.toUInt())) innerRoomListService.applyInput( RoomListInput.Viewport(ranges) ) } catch (exception: RoomListException) { Timber.e(exception, "Failed updating visible range") } } } override fun rebuildRoomSummaries() { sessionCoroutineScope.launch { allRoomsListProcessor.rebuildRoomSummaries() } } override val syncIndicator: StateFlow<RoomListService.SyncIndicator> = innerRoomListService.syncIndicator() .map { it.toSyncIndicator() } .onEach { syncIndicator -> Timber.d("SyncIndicator = $syncIndicator") } .distinctUntilChanged() .stateIn(sessionCoroutineScope, SharingStarted.Eagerly, RoomListService.SyncIndicator.Hide) override val state: StateFlow<RoomListService.State> = innerRoomListService.stateFlow() .map { it.toRoomListState() } .onEach { state -> Timber.d("RoomList state=$state") } .distinctUntilChanged() .stateIn(sessionCoroutineScope, SharingStarted.Eagerly, RoomListService.State.Idle) } private fun RoomListLoadingState.toLoadingState(): RoomList.LoadingState { return when (this) { is RoomListLoadingState.Loaded -> RoomList.LoadingState.Loaded(maximumNumberOfRooms?.toInt() ?: 0) RoomListLoadingState.NotLoaded -> RoomList.LoadingState.NotLoaded } } private fun RoomListServiceState.toRoomListState(): RoomListService.State { return when (this) { RoomListServiceState.INITIAL, RoomListServiceState.RECOVERING, RoomListServiceState.SETTING_UP -> RoomListService.State.Idle RoomListServiceState.RUNNING -> RoomListService.State.Running RoomListServiceState.ERROR -> RoomListService.State.Error RoomListServiceState.TERMINATED -> RoomListService.State.Terminated } } private fun RoomListServiceSyncIndicator.toSyncIndicator(): RoomListService.SyncIndicator { return when (this) { RoomListServiceSyncIndicator.SHOW -> RoomListService.SyncIndicator.Show RoomListServiceSyncIndicator.HIDE -> RoomListService.SyncIndicator.Hide } } private fun org.matrix.rustcomponents.sdk.RoomList.observeEntriesWithProcessor(processor: RoomSummaryListProcessor): Flow<List<RoomListEntriesUpdate>> { return entriesFlow { roomListEntries -> processor.postEntries(roomListEntries) }.onEach { update -> processor.postUpdate(update) } } private fun org.matrix.rustcomponents.sdk.RoomList.observeLoadingState(stateFlow: MutableStateFlow<RoomList.LoadingState>): Flow<RoomList.LoadingState> { return loadingStateFlow() .map { it.toLoadingState() } .onEach { stateFlow.value = it } }
105
Kotlin
32
8
33a3656df402925d704a5826a2a195588d85f7f4
7,172
schildichat-android-next
Apache License 2.0