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
src/2021/Day17_1.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import kotlin.math.absoluteValue import kotlin.math.max File("input/2021/day17").forEachLine { line -> val (xTarget, yTarget) = line.substring(13).split(", ") val (xMin, xMax) = xTarget.substring(2).split("..").map { it.toInt() }.sortedBy { it } val (yMin, yMax) = yTarget.substring(2).split("..").map { it.toInt() }.sortedBy { it } val xRange = xMin.toInt()..xMax.toInt() val yRange = yMin.toInt()..yMax.toInt() var initVel = Pair(0,0) var maxYPos = Int.MIN_VALUE for (x in 0..500) { for (y in -200..200) { var localYMax = Int.MIN_VALUE var position = Pair(0,0) var velocity = Pair(x,y) var steps = 0 var over = false while (true) { steps++ val nX = position.first + velocity.first val nY = position.second + velocity.second position = Pair(nX, nY) if (nY > localYMax) localYMax = nY val inX = position.first >= xRange.first && position.first <= xRange.last val inY = position.second >= yRange.first && position.second <= yRange.last if (inX && inY) break val short = (nX < xRange.first && nY < yRange.first) val long = (nX > xRange.last && nY < yRange.first) val toMuchY = (nY < yRange.last) if (short || long || toMuchY) { over = true break } val nVX = if (velocity.first > 0) velocity.first - 1 else if (velocity.first < 0) velocity.first + 1 else velocity.first val nVY = velocity.second - 1 velocity = Pair(nVX, nVY) } if (!over){ maxYPos = max(localYMax, maxYPos) initVel = Pair(x,y) } } } println(maxYPos) }
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,932
adventofcode
MIT License
shared/src/main/java/xyz/klinker/messenger/shared/util/BlacklistUtils.kt
zacharee
295,825,167
false
null
/* * Copyright (C) 2020 Luke Klinker * * 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 xyz.heart.sms.shared.util import android.content.Context import android.util.Log import xyz.heart.sms.shared.data.DataSource import xyz.heart.sms.shared.data.Settings import xyz.heart.sms.shared.data.model.Blacklist import xyz.heart.sms.shared.data.pojo.UnknownNumbersReception import java.util.regex.PatternSyntaxException /** * Helper for checking whether or not a contact is blacklisted. */ object BlacklistUtils { fun isBlacklisted(context: Context, incomingNumber: String, incomingText: String?): Boolean { val source = DataSource val cursor = source.getBlacklists(context) val numberIndex = cursor.getColumnIndex(Blacklist.COLUMN_PHONE_NUMBER) val phraseIndex = cursor.getColumnIndex(Blacklist.COLUMN_PHRASE) if (cursor.moveToFirst()) { do { val blacklistedNumber = cursor.getString(numberIndex) if (!blacklistedNumber.isNullOrBlank() && numbersMatch(incomingNumber, blacklistedNumber)) { Log.v("Blacklist", "$incomingNumber matched phone number blacklist: $blacklistedNumber") CursorUtil.closeSilent(cursor) return true } val blacklistedPhrase = cursor.getString(phraseIndex) val isBlacklisted = !blacklistedPhrase.isNullOrBlank() && if (Settings.blacklistPhraseRegex) textMatchesBlacklistRegex(blacklistedPhrase, incomingText) else textMatchesBlacklistPhrase(blacklistedPhrase, incomingText) if (isBlacklisted) { Log.v("Blacklist", "$incomingText matched phrase blacklist: $incomingText") CursorUtil.closeSilent(cursor) return true } } while (cursor.moveToNext()) } cursor.closeSilent() return isBlockedAsUnknownNumber(context, incomingNumber) } private fun textMatchesBlacklistPhrase(blacklistedPhrase: String, incomingText: String?): Boolean { return incomingText?.toLowerCase()?.contains(blacklistedPhrase.toLowerCase()) == true; } private fun textMatchesBlacklistRegex(blacklistedPhrase: String, incomingText: String?): Boolean { if (incomingText == null) { return false; } return try { Regex(blacklistedPhrase, setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE)).containsMatchIn(incomingText); } catch (e: PatternSyntaxException) { // Return false if they put in an invalid regex false; } } fun isMutedAsUnknownNumber(context: Context, number: String): Boolean { if (Settings.unknownNumbersReception != UnknownNumbersReception.MUTE) { return false } return !contactExists(context, number) } private fun isBlockedAsUnknownNumber(context: Context, number: String): Boolean { if (Settings.unknownNumbersReception != UnknownNumbersReception.BLOCK) { return false } return !contactExists(context, number) } private fun contactExists(context: Context, number: String) = try { val id = ContactUtils.findContactId(number, context) id != -1 } catch (e: NoSuchElementException) { false } fun numbersMatch(number: String, blacklisted: String): Boolean { if (number == blacklisted) { // some countries get spam from lettered number (HP-BHKPOS) // those would not get matched when it goes into the id matchers, // since the letters all get stripped out. return true } val number = PhoneNumberUtils.clearFormattingAndStripStandardReplacements(number) val blacklisted = PhoneNumberUtils.clearFormattingAndStripStandardReplacements(blacklisted) val numberMatchers = SmsMmsUtils.createIdMatcher(number) val blacklistMatchers = SmsMmsUtils.createIdMatcher(blacklisted) val shorterLength = if (number.length < blacklisted.length) number.length else blacklisted.length return when { shorterLength >= 10 -> numberMatchers.tenLetter == blacklistMatchers.tenLetter shorterLength in 8..9 -> numberMatchers.eightLetter == blacklistMatchers.eightLetter shorterLength == 7 -> numberMatchers.sevenLetter == blacklistMatchers.sevenLetter number.length == blacklisted.length -> numberMatchers.fiveLetter == blacklistMatchers.fiveLetter else -> false } } }
1
null
7
4
f957421823801b617194cd68e31ba31b96e6100b
5,173
pulse-sms-android
Apache License 2.0
src/test/kotlin/no/nav/syfo/testhelper/TestDatabase.kt
navikt
378,118,189
false
null
package no.nav.syfo.testhelper import com.opentable.db.postgres.embedded.EmbeddedPostgres import no.nav.syfo.application.database.DatabaseInterface import no.nav.syfo.behandler.database.* import no.nav.syfo.behandler.domain.* import no.nav.syfo.domain.PersonIdentNumber import org.flywaydb.core.Flyway import java.sql.Connection import java.util.* class TestDatabase : DatabaseInterface { private val pg: EmbeddedPostgres override val connection: Connection get() = pg.postgresDatabase.connection.apply { autoCommit = false } init { pg = try { EmbeddedPostgres.start() } catch (e: Exception) { EmbeddedPostgres.builder().setLocaleConfig("locale", "en_US").start() } Flyway.configure().run { dataSource(pg.postgresDatabase).load().migrate() } } fun stop() { pg.close() } } class TestDatabaseNotResponding : DatabaseInterface { override val connection: Connection get() = throw Exception("Not working") fun stop() { } } fun DatabaseInterface.createBehandlerForArbeidstaker( behandler: Behandler, arbeidstakerPersonIdent: PersonIdentNumber, ): UUID { this.connection.use { connection -> val pBehandlerKontor = connection.getBehandlerKontorForPartnerId(behandler.kontor.partnerId) val kontorId = if (pBehandlerKontor != null) { pBehandlerKontor.id } else { connection.createBehandlerKontor(behandler.kontor) } val createdBehandler = connection.createBehandler(behandler, kontorId) connection.createBehandlerArbeidstakerRelasjon( BehandlerArbeidstakerRelasjon( type = BehandlerArbeidstakerRelasjonType.FASTLEGE, arbeidstakerPersonident = arbeidstakerPersonIdent, ), createdBehandler.id ) connection.commit() return createdBehandler.behandlerRef } } fun DatabaseInterface.dropData() { val queryList = listOf( """ DELETE FROM BEHANDLER_DIALOGMELDING_BESTILLING """.trimIndent(), """ DELETE FROM BEHANDLER_ARBEIDSTAKER """.trimIndent(), """ DELETE FROM BEHANDLER """.trimIndent(), """ DELETE FROM BEHANDLER_KONTOR """.trimIndent(), ) this.connection.use { connection -> queryList.forEach { query -> connection.prepareStatement(query).execute() } connection.commit() } }
1
Kotlin
1
0
dd12b992684acda2da79c73c5364ece6d58f3dbd
2,570
isdialogmelding
MIT License
app/src/main/java/com/cornellappdev/android/volume/ui/screens/FlyerSuccessScreen.kt
cuappdev
466,793,799
false
{"Kotlin": 449813}
package com.cornellappdev.android.volume.ui.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.cornellappdev.android.volume.ui.components.general.VolumeButton import com.cornellappdev.android.volume.ui.theme.lato import com.cornellappdev.android.volume.ui.theme.notoserif @Composable fun FlyerSuccessScreen(onGoToFlyersClicked: () -> Unit) { Box(modifier = Modifier.fillMaxSize()) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Text( text = "Settings", fontSize = 20.sp, fontFamily = notoserif, modifier = Modifier.padding(top = 16.dp), ) } Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Flyer Published!", fontSize = 20.sp, fontFamily = notoserif, modifier = Modifier.padding(top = 16.dp), fontWeight = FontWeight.Bold ) Text(text = "Thank you for using Volume.", fontSize = 14.sp, fontFamily = lato) Spacer(Modifier.height(24.dp)) VolumeButton( text = "Go to Flyers", onClick = onGoToFlyersClicked, enabled = true, modifier = Modifier.padding(horizontal = 8.dp) ) } } }
1
Kotlin
1
2
0d2eed5b6cc20456e924b33c390205e302231c1f
2,190
volume-compose-android
MIT License
compiler/testData/cli/jvm/pluginSimpleUsage.kt
gigliovale
89,726,097
false
{"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721}
import android.view.* import android.app.* import android.widget.* import kotlinx.android.synthetic.main.layout.* class MyActivity : Activity() { { textView.setText("Some text") } }
0
Java
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
186
kotlin
Apache License 2.0
src/jsMain/kotlin/koin.kt
jillesvangurp
808,400,950
false
{"Kotlin": 61035, "JavaScript": 3746, "HTML": 2299, "Fluent": 2090, "Shell": 417, "CSS": 336}
import ai.translationServiceModule import dev.fritz2.core.RenderContext import dev.fritz2.core.render import files.fileLoaderModule import localization.TranslationStore import org.koin.core.Koin import org.koin.core.context.GlobalContext import org.koin.core.context.startKoin import routing.routingModule import settings.settingsModule inline fun <T> withKoin(block: Koin.() -> T): T = with(GlobalContext.get()) { block(this) } suspend fun startAppWithKoin(ui: RenderContext.()->Unit) { startKoin { modules( routingModule, settingsModule, fileLoaderModule, translationServiceModule, ) } withKoin { // load is a suspend function // so we declare this component last declare(TranslationStore.load(get(), fallback = "en-US")) } render("#target", content=ui) }
0
Kotlin
0
0
a3366ff5249f92d84b02a425913dfd5c2a3f24c7
873
fluent-ai
MIT License
app/src/main/java/com/example/taskmanagement/data/entities/relations/TaskWithTaskMembers.kt
ariya-darvishi
442,359,560
false
{"Kotlin": 78128}
package com.example.taskmanagement.data.entities.relations import androidx.room.Embedded import androidx.room.Relation import com.example.taskmanagement.data.entities.Task import com.example.taskmanagement.data.entities.TaskMember import com.example.taskmanagement.data.entities.User data class TaskWithTaskMembers( @Embedded val task: Task, @Relation( parentColumn = "taskId", entityColumn = "taskId" ) val taskMembers: List<TaskMember> )
0
Kotlin
0
1
e203a89feb086a589d33eb33ad88243200f90fb0
478
TaskManagement
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/gimlet2/kottpd/ClientThread.kt
gimlet2
65,999,896
false
null
package com.fabiomazzo.mayfly.server /** * Created by fabiomazzo on 13/03/2017. */ import java.io.BufferedReader import java.io.InputStreamReader import java.net.Socket import java.util.* class ClientThread(val socket: Socket, val match: (HttpRequest) -> (HttpRequest, HttpResponse) -> Any) : Runnable { override fun run() { val input = BufferedReader(InputStreamReader(socket.inputStream)) val out = socket.outputStream val request = readRequest(input, { LinkedHashMap<String, String>().apply { input.lineSequence().takeWhile(String::isNotBlank).forEach { line -> line.split(":").let { put(it[0], it[1].trim()) } } } }) val httpResponse = HttpResponse(stream = out) val result = match(request).invoke(request, httpResponse) if (result !is Unit) { httpResponse.send(result.toString()) } httpResponse.flush() socket.close() } fun readRequest(reader: BufferedReader, eval: () -> Map<String, String>): HttpRequest { reader.readLine().split(' ').let { return HttpRequest(HttpMethod.valueOf(it[0]), it[1], it[2], eval(), reader) } } }
12
Kotlin
15
74
748d0c4dd366318b5cf84ea1c71a54b0d30e101d
1,292
kottpd
MIT License
lib-common/src/main/kotlin/com/github/arhor/aws/graphql/federation/common/exception/EntityOperationRestrictedException.kt
arhor
651,576,809
false
{"Kotlin": 302224, "Java": 181286, "TypeScript": 67168, "JavaScript": 9167, "HTML": 596, "Shell": 569, "Dockerfile": 546, "Batchfile": 477, "CSS": 363}
package com.github.arhor.aws.graphql.federation.common.exception class EntityOperationRestrictedException @JvmOverloads constructor( entity: String, condition: String, operation: Operation, cause: Exception? = null, ) : EntityConditionException(entity, condition, operation, cause)
0
Kotlin
1
2
4b986d1aa42f729a607f2dd05d3a560fe00281db
299
aws-graphql-federation
Apache License 2.0
src/main/kotlin/compxclib/functions/Exponential.kt
KatieUmbra
576,068,427
false
null
package compxclib.functions import compxclib.* import compxclib.operators.div import compxclib.operators.times import kotlin.math.cos import kotlin.math.exp import kotlin.math.sin // exponential functions /** * Exp of a [ComplexNumber] * * exp(z) or e^z is defined used euler's formula * `e^(a+bi) = e^a * (cos(b) + isin(b))` * @param of that is a [ComplexNumber] * @return exp([ComplexNumber]) * @since Version 1.0 */ fun exp(of: ComplexNumber): ComplexNumber { return exp(of.re()) * ComplexNumber(cos(of.im()), sin(of.im())) } /** * Sqrt or Square Root of a [ComplexNumber] * * sqrt(z) is defined as `z pow 0.5` * @param of that is a [ComplexNumber] * @return sqrt([ComplexNumber]) * @since Version 1.0 */ @Suppress("unused") fun sqrt(of: ComplexNumber): ComplexNumber { return of pow 0.5 } /** * Cbrt or Cubic Root of a [ComplexNumber] * * cbrt(z) is defined as `z pow 0.333...` * @param of that is a [ComplexNumber] * @return cbrt([ComplexNumber]) * @since Version 1.0 */ @Suppress("unused") fun cbrt(of: ComplexNumber): ComplexNumber { return of pow 1/3 } /** * Nthrt or Nth Root of a [ComplexNumber] * * nthrt(z) is defined as `z pow 1/n` * @param of that is a [ComplexNumber] * @param n that is a [Number] * @return nthrt([ComplexNumber]) * @since Version 1.0 */ @Suppress("unused") fun nthrt(of: ComplexNumber, n: Number): ComplexNumber { return of pow 1/n.toDouble() } /** * Nthrt or Nth Root of a [ComplexNumber] * * nthrt(z, n) is defined as `z pow 1/n` * @param of that is a [ComplexNumber] * @param n that is a [ComplexNumber] * @return nthrt([ComplexNumber]) * @since Version 1.0 */ @Suppress("unused") fun nthrt(of: ComplexNumber, n: ComplexNumber): ComplexNumber { return of pow 1/n }
0
Kotlin
0
0
59f4d5c32e90c0ed1de3dd0b6a349a9eed99d80b
1,764
compxclib
MIT License
logging/src/main/java/com/lyscraft/logging/di/LogModule.kt
brahman10
843,088,920
false
{"Kotlin": 47388}
package com.lyscraft.logging.di import android.content.Context import com.lyscraft.logging.crashLogging.CrashLogger import com.lyscraft.logging.eventLogging.EventLogger import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object LogModule { @Provides @Singleton fun provideCrashLogger(context: Context): CrashLogger = CrashLogger(context) @Provides @Singleton fun provideEventLogger(context: Context): EventLogger = EventLogger(context) }
0
Kotlin
0
0
fdfbc5a48a48933d667f97aefba8348f11bf56d8
610
MovieAppCompose
MIT License
temperature/src/commonMain/kotlin/com/boswelja/temperature/TemperatureUnit.kt
boswelja
780,714,635
false
{"Kotlin": 43226}
@file:Suppress("MagicNumber") package com.boswelja.temperature import com.ionspin.kotlin.bignum.decimal.BigDecimal private val CELSIUS_KELVIN_OFFSET = BigDecimal.fromDouble(273.15) private val FAHRENHEIT_KELVIN_OFFSET = BigDecimal.fromDouble(459.67) private val FAHRENHEIT_KELVIN_FACTOR = BigDecimal.fromDouble(1.8) private val RANKINE_KELVIN_FACTOR = BigDecimal.fromDouble(1.8) private val REAUMUR_KELVIN_OFFSET = BigDecimal.fromDouble(273.15) private val REAUMUR_KELVIN_FACTOR = BigDecimal.fromDouble(1.25) /** * Defines various units supported by [Temperature]. We can convert to/from any of these. */ enum class TemperatureUnit( internal val toKelvin: (BigDecimal) -> BigDecimal, internal val fromKelvin: (BigDecimal) -> BigDecimal, ) { KELVIN({ it }, { it }), CELSIUS( toKelvin = { it + CELSIUS_KELVIN_OFFSET }, fromKelvin = { it - CELSIUS_KELVIN_OFFSET } ), FAHRENHEIT( toKelvin = { (it + FAHRENHEIT_KELVIN_OFFSET) / FAHRENHEIT_KELVIN_FACTOR }, fromKelvin = { (it * FAHRENHEIT_KELVIN_FACTOR) - FAHRENHEIT_KELVIN_OFFSET } ), RANKINE( toKelvin = { it / RANKINE_KELVIN_FACTOR }, fromKelvin = { it * RANKINE_KELVIN_FACTOR } ), REAUMUR( toKelvin = { (it * REAUMUR_KELVIN_FACTOR) + REAUMUR_KELVIN_OFFSET }, fromKelvin = { (it - REAUMUR_KELVIN_OFFSET) / REAUMUR_KELVIN_FACTOR } ) }
1
Kotlin
0
1
828841cb575721da0342de8112a09572ec3a1c14
1,554
kotlin-datatypes
Apache License 2.0
src/main/kotlin/org/teamvoided/voided_utils/registries/VUItems.kt
TeamVoided
670,363,471
false
null
package org.teamvoided.voided_utils.registries import net.fabricmc.fabric.api.item.v1.FabricItemSettings import net.minecraft.item.* import net.minecraft.registry.Registries import net.minecraft.registry.Registry import org.teamvoided.voided_utils.VoidedUtils.getConfig import org.teamvoided.voided_utils.VoidedUtils.id import java.util.* @Suppress("MemberVisibilityCanBePrivate") object VUItems { val ITEM_LIST = LinkedList<Item>() val ALL_ITEM_LIST = LinkedList<Item>() private val settings: FabricItemSettings = FabricItemSettings().maxCount(64) val CHARRED_SIGN: Item = SignItem(Item.Settings().maxCount(16), VUBlocks.CHARRED_SIGN, VUBlocks.CHARRED_WALL_SIGN) val CHARRED_HANGING_SIGN: Item = HangingSignItem(VUBlocks.CHARRED_HANGING_SIGN, VUBlocks.CHARRED_WALL_HANGING_SIGN, Item.Settings().maxCount(16)) fun init() { val c = getConfig() if (c.enableCharredWoodSet) { register("charred_sign", CHARRED_SIGN) register("charred_hanging_sign", CHARRED_HANGING_SIGN) } } private fun register(id: String, item: Item): Item { ITEM_LIST.add(item) ALL_ITEM_LIST.add(item) return Registry.register(Registries.ITEM, id(id), item) } }
0
Kotlin
0
0
a3b84c83f27ce7a07794329b53c39326a5bd6f29
1,251
VoidedUtils
MIT License
core/domain/src/main/java/com/github/mukiva/openweather/core/domain/settings/UnitsType.kt
MUKIVA
715,584,869
false
{"Kotlin": 323153}
package com.github.mukiva.openweather.core.domain.settings enum class UnitsType { METRIC, IMPERIAL, }
0
Kotlin
0
5
c616fcc30cbea2fa079fac76c4eb16ec6922705d
111
open-weather
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Bolt.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline 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.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.Bolt: ImageVector get() { if (_bolt != null) { return _bolt!! } _bolt = Builder(name = "Bolt", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 3.0f) lineToRelative(0.0f, 7.0f) lineToRelative(6.0f, 0.0f) lineToRelative(-8.0f, 11.0f) lineToRelative(0.0f, -7.0f) lineToRelative(-6.0f, 0.0f) lineToRelative(8.0f, -11.0f) } } .build() return _bolt!! } private var _bolt: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
1,621
compose-icon-collections
MIT License
app/readview/src/main/java/org/peyilo/readview/parser/ContentParser.kt
Peyilo
756,846,308
false
{"Kotlin": 95419, "Java": 29166}
package org.peyilo.readview.parser import org.peyilo.readview.data.ChapData interface ContentParser { /** * 解析ChapData的内容,生成一个由多个Content以及基本章节信息构成的ReadChapter */ fun parse(chapData: ChapData): ReadChapter }
0
Kotlin
0
0
dee34a96a891a284642a84113e86c50b3b9d2593
228
ReadView
MIT License
TheShareMaster/src/main/java/common/share/wx/WxSdkConfig.kt
feer921
323,617,736
false
null
package common.share.wx import common.share.core.ASdkConfig /** * ******************(^_^)***********************<br> * User: fee(QQ/WeiXin:1176610771)<br> * <P>DESC: * 微信SDK 的配置信息类 * </p> * ******************(^_^)*********************** */ class WxSdkConfig : ASdkConfig() { var needCheckSignature = true }
0
Kotlin
0
2
bd1d777f5bc02fc801696435d411667801bee1a1
319
ShareMaster
Apache License 2.0
compiler/tests-spec/testData/psi/linked/constant-literals/boolean-literals/p-1/neg/2.20.kt
haerulmuttaqin
156,727,010
true
{"Kotlin": 31513732, "Java": 7641810, "JavaScript": 152543, "HTML": 68411, "Lex": 18275, "IDL": 10060, "ANTLR": 9803, "Shell": 6769, "Groovy": 5466, "CSS": 4679, "Batchfile": 4437}
/* KOTLIN PSI SPEC TEST (NEGATIVE) SECTIONS: constant-literals, boolean-literals PARAGRAPH: 1 SENTENCE: [2] These are strong keywords which cannot be used as identifiers unless escaped. NUMBER: 20 DESCRIPTION: The use of Boolean literals as the identifier (without backtick) in the infixFunctionCall. NOTE: this test data is generated by FeatureInteractionTestDataGenerator. DO NOT MODIFY CODE MANUALLY! */ fun f() { 1 + 1 true 10..11 1 + 1 false 10..11 true 10 false -.9-9.0 }
0
Kotlin
1
2
8f2117685f9f1b76b7f61ef67c0f58431bbf2f0e
496
kotlin
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/PuzzlePiece.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.PuzzlePiece: ImageVector get() { if (_puzzlePiece != null) { return _puzzlePiece!! } _puzzlePiece = Builder(name = "PuzzlePiece", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.842f, 12.0f) arcTo(19.074f, 19.074f, 0.0f, false, false, 18.0f, 12.477f) verticalLineTo(9.5f) arcTo(3.5f, 3.5f, 0.0f, false, false, 14.5f, 6.0f) horizontalLineTo(11.521f) curveToRelative(0.061f, -0.337f, 0.128f, -0.7f, 0.193f, -1.033f) arcTo(12.623f, 12.623f, 0.0f, false, false, 12.0f, 3.158f) arcTo(2.949f, 2.949f, 0.0f, false, false, 9.0f, 0.0f) arcTo(2.949f, 2.949f, 0.0f, false, false, 6.0f, 3.158f) arcToRelative(13.691f, 13.691f, 0.0f, false, false, 0.3f, 1.913f) curveToRelative(0.058f, 0.308f, 0.118f, 0.627f, 0.173f, 0.929f) horizontalLineTo(3.409f) arcTo(3.419f, 3.419f, 0.0f, false, false, 0.0f, 9.422f) verticalLineTo(24.0f) horizontalLineTo(18.0f) verticalLineTo(17.521f) arcTo(19.065f, 19.065f, 0.0f, false, false, 20.842f, 18.0f) arcToRelative(3.0f, 3.0f, 0.0f, true, false, 0.0f, -6.0f) close() moveTo(15.0f, 21.0f) horizontalLineTo(11.521f) curveToRelative(0.061f, -0.337f, 0.128f, -0.7f, 0.193f, -1.033f) arcTo(12.623f, 12.623f, 0.0f, false, false, 12.0f, 18.158f) arcTo(2.949f, 2.949f, 0.0f, false, false, 9.0f, 15.0f) arcToRelative(2.949f, 2.949f, 0.0f, false, false, -3.0f, 3.158f) arcToRelative(13.691f, 13.691f, 0.0f, false, false, 0.3f, 1.913f) curveToRelative(0.058f, 0.308f, 0.118f, 0.627f, 0.173f, 0.929f) horizontalLineTo(3.0f) verticalLineTo(9.422f) arcTo(0.421f, 0.421f, 0.0f, false, true, 3.409f, 9.0f) horizontalLineTo(14.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f) close() } } .build() return _puzzlePiece!! } private var _puzzlePiece: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,189
icons
MIT License
privacysandbox/sdkruntime/sdkruntime-client/src/androidTest/java/androidx/privacysandbox/sdkruntime/client/controller/LocalControllerTest.kt
androidx
256,589,781
false
null
/* * Copyright 2023 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.privacysandbox.sdkruntime.client.controller import android.os.Binder import android.os.Bundle import androidx.privacysandbox.sdkruntime.client.activity.LocalSdkActivityHandlerRegistry import androidx.privacysandbox.sdkruntime.core.AppOwnedSdkSandboxInterfaceCompat import androidx.privacysandbox.sdkruntime.core.LoadSdkCompatException import androidx.privacysandbox.sdkruntime.core.SandboxedSdkCompat import androidx.privacysandbox.sdkruntime.core.activity.ActivityHolder import androidx.privacysandbox.sdkruntime.core.activity.SdkSandboxActivityHandlerCompat import androidx.privacysandbox.sdkruntime.core.controller.LoadSdkCallback import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class LocalControllerTest { private lateinit var localSdkRegistry: StubLocalSdkRegistry private lateinit var appOwnedSdkRegistry: StubAppOwnedSdkInterfaceRegistry private lateinit var controller: LocalController @Before fun setUp() { localSdkRegistry = StubLocalSdkRegistry() appOwnedSdkRegistry = StubAppOwnedSdkInterfaceRegistry() controller = LocalController(SDK_PACKAGE_NAME, localSdkRegistry, appOwnedSdkRegistry) } @Test fun loadSdk_whenSdkRegistryReturnsResult_returnResultFromSdkRegistry() { val expectedResult = SandboxedSdkCompat(Binder()) localSdkRegistry.loadSdkResult = expectedResult val sdkParams = Bundle() val callback = StubLoadSdkCallback() controller.loadSdk(SDK_PACKAGE_NAME, sdkParams, Runnable::run, callback) assertThat(callback.lastResult).isEqualTo(expectedResult) assertThat(callback.lastError).isNull() assertThat(localSdkRegistry.lastLoadSdkName).isEqualTo(SDK_PACKAGE_NAME) assertThat(localSdkRegistry.lastLoadSdkParams).isSameInstanceAs(sdkParams) } @Test fun loadSdk_whenSdkRegistryThrowsException_rethrowsExceptionFromSdkRegistry() { val expectedError = LoadSdkCompatException(RuntimeException(), Bundle()) localSdkRegistry.loadSdkError = expectedError val callback = StubLoadSdkCallback() controller.loadSdk(SDK_PACKAGE_NAME, Bundle(), Runnable::run, callback) assertThat(callback.lastError).isEqualTo(expectedError) assertThat(callback.lastResult).isNull() } @Test fun getSandboxedSdks_returnsResultsFromLocalSdkRegistry() { val sandboxedSdk = SandboxedSdkCompat(Binder()) localSdkRegistry.getLoadedSdksResult = listOf(sandboxedSdk) val result = controller.getSandboxedSdks() assertThat(result).containsExactly(sandboxedSdk) } @Test fun getAppOwnedSdkSandboxInterfaces_returnsResultsFromAppOwnedSdkRegistry() { val appOwnedInterface = AppOwnedSdkSandboxInterfaceCompat(name = "TestSDK", version = 1, binder = Binder()) appOwnedSdkRegistry.appOwnedSdks = listOf(appOwnedInterface) val result = controller.getAppOwnedSdkSandboxInterfaces() assertThat(result).containsExactly(appOwnedInterface) } @Test fun registerSdkSandboxActivityHandler_delegateToLocalSdkActivityHandlerRegistry() { val handler = object : SdkSandboxActivityHandlerCompat { override fun onActivityCreated(activityHolder: ActivityHolder) { // do nothing } } val token = controller.registerSdkSandboxActivityHandler(handler) val registeredHandler = LocalSdkActivityHandlerRegistry.getHandlerByToken(token) assertThat(registeredHandler).isSameInstanceAs(handler) } @Test fun registerSdkSandboxActivityHandler_registerWithCorrectSdkPackageName() { val token = controller.registerSdkSandboxActivityHandler( object : SdkSandboxActivityHandlerCompat { override fun onActivityCreated(activityHolder: ActivityHolder) { // do nothing } } ) val anotherSdkController = LocalController("LocalControllerTest.anotherSdk", localSdkRegistry, appOwnedSdkRegistry) val anotherSdkHandler = object : SdkSandboxActivityHandlerCompat { override fun onActivityCreated(activityHolder: ActivityHolder) { // do nothing } } val anotherSdkToken = anotherSdkController.registerSdkSandboxActivityHandler(anotherSdkHandler) LocalSdkActivityHandlerRegistry.unregisterAllActivityHandlersForSdk(SDK_PACKAGE_NAME) assertThat(LocalSdkActivityHandlerRegistry.isRegistered(token)).isFalse() assertThat(LocalSdkActivityHandlerRegistry.isRegistered(anotherSdkToken)).isTrue() } @Test fun unregisterSdkSandboxActivityHandler_delegateToLocalSdkActivityHandlerRegistry() { val handler = object : SdkSandboxActivityHandlerCompat { override fun onActivityCreated(activityHolder: ActivityHolder) { // do nothing } } val token = controller.registerSdkSandboxActivityHandler(handler) controller.unregisterSdkSandboxActivityHandler(handler) val registeredHandler = LocalSdkActivityHandlerRegistry.getHandlerByToken(token) assertThat(registeredHandler).isNull() } private class StubLocalSdkRegistry : SdkRegistry { var getLoadedSdksResult: List<SandboxedSdkCompat> = emptyList() var loadSdkResult: SandboxedSdkCompat? = null var loadSdkError: LoadSdkCompatException? = null var lastLoadSdkName: String? = null var lastLoadSdkParams: Bundle? = null override fun isResponsibleFor(sdkName: String): Boolean { throw IllegalStateException("Unexpected call") } override fun loadSdk(sdkName: String, params: Bundle): SandboxedSdkCompat { lastLoadSdkName = sdkName lastLoadSdkParams = params if (loadSdkError != null) { throw loadSdkError!! } return loadSdkResult!! } override fun unloadSdk(sdkName: String) { throw IllegalStateException("Unexpected call") } override fun getLoadedSdks(): List<SandboxedSdkCompat> = getLoadedSdksResult } private class StubLoadSdkCallback : LoadSdkCallback { var lastResult: SandboxedSdkCompat? = null var lastError: LoadSdkCompatException? = null override fun onResult(result: SandboxedSdkCompat) { lastResult = result } override fun onError(error: LoadSdkCompatException) { lastError = error } } private class StubAppOwnedSdkInterfaceRegistry : AppOwnedSdkRegistry { var appOwnedSdks: List<AppOwnedSdkSandboxInterfaceCompat> = emptyList() override fun registerAppOwnedSdkSandboxInterface( appOwnedSdk: AppOwnedSdkSandboxInterfaceCompat ) { throw IllegalStateException("Unexpected call") } override fun unregisterAppOwnedSdkSandboxInterface(sdkName: String) { throw IllegalStateException("Unexpected call") } override fun getAppOwnedSdkSandboxInterfaces(): List<AppOwnedSdkSandboxInterfaceCompat> = appOwnedSdks } companion object { private const val SDK_PACKAGE_NAME = "LocalControllerTest.sdk" } }
30
null
950
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
8,292
androidx
Apache License 2.0
cosec-core/src/main/kotlin/me/ahoo/cosec/policy/condition/context/InTenantConditionMatcher.kt
Ahoo-Wang
567,999,401
false
{"Kotlin": 588793, "Dockerfile": 594}
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.cosec.policy.condition.context import me.ahoo.cosec.api.configuration.Configuration import me.ahoo.cosec.api.context.SecurityContext import me.ahoo.cosec.api.context.request.Request import me.ahoo.cosec.api.policy.ConditionMatcher import me.ahoo.cosec.policy.condition.AbstractConditionMatcher import me.ahoo.cosec.policy.condition.ConditionMatcherFactory enum class TenantType { DEFAULT, USER, PLATFORM } class InTenantConditionMatcher(configuration: Configuration) : AbstractConditionMatcher(InTenantConditionMatcherFactory.TYPE, configuration) { private val value: TenantType = configuration.getRequired(InTenantConditionMatcher::value.name).asString().let { TenantType.valueOf(it.uppercase()) } override fun internalMatch(request: Request, securityContext: SecurityContext): Boolean { return when (value) { TenantType.DEFAULT -> securityContext.tenant.isDefaultTenant TenantType.USER -> securityContext.tenant.isUserTenant TenantType.PLATFORM -> securityContext.tenant.isPlatformTenant } } } class InTenantConditionMatcherFactory : ConditionMatcherFactory { companion object { const val TYPE = "inTenant" } override val type: String get() = TYPE override fun create(configuration: Configuration): ConditionMatcher { return InTenantConditionMatcher(configuration) } }
1
Kotlin
4
32
668cabb23c3947f8d6dd5251ecb50b80f5defc91
2,059
CoSec
Apache License 2.0
multiplatform/common/src/test/kotlin/reagent/MaybeSourceTest.kt
reyadrahman
114,793,065
true
{"Kotlin": 80419, "Java": 214}
/* * Copyright 2016 <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 reagent import reagent.tester.testMaybe import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class MaybeSourceTest { @Test fun just() { Maybe.just("Hello") .testMaybe { item("Hello") } } @Test fun empty() { Maybe.empty<Any>() .testMaybe { nothing() } } @Test fun error() { val exception = RuntimeException("Oops!") Maybe.error<Any>(exception) .testMaybe { error(exception) } } @Test fun returning() { var called = false Maybe.returning { called = true; 0 } .testMaybe { item(0) } assertTrue(called) } @Test fun returningThrowing() { val exception = RuntimeException("Oops!") Maybe.returning { throw exception } .testMaybe { error(exception) } } @Test fun running() { var called = false Maybe.running<Any> { called = true } .testMaybe { nothing() } assertTrue(called) } @Test fun runningThrowing() { val exception = RuntimeException("Oops!") Maybe.running<Any> { throw exception } .testMaybe { error(exception) } } @Test fun defer() { var called = 0 val deferred = Maybe.defer { called++; Maybe.just("Hello") } deferred.testMaybe { item("Hello") } assertEquals(1, called) deferred.testMaybe { item("Hello") } assertEquals(2, called) } }
0
Kotlin
0
0
74e831b5c809aa5d6046615697dc2d3387cb9ee5
2,089
Reagent
Apache License 2.0
src/main/kotlin/com/learn/base/KtBase14.kt
007168
578,936,809
false
{"Kotlin": 14464}
package com.learn.base // TODO 14.Kotlin语言的when表达式 fun main() { val dayInWeek = 6 val info = when(dayInWeek) { 0 -> { println("咦,今天是星期0?") } 1 -> "今天星期一" 2 -> "今天星期二" 3 -> "今天星期三" 4 -> "今天星期四" 5 -> "今天星期五" 6 -> "今天星期六,休息" 7 -> "今天星期七,今天休息,明天上班" else -> { println("额,不知道今天星期几了") // kotlin用unit对象代替了java中的void关键字 } } println(info) }
0
Kotlin
0
0
701919ba0cd0f9995d273b9955fc441d0feb5b5b
472
KotlinLearning
Apache License 2.0
Droidcon-Boston/app/src/main/java/com/mentalmachines/droidconboston/views/MainActivity.kt
Droidcon-Boston
83,487,424
false
null
package com.mentalmachines.droidconboston.views import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.text.TextUtils import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.mentalmachines.droidconboston.R import com.mentalmachines.droidconboston.R.id import com.mentalmachines.droidconboston.R.string import com.mentalmachines.droidconboston.data.Schedule.ScheduleRow import com.mentalmachines.droidconboston.firebase.AuthController import com.mentalmachines.droidconboston.utils.ServiceLocator import com.mentalmachines.droidconboston.views.agenda.AgendaFragment import com.mentalmachines.droidconboston.views.detail.AgendaDetailFragment import com.mentalmachines.droidconboston.views.search.SearchDialog import com.mentalmachines.droidconboston.views.social.SocialFragment import com.mentalmachines.droidconboston.views.social.TwitterFragment import com.mentalmachines.droidconboston.views.speaker.SpeakerFragment import com.mentalmachines.droidconboston.views.volunteer.VolunteerFragment import kotlinx.android.synthetic.main.main_activity.* class MainActivity : AppCompatActivity() { private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle private val searchDialog = SearchDialog() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) initNavDrawerToggle() setInitialFragment(savedInstanceState) initFragmentsFromIntent(intent) initSearchDialog() updateDrawerLoginState() } private fun initSearchDialog() { searchDialog.itemClicked = { AgendaDetailFragment.addDetailFragmentToStack(supportFragmentManager, it) } } private fun setInitialFragment(savedInstanceState: Bundle?) { if (savedInstanceState == null) { replaceFragment(getString(string.str_agenda)) } } private fun initFragmentsFromIntent(initialIntent: Intent) { val sessionDetails = initialIntent.extras?.getString(EXTRA_SESSION_DETAILS) if (!TextUtils.isEmpty(sessionDetails)) { replaceFragment(getString(string.str_agenda)) AgendaDetailFragment.addDetailFragmentToStack( supportFragmentManager, ServiceLocator.gson.fromJson(sessionDetails, ScheduleRow::class.java) ) updateSelectedNavItem(supportFragmentManager) } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) intent?.let { initFragmentsFromIntent(it) } } override fun onBackPressed() { // If drawer is open if (drawer_layout.isDrawerOpen(GravityCompat.START)) { // close the drawer drawer_layout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() val manager = supportFragmentManager if (manager.backStackEntryCount == 0) { // special handling where user clicks on back button in a detail fragment updateSelectedNavItem(manager) } } } private fun updateSelectedNavItem(manager: FragmentManager) { val currentFragment = manager.findFragmentById(id.fragment_container) if (currentFragment is AgendaFragment) { if (currentFragment.isMyAgenda()) { checkNavMenuItem(getString(string.str_my_schedule)) } else { checkNavMenuItem(getString(string.str_agenda)) } } else if (currentFragment is SpeakerFragment) { checkNavMenuItem(getString(string.str_speakers)) } } private fun checkNavMenuItem(title: String) { processMenuItems( { item -> item.title == title }, { item -> item.setChecked(true).isChecked }, processAll = true ) } private fun isNavItemChecked(title: String): Boolean { return processMenuItems({ item -> item.title == title }, { item -> item.isChecked }) } fun uncheckAllMenuItems() { processMenuItems({ true }, { item -> item.setChecked(false).isChecked }, true) } private fun processMenuItems( titleMatcher: (MenuItem) -> Boolean, matchFunc: (MenuItem) -> Boolean, processAll: Boolean = false ): Boolean { val menu = navView.menu for (i in 0 until menu.size()) { val item = menu.getItem(i) when { item.hasSubMenu() -> { val subMenu = item.subMenu for (j in 0 until subMenu.size()) { val subMenuItem = subMenu.getItem(j) if (titleMatcher(subMenuItem)) { val result = matchFunc(subMenuItem) if (!processAll) { return result } } } } titleMatcher(item) -> { val result = matchFunc(item) if (!processAll) { return result } } else -> item.isChecked = false } } return processAll } private fun initNavDrawerToggle() { setSupportActionBar(toolbar) actionBarDrawerToggle = ActionBarDrawerToggle( this, drawer_layout, R.string.drawer_open, R.string.drawer_close ) drawer_layout.addDrawerListener(actionBarDrawerToggle) navView.setNavigationItemSelectedListener { item -> // Closing drawer on item click drawer_layout.closeDrawers() when (item.itemId) { // Respond to the action bar's Up/Home button android.R.id.home -> if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else if (supportFragmentManager?.backStackEntryCount == 1) { // to avoid looping below on initScreen super.onBackPressed() finish() } R.id.nav_agenda -> replaceFragment(getString(R.string.str_agenda)) R.id.nav_my_schedule -> replaceFragment(getString(R.string.str_my_schedule)) R.id.nav_faq -> replaceFragment(getString(R.string.str_faq)) R.id.nav_social -> replaceFragment(getString(R.string.str_social)) R.id.nav_coc -> replaceFragment(getString(R.string.str_coc)) R.id.nav_about -> replaceFragment(getString(R.string.str_about_us)) R.id.nav_speakers -> replaceFragment(getString(R.string.str_speakers)) R.id.nav_volunteers -> replaceFragment(getString(R.string.str_volunteers)) R.id.nav_login_logout -> { if (AuthController.isLoggedIn) { logout() } else { login() } } R.id.nav_tweet_feed -> replaceFragment(getString(R.string.str_twitter_feed)) } if (item.itemId != R.id.nav_login_logout) { navView.setCheckedItem(item.itemId) } else { updateSelectedNavItem(supportFragmentManager) } true } if (supportActionBar != null) { supportActionBar?.setHomeButtonEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) } } public override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) actionBarDrawerToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) actionBarDrawerToggle.onConfigurationChanged(newConfig) } override fun onOptionsItemSelected(item: MenuItem): Boolean { // This is required to make the drawer toggle work return if (actionBarDrawerToggle.onOptionsItemSelected(item)) { true } else super.onOptionsItemSelected(item) } private fun replaceFragment(title: String) { checkNavMenuItem(title) updateToolbarTitle(title) // Get the fragment by tag var fragment: androidx.fragment.app.Fragment? = supportFragmentManager.findFragmentByTag(title) if (fragment == null) { // Initialize the fragment based on tag fragment = createFragmentForTitle(title) } else { // For Agenda and My Schedule Screen, which add more fragments to backstack. // Remove all fragment except the last one when navigating via the nav drawer. when (title) { resources.getString(R.string.str_agenda), resources.getString(R.string.str_my_schedule) -> { supportFragmentManager.popBackStack( title, FragmentManager.POP_BACK_STACK_INCLUSIVE ) } } } fragment?.let { supportFragmentManager?.beginTransaction() // replace in container ?.replace(R.id.fragment_container, it, title) // commit fragment transaction ?.commit() } } private fun createFragmentForTitle(title: String): Fragment? { return when (title) { resources.getString(string.str_agenda) -> AgendaFragment.newInstance() resources.getString(string.str_my_schedule) -> AgendaFragment.newInstanceMySchedule() resources.getString(string.str_faq) -> FAQFragment() resources.getString(string.str_social) -> SocialFragment() resources.getString(string.str_coc) -> CocFragment() resources.getString(string.str_about_us) -> AboutFragment() resources.getString(string.str_speakers) -> SpeakerFragment() resources.getString(string.str_volunteers) -> VolunteerFragment() resources.getString(string.str_twitter_feed) -> TwitterFragment.newInstance() else -> null } } private fun updateToolbarTitle(title: String) { if (supportActionBar != null) { supportActionBar?.title = title } } private fun login() { AuthController.login(this, RC_SIGN_IN, R.mipmap.ic_launcher) } private fun logout() { AuthController.logout(this) { updateDrawerLoginState() } } private fun updateDrawerLoginState() { navView.menu.findItem(R.id.nav_login_logout).title = getString( if (AuthController.isLoggedIn) { R.string.str_logout } else { R.string.str_login } ) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) AuthController.handleLoginResult(this, resultCode, data)?.let { AlertDialog.Builder(this) .setTitle(R.string.str_title_error) .setMessage(it) .show() } ?: run { updateDrawerLoginState() } } override fun onSearchRequested(): Boolean { searchDialog.show(supportFragmentManager, SEARCH_DIALOG_TAG) return true } companion object { private const val EXTRA_SESSIONID = "MainActivity.EXTRA_SESSIONID" private const val EXTRA_SESSION_DETAILS = "MainActivity.EXTRA_SESSION_DETAILS" private const val SEARCH_DIALOG_TAG = "agenda_search_tag" private const val RC_SIGN_IN = 1 fun getSessionDetailIntent( context: Context, sessionId: String, sessionDetail: String ): Intent { return Intent(context, MainActivity::class.java).apply { putExtra(EXTRA_SESSIONID, sessionId) putExtra(EXTRA_SESSION_DETAILS, sessionDetail) flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP } } } }
28
Kotlin
25
99
4edea2eb73f8b3581487a073ce7e1eec6a85e4cf
12,700
conference-app-android
Apache License 2.0
app/src/androidTest/java/banquemisr/challenge05/data/utils/MoviesFactory.kt
OmneyaOsman
787,421,468
false
{"Kotlin": 103894}
package banquemisr.challenge05.data.utils import android.content.Context import androidx.paging.PagingConfig import androidx.paging.PagingState import androidx.room.Room import androidx.test.core.app.ApplicationProvider import banquemisr.challenge05.data.db.GenereListConverter import banquemisr.challenge05.data.db.MoviesDatabase import banquemisr.challenge05.data.entities.GenreEntity import banquemisr.challenge05.data.entities.MovieEntity import banquemisr.challenge05.domain.model.Genre import banquemisr.challenge05.domain.model.Movie import com.squareup.moshi.Moshi object MoviesFactory { fun createDB(applicationContext: Context): MoviesDatabase { val moshi = Moshi.Builder().build() return Room.inMemoryDatabaseBuilder( applicationContext, MoviesDatabase::class.java ) .allowMainThreadQueries() .addTypeConverter(GenereListConverter(moshi)) .build() } fun moviesList() = listOf( MovieEntity( 929590, "/uv2twFGMk2qBdyJBJAVcrpRtSa9.jpg", listOf(GenreEntity(0,"genre 1")), "en", "Civil War", "In the near future, a group of war journalists attempt to survive while reporting the truth as the United States stands on the brink of civil war.", 532.705, "/sh7Rg8Er3tFcN9BpKIPOMvALgZd.jpg", "2024-04-10", 0, "Civil War", 7.404, 120, "now_playing",1 ), MovieEntity( 823464, "/j3Z3XktmWB1VhsS8iXNcrR86PXi.jpg", listOf(GenreEntity(0,"genre")), "en", "Godzilla x Kong: The New Empire", "Following their explosive showdown, Godzilla and Kong must reunite against a colossal undiscovered threat hidden within our world, challenging their very existence – and our own.", 1851.749, "/tMefBSflR6PGQLv7WvFPpKLZkyk.jpg", "2024-03-27", 0, "Godzilla x Kong: The New Empire", 6.699, 654, "now_playing",1 ) ) val mockedPagingState = PagingState<Int, MovieEntity>( listOf(), null, PagingConfig(10), 10 ) val resultList = listOf( Movie( 929590, "/uv2twFGMk2qBdyJBJAVcrpRtSa9.jpg", listOf(Genre(0, "genre 1")), "en", "Civil War", "In the near future, a group of war journalists attempt to survive while reporting the truth as the United States stands on the brink of civil war.", 532.705, "/sh7Rg8Er3tFcN9BpKIPOMvALgZd.jpg", "2024-04-10", 0, "Civil War", 7.404, 120, toString() ), Movie( 823464, "/j3Z3XktmWB1VhsS8iXNcrR86PXi.jpg", listOf(Genre(0, "genre")), "en", "Godzilla x Kong: The New Empire", "Following their explosive showdown, Godzilla and Kong must reunite against a colossal undiscovered threat hidden within our world, challenging their very existence – and our own.", 1851.749, "/tMefBSflR6PGQLv7WvFPpKLZkyk.jpg", "2024-03-27", 0, "Godzilla x Kong: The New Empire", 6.699, 654, toString() ) ) }
0
Kotlin
0
1
6a1d7680399a78d58c87c68bfc58cd48ee485078
3,350
Movie-App
MIT License
k8s-plugin-keel/src/main/kotlin/com/amazon/spinnaker/keel/k8s/service/IgorArtifactService.kt
nimakaviani
287,605,692
false
null
// Copyright 2021 Amazon.com, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.amazon.spinnaker.keel.k8s.service import com.amazon.spinnaker.keel.k8s.model.GitVersion import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spinnaker.config.DefaultServiceEndpoint import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider import com.netflix.spinnaker.keel.retrofit.InstrumentedJacksonConverter import okhttp3.HttpUrl import retrofit2.Retrofit import retrofit2.http.GET import retrofit2.http.Path interface IgorArtifactRestService { @GET("/git/version/{type}/{project}/{slug}") suspend fun getGitVersions( @Path("type") type: String, @Path("project") project: String, @Path("slug") slug: String ): List<GitVersion> @GET("/git/version/{type}/{project}/{slug}/{version}") suspend fun getGitVersion( @Path("type") type: String, @Path("project") project: String, @Path("slug") slug: String, @Path("version") version: String ): GitVersion } class IgorArtifactServiceSupplier( igorEndpoint: HttpUrl, objectMapper: ObjectMapper, clientProvider: OkHttpClientProvider ): IgorArtifactRestService { private val client = Retrofit.Builder() .addConverterFactory(InstrumentedJacksonConverter.Factory("igor", objectMapper)) .baseUrl(igorEndpoint) .client(clientProvider.getClient(DefaultServiceEndpoint("igor", igorEndpoint.toString()))) .build() .create(IgorArtifactRestService::class.java) override suspend fun getGitVersions(type: String, project: String, slug: String): List<GitVersion> { return client.getGitVersions(type,project, slug) } override suspend fun getGitVersion(type: String, project: String, slug: String, version: String): GitVersion { return client.getGitVersion(type, project, slug, version) } }
7
Kotlin
9
9
00c58d357a2ee673721cb189b2a95ec584ae0c8e
2,422
managed-delivery-k8s-plugin
Apache License 2.0
logLib/src/main/java/com/worson/lib/log/printer/file/handler/LogFileHandler.kt
worson
299,943,706
false
null
package com.langogo.lib.log.printer.file.handler import com.langogo.lib.log.internal.LogDebug import java.io.File import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.attribute.BasicFileAttributeView /** * 说明: * @author worson 07.17 2020 */ abstract open class LogFileHandler(private val fileDir:String) { private val TAG = "LogFileHandler" private val L = LogDebug.debugLogger init { checkFolder() } private fun checkFolder() { val folder = File(fileDir) if (!folder.exists()) { folder.mkdirs() } } abstract open fun onLogHandle( logfile:File, isFlush:Boolean,flushType:Int) /** * 返回log文件列表 */ protected fun logFiles():List<File>{ val dirFile = File(fileDir) val files=dirFile.listFiles().apply { sortBy { it.lastModified() } }.toList().filter { it.isFile && (!it.extension.endsWith("zip")) } return files } /** * 删除所有日志文件 */ fun deleteLogFiles(){ logFiles()?.forEach{ if (it.exists()) { it.delete() } } } /** * 根据大小限定日志文件 */ protected fun filesLimitCut(limitSize:Long=20*1024*1024){ // println("filesLimitCut:limitSize=$limitSize") var files=logFiles() var totalSize=files.fold(0L){ a,f -> a+f.length() } if (totalSize>limitSize){ val targetSize=limitSize/2 L.i(TAG,"filesLimitCut:totalSize=$totalSize,targetSize=${targetSize}") while (totalSize>targetSize){ files?.first()?.delete() files=logFiles() totalSize=files?.fold(0L){ a,f -> a+f.length() } } } } }
1
Kotlin
0
0
b7ec98bfa166c027aba12ad8076f8feb6083d858
1,915
AwesomeLog
Apache License 2.0
dispatch-android-espresso/src/test/java/dispatch/android/espresso/IdlingDispatcherProviderRuleTest.kt
RBusarow
206,223,913
false
null
/* * Copyright (C) 2021 Rick Busarow * 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 dispatch.android.espresso import androidx.test.espresso.* import io.kotest.matchers.* import io.mockk.* import org.junit.* import org.junit.rules.* import org.junit.runner.* import org.robolectric.* @RunWith(RobolectricTestRunner::class) class IdlingDispatcherProviderRuleTest { val idlingDispatcherProvider = IdlingDispatcherProvider() @JvmField @Rule val mockkRule = EspressoMockingWrapper() @JvmField @Rule val idlingRule = IdlingDispatcherProviderRule { idlingDispatcherProvider } @Test fun `rule's DispatcherProvider should be what is returned by the factory`() { idlingRule.dispatcherProvider shouldBe idlingDispatcherProvider } @Test fun `dispatcherProvider should be registered with IdlingRegistry before test begins`() { val registry = mockkRule.idlingRegistry verify { registry.register(idlingDispatcherProvider.default.counter) } verify { registry.register(idlingDispatcherProvider.io.counter) } verify { registry.register(idlingDispatcherProvider.main.counter) } verify { registry.register(idlingDispatcherProvider.mainImmediate.counter) } verify { registry.register(idlingDispatcherProvider.unconfined.counter) } } } class EspressoMockingWrapper : TestWatcher() { val idlingRegistry = mockk<IdlingRegistry>(relaxed = true) override fun starting(description: Description?) { mockkStatic(IdlingRegistry::class) every { IdlingRegistry.getInstance() } returns idlingRegistry } override fun finished(description: Description?) { unmockkStatic(IdlingRegistry::class) } }
27
null
6
128
a9b5f3aa0156b8cbd6402173f0b33edaa1622d81
2,166
Dispatch
Apache License 2.0
app/src/androidTest/java/shvyn22/flexingfinalspace/presentation/character/details/CharacterDetailsFragmentTest.kt
shvyn22
370,406,036
false
{"Kotlin": 96371}
package shvyn22.flexingfinalspace.presentation.character.details import android.content.Context import android.os.Bundle import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import org.junit.Before import org.junit.Rule import org.junit.Test import shvyn22.flexingfinalspace.R import shvyn22.flexingfinalspace.data.util.fromCharacterDTOToModel import shvyn22.flexingfinalspace.util.character1 import shvyn22.flexingfinalspace.util.character2 import shvyn22.flexingfinalspace.util.launchFragmentInHiltContainer import shvyn22.flexingfinalspace.util.withImageDrawable @HiltAndroidTest class CharacterDetailsFragmentTest { @get:Rule val hiltRule = HiltAndroidRule(this) @Before fun init() { hiltRule.inject() } @Test fun passAliveCharacter_ValidInformationIsDisplayed() { val res = ApplicationProvider.getApplicationContext<Context>().resources val alias = res.getString( R.string.text_alias, character1.alias?.joinToString(", ") ) val species = res.getString( R.string.text_species, character1.species ) val gender = res.getString( R.string.text_gender, character1.gender ) val hair = res.getString( R.string.text_hair, character1.hair ) val origin = res.getString( R.string.text_origin, character1.origin ) val abilities = res.getString( R.string.text_abilities, character1.abilities?.joinToString(", ") ) launchFragmentInHiltContainer<CharacterDetailsFragment>( fragmentArgs = Bundle().apply { putParcelable( "character", fromCharacterDTOToModel(character1) ) } ) onView(withId(R.id.iv_status)) .check( matches( withImageDrawable( R.drawable.ic_alive ) ) ) onView(withId(R.id.tv_name)) .check(matches(withText(character1.name))) onView(withId(R.id.tv_alias)) .check(matches(withText(alias))) onView(withId(R.id.tv_species)) .check(matches(withText(species))) onView(withId(R.id.tv_gender)) .check(matches(withText(gender))) onView(withId(R.id.tv_hair)) .check(matches(withText(hair))) onView(withId(R.id.tv_origin)) .check(matches(withText(origin))) onView(withId(R.id.tv_abilities)) .check(matches(withText(abilities))) } @Test fun passDeceasedCharacter_ValidInformationIsDisplayed() { val res = ApplicationProvider.getApplicationContext<Context>().resources val alias = res.getString( R.string.text_alias, character1.alias?.joinToString(", ") ) val species = res.getString( R.string.text_species, character1.species ) val gender = res.getString( R.string.text_gender, character1.gender ) val hair = res.getString( R.string.text_hair, character1.hair ) val origin = res.getString( R.string.text_origin, character1.origin ) val abilities = res.getString( R.string.text_abilities, character1.abilities?.joinToString(", ") ) launchFragmentInHiltContainer<CharacterDetailsFragment>( fragmentArgs = Bundle().apply { putParcelable( "character", fromCharacterDTOToModel(character1).copy(status = "Deceased") ) } ) onView(withId(R.id.iv_status)) .check( matches( withImageDrawable( R.drawable.ic_dead ) ) ) onView(withId(R.id.tv_name)) .check(matches(withText(character1.name))) onView(withId(R.id.tv_alias)) .check(matches(withText(alias))) onView(withId(R.id.tv_species)) .check(matches(withText(species))) onView(withId(R.id.tv_gender)) .check(matches(withText(gender))) onView(withId(R.id.tv_hair)) .check(matches(withText(hair))) onView(withId(R.id.tv_origin)) .check(matches(withText(origin))) onView(withId(R.id.tv_abilities)) .check(matches(withText(abilities))) } @Test fun passUnknownStatusCharacter_ValidInformationIsDisplayed() { val res = ApplicationProvider.getApplicationContext<Context>().resources val alias = res.getString( R.string.text_alias, character2.alias?.joinToString(", ") ) val species = res.getString( R.string.text_species, character2.species ) val gender = res.getString( R.string.text_gender, character2.gender ) val hair = res.getString( R.string.text_hair, character2.hair ) val origin = res.getString( R.string.text_origin, character2.origin ) val abilities = res.getString( R.string.text_abilities, character2.abilities?.joinToString(", ") ) launchFragmentInHiltContainer<CharacterDetailsFragment>( fragmentArgs = Bundle().apply { putParcelable( "character", fromCharacterDTOToModel(character2) ) } ) onView(withId(R.id.iv_status)) .check( matches( withImageDrawable( R.drawable.ic_unknown ) ) ) onView(withId(R.id.tv_name)) .check(matches(withText(character2.name))) onView(withId(R.id.tv_alias)) .check(matches(withText(alias))) onView(withId(R.id.tv_species)) .check(matches(withText(species))) onView(withId(R.id.tv_gender)) .check(matches(withText(gender))) onView(withId(R.id.tv_hair)) .check(matches(withText(hair))) onView(withId(R.id.tv_origin)) .check(matches(withText(origin))) onView(withId(R.id.tv_abilities)) .check(matches(withText(abilities))) } }
0
Kotlin
0
0
8737794f8ce0ef130bedebd25f941017eec57fb0
7,000
FlexingFinalSpace
MIT License
domain/src/test/java/com/nytimes/domain/mapper/MostPopularDomainFilterImplTest.kt
ahmed-mahmoud-abo-elnaga
529,899,354
false
null
package com.nytimes.domain.mapper import com.nytimes.domain.model.MostPopularDomainModel import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class MostPopularDomainFilterImplTest { private lateinit var mostPopularDomainFilter: MostPopularDomainFilter @Before fun setup() { mostPopularDomainFilter = MostPopularDomainFilterImpl() } @Test fun `Given MostPopular and filter Ascendant flag when filter then return expected result`() { val MostPopular = listOf( MostPopularDomainModel("c", "url", "test",""), MostPopularDomainModel("b", "url", "test",""), MostPopularDomainModel("a", "url", "test"," "), ) val expected = listOf( MostPopularDomainModel("a", "url", "test"," "), MostPopularDomainModel("b", "url", "test",""), MostPopularDomainModel("c", "url", "test",""), ) //when val actualValue = mostPopularDomainFilter.order(MostPopular, true) // then assertEquals(expected, actualValue) } @Test fun `Given MostPopular and filter Descendant flag when filter then return expected result`() { val MostPopular = listOf( MostPopularDomainModel("a", "url", "test"," "), MostPopularDomainModel("c", "url", "test",""), MostPopularDomainModel("b", "url", "test",""), ) val expected = listOf( MostPopularDomainModel("c", "url", "test",""), MostPopularDomainModel("b", "url", "test",""), MostPopularDomainModel("a", "url", "test"," "), ) //when val actualValue = mostPopularDomainFilter.order(MostPopular, false) // then assertEquals(expected, actualValue) } }
0
Kotlin
0
8
14d2920c27cfcc735febb7059dbfafe8eb7147a3
1,803
NyTime
Apache License 2.0
app/src/main/java/com/pengxh/easywallpaper/utils/HTMLParseUtil.kt
AndroidCoderPeng
271,505,720
false
null
package com.pengxh.easywallpaper.utils import com.pengxh.easywallpaper.bean.* import org.jsoup.nodes.Document /** * @description: TODO html数据解析 * @author: Pengxh * @email: <EMAIL> * @date: 2020/6/12 23:42 */ class HTMLParseUtil { companion object { private const val Tag: String = "HTMLParseUtil" /** * 解析Banner数据 * */ fun parseBannerData(document: Document): ArrayList<BannerBean> { val bannerList: ArrayList<BannerBean> = ArrayList() //取网站轮播图div val bannerBox = document.getElementsByClass("ck-slide-wrapper") //筛选div val targetElements = bannerBox.select("a[href]") targetElements.forEach { val title = it.select("img[src]").first().attr("alt") val image = it.select("img[src]").first().attr("src") val link = it.select("a[href]").first().attr("href") val bannerBean = BannerBean() bannerBean.bannerTitle = title bannerBean.bannerImage = image bannerBean.bannerLink = link bannerList.add(bannerBean) } return bannerList } /** * 解析ul标签下的图片集合 */ fun parseWallpaperUpdateData(document: Document): ArrayList<WallpaperBean> { val wallpaperList: ArrayList<WallpaperBean> = ArrayList() //取第三个ul内容 val ulElement = document.select("ul[class]")[2] //筛选ul val targetElements = ulElement.select("div[class]") targetElements.forEach { val title = it.select("a[class]").first().text() val image = it.getElementsByClass("img").select("img[data-src]").attr("data-src") //最新壁纸分类地址 val url = it.select("a[href]").first().attr("href") val wallpaperBean = WallpaperBean() wallpaperBean.wallpaperTitle = title wallpaperBean.wallpaperImage = image wallpaperBean.wallpaperURL = url wallpaperList.add(wallpaperBean) } return wallpaperList } /** * 解析首页最新壁纸分类下连接的壁纸集合 * */ fun parseWallpaperData(document: Document): ArrayList<String> { val list = ArrayList<String>() val elements = document.select("ul[class]")[2].select("li") elements.forEach { list.add(it.select("a[href]").first().attr("href")) } return list } /** * 高清壁纸大图地址 * */ fun parseWallpaperURL(document: Document): String { val e = document.getElementsByClass("pic-large").first() var bigImageUrl = e.attr("url") //备用地址 if (bigImageUrl == "") { bigImageUrl = e.attr("src") } return bigImageUrl } /** * 解析【发现】数据 */ fun parseDiscoverData(document: Document): ArrayList<DiscoverBean> { val discoverList: ArrayList<DiscoverBean> = ArrayList() //取第四个ul内容 val ulElement = document.select("ul[class]")[2] //筛选ul val liElements = ulElement.select("li") liElements.forEach { li -> val discoverBean = DiscoverBean() /** * 解析左边的div * */ val leftDiv = li.getElementsByClass("cll_l")[0] //标题 val title = leftDiv.select("h6").first().text() //简介 val synopsis = leftDiv.select("p").text() //大图 val bitImg = leftDiv.getElementsByClass("cll_img").select("img[src]").first().attr("data-src") //链接 val link = leftDiv.select("a[href]").first().attr("href") /** * 解析第二个div * */ val imageDiv = li.getElementsByClass("cll_r")[0] val imageElements = imageDiv.select("a[href]") val smallImageList: ArrayList<DiscoverBean.SmallImageBean> = ArrayList() imageElements.forEach { img -> val smallImageBean = DiscoverBean.SmallImageBean() smallImageBean.smallImage = img.select("img[data-src]").first().attr("data-src") smallImageList.add(smallImageBean) } discoverBean.discoverTitle = title discoverBean.discoverSynopsis = synopsis discoverBean.discoverURL = link discoverBean.bigImage = bitImg discoverBean.smallImages = smallImageList discoverList.add(discoverBean) } return discoverList } /** * 解析探索发现 * */ fun parseDiscoverDetailData(document: Document): ArrayList<WallpaperBean> { val wallpaperList: ArrayList<WallpaperBean> = ArrayList() //先选出目标内容的最外层div val mainDiv = document.getElementsByClass("list_cont list_cont2 w1180") mainDiv.forEach { main -> val ulElement = main.select("li") ulElement.forEach { val title = it.text() val image = it.select("img[data-original]").first().attr("data-original") val link = it.select("a[href]").first().attr("href") /** * 去掉mt,重复数据太多 * http://www.win4000.com/mt/Pinky.html * * 去掉meinvtag,重复数据太多 * http://www.win4000.com/meinvtag43591.html * * 保留如下类型数据 * http://www.win4000.com/meinv199524.html * */ if (!link.contains("/mt/")) { if (!link.contains("/meinvtag")) { val wallpaperBean = WallpaperBean() wallpaperBean.wallpaperTitle = title wallpaperBean.wallpaperImage = image wallpaperBean.wallpaperURL = link wallpaperList.add(wallpaperBean) } } } } return wallpaperList } /** * 解析壁纸分类数据 * */ fun parseCategoryData(document: Document): ArrayList<CategoryBean> { val categoryList: ArrayList<CategoryBean> = ArrayList() val elements = document .getElementsByClass("product_query").first() .getElementsByClass("cont1").first() .select("a[href]") //去掉第一个 for (i in elements.indices) { if (i == 0) continue val element = elements[i] val categoryBean = CategoryBean() categoryBean.categoryName = element.text() categoryBean.categoryLink = element.select("a[href]").first().attr("href") categoryList.add(categoryBean) } return categoryList } /** * 解析明星分类数据 * */ fun parseStarData(document: Document): ArrayList<CategoryBean> { val categoryList: ArrayList<CategoryBean> = ArrayList() val elements = document .getElementsByClass("cb_cont").first() .select("a[href]") //替换第一个 for (i in elements.indices) { if (i == 0) { //抓取顶部圆头像 val categoryBean = CategoryBean() categoryBean.categoryName = "推荐" categoryBean.categoryLink = "http://www.win4000.com/mt/star.html" categoryList.add(0, categoryBean) } else { val element = elements[i] val categoryBean = CategoryBean() categoryBean.categoryName = element.text() categoryBean.categoryLink = element.select("a[href]").first().attr("href") categoryList.add(i, categoryBean) } } return categoryList } /** * 解析顶部圆形头像数据 * */ fun parseCircleImageData(document: Document): ArrayList<WallpaperBean> { val circleImageList: ArrayList<WallpaperBean> = ArrayList() val elements = document.getElementsByClass("nr_zt w1180").first().select("li") elements.forEach { val title = it.text() val image = it.select("img[src]").first().attr("src") val link = Constant.BaseURL + it.select("a[href]").first().attr("href") val wallpaperBean = WallpaperBean() wallpaperBean.wallpaperTitle = title wallpaperBean.wallpaperImage = image wallpaperBean.wallpaperURL = link circleImageList.add(wallpaperBean) } return circleImageList } /** * 解析搜索结果 * */ fun parseSearchData(document: Document): ArrayList<WallpaperBean> { val searchList: ArrayList<WallpaperBean> = ArrayList() val elements = document.getElementsByClass("tab_box").first().select("li") elements.forEach { val title = it.text() val image = it.select("img[data-original]").first().attr("data-original") val link = it.select("a[href]").first().attr("href") val wallpaperBean = WallpaperBean() wallpaperBean.wallpaperTitle = title wallpaperBean.wallpaperImage = image wallpaperBean.wallpaperURL = link searchList.add(wallpaperBean) } return searchList } /** * 解析明星写真页面壁纸数据 * */ fun parseStarPersonalData(document: Document): ArrayList<WallpaperBean> { val starList: ArrayList<WallpaperBean> = ArrayList() val elements = document.select("ul[class]")[2].select("li") elements.forEach { val title = it.text() val image = it.select("img[src]").first().attr("src") val link = it.select("a[href]").first().attr("href") val wallpaperBean = WallpaperBean() wallpaperBean.wallpaperTitle = title wallpaperBean.wallpaperImage = image wallpaperBean.wallpaperURL = link starList.add(wallpaperBean) } return starList } /** * 解析精选头像数据 * */ fun parseHeadImageData(document: Document): ArrayList<HeadImageBean> { val list = ArrayList<HeadImageBean>() val elements = document.getElementsByClass("g-gxlist-imgbox").select("li") elements.forEach { val image = it.select("img[src]").first().attr("src") //大图页面链接 val link = it.select("a[href]").first().attr("href") val headImageBean = HeadImageBean() headImageBean.headImage = image headImageBean.headImageLink = link list.add(headImageBean) } return list } /** * 获取头像大图地址 * */ fun parseHeadImageURL(document: Document): String = document .getElementsByClass("img-list4").first() .select("img").attr("src") } }
0
Kotlin
1
1
af5183c974788c726a974db82d931b7da1ea1c76
11,719
EasyWallpaper
Apache License 2.0
order/src/main/kotlin/kz/kasip/order/ui/offerservice/OfferAServiceScreen.kt
SherkhanAmandyk
772,507,371
false
{"Kotlin": 322369}
package kz.kasip.order.ui.offerservice import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import kz.kasip.designcore.KasipTopAppBar import kz.kasip.designcore.theme.DialogBackground import kz.kasip.designcore.theme.PrimaryBackgroundGreen import kz.kasip.order.R import kz.kasip.order.OrderUi @Composable fun OfferAServiceScreen( orderUi: OrderUi, viewModel: OfferAServiceViewModel = hiltViewModel<OfferAServiceViewModel, OfferAServiceViewModelFactory> { it.create(orderUi) }, onBack: () -> Unit, ) { val order by viewModel.orderUiFlow.collectAsState() val isCreated by viewModel.isCreated.collectAsState() if (isCreated) { onBack() viewModel.invalidate() } Surface { Scaffold( topBar = { KasipTopAppBar( title = stringResource(id = R.string.offer_a_service), color = Color.White, onBack = onBack ) } ) { Box( modifier = Modifier .padding(it) .background(color = DialogBackground) .fillMaxSize() ) { Column { Spacer(modifier = Modifier.height(16.dp)) Box( modifier = Modifier .padding(end = 28.dp) .background( color = PrimaryBackgroundGreen, shape = RoundedCornerShape( topEnd = 50.dp, bottomEnd = 50.dp ) ) ) { Text( modifier = Modifier .padding(horizontal = 18.dp, vertical = 8.dp), text = order.name, fontSize = 20.sp, color = Color.White ) } Box(modifier = Modifier.padding(horizontal = 18.dp)) { Column( verticalArrangement = Arrangement.spacedBy(8.dp) ) { Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(id = R.string.description_of_project), fontSize = 16.sp ) Card( modifier = Modifier .fillMaxWidth(), colors = CardDefaults.elevatedCardColors().copy( containerColor = TextFieldDefaults.colors().unfocusedContainerColor ) ) { Text( modifier = Modifier.padding(6.dp), text = order.description ) } Row( verticalAlignment = Alignment.Bottom ) { Text( text = "${order.rubric?.name}: ", fontSize = 16.sp ) Text(text = order.subrubric?.name ?: "") } Row( verticalAlignment = Alignment.Bottom ) { Text( text = "Desired budget: ", fontSize = 16.sp ) Text(text = "to ") Text( text = order.price, color = PrimaryBackgroundGreen, fontSize = 20.sp ) } Row { Image( modifier = Modifier .width(56.dp) .height(50.dp), painter = painterResource(id = R.drawable.filter), contentDescription = "" ) Column( modifier = Modifier.height(50.dp), ) { Text( modifier = Modifier .weight(1F) .wrapContentSize(), text = order.buyer?.name ?: "", fontSize = 10.sp ) Text( modifier = Modifier .weight(1F) .wrapContentSize(), text = stringResource( id = R.string.rate, order.buyer?.rate ?: "" ), fontSize = 10.sp, ) Text( modifier = Modifier .weight(1F) .wrapContentSize(), text = stringResource(id = R.string.history), fontSize = 10.sp, ) } } Spacer(modifier = Modifier.height(36.dp)) Card( modifier = Modifier .fillMaxWidth(), colors = CardDefaults.elevatedCardColors().copy( containerColor = Color.White ) ) { val offerText by viewModel.offerTextFlow.collectAsState() TextField( modifier = Modifier.fillMaxWidth(), value = offerText, onValueChange = viewModel::onOfferTextChange, label = { Text( text = "Write how you will solve the client’s problem", fontSize = 10.sp ) }, textStyle = LocalTextStyle.current.copy(fontSize = 10.sp) ) } val price by viewModel.priceFlow.collectAsState() Text( text = "Cost", fontSize = 16.sp ) TextField( modifier = Modifier.fillMaxWidth(), value = price, onValueChange = viewModel::onPriceChange, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Decimal ) ) Button( modifier = Modifier .padding(horizontal = 32.dp) .fillMaxWidth(), onClick = viewModel::onOffer, colors = ButtonDefaults.buttonColors() .copy(containerColor = PrimaryBackgroundGreen) ) { Text(text = "Offer") } } } } } } } }
0
Kotlin
0
0
9ff168443c9f5066329eca664c6c2becde60ae73
10,520
kasip-kz
Apache License 2.0
app/src/main/java/in/ac/svit/prakarsh/HomeFragment.kt
itsarjunsinh
116,944,160
false
null
package `in`.ac.svit.prakarsh import android.content.Context import android.content.Intent import android.os.Bundle import android.os.CountDownTimer import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.android.volley.Request import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import kotlinx.android.synthetic.main.fragment_home.* import kotlinx.android.synthetic.main.item_featured.view.* import org.json.JSONArray import java.util.* import kotlin.collections.ArrayList /** * Created by itsarjunsinh on 1/11/18. */ class HomeFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Log.d(javaClass.name, "Started") updateViewsFromJson() } private fun updateViewsFromJson() { //Timer section var url = context?.getString(R.string.url_main) var req = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response -> Log.d(javaClass.name, "Main JSON Successfully fetched") val prakarshDate = Calendar.getInstance() var year = 0 var month = 0 var date = 0 var hours = 0 var minutes = 0 if (response.has("eventDate")) { if (response.getJSONObject("eventDate").has("year")) { year = response.getJSONObject("eventDate").getInt("year") } if (response.getJSONObject("eventDate").has("month")) { month = response.getJSONObject("eventDate").getInt("month") - 1 } if (response.getJSONObject("eventDate").has("date")) { date = response.getJSONObject("eventDate").getInt("date") } if (response.getJSONObject("eventDate").has("hours")) { hours = response.getJSONObject("eventDate").getInt("hours") } if (response.getJSONObject("eventDate").has("minutes")) { minutes = response.getJSONObject("eventDate").getInt("minutes") } } prakarshDate.set(year, month, date, hours, minutes, 0) startCountdown(prakarshDate) }, Response.ErrorListener { error -> Log.d(javaClass.name, "Volley Response Error Occurred, URL: $url Error: ${error.message}") }) VolleySingleton.getInstance(context?.applicationContext).requestQueue.add(req) // Featured events & speakers section. url = context?.getString(R.string.url_featured) req = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response -> Log.d(javaClass.name, "Featured JSON Successfully fetched") // Get featured events & speakers label and get boolean for checking whether they should be displayed. var showFeaturedEvents = false var showFeaturedSpeakers = false var featuredEventsLabel = "" var featuredSpeakersLabel = "" if (response.has("show") && response.has("labels")) { if (response.getJSONObject("show").has("featuredEvents") && response.getJSONObject("labels").has("featuredEvents")) { showFeaturedEvents = response.getJSONObject("show").getBoolean("featuredEvents") featuredEventsLabel = response.getJSONObject("labels").getString("featuredEvents") } if (response.getJSONObject("show").has("featuredSpeakers") && response.getJSONObject("labels").has("featuredSpeakers")) { showFeaturedSpeakers = response.getJSONObject("show").getBoolean("featuredSpeakers") featuredSpeakersLabel = response.getJSONObject("labels").getString("featuredSpeakers") } } // Featured events section. if (showFeaturedEvents) { home_txt_featured_events?.text = featuredEventsLabel if (response.has("featuredEvents")) { val featuredEvents = response.getJSONArray("featuredEvents") home_rv_featured_events?.apply { layoutManager = LinearLayoutManager(context) adapter = FeaturedRecyclerAdapter(context, getFeaturedList(featuredEvents)) } } } // Featured speakers section. if (showFeaturedSpeakers) { home_txt_featured_speakers?.text = featuredSpeakersLabel if (response.has("featuredSpeakers")) { val featuredSpeakers = response.getJSONArray("featuredSpeakers") home_rv_featured_speakers?.apply { layoutManager = LinearLayoutManager(context) adapter = FeaturedRecyclerAdapter(context, getFeaturedList(featuredSpeakers)) } } } }, Response.ErrorListener { error -> Log.d(javaClass.name, "Volley Response Error Occurred, URL: $url Error: ${error.message}") }) VolleySingleton.getInstance(context?.applicationContext).requestQueue.add(req.setShouldCache(false)) } private fun startCountdown(eventDate: Calendar) { val finishedText = "${context?.getString(R.string.timer_finished)}!" val today = Calendar.getInstance() val timeInterval = eventDate.timeInMillis - today.timeInMillis if (timeInterval > 1) { // Show Timer if the event is yet to start. home_txt_timer?.visibility = View.VISIBLE val countDown = object : CountDownTimer(timeInterval, 1000) { override fun onTick(millisUntilFinished: Long) { home_txt_timer?.text = (remainingTimeText(millisUntilFinished)) } override fun onFinish() { // When timer completed show finished text. Will only be shown once if the user sees the countdown go to 0. home_txt_timer?.text = finishedText } } countDown.start() } } private fun remainingTimeText(millisLeft: Long): String { val SECOND = 1000 val MINUTE = SECOND * 60 val HOUR = MINUTE * 60 val DAY = HOUR * 24 // Convert remaining milliseconds to human comprehensible form. val remainingDays = (millisLeft / DAY) val remainingHours = (millisLeft % DAY) / HOUR val remainingMinutes = (millisLeft % HOUR) / MINUTE val remainingSeconds = (millisLeft % MINUTE) / SECOND // Generate the text to be displayed in the timer. var remainingText = "" if (remainingDays > 1) { remainingText = "$remainingDays Days\n" } else if (remainingDays == 1L) { remainingText = "$remainingDays Day\n" } remainingText += String.format("%02d Hours : %02d Minutes: %02d Seconds", remainingHours, remainingMinutes, remainingSeconds) return remainingText } private class FeaturedItem(var heading: String = "", var subHeading: String = "", var description: String = "", var dataUrl: String? = null, var imageUrl: String? = null, var date: String = "", var time: String = "") private fun getFeaturedList(jsonArray: JSONArray): ArrayList<FeaturedItem> { val featuredList = ArrayList<FeaturedItem>() for (i in 0..(jsonArray.length() - 1)) { val featuredEventsItem = FeaturedItem() if (jsonArray.getJSONObject(i).has("name")) { featuredEventsItem.heading = jsonArray.getJSONObject(i).getString("name") } if (jsonArray.getJSONObject(i).has("shortDescription")) { featuredEventsItem.subHeading = jsonArray.getJSONObject(i).getString("shortDescription") } if (jsonArray.getJSONObject(i).has("description")) { featuredEventsItem.description = jsonArray.getJSONObject(i).getString("description") } if (jsonArray.getJSONObject(i).has("dataUrl")) { featuredEventsItem.dataUrl = jsonArray.getJSONObject(i).getString("dataUrl") } if (jsonArray.getJSONObject(i).has("imageUrl")) { featuredEventsItem.imageUrl = jsonArray.getJSONObject(i).getString("imageUrl") } if (jsonArray.getJSONObject(i).has("date")) { featuredEventsItem.date = jsonArray.getJSONObject(i).getString("date") } if (jsonArray.getJSONObject(i).has("time")) { featuredEventsItem.time = jsonArray.getJSONObject(i).getString("time") } featuredList.add(featuredEventsItem) } return featuredList } private class FeaturedRecyclerAdapter(private val context: Context?, private val featuredItemList: ArrayList<FeaturedItem>) : RecyclerView.Adapter<FeaturedRecyclerAdapter.CustomViewHolder>() { class CustomViewHolder(val view: View) : RecyclerView.ViewHolder(view) override fun getItemCount(): Int { return featuredItemList.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CustomViewHolder { val layoutInflater = LayoutInflater.from(parent?.context) val cellForRow = layoutInflater.inflate(R.layout.item_featured, parent, false) return CustomViewHolder(cellForRow) } override fun onBindViewHolder(holder: CustomViewHolder?, position: Int) { // Show event info text. holder?.view?.featured_txt_heading?.text = featuredItemList[position].heading holder?.view?.featured_txt_subheading?.text = featuredItemList[position].subHeading holder?.view?.featured_txt_description?.text = featuredItemList[position].description holder?.view?.featured_txt_date?.text = featuredItemList[position].date holder?.view?.featured_txt_time?.text = featuredItemList[position].time if (featuredItemList[position].imageUrl != null) { // Show image if image url exists. holder?.view?.featured_card_image?.visibility = View.VISIBLE holder?.view?.featured_img_speaker?.apply { setDefaultImageResId(R.drawable.ic_image_black) setErrorImageResId(R.drawable.ic_broken_image_black) setImageUrl(featuredItemList[position].imageUrl, VolleySingleton.getInstance(context).imageLoader) } } if (featuredItemList[position].dataUrl != null) { // Change to EventInfo activity on click event if data url exists. holder?.view?.setOnClickListener { Log.d(javaClass.name, "${featuredItemList[position].heading} Clicked") val intent = Intent(context, EventInfoActivity::class.java) intent.putExtra("url", featuredItemList[position].dataUrl) context?.startActivity(intent) } } } } }
1
null
1
1
72a2abb7ac3b0d3122ad54de1a975b2ca4150302
12,259
PrakarshApp
The Unlicense
tests/scalar-adapters/src/main/kotlin/custom/scalars/MyIntAdapter.kt
apollographql
69,469,299
false
{"Kotlin": 3463807, "Java": 198208, "CSS": 34435, "HTML": 5844, "JavaScript": 1191}
package custom.scalars import com.apollographql.apollo.api.Adapter import com.apollographql.apollo.api.CustomScalarAdapters import com.apollographql.apollo.api.json.JsonReader import com.apollographql.apollo.api.json.JsonWriter class MyInt(val value: Int) class MyIntAdapter : Adapter<MyInt> { override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): MyInt { return MyInt(reader.nextInt()) } override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: MyInt) { writer.value(value.value) } }
135
Kotlin
651
3,750
174cb227efe76672cf2beac1affc7054f6bb2892
572
apollo-kotlin
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/task/command/mapper/TaskAvroSnapshotMapper.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.task.command.mapper import com.bosch.pt.csm.cloud.common.command.mapper.AbstractAvroSnapshotMapper import com.bosch.pt.csm.cloud.common.extensions.toEpochMilli import com.bosch.pt.csm.cloud.common.messages.AggregateIdentifierAvro import com.bosch.pt.csm.cloud.projectmanagement.common.ProjectmanagementAggregateTypeEnum.PARTICIPANT import com.bosch.pt.csm.cloud.projectmanagement.common.ProjectmanagementAggregateTypeEnum.TASK import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskAggregateAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskEventAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskEventEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskStatusEnumAvro import com.bosch.pt.iot.smartsite.project.project.toAggregateReference import com.bosch.pt.iot.smartsite.project.projectcraft.domain.toAggregateReference import com.bosch.pt.iot.smartsite.project.task.command.snapshotstore.TaskSnapshot import com.bosch.pt.iot.smartsite.project.workarea.domain.toAggregateReference object TaskAvroSnapshotMapper : AbstractAvroSnapshotMapper<TaskSnapshot>() { override fun <E : Enum<*>> toAvroMessageWithNewVersion( snapshot: TaskSnapshot, eventType: E ): TaskEventAvro = with(snapshot) { TaskEventAvro.newBuilder() .setName(eventType as TaskEventEnumAvro) .setAggregateBuilder( TaskAggregateAvro.newBuilder() .setAggregateIdentifier(toAggregateIdentifierAvroWithNextVersion(snapshot)) .setAuditingInformation(toUpdatedAuditingInformationAvro(snapshot)) .setAssignee( assigneeIdentifier?.let { AggregateIdentifierAvro.newBuilder() .setIdentifier(it.identifier.toString()) .setVersion(0) .setType(PARTICIPANT.value) .build() }) .setCraft(projectCraftIdentifier.toAggregateReference()) .setDescription(description) .setEditDate(editDate?.toEpochMilli()) .setLocation(location) .setName(name) .setProject(projectIdentifier.toAggregateReference()) .setStatus(TaskStatusEnumAvro.valueOf(status.toString())) .setWorkarea(workAreaIdentifier?.toAggregateReference())) .build() } override fun getAggregateType() = TASK.value override fun getRootContextIdentifier(snapshot: TaskSnapshot) = snapshot.projectIdentifier.toUuid() }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
2,977
bosch-pt-refinemysite-backend
Apache License 2.0
library/src/main/java/dev/storeforminecraft/skinviewandroid/library/threedimension/render/Steve.kt
storeforminecraft
517,862,529
false
{"Kotlin": 44552}
package dev.storeforminecraft.skinviewandroid.library.threedimension.render import android.graphics.Bitmap import android.opengl.GLES20 import android.opengl.GLES31 import android.opengl.GLUtils import dev.storeforminecraft.skinviewandroid.library.libs.BufferUtil import dev.storeforminecraft.skinviewandroid.library.datas.ModelSourceTextureType import dev.storeforminecraft.skinviewandroid.library.libs.SkinUtil import dev.storeforminecraft.skinviewandroid.library.threedimension.model.SteveCoords import dev.storeforminecraft.skinviewandroid.library.threedimension.model.texture.Steve3DTexture import dev.storeforminecraft.skinviewandroid.library.threedimension.render.SkinView3DRenderer.Companion.loadShader import java.nio.FloatBuffer import java.nio.ShortBuffer /** * Minecraft Character Model for OpenGl render */ class Steve(val bitmap: Bitmap) { private val vertexShaderCode = // This matrix member variable provides a hook to manipulate // the coordinates of the objects that use this vertex shader "uniform mat4 uMVPMatrix;" + "attribute vec4 vPosition;" + "attribute vec2 a_texCoord;" + "varying vec2 v_texCoord;" + "void main() {" + " v_texCoord = a_texCoord;" + " gl_Position = uMVPMatrix * vPosition;" + "}" private val fragmentShaderCode = "precision mediump float;" + "varying vec2 v_texCoord;" + "uniform sampler2D s_texture;" + "uniform vec4 vColor;" + "void main() {" + " gl_FragColor = texture2D(s_texture, v_texCoord);" + "}" private var program: Int private val steveModelType: ModelSourceTextureType private val steveTextureCoords: FloatArray private val steveModelCoords: FloatArray private val steveModelDrawOrder: ShortArray private val textureBuffer: FloatBuffer private val vertexBuffer: FloatBuffer private val drawListBuffer: ShortBuffer init { val vertexShader: Int = loadShader(GLES31.GL_VERTEX_SHADER, vertexShaderCode) val fragmentShader: Int = loadShader(GLES31.GL_FRAGMENT_SHADER, fragmentShaderCode) steveModelType = SkinUtil.getTexType(bitmap) val steve = SteveCoords.getSteve(steveModelType) steveModelCoords = steve.first steveModelDrawOrder = steve.second steveTextureCoords = Steve3DTexture.getSteveTexture(steveModelType) vertexBuffer = BufferUtil.createFloatBuffer(steveModelCoords) drawListBuffer = BufferUtil.createShortBuffer(steveModelDrawOrder) textureBuffer = BufferUtil.createFloatBuffer(steveTextureCoords) // create empty OpenGL ES Program program = GLES31.glCreateProgram().also { // add the vertex shader to program GLES31.glAttachShader(it, vertexShader) // add the fragment shader to program GLES31.glAttachShader(it, fragmentShader) // creates OpenGL ES program executables GLES31.glLinkProgram(it) } loadTexture() } private fun loadTexture() { val textures = IntArray(1) GLES31.glGenTextures(1, textures, 0) GLES31.glActiveTexture(GLES31.GL_TEXTURE0) GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textures[0]) GLES31.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR ) GLES31.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST ) GLES31.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE ) GLES31.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE ) GLUtils.texImage2D(GLES31.GL_TEXTURE_2D, 0, bitmap, 0) } fun draw(mvpMatrix: FloatArray) { // Add program to OpenGL ES environment GLES31.glUseProgram(program) val positionHandle = GLES31.glGetAttribLocation(program, "vPosition") GLES31.glEnableVertexAttribArray(positionHandle) GLES31.glVertexAttribPointer(positionHandle, 3, GLES31.GL_FLOAT, false, 3 * 4, vertexBuffer) val vPMatrixHandle = GLES31.glGetUniformLocation(program, "uMVPMatrix") GLES31.glUniformMatrix4fv(vPMatrixHandle, 1, false, mvpMatrix, 0) val textureCoordHandle = GLES31.glGetAttribLocation(program, "a_texCoord") GLES31.glEnableVertexAttribArray(textureCoordHandle) GLES31.glVertexAttribPointer( textureCoordHandle, 2, GLES31.GL_FLOAT, false, 2 * 4, textureBuffer ) GLES31.glGetUniformLocation(program, "s_texture").also { textureHandle -> GLES31.glUniform1i(textureHandle, 0) } GLES31.glDrawElements( GLES31.GL_TRIANGLES, steveModelDrawOrder.size, GLES31.GL_UNSIGNED_SHORT, drawListBuffer ) GLES31.glDisableVertexAttribArray(positionHandle) GLES31.glDisableVertexAttribArray(textureCoordHandle) } }
0
Kotlin
0
7
13669724f73798ce873e4ea3f95807086e48a2a7
5,330
SkinViewAndroid
MIT License
microapp/smartintel/src/main/java/bruhcollective/itaysonlab/microapp/smartintel/ui/tiles/RewardTile.kt
iTaysonLab
525,967,051
false
{"Kotlin": 203833}
package bruhcollective.itaysonlab.microapp.smartintel.ui.tiles import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Toll import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.surfaceColorAtElevation 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.draw.drawWithContent import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.ColorPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import bruhcollective.itaysonlab.jetisoft.models.SmartIntelNode import bruhcollective.itaysonlab.microapp.smartintel.R import coil.compose.AsyncImage @Composable internal fun RewardTile( node: SmartIntelNode.Reward ) { Box( Modifier .background(MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp)) .padding(horizontal = 16.dp) .clip(RoundedCornerShape(8.dp)) .background(MaterialTheme.colorScheme.surface) .fillMaxWidth() .height(IntrinsicSize.Min) ) { AsyncImage( model = node.reward.imageUrl, contentDescription = null, modifier = Modifier .fillMaxSize() .drawWithContent { drawContent() drawRect( Brush.verticalGradient( colorStops = arrayOf( 0f to Color.Black.copy(alpha = 0.5f), 1f to Color.Black, ) ) ) }, placeholder = ColorPainter(MaterialTheme.colorScheme.surfaceVariant), contentScale = ContentScale.Crop ) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(16.dp) .align(Alignment.TopStart)) { Icon(Icons.Rounded.Toll, contentDescription = null) Spacer(modifier = Modifier.width(16.dp)) Column { Text(text = stringResource(id = R.string.smart_intel_balance), fontSize = 13.sp) Text(text = stringResource(id = R.string.x_units, node.reward.viewer?.node?.unitsBalance ?: 0), fontSize = 13.sp) } } Column(modifier = Modifier .padding(16.dp) .align(Alignment.BottomStart)) { Spacer(modifier = Modifier.height(96.dp)) Text( text = node.reward.name, color = MaterialTheme.colorScheme.onSurface ) Text( text = stringResource(id = R.string.units_with_rarity, node.reward.rarity, node.reward.cost), color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f) ) } } }
0
Kotlin
0
13
f651cfc692852c378c9cd3b4e41d8aa1b5a76eb5
3,343
jetisoft
Apache License 2.0
microapp/smartintel/src/main/java/bruhcollective/itaysonlab/microapp/smartintel/ui/tiles/RewardTile.kt
iTaysonLab
525,967,051
false
{"Kotlin": 203833}
package bruhcollective.itaysonlab.microapp.smartintel.ui.tiles import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Toll import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.surfaceColorAtElevation 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.draw.drawWithContent import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.ColorPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import bruhcollective.itaysonlab.jetisoft.models.SmartIntelNode import bruhcollective.itaysonlab.microapp.smartintel.R import coil.compose.AsyncImage @Composable internal fun RewardTile( node: SmartIntelNode.Reward ) { Box( Modifier .background(MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp)) .padding(horizontal = 16.dp) .clip(RoundedCornerShape(8.dp)) .background(MaterialTheme.colorScheme.surface) .fillMaxWidth() .height(IntrinsicSize.Min) ) { AsyncImage( model = node.reward.imageUrl, contentDescription = null, modifier = Modifier .fillMaxSize() .drawWithContent { drawContent() drawRect( Brush.verticalGradient( colorStops = arrayOf( 0f to Color.Black.copy(alpha = 0.5f), 1f to Color.Black, ) ) ) }, placeholder = ColorPainter(MaterialTheme.colorScheme.surfaceVariant), contentScale = ContentScale.Crop ) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(16.dp) .align(Alignment.TopStart)) { Icon(Icons.Rounded.Toll, contentDescription = null) Spacer(modifier = Modifier.width(16.dp)) Column { Text(text = stringResource(id = R.string.smart_intel_balance), fontSize = 13.sp) Text(text = stringResource(id = R.string.x_units, node.reward.viewer?.node?.unitsBalance ?: 0), fontSize = 13.sp) } } Column(modifier = Modifier .padding(16.dp) .align(Alignment.BottomStart)) { Spacer(modifier = Modifier.height(96.dp)) Text( text = node.reward.name, color = MaterialTheme.colorScheme.onSurface ) Text( text = stringResource(id = R.string.units_with_rarity, node.reward.rarity, node.reward.cost), color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f) ) } } }
0
Kotlin
0
13
f651cfc692852c378c9cd3b4e41d8aa1b5a76eb5
3,343
jetisoft
Apache License 2.0
app/src/main/java/com/example/svbookmarket/activities/model/Book.kt
khangbdd
406,396,585
true
{"Kotlin": 317416, "Java": 4114}
package com.example.svbookmarket.activities.model import android.net.Uri import android.os.Parcel import android.os.Parcelable data class Book( var id: String? = "1", var Image: String? = "", var Name: String? = "1", var Author: String? = "1", var Price: Int = 1, var rate: Int = 10, var Kind: String? ="1", var Counts:Int = 1, var Description: String? = "1", var Saler: String? = "", var SalerName: String?=""):Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readInt(), parcel.readInt(), parcel.readString(), parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString(), ) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(Image) parcel.writeString(Name) parcel.writeString(Author) parcel.writeInt(Price) parcel.writeInt(rate) parcel.writeString(Kind) parcel.writeInt(Counts) parcel.writeString(Description) parcel.writeString(Saler) parcel.writeString(SalerName) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<Book> { override fun createFromParcel(parcel: Parcel): Book { return Book(parcel) } override fun newArray(size: Int): Array<Book?> { return arrayOfNulls(size) } } }
0
null
0
0
880507764d14c4b4ba6285caf07ae3ac403064f2
1,618
OnlineBookMarketForSeller
Apache License 2.0
andkit-libs/andkit-lifecycle/src/main/java/com/anymore/andkit/lifecycle/activity/ActivityWrapper.kt
anymao
234,439,982
false
null
package com.anymore.andkit.lifecycle.activity import android.app.Activity import android.os.Bundle import dagger.android.AndroidInjection import org.greenrobot.eventbus.EventBus import timber.log.Timber /** * Created by liuyuanmao on 2019/2/20. */ class ActivityWrapper(private var mActivity: Activity, private var iActivity: IActivity) : IActivityLifecycle { override fun onCreate(savedInstanceState: Bundle?) { Timber.i("onCreate") if (iActivity.useEventBus()) { EventBus.getDefault().register(mActivity) } if (iActivity.injectable()) { Timber.d("need inject ,do AndroidInjection.inject(mActivity)") AndroidInjection.inject(mActivity) } } override fun onDestroy() { Timber.i("onDestroy") if (iActivity.useEventBus()) { EventBus.getDefault().unregister(mActivity) } } }
0
Kotlin
0
5
f0c89b016e16303840e61c60337c39e82bf8c872
908
Andkit
MIT License
app/src/main/java/com/nicolasguillen/kointlin/ui/views/DisplayableAsset.kt
nicolasguillen
113,652,016
false
{"Kotlin": 96449, "Ruby": 5242}
package com.nicolasguillen.kointlin.ui.views import com.nicolasguillen.kointlin.storage.entities.Asset class DisplayableAsset( val asset: Asset, val currentPrice: Double, val variant: Double, val currencyCode: String )
2
Kotlin
0
2
569c5817777ad75d052221a51ea56f8916590e56
252
kointlin
Apache License 2.0
cordapp/src/main/kotlin/tech/industria/training/iou/plugin/IOUWebPlugin.kt
gatsinski
141,544,650
true
{"Kotlin": 42977, "HTML": 207}
package tech.industria.training.iou.plugin import java.util.function.Function import net.corda.core.messaging.CordaRPCOps import net.corda.webserver.services.WebServerPluginRegistry import tech.industria.training.iou.api.IOUApi class IOUWebPlugin : WebServerPluginRegistry { // A list of classes that expose web JAX-RS REST APIs. override val webApis: List<java.util.function.Function<CordaRPCOps, out Any>> = listOf(Function(::IOUApi)) //A list of directories in the resources directory that will be served by Jetty under /web. // This template's web frontend is accessible at /web/template. override val staticServeDirs: Map<String, String> = mapOf( // This will serve the iou directory in resources to /web/iou "iou" to javaClass.classLoader.getResource("iou").toExternalForm() ) }
0
Kotlin
0
0
a9d08e2c3bac73f9624acfce8ea90eb5f73463ca
834
cordapp-iou-training
Apache License 2.0
app/src/androidTest/java/com/mustafa/movieguideapp/fragment/tv/TvSearchResultFragmentTest.kt
Mustafashahoud
231,958,118
false
null
package com.mustafa.movieguideapp.fragment.tv import androidx.databinding.DataBindingComponent import androidx.fragment.app.testing.launchFragmentInContainer import androidx.lifecycle.MutableLiveData import androidx.navigation.Navigation import androidx.navigation.testing.TestNavHostController import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread import com.mustafa.movieguideapp.R import com.mustafa.movieguideapp.binding.FragmentBindingAdapters import com.mustafa.movieguideapp.models.Resource import com.mustafa.movieguideapp.models.entity.Tv import com.mustafa.movieguideapp.util.* import com.mustafa.movieguideapp.utils.MockTestUtil import com.mustafa.movieguideapp.view.ui.search.TvSearchViewModel import com.mustafa.movieguideapp.view.ui.search.result.TvSearchResultFragment import com.mustafa.movieguideapp.view.ui.search.result.TvSearchResultFragmentArgs import com.nhaarman.mockitokotlin2.never import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.not import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.mock /** * @author <NAME> * 4/19/2020 */ @RunWith(AndroidJUnit4::class) class TvSearchResultFragmentTest { @Rule @JvmField val executorRule = TaskExecutorWithIdlingResourceRule() @Rule @JvmField val countingAppExecutors = CountingAppExecutorsRule() @Rule @JvmField val dataBindingIdlingResourceRule = DataBindingIdlingResourceRule() private val navController = TestNavHostController(ApplicationProvider.getApplicationContext()) private lateinit var viewModel: TvSearchViewModel private lateinit var mockBindingAdapter: FragmentBindingAdapters private val resultsLiveData = MutableLiveData<Resource<List<Tv>>>() @Before fun init() { mockBindingAdapter = mock(FragmentBindingAdapters::class.java) viewModel = mock(TvSearchViewModel::class.java) `when`(viewModel.searchTvListLiveData).thenReturn(resultsLiveData) val bundle = TvSearchResultFragmentArgs("Ozarks").toBundle() // val bundle = bundleOf("query" to "Troy") val scenario = launchFragmentInContainer( bundle, themeResId = R.style.AppTheme ) { TvSearchResultFragment().apply { appExecutors = countingAppExecutors.appExecutors viewModelFactory = ViewModelUtil.createFor(viewModel) dataBindingComponent = object : DataBindingComponent { override fun getFragmentBindingAdapters(): FragmentBindingAdapters { return mockBindingAdapter } } } } dataBindingIdlingResourceRule.monitorFragment(scenario) runOnUiThread { navController.setGraph(R.navigation.tv) } /*THIS IS SO IMPORTANT To tel the navController that Here we are now */ /*Otherwise the navController won't know and the nodeDis will null */ runOnUiThread { navController.setCurrentDestination(R.id.tvSearchFragmentResult) } scenario.onFragment { fragment -> Navigation.setViewNavController(fragment.requireView(), navController) } } @Test fun testError() { resultsLiveData.postValue(Resource.error("Something Unexpected happened", null)) onView(withId(R.id.error_msg)).check(matches(isDisplayed())) onView(withId(R.id.error_msg)).check(matches(withText("Something Unexpected happened"))) } @Test fun testLoadingWithoutData() { onView(withId(R.id.progress_bar)).check(matches(not(isDisplayed()))) resultsLiveData.postValue(Resource.loading(null)) onView(withId(R.id.progress_bar)).check(matches(isDisplayed())) } @Test fun testLoadingData() { resultsLiveData.postValue( Resource.success( listOf( Tv(1, name = "Ozark1"), Tv(2, name = "Ozark2") ), true ) ) onView(listMatcher().atPosition(0)).check(matches(isDisplayed())) onView(listMatcher().atPosition(0)).check(matches(hasDescendant(withText("Ozark1")))) onView(listMatcher().atPosition(1)).check(matches(isDisplayed())) onView(listMatcher().atPosition(1)).check(matches(hasDescendant(withText("Ozark2")))) // Test navigation onView(listMatcher().atPosition(0)).perform(click()) assertThat(navController.currentDestination?.id, `is`(R.id.tvDetail)) } @Test fun testScrollingWithNextPageTrue() { resultsLiveData.postValue( Resource.success( MockTestUtil.createTvs(20), true ) ) val action = RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(19) onView(withId(R.id.recyclerView_search_result_tvs)).perform(action) onView(listMatcher().atPosition(19)).check(matches(isDisplayed())) Mockito.verify(viewModel).loadMore() } @Test fun testScrollingWithNextPageFalse() { resultsLiveData.postValue( Resource.success( MockTestUtil.createTvs(20), false ) ) val action = RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(19) onView(withId(R.id.recyclerView_search_result_tvs)).perform(action) onView(listMatcher().atPosition(19)).check(matches(isDisplayed())) Mockito.verify(viewModel, never()).loadMore() } private fun listMatcher() = RecyclerViewMatcher(R.id.recyclerView_search_result_tvs) }
2
null
10
98
5f12624e566610349ba31d1eece34a32b90aa344
6,221
MoviesApp
Apache License 2.0
slider/src/main/java/com/litao/slider/Utils.kt
litao0621
601,010,510
false
{"Kotlin": 170702, "Shell": 343}
package com.litao.slider import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.res.Resources import android.util.TypedValue import androidx.annotation.Dimension import java.lang.ref.WeakReference import kotlin.math.roundToInt /** * @author : litao * @date : 2023/3/20 17:37 */ object Utils { fun dpToPx(@Dimension(unit = Dimension.DP) dp: Int): Int { val r = Resources.getSystem() return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), r.displayMetrics).roundToInt() } fun getWindowWidth(context: Context): Int { return dpToPx(context.resources.configuration.screenWidthDp) } fun isActivityAlive(context: Context?): Boolean { return isActivityAlive(getActivityByContext(context) ) } fun isActivityAlive(activity: Activity?): Boolean { return activity != null && !activity.isFinishing && !activity.isDestroyed } fun getActivityByContext(context: Context?): Activity? { val activity: Activity? = getActivityByContextInner(context) return if (!isActivityAlive(activity)) null else activity } private fun getActivityByContextInner(context: Context?): Activity? { var context: Context? = context ?: return null val list: MutableList<Context> = ArrayList() while (context is ContextWrapper) { if (context is Activity) { return context } val activity = getActivityFromDecorContext(context) if (activity != null) return activity list.add(context) context = context.baseContext if (context == null) { return null } if (list.contains(context)) { // loop context return null } } return null } private fun getActivityFromDecorContext(context: Context?): Activity? { if (context == null) return null if (context.javaClass.name == "com.android.internal.policy.DecorContext") { try { val mActivityContextField = context.javaClass.getDeclaredField("mActivityContext") mActivityContextField.isAccessible = true return (mActivityContextField[context] as WeakReference<Activity?>).get() } catch (ignore: Exception) { } } return null } }
0
Kotlin
10
82
2b191d23e5cae3bca9f40fcd2fb84109ef79246f
2,479
nifty-slider
Apache License 2.0
src/test/kotlin/xyz/magentaize/dynamicdata/list/ReverseFixture.kt
Magentaize
290,133,754
false
null
package xyz.magentaize.dynamicdata.list import xyz.magentaize.dynamicdata.list.test.asAggregator import org.amshove.kluent.shouldBeEqualTo import kotlin.test.Test class ReverseFixture { val source = SourceList<Int>() val result = source.connect().reverse().asAggregator() @Test fun addRange() { source.addRange(1..5) result.data.toList() shouldBeEqualTo (5 downTo 1).toList() } @Test fun removes() { source.addRange(1..5) source.remove(1) source.remove(4) result.data.toList() shouldBeEqualTo listOf(5, 3, 2) } @Test fun removeRange() { source.addRange(1..5) source.removeRange(1, 3) result.data.toList() shouldBeEqualTo listOf(5, 1) } @Test fun removeRangeThenInsert() { source.addRange(1..5) source.removeRange(1, 3) source.add(1, 3) result.data.toList() shouldBeEqualTo listOf(5, 3, 1) } @Test fun replace() { source.addRange(1..5) source.replaceAt(2, 100) result.data.toList() shouldBeEqualTo listOf(5, 4, 100, 2, 1) } @Test fun clear() { source.addRange(1..5) source.clear() result.data.size shouldBeEqualTo 0 } @Test fun move() { source.addRange(1..5) source.move(4, 1) result.data.toList() shouldBeEqualTo listOf(4, 3, 2, 5, 1) } @Test fun move2() { source.addRange(1..5) source.move(1, 4) result.data.toList() shouldBeEqualTo listOf(2, 5, 4, 3, 1) } }
0
Kotlin
0
3
dda522f335a6ab3847cc90ff56e8429c15834800
1,574
dynamicdata-kotlin
MIT License
src/main/java/ir/reservs/reservs/ui/main/times/TimesAdapter.kt
SajjadSabzkar
363,083,676
false
{"Kotlin": 151278, "Java": 27552}
package ir.reservs.reservs.ui.main.times import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import ir.reservs.reservs.R import ir.reservs.reservs.model.Time import ir.reservs.reservs.utils.CommonUtils import ir.reservs.reservs.utils.TimeUtils import kotlinx.android.synthetic.main.times_item.view.* class TimesAdapter : RecyclerView.Adapter<TimesAdapter.Holder>() { val times: MutableList<Time> = arrayListOf() var listener: OnClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.times_item, parent, false) return Holder(view) } override fun getItemCount(): Int { return times.size } override fun onBindViewHolder(holder: Holder, position: Int) { holder.txtStart.text = times[position].start holder.txtEnd.text = times[position].end val diff = TimeUtils.diff(times[position].start, times[position].end) holder.txtRemaining.text = TimeUtils.toString(diff) holder.txtPrice.text = CommonUtils.moneyDisplayFormat(times[position].price.toString()) holder.btnReserve.setOnClickListener { listener?.click(times[position]) } } fun addTimes(times: MutableList<Time>) { this.times.clear() this.times.addAll(times) notifyDataSetChanged() } fun setOnClickListener(listener: OnClickListener) { this.listener = listener } fun clearAll() { this.times.clear() notifyDataSetChanged() } class Holder(view: View) : RecyclerView.ViewHolder(view) { val txtEnd: TextView = view.txtEnd val txtStart: TextView = view.txtStart val btnReserve: Button = view.btnReserve val txtRemaining: TextView = view.txtRemaining val txtPrice: TextView = view.txtPrice } }
0
Kotlin
0
0
409f87d2cf0e32716760862a463b998a58aeb76d
2,048
Reservs
MIT License
frontend/compose/src/commonMain/kotlin/ui/screen/tools/root/tabs/toolholder/AddEditToolHolderScreen.kt
85vmh
543,628,296
false
null
package ui.screen.tools.root.tabs.toolholder import androidx.compose.foundation.layout.RowScope import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import com.mindovercnc.model.tool.ToolHolder import com.mindovercnc.linuxcnc.screen.rememberScreenModel import org.kodein.di.bindProvider import com.mindovercnc.linuxcnc.screen.manual.Manual class AddEditHolderScreen( private val toolHolder: ToolHolder? = null, private val onChanges: () -> Unit ) : Manual( when (toolHolder) { null -> "Add Tool Holder" else -> "Edit Tool Holder #${toolHolder.holderNumber}" } ) { @Composable override fun RowScope.Actions() { val screenModel: AddEditToolHolderScreenModel = when (toolHolder) { null -> rememberScreenModel() else -> rememberScreenModel { bindProvider { toolHolder } } } val navigator = LocalNavigator.currentOrThrow IconButton( modifier = iconButtonModifier, onClick = { screenModel.applyChanges() onChanges.invoke() navigator.pop() } ) { Icon( imageVector = Icons.Default.Check, contentDescription = "", ) } } @Composable override fun Content() { val screenModel: AddEditToolHolderScreenModel = when (toolHolder) { null -> rememberScreenModel() else -> rememberScreenModel { bindProvider { toolHolder } } } val state by screenModel.state.collectAsState() AddEditHolderContent( state, onHolderNumber = screenModel::setHolderNumber, onHolderType = screenModel::setHolderType, onLatheTool = screenModel::setLatheTool ) } }
0
Kotlin
1
2
56a3a01d7068c23170425944f6887e4600ae4a61
2,020
mindovercnclathe
Apache License 2.0
app/src/test/java/com/kickstarter/viewmodels/PrelaunchProjectViewModelTest.kt
kickstarter
76,278,501
false
null
package com.kickstarter.viewmodels import android.content.Intent import android.content.SharedPreferences import android.util.Pair import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.Environment import com.kickstarter.libs.MockCurrentUser import com.kickstarter.libs.MockCurrentUserV2 import com.kickstarter.libs.featureflag.FlagKey import com.kickstarter.libs.utils.ThirdPartyEventValues import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.libs.utils.extensions.reduceToPreLaunchProject import com.kickstarter.mock.MockFeatureFlagClient import com.kickstarter.mock.factories.ProjectFactory import com.kickstarter.mock.factories.UserFactory import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.models.Project import com.kickstarter.models.Urls import com.kickstarter.models.Web import com.kickstarter.ui.IntentKey import com.kickstarter.ui.SharedPreferenceKey import com.kickstarter.ui.intentmappers.ProjectIntentMapper import com.kickstarter.viewmodels.projectpage.PrelaunchProjectViewModel import com.kickstarter.viewmodels.usecases.TPEventInputData import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subscribers.TestSubscriber import okhttp3.ResponseBody import org.joda.time.DateTime import org.joda.time.DateTimeZone import org.junit.After import org.junit.Test import org.mockito.Mockito import retrofit2.HttpException import rx.subjects.BehaviorSubject import java.util.concurrent.TimeUnit class PrelaunchProjectViewModelTest : KSRobolectricTestCase() { private lateinit var vm: PrelaunchProjectViewModel.PrelaunchProjectViewModel private val project = BehaviorSubject.create<Project>() private val showShareSheet = BehaviorSubject.create<Pair<String, String>>() private val startLoginToutActivity = TestSubscriber.create<Unit>() private val showSavedPrompt = TestSubscriber.create<Unit>() private val startCreatorView = BehaviorSubject.create<Project>() private val resultTest = TestSubscriber.create<Project>() private val disposables = CompositeDisposable() val creator = UserFactory.creator() val slug = "best-project-2k19" val intent = Intent().putExtra(IntentKey.PROJECT_PARAM, slug) private val prelaunchProject by lazy { val projectUrl = "https://www.kck.str/projects/" + creator.id().toString() + "/" + slug val webUrls = Web.builder() .project(projectUrl) .rewards("$projectUrl/rewards") .updates("$projectUrl/posts") .build() ProjectFactory .prelaunchProject("https://www.kickstarter.com/projects/1186238668/skull-graphic-tee") .toBuilder() .name("Best Project 2K19") .sendThirdPartyEvents(true) .isStarred(false) .urls(Urls.builder().web(webUrls).build()) .build() } private val mockApolloClientV2 = object : MockApolloClientV2() { override fun getProject(slug: String): Observable<Project> { return Observable .just(prelaunchProject) } override fun getProject(project: Project): Observable<Project> { return Observable .just(prelaunchProject) } override fun watchProject(project: Project): Observable<Project> { return Observable .just(project.toBuilder().isStarred(true).build()) } override fun unWatchProject(project: Project): Observable<Project> { return Observable .just(project.toBuilder().isStarred(false).build()) } override fun triggerThirdPartyEvent(eventInput: TPEventInputData): Observable<Pair<Boolean, String>> { return Observable.just(Pair(true, "")) } } private val testScheduler = io.reactivex.schedulers.TestScheduler() private val testEnvironment by lazy { environment() .toBuilder() .apolloClientV2(mockApolloClientV2) .schedulerV2(testScheduler) .build() } private fun setUpEnvironment(environment: Environment) { this.vm = PrelaunchProjectViewModel.PrelaunchProjectViewModel(environment) this.vm.outputs.project().subscribe { this.project.onNext(it) } .addToDisposable(disposables) this.vm.outputs .showShareSheet() .subscribe { this.showShareSheet.onNext(it) } .addToDisposable(disposables) this.vm.outputs .startLoginToutActivity().subscribe { this.startLoginToutActivity.onNext(it) } .addToDisposable(disposables) this.vm.outputs .showSavedPrompt().subscribe { this.showSavedPrompt.onNext(it) } .addToDisposable(disposables) this.vm.outputs .startCreatorView().subscribe { this.startCreatorView.onNext(it) } .addToDisposable(disposables) ProjectIntentMapper.project(intent, MockApolloClientV2()).subscribe { resultTest.onNext(prelaunchProject) }.addToDisposable(disposables) } @Test fun testProject_loadDeepLinkProject() { val user = UserFactory.germanUser().toBuilder().chosenCurrency("CAD").build() val deadline = DateTime(DateTimeZone.UTC).plusDays(10) val reducedProject = ProjectFactory.project().toBuilder() .watchesCount(10) .isStarred(true) .creator(user) .build() .reduceToPreLaunchProject().toBuilder().deadline(deadline).build() setUpEnvironment(testEnvironment) vm.inputs.configureWith(intent = intent.putExtra(IntentKey.PROJECT, reducedProject)) testScheduler.advanceTimeBy(2, TimeUnit.SECONDS) assertEquals(project.value, reducedProject) } @Test fun testProject_loadProject() { setUpEnvironment( environment() .toBuilder() .apolloClientV2(object : MockApolloClientV2() { override fun getProject(slug: String): Observable<Project> { return Observable .error( HttpException( retrofit2.Response.error<String>( 426, ResponseBody.create( null, content = "Too Many Calls", ), ), ), ) } override fun getProject(project: Project): Observable<Project> { return Observable .error( HttpException( retrofit2.Response.error<String>( 426, ResponseBody.create( null, content = "Too Many Calls", ), ), ), ) } }) .schedulerV2(testScheduler) .build(), ) vm.inputs.configureWith(intent = intent) assertEquals(project.value, null) } @Test fun testProject_loadProject_withError() { setUpEnvironment(testEnvironment) vm.inputs.configureWith(intent = intent) assertEquals(project.value, prelaunchProject) } @Test fun testToggleBookmark() { val currentUser = MockCurrentUser() val currentUserV2 = MockCurrentUserV2() val mockedEnv = testEnvironment.toBuilder().currentUser(currentUser) .currentUserV2(currentUserV2).build() setUpEnvironment(mockedEnv) vm.inputs.configureWith(intent = intent) assertEquals(project.value, prelaunchProject) currentUser.refresh(UserFactory.user()) currentUserV2.refresh(UserFactory.user()) vm.inputs.bookmarkButtonClicked() assertEquals(project.value.isStarred(), true) vm.inputs.bookmarkButtonClicked() assertEquals(project.value.isStarred(), false) } @Test fun testShowShareSheet() { setUpEnvironment(testEnvironment) val intent = Intent().putExtra(IntentKey.PROJECT_PARAM, "skull-graphic-tee") vm.inputs.configureWith(intent = intent) this.vm.inputs.shareButtonClicked() val expectedName = "Best Project 2K19" val expectedShareUrl = "https://www.kck.str/projects/" + creator.id().toString() + "/" + slug + "?ref=android_project_share" assertEquals(showShareSheet.value.first, expectedName) assertEquals(showShareSheet.value.second, expectedShareUrl) } @Test fun testLoggedOutStarProjectFlow() { val currentUser = MockCurrentUser() val currentUserV2 = MockCurrentUserV2() val mockedEnv = testEnvironment.toBuilder().currentUser(currentUser) .currentUserV2(currentUserV2).build() setUpEnvironment(mockedEnv) // Start the view model with a project vm.inputs.configureWith(intent = intent) assertEquals(project.value, prelaunchProject) // Try starring while logged out vm.inputs.bookmarkButtonClicked() assertEquals(project.value.isStarred(), false) this.showSavedPrompt.assertValueCount(0) this.startLoginToutActivity.assertValueCount(1) // Login currentUser.refresh(UserFactory.user()) currentUserV2.refresh(UserFactory.user()) vm.inputs.bookmarkButtonClicked() vm.inputs.bookmarkButtonClicked() assertEquals(true, project.value.isStarred()) this.showSavedPrompt.assertValueCount(1) vm.inputs.bookmarkButtonClicked() assertEquals(false, project.value.isStarred()) this.showSavedPrompt.assertValueCount(1) } @Test fun testCreatorDetailsClicked() { setUpEnvironment(testEnvironment) val intent = Intent().putExtra(IntentKey.PROJECT_PARAM, "skull-graphic-tee") vm.inputs.configureWith(intent = intent) this.vm.inputs.creatorInfoButtonClicked() assertEquals(project.value, prelaunchProject) } @Test fun testThirdPartyEventSent() { var sharedPreferences: SharedPreferences = Mockito.mock(SharedPreferences::class.java) Mockito.`when`(sharedPreferences.getBoolean(SharedPreferenceKey.CONSENT_MANAGEMENT_PREFERENCE, false)) .thenReturn(true) val mockFeatureFlagClient: MockFeatureFlagClient = object : MockFeatureFlagClient() { override fun getBoolean(FlagKey: FlagKey): Boolean { return true } } val currentUser = MockCurrentUser() val currentUserV2 = MockCurrentUserV2() val mockedEnv = testEnvironment.toBuilder().currentUser(currentUser) .currentUserV2(currentUserV2) .featureFlagClient(mockFeatureFlagClient) .sharedPreferences(sharedPreferences) .build() setUpEnvironment(mockedEnv) val intent = Intent() .putExtra(IntentKey.PROJECT_PARAM, "skull-graphic-tee") .putExtra(IntentKey.PREVIOUS_SCREEN, ThirdPartyEventValues.ScreenName.DEEPLINK.value) vm.inputs.configureWith(intent = intent) assertEquals(true, this.vm.onThirdPartyEventSent.value) } @After fun cleanUp() { disposables.clear() } }
8
null
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
11,904
android-oss
Apache License 2.0
app/src/main/kotlin/com/subtlefox/currencyrates/domain/implementation/ObserveConnectivityUseCaseImpl.kt
Subtle-fox
177,306,258
false
null
package com.subtlefox.currencyrates.domain.implementation import com.subtlefox.currencyrates.domain.ObserveConnectivityUseCase import com.subtlefox.currencyrates.domain.repository.ConnectivityRepository import io.reactivex.Observable import javax.inject.Inject class ObserveConnectivityUseCaseImpl @Inject constructor( private val repository: ConnectivityRepository ) : ObserveConnectivityUseCase { override fun stream(): Observable<Boolean> { return repository .observeConnectivity() .distinctUntilChanged() } }
0
Kotlin
0
0
cdcaf7d6ccef790aa903de419ffbc6206dc3c4d8
560
currency-exchange-rates
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/clipboard/ClipboardEvent.types.kt
karakum-team
393,199,102
false
{"Kotlin": 6619312}
// Automatically generated - do not modify! @file:Suppress( "NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE", ) package web.clipboard import seskar.js.JsValue import web.events.EventType sealed external interface ClipboardEventTypes { @JsValue("copy") val COPY: EventType<ClipboardEvent> get() = definedExternally @JsValue("cut") val CUT: EventType<ClipboardEvent> get() = definedExternally @JsValue("paste") val PASTE: EventType<ClipboardEvent> get() = definedExternally }
0
Kotlin
6
28
2e94b60c9e3838c464ab9da211ca44de54e74133
527
types-kotlin
Apache License 2.0
feature/settings/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/settings/view/implementation/ui/SettingsProgressUI.kt
savvasdalkitsis
485,908,521
false
null
/* Copyright 2022 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.ui import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.ChangeShouldShowFeedDetailsSyncProgress import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.ChangeShouldShowFullSyncProgress import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.ChangeShouldShowLocalProgress import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.ChangeShouldShowPrecacheProgress import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.SettingsAction import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.ui.state.SettingsState import com.savvasdalkitsis.uhuruphotos.foundation.icons.api.R.drawable import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string @Composable internal fun SettingsProgressUI( state: SettingsState, action: (SettingsAction) -> Unit, ) { SettingsCheckBox( text = stringResource(string.show_feed_sync_progress), icon = drawable.ic_feed, isChecked = state.shouldShowFeedSyncProgress, ) { action(ChangeShouldShowFullSyncProgress(!state.shouldShowFeedSyncProgress)) } SettingsCheckBox( text = stringResource(string.show_feed_details_sync_progress), icon = drawable.ic_feed, isChecked = state.shouldShowFeedDetailsSyncProgress, ) { action(ChangeShouldShowFeedDetailsSyncProgress(!state.shouldShowFeedDetailsSyncProgress)) } SettingsCheckBox( text = stringResource(string.show_precache_progress), icon = drawable.ic_photo, isChecked = state.shouldShowPrecacheProgress, ) { action(ChangeShouldShowPrecacheProgress(!state.shouldShowPrecacheProgress)) } SettingsCheckBox( text = stringResource(string.show_local_progress), icon = drawable.ic_folder, isChecked = state.shouldShowLocalSyncProgress, ) { action(ChangeShouldShowLocalProgress(!state.shouldShowLocalSyncProgress)) } }
70
null
26
358
a1159f2236f66fe533f7ba785d47e4201e10424a
2,782
uhuruphotos-android
Apache License 2.0
shared/src/commonMain/kotlin/com/kurt/jokes/mobile/domain/repositories/JokesRepository.kt
kuuuurt
204,830,316
false
null
package com.kurt.jokes.mobile.domain.repositories import com.kurt.jokes.mobile.domain.entities.Joke interface JokesRepository { suspend fun getJokes(): List<Joke> }
1
Kotlin
11
111
d5ad5d8634faf0b14661f7c9b2a824677cafe738
170
jokes-app-multiplatform
Apache License 2.0
ui/features/tags/src/main/java/com/example/tags/utils/HashTagLayout.kt
City-Zouitel
576,223,915
false
null
package com.example.tags import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.example.common_ui.Icons.CIRCLE_ICON_18 import com.example.common_ui.Icons.CROSS_CIRCLE_ICON import com.example.local.model.Label import com.google.accompanist.flowlayout.FlowRow @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun HashTagLayout( labelVM: LabelVM = hiltViewModel(), labelDialogState: MutableState<Boolean>, hashTags: Collection<Label>, idState: MutableState<Long>, labelState: MutableState<String> ) { FlowRow( mainAxisSpacing = 3.dp ) { hashTags.forEach { label -> ElevatedFilterChip( selected = true, onClick = {}, leadingIcon = { Icon( painter = painterResource(id = CIRCLE_ICON_18), contentDescription = null, tint = Color(label.color), modifier = Modifier.size(10.dp) ) }, trailingIcon = { Icon( painterResource(CROSS_CIRCLE_ICON), null, modifier = Modifier.clickable { labelVM.deleteLabel(label) } ) }, label = { label.label?.let { Surface( color = Color.Transparent, modifier = Modifier.combinedClickable( onLongClick = { labelState.value = label.label!! idState.value = label.id labelDialogState.value = true }, ){ labelState.value = label.label!! idState.value = label.id } ) { Text(it) } } }, shape = CircleShape ) } } }
27
null
6
67
eddb26dd83a46123c36829efc47bf4f26eac2776
2,895
JetNote
Apache License 2.0
features/third_party/rxjava2/test_utils/src/main/java/com/ruslan/hlushan/third_party/rxjava2/test/utils/TestRxUtils.kt
game-x50
361,364,864
false
null
package com.ruslan.hlushan.third_party.rxjava2.test.utils import io.reactivex.observers.TestObserver fun <T> TestObserver<T>.assertNotCompleteNoErrorsNoValues(): TestObserver<T> = assertNotComplete() .assertNoErrors() .assertNoValues()
22
Kotlin
0
0
159a035109fab5cf777dd7a60f142a89f441df63
277
android_client_app
Apache License 2.0
library/src/commonMain/kotlin/dev/kryptonreborn/cbor/encoder/CborUnicodeStringEncoder.kt
KryptonReborn
792,268,202
false
{"Kotlin": 170662}
package dev.kryptonreborn.cbor.encoder import dev.kryptonreborn.cbor.CborEncoder import dev.kryptonreborn.cbor.model.CborNull import dev.kryptonreborn.cbor.model.CborUnicodeString import dev.kryptonreborn.cbor.model.MajorType import kotlinx.io.Sink class CborUnicodeStringEncoder( sink: Sink, cborEncoder: CborEncoder, ) : BaseEncoder<CborUnicodeString>(sink, cborEncoder) { override fun encode(data: CborUnicodeString) { if (data.chunked) { writeIndefiniteLengthType(MajorType.UNICODE_STRING) if (data.string == null) { return } } else if (data.string == null) { encoder.encode(CborNull) return } val bytes = data.string.encodeToByteArray() writeType(MajorType.UNICODE_STRING, bytes.size.toLong()) writeBytes(*bytes) } }
1
Kotlin
0
0
e5e3bb96b1d315871387ebc446c1cd825d9e4fed
864
kotlin-cbor
Apache License 2.0
aws-runtime/aws-config/jvm/src/aws/sdk/kotlin/runtime/auth/credentials/SdkIOException.kt
awslabs
121,333,316
false
{"Kotlin": 1001977, "Smithy": 11420, "Python": 3618, "TypeScript": 1488, "JavaScript": 1134, "Dockerfile": 391}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.sdk.kotlin.runtime.auth.credentials import java.io.IOException @Suppress("ACTUAL_WITHOUT_EXPECT") internal actual typealias SdkIOException = IOException
75
Kotlin
35
308
82134e3eba5cae90094a5a753db9ceb93346e5b7
283
aws-sdk-kotlin
Apache License 2.0
src/main/kotlin/me/study/opensearch/config/properties/OpensearchProperties.kt
JinseongHwang
774,682,348
false
{"Kotlin": 4200}
package me.study.opensearch.config.properties import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.bind.ConstructorBinding @ConfigurationProperties(prefix = "opensearch") data class OpensearchProperties @ConstructorBinding constructor( val region: String, val signingServiceName: String, val host: String, val username: String, val password: String )
0
Kotlin
0
0
3a92340c9157964604601b8ac91e881eb6e48911
446
spring-boot-opensearch-poc
MIT License
app/src/main/java/com/suihan74/satena/models/EntrySearchSetting.kt
suihan74
207,459,108
false
{"Kotlin": 1734003, "Java": 10330}
package com.suihan74.satena.models import com.suihan74.hatenaLib.SearchType import com.suihan74.satena.R import java.time.LocalDate /** * エントリ検索パラメータ */ data class EntrySearchSetting( /** 検索対象 */ val searchType: SearchType = SearchType.Title, /** 最小ブクマ数 */ val users : Int = 1, /** 期間指定の方法 */ val dateMode: EntrySearchDateMode = EntrySearchDateMode.RECENT, /** 対象期間(開始) */ val dateBegin : LocalDate? = null, /** 対象期間(終了) */ val dateEnd : LocalDate? = null, /** セーフサーチ */ val safe : Boolean = false ) // ------ // /** 期間指定の方法 */ enum class EntrySearchDateMode( override val textId: Int ) : TextIdContainer { /** 直近N日間 */ RECENT(R.string.entry_search_date_mode_recent), /** カレンダーで指定 */ CALENDAR(R.string.entry_search_date_mode_calendar); } val EntrySearchDateMode?.orDefault get() = this ?: EntrySearchDateMode.RECENT
14
Kotlin
1
7
d18b936e17647745920115041fe15d761a209d8a
895
Satena
MIT License
dbflow-tests/src/test/java/com/raizlabs/android/dbflow/models/OneToManyModelTest.kt
lstNull
111,766,134
true
{"Java": 725156, "Kotlin": 505078}
package com.raizlabs.android.dbflow.models import com.raizlabs.android.dbflow.BaseUnitTest import com.raizlabs.android.dbflow.kotlinextensions.delete import com.raizlabs.android.dbflow.kotlinextensions.exists import com.raizlabs.android.dbflow.kotlinextensions.from import com.raizlabs.android.dbflow.kotlinextensions.list import com.raizlabs.android.dbflow.kotlinextensions.result import com.raizlabs.android.dbflow.kotlinextensions.save import com.raizlabs.android.dbflow.kotlinextensions.select import com.raizlabs.android.dbflow.kotlinextensions.writableDatabaseForTable import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test class OneToManyModelTest : BaseUnitTest() { @Test fun testOneToManyModel() { var testModel2 = TwoColumnModel("Greater", 4) testModel2.save() testModel2 = TwoColumnModel("Lesser", 1) testModel2.save() // assert we save var oneToManyModel = OneToManyModel("HasOrders") oneToManyModel.save() assertTrue(oneToManyModel.exists()) // assert loading works as expected. oneToManyModel = (select from OneToManyModel::class).result!! assertNotNull(oneToManyModel.getRelatedOrders()) assertTrue(!oneToManyModel.getRelatedOrders().isEmpty()) // assert the deletion cleared the variable oneToManyModel.delete() assertFalse(oneToManyModel.exists()) assertNull(oneToManyModel.orders) // assert singular relationship was deleted. val list = (select from TwoColumnModel::class).list assertTrue(list.size == 1) } }
0
Java
0
1
fcbad3b591fdc7d61140b76834e8d4582f642b2b
1,711
DBFlow
MIT License
app/src/main/java/com/eighthours/flow/presenter/adapter/PositionListAdapter.kt
motch0214
88,235,250
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 2, "XML": 31, "Kotlin": 70}
package com.eighthours.flow.presenter.adapter import android.content.Context import android.databinding.ViewDataBinding import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.eighthours.flow.databinding.* import com.eighthours.flow.presenter.behavior.bean.position.* import io.reactivex.disposables.Disposable class PositionListAdapter( context: Context) : RecyclerView.Adapter<PositionListAdapter.ViewHolder>() { private val inflater = LayoutInflater.from(context) class ViewHolder( val binding: ViewDataBinding ) : RecyclerView.ViewHolder(binding.root) private var items: List<GroupPositionBean> = emptyList() override fun getItemCount(): Int { return items.size } override fun getItemViewType(index: Int): Int { return items[index].type.ordinal } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val type = PositionBeanType.values()[viewType] val binding = when (type) { PositionBeanType.TOTAL_ASSET -> ItemTotalAssetPositionBinding.inflate(inflater) PositionBeanType.TOTAL_PL -> ItemTotalPlPositionBinding.inflate(inflater) PositionBeanType.ASSET_GROUP -> ItemAssetGroupPositionBinding.inflate(inflater) PositionBeanType.PL_GROUP -> ItemPlGroupPositionBinding.inflate(inflater) } return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, index: Int) { val type = items[index].type when (type) { PositionBeanType.TOTAL_ASSET -> { holder.binding as ItemTotalAssetPositionBinding holder.binding.bean = items[index] as TotalAssetPositionBean } PositionBeanType.TOTAL_PL -> { holder.binding as ItemTotalPlPositionBinding holder.binding.bean = items[index] as TotalPLPositionBean } PositionBeanType.ASSET_GROUP -> { holder.binding as ItemAssetGroupPositionBinding (holder.binding.bean as? Disposable)?.dispose() bind(holder.binding, items[index] as AssetGroupPositionBean) } PositionBeanType.PL_GROUP -> { holder.binding as ItemPlGroupPositionBinding bind(holder.binding, items[index] as PLGroupPositionBean) } } } fun update(items: List<GroupPositionBean>) { val old = this.items this.items = items DiffUtil.calculateDiff(Callback(old, items)).dispatchUpdatesTo(this) } private class Callback(old: List<GroupPositionBean>, new: List<GroupPositionBean>) : DiffCallback<GroupPositionBean>(old, new) { override fun areItemsTheSame(oldItem: GroupPositionBean, newItem: GroupPositionBean): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: GroupPositionBean, newItem: GroupPositionBean): Boolean { return oldItem == newItem } } private fun bind(binding: ItemAssetGroupPositionBinding, bean: AssetGroupPositionBean) { binding.bean = bean val existence = binding.positions.childCount for ((i, position) in bean.positions.withIndex()) { val b = if (i < existence) { binding.positions.getChildAt(i).tag as ItemAssetPositionBinding } else { ItemAssetPositionBinding.inflate(inflater).apply { root.tag = this binding.positions.addView(root) } } b.bean = position } for (i in bean.positions.size until existence) { binding.positions.removeViewAt(bean.positions.size) } } private fun bind(binding: ItemPlGroupPositionBinding, bean: PLGroupPositionBean) { binding.bean = bean val existence = binding.positions.childCount for ((i, position) in bean.positions.withIndex()) { val b = if (i < existence) { binding.positions.getChildAt(i).tag as ItemInoutPositionBinding } else { ItemInoutPositionBinding.inflate(inflater).apply { root.tag = this binding.positions.addView(root) } } b.bean = position } for (i in bean.positions.size until existence) { binding.positions.removeViewAt(bean.positions.size) } } }
1
null
1
1
d964a5ffac9d8dfb0ba7e9cac2bcd6fd99158e9d
4,648
flow
MIT License
compiler/fir/checkers/checkers.jvm/src/org/jetbrains/kotlin/fir/analysis/jvm/checkers/expression/FirDeprecatedJavaAnnotationsChecker.kt
krzema12
312,049,057
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.analysis.jvm.checkers.expression import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.fir.FirRealSourceElementKind import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirAnnotationCallChecker import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.fir.analysis.diagnostics.jvm.FirJvmErrors import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall import org.jetbrains.kotlin.fir.types.ConeClassLikeType import org.jetbrains.kotlin.fir.types.coneTypeSafe import org.jetbrains.kotlin.load.java.JvmAnnotationNames import org.jetbrains.kotlin.name.FqName object FirDeprecatedJavaAnnotationsChecker : FirAnnotationCallChecker() { private val javaToKotlinNameMap: Map<FqName, FqName> = mapOf( JvmAnnotationNames.TARGET_ANNOTATION to StandardNames.FqNames.target, JvmAnnotationNames.RETENTION_ANNOTATION to StandardNames.FqNames.retention, JvmAnnotationNames.DEPRECATED_ANNOTATION to StandardNames.FqNames.deprecated, JvmAnnotationNames.DOCUMENTED_ANNOTATION to StandardNames.FqNames.mustBeDocumented ) override fun check(expression: FirAnnotationCall, context: CheckerContext, reporter: DiagnosticReporter) { if (context.containingDeclarations.lastOrNull()?.source?.kind != FirRealSourceElementKind) return val lookupTag = expression.annotationTypeRef.coneTypeSafe<ConeClassLikeType>()?.lookupTag ?: return javaToKotlinNameMap[lookupTag.classId.asSingleFqName()]?.let { betterName -> reporter.reportOn(expression.source, FirJvmErrors.DEPRECATED_JAVA_ANNOTATION, betterName, context) } } }
34
null
2
24
af0c7cfbacc9fa1cc9bec5c8e68847b3946dc33a
2,077
kotlin-python
Apache License 2.0
app/src/main/java/com/freshdigitable/udonroad2/user/UserActivityNavigationDelegate.kt
akihito104
149,869,805
false
null
package com.freshdigitable.udonroad2.user import android.view.View import com.freshdigitable.udonroad2.R import com.freshdigitable.udonroad2.media.MediaActivity import com.freshdigitable.udonroad2.media.MediaActivityArgs import com.freshdigitable.udonroad2.model.app.navigation.ActivityEffectDelegate import com.freshdigitable.udonroad2.model.app.navigation.AppEffect import com.freshdigitable.udonroad2.model.app.navigation.FeedbackMessage import com.freshdigitable.udonroad2.model.app.navigation.SnackbarFeedbackMessageDelegate import com.freshdigitable.udonroad2.model.app.navigation.TimelineEffect import com.freshdigitable.udonroad2.model.app.weakRef class UserActivityNavigationDelegate( userActivity: UserActivity, ) : ActivityEffectDelegate { private val feedbackDelegate = SnackbarFeedbackMessageDelegate( weakRef(userActivity) { it.findViewById<View>(R.id.user_pager).parent as View } ) private val activity: UserActivity by weakRef(userActivity) override fun accept(event: AppEffect) { when (event) { is TimelineEffect.Navigate.UserInfo -> UserActivity.start(activity, event.tweetUserItem) is TimelineEffect.Navigate.MediaViewer -> MediaActivity.start( activity, MediaActivityArgs(event.tweetId, event.index) ) is FeedbackMessage -> feedbackDelegate.dispatchFeedbackMessage(event) } } }
21
null
1
1
7ec50f204fda79cf222b24623f22e80d05301555
1,429
UdonRoad2
Apache License 2.0
compiler/testData/diagnostics/tests/controlFlowAnalysis/deadCode/commentsInDeadCode.fir.kt
android
263,405,600
true
null
package a fun test1() { bar( 11, todo(),//comment1 ""//comment2 ) } fun test2() { bar(11, todo()/*comment1*/, ""/*comment2*/) } fun test3() { bar(11, l@(todo()/*comment*/), "") } fun todo(): Nothing = throw Exception() fun bar(i: Int, s: String, a: Any) {}
0
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
303
kotlin
Apache License 2.0
amity-sample-app/src/main/java/com/amity/sample/ascsdk/channellist/filter/includetags/IncludeTagFilterViewModel.kt
EkoCommunications
137,022,637
false
{"Gradle": 5, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "INI": 1, "Proguard": 2, "XML": 99, "Kotlin": 118, "Java": 41}
package com.amity.sample.ascsdk.channellist.filter.includetags import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class IncludeTagFilterViewModel : ViewModel() { var includingTags: MutableLiveData<String> = MutableLiveData<String>().apply { this.value = "" } }
0
Kotlin
2
2
cfe4c6fca78fbf3505901499689fc5f94408f9a2
308
EkoMessagingSDKAndroidSample
Apache License 2.0
uniswapkit/src/main/java/io/horizontalsystems/uniswapkit/contract/SwapContractMethodFactories.kt
horizontalsystems
152,531,605
false
null
package io.horizontalsystems.uniswapkit.contract import io.horizontalsystems.ethereumkit.contracts.ContractMethodFactories object SwapContractMethodFactories : ContractMethodFactories() { init { val swapContractMethodFactories = listOf( SwapETHForExactTokensMethodFactory, SwapExactETHForTokensMethodFactory, SwapExactETHForTokensSupportingFeeOnTransferTokensMethodFactory, SwapExactTokensForETHMethodFactory, SwapExactTokensForETHSupportingFeeOnTransferTokensMethodFactory, SwapExactTokensForTokensMethodFactory, SwapExactTokensForTokensSupportingFeeOnTransferTokensMethodFactory, SwapTokensForExactETHMethodFactory, SwapTokensForExactTokensMethodFactory ) registerMethodFactories(swapContractMethodFactories) } }
10
null
54
98
3d83900bc513f4df6575277519277f1a7cc77ab6
893
ethereum-kit-android
MIT License
common/src/main/java/com/ishow/common/utils/http/ip/IpUtils.kt
i-show
62,766,394
false
null
package com.ishow.common.utils.http.ip import android.content.Context import com.ishow.common.app.provider.InitProvider import com.ishow.common.extensions.parseJSON import com.ishow.common.extensions.toJSON import com.ishow.common.utils.StorageUtils import com.ishow.common.utils.http.ip.entries.IpSource import com.ishow.common.utils.http.ip.executor.FSExecutor import com.ishow.common.utils.http.ip.executor.IFYExecutor import com.ishow.common.utils.http.ip.executor.SohuExecutor import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import okhttp3.OkHttpClient class IpUtils private constructor() { private var ipInfo: IpInfo? = null private val okHttpClient by lazy { OkHttpClient.Builder() .build() } private fun save(info: IpInfo) { StorageUtils.save() .group("ip") .addParam(KEY_CACHE, info.toJSON()) .apply() } private fun getCache(context: Context?): IpInfo? { if (context == null) return null val sp = context.getSharedPreferences("ip", Context.MODE_PRIVATE) val cache = sp.getString(KEY_CACHE, null) if (cache.isNullOrEmpty()) return null ipInfo = cache.parseJSON() return ipInfo } private suspend fun start(callBack: IpCallBack? = null): IpInfo? { var info = FSExecutor(okHttpClient).execute() if (info == null) { info = SohuExecutor(okHttpClient).execute() } if (info == null) { info = IFYExecutor(okHttpClient).execute() } callBack?.invoke(info) info?.let { ipInfo = it save(it) } return info } companion object { private const val KEY_CACHE = "IP_CACHE" val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { IpUtils() } fun getIp(callBack: IpCallBack? = null): IpInfo? { val instance = instance if (instance.ipInfo == null) { instance.getCache(InitProvider.app) } InitProvider.scope.launch(Dispatchers.IO) { instance.start(callBack) } return instance.ipInfo } } data class IpInfo( val source: IpSource, val type: Int ) { lateinit var ip: String } }
1
null
1
1
0b823a69256345078a0c110798c8e9ac4ae2b565
2,320
android-Common
Apache License 2.0
platform/platform-tests/testSrc/com/intellij/ui/charts/LineChartKotlinTest.kt
ingokegel
72,937,917
true
null
package com.intellij.ui.charts import com.intellij.ui.charts.* import com.intellij.util.ui.ImageUtil import org.junit.Assert import org.junit.Test import java.awt.Dimension import java.awt.image.BufferedImage import kotlin.math.roundToInt class LineChartKotlinTest { @Test fun simpleCreation() { val chart = lineChart<Int, Int> { datasets { dataset { values { x = listOf(2, 3, 4) y = listOf(1, 2, 3) } } } } val xy = chart.findMinMax() Assert.assertEquals(2, xy.xMin) Assert.assertEquals(4, xy.xMax) Assert.assertEquals(1, xy.yMin) Assert.assertEquals(3, xy.yMax) } @Test fun checkDoubleCreation() { val chart = lineChart<Double, Double> { datasets { dataset { generate { x = generator(0.01).prepare(0.0, 100.0) y = { it } } } } } val xy = chart.findMinMax() Assert.assertEquals(0.0, xy.xMin, 1e-6) Assert.assertEquals(100.0, xy.xMax, 1e-6) Assert.assertEquals(0.0, xy.yMin, 1e-6) Assert.assertEquals(100.0, xy.yMax, 1e-6) } @Test fun testLinearChart() { val size = 1000 val chart = lineChart<Double, Double> { dataset { generate { x = generator(10.0 / size).prepare(0.0, size / 10.0) y = { it } } } } val img = ImageUtil.createImage(size, size, BufferedImage.TYPE_INT_RGB) chart.component.apply { this.size = Dimension(size, size) invalidate() paint(img.createGraphics()) } val xy = chart.findMinMax() for (i in 0..size) { val loc = chart.findLocation(xy, i / 10.0 to i / 10.0) Assert.assertEquals("x fails, i = $i", i.toDouble(), loc.x, 1e-6) Assert.assertEquals("y fails, i = $i", (size - i).toDouble(), loc.y, 1e-6) } } @Test fun testLinearChartAndScaled() { val size = 1000 val chart = lineChart<Double, Double> { dataset { generate { x = generator(10.0 / size).prepare(0.0, size / 10.0) y = { it } } } } val img = ImageUtil.createImage(size, size, BufferedImage.TYPE_INT_RGB) chart.component.apply { this.size = Dimension(size, (size * 1.5).roundToInt()) invalidate() paint(img.createGraphics()) } val xy = chart.findMinMax() for (i in 0..size) { val loc = chart.findLocation(xy, i / 10.0 to i / 10.0) Assert.assertEquals("x fails, i = $i", i.toDouble(), loc.x, 1e-6) Assert.assertEquals("y fails, i = $i", (size - i) * 1.5, loc.y, 1e-6) } } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,622
intellij-community
Apache License 2.0
app/src/main/java/fm/peremen/android/utils/ContextExtensions.kt
rusmonster
341,655,134
false
null
package fm.peremen.android.utils import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.core.content.ContextCompat fun Context.hasGpsPermission() = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
1
null
1
1
f75666fd82b4b8f10e0a8bbd7e33b79e2f004c22
330
peremenfm
Apache License 2.0
androidApp/app/src/main/java/ru/hsHelper/androidApp/rest/codegen/apis/SheetsControllerApi.kt
HSHelper
344,596,407
false
null
/** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: Api Documentation * * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package ru.hsHelper.androidApp.rest.codegen.apis import retrofit2.http.Headers import retrofit2.http.POST import ru.hsHelper.androidApp.rest.codegen.models.SheetInitData @JvmSuppressWildcards interface SheetsControllerApi { /** * createSheet * The endpoint is owned by server REST api service owner * @param sheetInitData sheetInitData (required) */ @Headers( "X-Operation-ID: createSheetUsingPOST", "Content-Type: application/json" ) @POST("sheets/create") suspend fun createSheetUsingPOST( @retrofit2.http.Body sheetInitData: SheetInitData ): Long /** * updateSheet * The endpoint is owned by server REST api service owner * @param id id (required) */ @Headers( "X-Operation-ID: updateSheetUsingPOST", "Content-Type: application/json" ) @POST("sheets/update/{id}") suspend fun updateSheetUsingPOST( @retrofit2.http.Path("id") id: Long ): Unit }
1
null
3
2
8ad2f5227325a4da263209b0fcd7ab6f89ae7780
1,191
HSHelper
MIT License
compiler/tests-spec/testData/diagnostics/linked/type-inference/smart-casts/smart-casts-sources/p-4/pos/1.17.kt
damenez
176,209,431
true
{"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1}
// !LANGUAGE: +NewInference // !DIAGNOSTICS: -UNUSED_EXPRESSION // SKIP_TXT /* * KOTLIN DIAGNOSTICS SPEC TEST (POSITIVE) * * SPEC VERSION: 0.1-draft * PLACE: type-inference, smart-casts, smart-casts-sources -> paragraph 4 -> sentence 1 * RELEVANT PLACES: * paragraph 1 -> sentence 2 * paragraph 6 -> sentence 1 * paragraph 9 -> sentence 3 * paragraph 9 -> sentence 4 * NUMBER: 17 * DESCRIPTION: Smartcasts from nullability condition (value or reference equality with `null` and `throw` after it) using if expression. * UNSPECIFIED BEHAVIOR * HELPERS: objects, properties, classes */ // TESTCASE NUMBER: 1 fun case_1(x: Int?) { if (x == null) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.inv() } // TESTCASE NUMBER: 2 fun case_2(x: Unit?) { if (x === null) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Unit & kotlin.Unit?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 3 fun case_3(x: Nothing?) { if (<!SENSELESS_COMPARISON!><!DEBUG_INFO_CONSTANT!>x<!> != null<!>) else throw Exception() <!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("kotlin.Nothing?")!>x<!> } // TESTCASE NUMBER: 4 fun case_4(x: Number?) { if (x !== null) else { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Number & kotlin.Number?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 5 fun case_5(x: Char?, y: Nothing?) { if (x != <!DEBUG_INFO_CONSTANT!>y<!>) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Char & kotlin.Char?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 6 fun case_6(x: Object?) { if (x !== <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) else { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("Object & Object?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Object & Object?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 7 fun case_7(x: Class?) { if (x === <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || false || false || false) { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("Class & Class?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Class & Class?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 8 fun case_8(x: Int?) { if (false || false || false || x == <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.inv() } // TESTCASE NUMBER: 9 fun case_9(x: String?) { if (x != <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> && true && true && true) else { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.String & kotlin.String?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.String & kotlin.String?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 10 fun case_10(x: Float?) { if (true && true && true && x !== null) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 11 fun case_11(x: Out<*>?) { if (x == null) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("Out<*> & Out<*>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Out<*> & Out<*>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 12 fun case_12(x: Map<Unit, Nothing?>?) { if (x === null) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.Map<kotlin.Unit, kotlin.Nothing?> & kotlin.collections.Map<kotlin.Unit, kotlin.Nothing?>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.Map<kotlin.Unit, kotlin.Nothing?> & kotlin.collections.Map<kotlin.Unit, kotlin.Nothing?>?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 13 fun case_13(x: Map<out Number, *>?) { if (x != null) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.Map<out kotlin.Number, *> & kotlin.collections.Map<out kotlin.Number, *>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.Map<out kotlin.Number, *> & kotlin.collections.Map<out kotlin.Number, *>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 14 fun case_14(x: MutableCollection<in Number>?) { if (x !== null) else { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableCollection<in kotlin.Number> & kotlin.collections.MutableCollection<in kotlin.Number>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableCollection<in kotlin.Number> & kotlin.collections.MutableCollection<in kotlin.Number>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 15 fun case_15(x: MutableCollection<out Nothing?>?, y: Nothing?) { if (x != <!DEBUG_INFO_CONSTANT!>y<!>) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableCollection<out kotlin.Nothing?> & kotlin.collections.MutableCollection<out kotlin.Nothing?>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableCollection<out kotlin.Nothing?> & kotlin.collections.MutableCollection<out kotlin.Nothing?>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 16 fun case_16(x: Collection<Collection<Collection<Collection<Collection<Collection<Collection<*>>>>>>>?) { if (x !== <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!>) else { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<*>>>>>>> & kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<*>>>>>>>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<*>>>>>>> & kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<kotlin.collections.Collection<*>>>>>>>?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 17 fun case_17(x: MutableMap<*, *>?) { if (x === <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> || false) { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableMap<*, *> & kotlin.collections.MutableMap<*, *>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableMap<*, *> & kotlin.collections.MutableMap<*, *>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 18 fun case_18(x: MutableMap<out Number, in Number>?) { if (false || false || false || x == <!DEBUG_INFO_CONSTANT!>nullableNothingProperty<!>) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableMap<out kotlin.Number, in kotlin.Number> & kotlin.collections.MutableMap<out kotlin.Number, in kotlin.Number>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.collections.MutableMap<out kotlin.Number, in kotlin.Number> & kotlin.collections.MutableMap<out kotlin.Number, in kotlin.Number>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 19 fun case_19(x: Inv<in Inv<in Inv<in Inv<in Inv<in Inv<in Inv<in Int>>>>>>>?) { if (x === <!DEBUG_INFO_CONSTANT!>implicitNullableNothingProperty<!> && true) else { throw Exception() } <!DEBUG_INFO_CONSTANT, DEBUG_INFO_EXPRESSION_TYPE("Inv<in Inv<in Inv<in Inv<in Inv<in Inv<in Inv<in kotlin.Int>>>>>>>? & kotlin.Nothing?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Inv<in Inv<in Inv<in Inv<in Inv<in Inv<in Inv<in kotlin.Int>>>>>>>? & kotlin.Nothing?")!>x<!>.equals(<!DEBUG_INFO_CONSTANT!>x<!>) } // TESTCASE NUMBER: 20 fun case_20(x: Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out Number>>>>>>>?) { if (true && true && true && x !== null) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out kotlin.Number>>>>>>> & Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out kotlin.Number>>>>>>>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out kotlin.Number>>>>>>> & Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out Inv<out kotlin.Number>>>>>>>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 21 fun <T> case_21(x: T) { if (x == null) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("T & T!!")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("T & T!!"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 22 fun <T> case_22(x: T?) { if (x === null) throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("T!! & T?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("T!! & T?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(x) } // TESTCASE NUMBER: 23 fun <T> case_23(x: Inv<in T>?) { if (x !== null) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("Inv<in T> & Inv<in T>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Inv<in T> & Inv<in T>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 24 fun <T> case_24(x: Inv<out T?>?, y: Nothing?) { if (x !== <!DEBUG_INFO_CONSTANT!>y<!> && true) else throw Exception() <!DEBUG_INFO_EXPRESSION_TYPE("Inv<out T?> & Inv<out T?>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Inv<out T?> & Inv<out T?>?")!>x<!>.equals(x) } // TESTCASE NUMBER: 25 fun <T> case_25(x: Inv<out T?>?, y: Nothing?) { if (x !== <!DEBUG_INFO_CONSTANT!>y<!>) else try { <!UNREACHABLE_CODE!>throw<!> Exception() } finally { throw Exception() } <!DEBUG_INFO_EXPRESSION_TYPE("Inv<out T?> & Inv<out T?>?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("Inv<out T?> & Inv<out T?>?")!>x<!>.equals(x) }
0
Kotlin
0
2
9a2178d96bd736c67ba914b0f595e42d1bba374d
10,102
kotlin
Apache License 2.0
app/src/main/kotlin/org/bbqapp/android/api/model/Entities.kt
bbqapp
41,700,975
false
{"Java": 119515, "Kotlin": 61527}
/* * The MIT License (MIT) * * Copyright (c) 2015 bbqapp * * 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 org.bbqapp.android.api.model import android.net.Uri import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import java.io.* import org.bbqapp.android.extension.copyTo; import timber.log.Timber @JsonIgnoreProperties(ignoreUnknown = true) interface Entity interface HasId : Entity { val id: String? } data class Id(@JsonProperty("_id") override val id: String? = null) : HasId data class Address(val country: String) : Entity data class Location( val coordinates: List<Double>, val type: String) : Entity data class Comment(val comment: String, val score: Int) : Entity data class Place( @JsonProperty("_id") override val id: String? = null, val tags: List<String>? = null, val address: Address? = null, val location: Location, val comments: List<Comment>? = null) : HasId data class PictureInfo( @JsonProperty("_id") override val id: String, @JsonProperty("_place") val placeId: String, val meta: PictureMeta) : HasId data class PictureMeta( val mimeType: String?, val url: String) : Entity data class Picture(val input: InputStream, val length: Long = -1, val progress: ((Long, Long) -> Unit)? = null) { constructor(file: File, progress: ((Long, Long) -> Unit)? = null ) : this(FileInputStream(file), file.length(), progress) @Throws(FileNotFoundException::class) constructor(uri: Uri, progress: ((Long, Long) -> Unit)? = null ) : this(File(uri.toString()), progress) @Throws(IOException::class) fun out(out: OutputStream, progress: ((Long, Long) -> Unit)? = null): Long { try { val listener = fun(transferred: Long): Unit { progress?.invoke(length, transferred) this.progress?.invoke(length, transferred) } return input.copyTo(out, listener) } finally { try { input.close() } catch (e: IOException) { Timber.w(e, "Could not close input stream") } } } }
1
Java
1
1
221516722251d9a4935796d516402d089e2a1c1c
3,347
bbqapp-android
MIT License
mvicore-plugin/idea/src/main/java/com/badoo/mvicore/plugin/ui/EventList.kt
emreakcan
287,947,555
true
{"Gradle": 15, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 13, "Batchfile": 1, "YAML": 2, "Markdown": 31, "Kotlin": 130, "XML": 31, "Proguard": 6, "Java": 5}
package com.badoo.mvicore.plugin.ui import com.badoo.mvicore.plugin.model.Event.Item import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.ListSpeedSearch import com.intellij.ui.components.JBList import javax.swing.JList import javax.swing.ListSelectionModel class EventList: JBList<Item>() { private val items = EventListModel() // what we show private var itemSelectionListener: ((Item) -> Unit)? = null init { model = items cellRenderer = CellRenderer() addListSelectionListener { if (it.valueIsAdjusting || selectedIndex < 0) return@addListSelectionListener val item = model.getElementAt(selectedIndex) itemSelectionListener?.invoke(item) } selectionMode = ListSelectionModel.SINGLE_SELECTION ListSpeedSearch(this) } fun add(item: Item) { items.add(item) scrollToBottom() } fun clear() { clearSelection() items.clear() } fun setFilter(filter: (Item) -> Boolean) { clearSelection() items.setFilter(filter) } fun resetFilter() { clearSelection() items.resetFilter() } fun setItemSelectionListener(itemSelected: (Item) -> Unit) { itemSelectionListener = itemSelected } private fun scrollToBottom() { if (lastVisibleIndex == model.size - 2) { ensureIndexIsVisible(model.size - 1) } } private class CellRenderer : ColoredListCellRenderer<Item>() { override fun customizeCellRenderer(list: JList<out Item>, value: Item?, index: Int, selected: Boolean, hasFocus: Boolean) { append(value?.name().orEmpty()) } private fun Item.name() = element.asJsonObject ?.keySet() ?.first() } }
0
Kotlin
0
2
b381a0c3684afca743a39808fbc8a2e37a722375
1,840
MVICore
Apache License 2.0
app/src/main/java/com/shevelev/comics_viewer/ui/activities/view_comics/bitmap_repository/IBitmapRepository.kt
AlShevelev
232,800,756
false
null
package com.shevelev.comics_viewer.ui.activities.view_comics.bitmap_repository import android.graphics.Bitmap /** * Created by Syleiman on 26.11.2015. */ interface IBitmapRepository { /** * * @param index index of page * @return */ fun getByIndex(index: Int, viewAreaWidth: Int, viewAreaHeight: Int): Bitmap? val pageCount: Int }
1
null
1
1
884ffda569da9c00977b01472b74fe9f68674b25
366
comics_viewer
MIT License
pluto/src/main/java/com/mocklets/pluto/core/extensions/StringsKtx.kt
mocklets
459,260,997
false
null
package com.mocklets.pluto.core.extensions import java.util.Locale fun String.capitalizeText(default: Locale = Locale.getDefault()): String = replaceFirstChar { if (it.isLowerCase()) it.titlecase(default) else it.toString() }
0
Kotlin
2
8
87dc5a27272e0fc5c38e042fa95689a143ae5446
232
pluto
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/bedrock/TransformationFunctionPropertyDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5279682}
package com.faendir.awscdkkt.generated.services.bedrock import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.bedrock.CfnDataSource @Generated public fun buildHierarchicalChunkingLevelConfigurationProperty(initializer: @AwsCdkDsl CfnDataSource.HierarchicalChunkingLevelConfigurationProperty.Builder.() -> Unit = {}): CfnDataSource.HierarchicalChunkingLevelConfigurationProperty = CfnDataSource.HierarchicalChunkingLevelConfigurationProperty.Builder().apply(initializer).build()
2
Kotlin
0
4
f1542b808f0e2cf4fcdd0d84d025a8fbaf09e90d
570
aws-cdk-kt
Apache License 2.0
parser/src/commonMain/kotlin/models/Channel.kt
shalva97
371,007,326
false
{"Kotlin": 45824, "HTML": 470, "CSS": 83}
package models data class Channel(val name: String, val url: String) { companion object { operator fun invoke(video: YoutubeVideo): Channel { val first = video.channel?.first() return Channel(first?.name ?: "unknown channel", first?.url ?: "unknown url") } } }
22
Kotlin
0
13
350cd8d93f0b4b28e9751f7b41c001e05ef9b642
309
Youtube_history_parser
The Unlicense
parser/src/commonMain/kotlin/models/Channel.kt
shalva97
371,007,326
false
{"Kotlin": 45824, "HTML": 470, "CSS": 83}
package models data class Channel(val name: String, val url: String) { companion object { operator fun invoke(video: YoutubeVideo): Channel { val first = video.channel?.first() return Channel(first?.name ?: "unknown channel", first?.url ?: "unknown url") } } }
22
Kotlin
0
13
350cd8d93f0b4b28e9751f7b41c001e05ef9b642
309
Youtube_history_parser
The Unlicense
app/src/main/java/org/listenbrainz/android/model/User.kt
metabrainz
550,726,972
false
{"Kotlin": 1481175, "Ruby": 423}
package org.listenbrainz.android.model import com.google.gson.annotations.SerializedName data class User( @SerializedName("user_name") val username: String, @SerializedName("is_followed") val isFollowed: Boolean = false )
25
Kotlin
31
99
573ab0ec6c5b87ea963f013174159ddfcd123976
231
listenbrainz-android
Apache License 2.0
src/main/kotlin/id/walt/services/vc/JsonLdCredentialService.kt
walt-id
392,607,264
false
null
package id.walt.services.vc import id.walt.auditor.VerificationPolicyResult import id.walt.credentials.w3c.PresentableCredential import id.walt.credentials.w3c.VerifiableCredential import id.walt.servicematrix.ServiceProvider import id.walt.services.WaltIdService import id.walt.signatory.ProofConfig import info.weboftrust.ldsignatures.LdProof import kotlinx.serialization.Serializable import java.net.URI import java.time.Instant enum class VerificationType { VERIFIABLE_CREDENTIAL, VERIFIABLE_PRESENTATION } @Serializable data class VerificationResult(val verified: Boolean, val verificationType: VerificationType) abstract class JsonLdCredentialService : WaltIdService() { override val implementation get() = serviceImplementation<JsonLdCredentialService>() open fun sign(jsonCred: String, config: ProofConfig): String = implementation.sign(jsonCred, config) open fun verify(vcOrVp: String): VerificationResult = implementation.verify(vcOrVp) open fun present( vcs: List<PresentableCredential>, holderDid: String, domain: String?, challenge: String?, expirationDate: Instant? ): String = implementation.present(vcs, holderDid, domain, challenge, expirationDate) open fun listVCs(): List<String> = implementation.listVCs() open fun addProof(credMap: Map<String, String>, ldProof: LdProof): String = implementation.addProof(credMap, ldProof) open fun validateSchema(vc: VerifiableCredential, schemaURI: URI): VerificationPolicyResult = implementation.validateSchema(vc, schemaURI) open fun validateSchemaTsr(vc: String): VerificationPolicyResult = implementation.validateSchemaTsr(vc) companion object : ServiceProvider { override fun getService() = object : JsonLdCredentialService() {} override fun defaultImplementation() = WaltIdJsonLdCredentialService() } }
7
null
34
97
1a8776a899ac97aa32f58d2f70aba23683d2c9b3
1,892
waltid-ssikit
Apache License 2.0
app/src/main/java/com/kire/audio/presentation/ui/details/list_screen_ui/top_block/AlbumSuggestionPanel.kt
KiREHwYE
674,992,893
false
{"Kotlin": 403392}
package com.kire.audio.presentation.ui.details.list_screen_ui.top_block import android.net.Uri import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.kire.audio.presentation.ui.details.common.SuggestionItem import com.kire.audio.presentation.ui.theme.dimen.Dimens /** * Список с альбомами для отрисовки в TopBlock * * @param albums список альбомов * @param onAlbumSuggestionClick lambda для обработки нажатия на альбом * @param getImageUri lambda для получения Uri изображения альбома * @param getAlbumArtist lambda для получения исполнителя альбома * * @author <NAME> (KiREHwYE) */ @Composable fun AlbumSuggestionPanel( albums: List<String>, onAlbumSuggestionClick: (String) -> Unit, getImageUri: (String) -> Uri?, getAlbumArtist: (String) -> String ) { /** Список с альбомами */ LazyRow( modifier = Modifier .fillMaxWidth() .wrapContentHeight(), contentPadding = PaddingValues(horizontal = Dimens.universalPad), horizontalArrangement = Arrangement.spacedBy(Dimens.columnAndRowUniversalSpacedBy) ) { items(albums) { album -> /** Элемент списка в виде плитки с обложкой и 2-мя текстами */ SuggestionItem( imageUri = getImageUri(album), mainText = album, satelliteText = getAlbumArtist(album), onSuggestionClick = onAlbumSuggestionClick, ) } } }
0
Kotlin
0
0
472015ad95e5e02ee3f72a37d15240414f79d042
1,810
RE13
Apache License 2.0
sdk-openapi/src/main/kotlin/org/sinou/pydia/openapi/model/RestUpdateSharePoliciesRequest.kt
bsinou
434,248,316
false
{"Kotlin": 2133584, "Java": 10237}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.sinou.pydia.openapi.model import org.sinou.pydia.openapi.model.ServiceResourcePolicy import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * * * @param policies * @param uuid */ data class RestUpdateSharePoliciesRequest ( @Json(name = "Policies") val policies: kotlin.collections.List<ServiceResourcePolicy>? = null, @Json(name = "Uuid") val uuid: kotlin.String? = null ) { }
0
Kotlin
0
1
51a128c49a24eedef1baf2d4f295f14aa799b5d3
712
pydia
Apache License 2.0
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/popup/CodeVisionContextPopup.kt
JetBrains
2,489,216
false
null
package com.intellij.codeInsight.codeVision.ui.popup import com.intellij.codeInsight.codeVision.CodeVisionEntry import com.intellij.codeInsight.codeVision.CodeVisionEntryExtraActionModel import com.intellij.codeInsight.codeVision.ui.model.CodeVisionListData import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.ListSeparator import com.intellij.ui.popup.list.ListPopupImpl class CodeVisionContextPopup private constructor(project: Project, aStep: ListPopupStep<CodeVisionEntryExtraActionModel>) : ListPopupImpl( project, aStep) { companion object { fun createLensList(entry: CodeVisionEntry, model: CodeVisionListData, project: Project): CodeVisionContextPopup { val lst = entry.extraActions + model.projectModel.hideLens val aStep = object : SubCodeVisionMenu(lst, { model.rangeCodeVisionModel.handleLensExtraAction(entry, it) }) { override fun getSeparatorAbove(value: CodeVisionEntryExtraActionModel): ListSeparator? { return super.getSeparatorAbove(value) ?: if (value == model.projectModel.hideLens) ListSeparator() else null } } return CodeVisionContextPopup(project, aStep) } } init { setMaxRowCount(15) } override fun beforeShow(): Boolean { setHandleAutoSelectionBeforeShow(false) list.clearSelection() return super.beforeShow() } override fun afterShow() { } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
1,591
intellij-community
Apache License 2.0
compass-geolocation/src/commonMain/kotlin/dev/jordond/compass/geolocation/Extensions.kt
jordond
772,795,864
false
{"Kotlin": 262383}
package dev.jordond.compass.geolocation import dev.jordond.compass.Location import dev.jordond.compass.geolocation.internal.DefaultGeolocator /** * Gets the current location or null if the location is not available. * * @receiver The [Geolocator] to get the location from. * @return The current location or null if the location is not available. */ public suspend fun Geolocator.currentLocationOrNull(): Location? = current().getOrNull() /** * Check if the current [Geolocator] has the permissions required for geolocation. * * This will always return `true` if the [Locator] used by the [Geolocator] is not a [PermissionLocator]. * * @receiver The [Geolocator] to check the permissions of. * @return True if the [Geolocator] has the permissions required for geolocation, false otherwise. */ public fun Geolocator.hasPermission(): Boolean { val locator = (this as? DefaultGeolocator)?.locator return (locator as? PermissionLocator)?.hasPermission() ?: true } /** * Check if the current [GeolocatorResult] is a [GeolocatorResult.PermissionDenied]. * * @receiver The [GeolocatorResult] to check. * @return True if the [GeolocatorResult] is a [GeolocatorResult.PermissionDenied], false otherwise. */ public fun GeolocatorResult.Error.isPermissionDenied(): Boolean { return this is GeolocatorResult.PermissionDenied } /** * Check if the current [GeolocatorResult] is a [GeolocatorResult.PermissionDenied]. * * @receiver The [GeolocatorResult] to check. * @return True if the [GeolocatorResult] is a [GeolocatorResult.PermissionDenied], false otherwise. */ public fun GeolocatorResult.Error.isPermissionDeniedForever(): Boolean { return (this as? GeolocatorResult.PermissionDenied)?.forever ?: false }
5
Kotlin
4
89
d0ef39ed66f7af237bbe21ba630dfcdd6f2ff258
1,739
compass
MIT License
src/main/kotlin/com/amcentral365/service/Main.kt
am-central-365
122,803,808
false
null
package com.amcentral365.service import com.amcentral365.service.api.SchemaUtils import com.amcentral365.service.mergedata.MergeRoles import com.amcentral365.service.mergedata.MergeAssets import mu.KotlinLogging private const val VERSION = "0.0.1" private val logger = KotlinLogging.logger {} internal lateinit var config: Configuration internal var authUser: AuthenticatedUser = AuthenticatedUser("amcentral365", "<EMAIL>", "Internal User") internal val authorizer: Authorization = Authorization() //internal lateinit var thisWorkerAsset: Asset val webServer = WebServer() lateinit var schemaUtils: SchemaUtils lateinit var databaseStore: DatabaseStore @Volatile var keepRunning = true /** Global 'lights out' flag */ fun main(args: Array<String>) { logger.info { "AM-Central-365 version $VERSION is starting" } logger.info { "parsing arguments" } config = Configuration(args) logger.info { "initializing globals" } databaseStore = DatabaseStore() schemaUtils = SchemaUtils(config.schemaCacheSizeInNodes) logger.info { "merging data" } if( !mergeData() ) return logger.info { "starting the Web server" } webServer.start(config.bindPort) Thread.sleep(500) // give the web server some breath time logger.info { "AM-Central-365 is ready to serve requests at http://${config.clusterFQDN.first}:${config.bindPort}" } } fun callMeFromJavaForHighFive(p1: Int) = p1 + 5 private fun mergeData(): Boolean { if( config.mergeRoles ) { val failures = MergeRoles("roles").merge() if( failures > 0 ) { logger.error { "Roles merge failed with $failures error(s). Can't start until all problems are fixed. To bypass the merge, use --no-merge-roles parameter" } return false } } else { logger.info("Merge roles is disabled, skipping") } if( config.mergeAssets ) { val failures = MergeAssets("assets").merge() if( failures > 0 ) { logger.error { "Assets merge failed with $failures error(s). Can't start until all problems are fixed. To bypass the merge, use --no-merge-assets parameter" } return false } } else { logger.info("Merge assets is disabled, skipping") } return true }
4
null
1
1
ba94f3c9048c9eface9bf6814dac3abe86a6159f
2,280
back-end
MIT License
android-transformer-sample-kotlin/src/main/java/com/mobandme/sample/kotlin/app/model/NetworkHome.kt
dimorinny
59,245,687
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Java": 12, "Proguard": 2, "XML": 12, "Kotlin": 3}
package com.mobandme.sample.kotlin.app.model /** * Created by Dimorinny on 20.05.16. */ data class NetworkHome( var name: String = "", var city: String = "" )
1
null
1
1
7123afc3c642ff94c7e946c10841112310edcdea
177
android-transformer
Apache License 2.0
welite-core/src/androidTest/java/com/ealva/welite/db/android/DatabaseTests.kt
ealva-com
265,936,796
false
null
/* * Copyright 2020 eAlva.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress( "NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING", "NO_EXPLICIT_RETURN_TYPE_IN_API_MODE_WARNING" ) package com.ealva.welite.db.android import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ealva.welite.db.DatabaseConfiguration import com.ealva.welite.db.UnmarkedTransactionException import com.ealva.welite.test.shared.CoroutineRule import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import org.junit.runner.RunWith import com.ealva.welite.test.db.CommonDatabaseTests as Common @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) class DatabaseTests { @get:Rule var coroutineRule = CoroutineRule() @Suppress("DEPRECATION") @get:Rule var thrown: ExpectedException = ExpectedException.none() private lateinit var appCtx: Context private var config: DatabaseConfiguration? = null @Before fun setup() { appCtx = ApplicationProvider.getApplicationContext() config = null } @Test fun testInTransaction() = coroutineRule.runBlockingTest { Common.testInTransaction(appCtx, coroutineRule.testDispatcher) } @Test fun testSqliteVersion() = coroutineRule.runBlockingTest { Common.testSqliteVersion(appCtx, coroutineRule.testDispatcher) } @Test fun testDbLifecycle() = coroutineRule.runBlockingTest { Common.testDbLifecycle(appCtx, coroutineRule.testDispatcher) } @Test fun createTableTest() = coroutineRule.runBlockingTest { Common.createTableTest(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateTablesRearrangeOrderForCreate() = coroutineRule.runBlockingTest { Common.testCreateTablesRearrangeOrderForCreate(appCtx, coroutineRule.testDispatcher) } @Test fun testIntegritySunnyDay() = coroutineRule.runBlockingTest { Common.testIntegritySunnyDay(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateTablesWithForeignKeys() = coroutineRule.runBlockingTest { Common.testCreateTablesWithForeignKeys(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateAndDropTable() = coroutineRule.runBlockingTest { Common.testCreateAndDropTable(appCtx, coroutineRule.testDispatcher) } @ExperimentalUnsignedTypes @Test fun testCreateAndDropView() = coroutineRule.runBlockingTest { Common.testCreateAndDropView(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateAndDropTrigger() = coroutineRule.runBlockingTest { Common.testCreateAndDropTrigger(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateAndDropIndex() = coroutineRule.runBlockingTest { Common.testCreateAndDropIndex(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateAndRollback() = coroutineRule.runBlockingTest { Common.testCreateAndRollback(appCtx, coroutineRule.testDispatcher) } @Test fun testTxnToString() = coroutineRule.runBlockingTest { Common.testTxnToString(appCtx, coroutineRule.testDispatcher) } @Test fun testSQLiteSequence() = coroutineRule.runBlockingTest { Common.testSQLiteSequence(appCtx, coroutineRule.testDispatcher) } @Test fun testCreateSQLiteSequence() = coroutineRule.runBlockingTest { // Can't create a system table thrown.expect(IllegalStateException::class.java) Common.testCreateSQLiteSequence() } @Test fun testCreateSQLiteScheme() = coroutineRule.runBlockingTest { // Can't create a system table thrown.expect(IllegalStateException::class.java) Common.testCreateSQLiteScheme() } @Test fun testNoAutoCommitTxnWithoutMarkingSuccessOrRollback() = coroutineRule.runBlockingTest { thrown.expect(UnmarkedTransactionException::class.java) Common.testNoAutoCommitTxnWithoutMarkingSuccessOrRollback( appCtx, coroutineRule.testDispatcher ) } }
0
null
0
3
7d9c5a82c289b04fad34ecc484e5fb3224f41699
4,533
welite
Apache License 2.0
src/main/kotlin/com/goulash/script/grammar/ContainerScriptGrammar.kt
Goulash-Engine
515,495,249
false
null
package com.goulash.script.grammar import com.github.h0tk3y.betterParse.combinators.map import com.github.h0tk3y.betterParse.combinators.times import com.github.h0tk3y.betterParse.combinators.unaryMinus import com.github.h0tk3y.betterParse.combinators.use import com.github.h0tk3y.betterParse.combinators.zeroOrMore import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.lexer.literalToken import com.github.h0tk3y.betterParse.lexer.regexToken import com.goulash.script.logic.ContainerScriptContext import com.goulash.script.logic.ScriptHead class ContainerScriptGrammar : Grammar<ContainerScriptContext>() { private val space by regexToken("\\s+", ignore = true) private val newLine by literalToken("\n", ignore = true) private val containerKeyword by regexToken("^container\\s+[a-z_]+\\s*") private val logicKeyword by regexToken("^logic\\s+[a-z_]+\\s*") private val openBraces by literalToken("{") private val logicBlock by regexToken("^[actors[\\[\\]a-z.<>=\\d\\s]*::[a-z]+\\([a-z]+\\)\\.[a-z]+\\([\\d.\\d\\\\]+\\);\\s*]+") private val closedBraces by literalToken("}") /** * logic <name> */ private val scriptHeadParser by containerKeyword use { ScriptHead(text.removePrefix("container").trim()) } private val logicParser by logicKeyword * -openBraces * logicBlock * -closedBraces map { (logic, block) -> Logic( logic.text.removePrefix("logic").trim(), block.text.replace(Regex("\\s+"), "").trim() ) } private val statementsParser by -openBraces * zeroOrMore(logicParser) * -closedBraces override val rootParser by (scriptHeadParser * statementsParser) map { (scriptHead, logics) -> ContainerScriptContext(scriptHead, logics.associate { it.toPair() }) } }
3
Kotlin
0
0
66d18491e99b3316acb52192cdbabbab489cb588
1,816
goulash-engine
MIT License
app/src/main/java/nick/mirosh/newsapp/data/repository/NetworkConnectivityManager.kt
nsmirosh
644,001,365
false
{"Kotlin": 64385}
package nick.mirosh.newsapp.data.repository import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import kotlinx.coroutines.flow.MutableStateFlow import nick.mirosh.newsapp.domain.network.repository.NetworkConnectivityService class NetworkConnectivityManager ( context: Context, ) : NetworkConnectivityService { private val _isNetworkAvailable = MutableStateFlow(false) private val networkRequest = NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build() private val connectivityManager = context.getSystemService(ConnectivityManager::class.java) private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) _isNetworkAvailable.value = true } override fun onLost(network: Network) { super.onLost(network) _isNetworkAvailable.value = false } } init { connectivityManager?.requestNetwork(networkRequest, networkCallback) } override fun isAvailable() = _isNetworkAvailable fun stop() { connectivityManager?.unregisterNetworkCallback(networkCallback) } }
0
Kotlin
1
2
e12d356daf6149d24883321e1ca9cb79163ab46c
1,374
NewsApp
MIT License
SharedCodeClient/src/commonMain/kotlin/com/jarroyo/sharedcodeclient/domain/base/BaseRequest.kt
jarroyoesp
345,142,032
false
null
package com.jarroyo.sharedcodeclient.domain.base interface BaseRequest { fun validate(): Boolean }
0
Kotlin
0
0
d82dcd8c96e6a6aa3317e3c8ab0263f105293382
104
android-dev-challenge-compose
Apache License 2.0
documentation/src/test/kotlin/guides/Coroutines.kt
smallrye
198,222,234
false
null
import io.smallrye.mutiny.Multi import io.smallrye.mutiny.Uni // tag::importStatements[] import io.smallrye.mutiny.coroutines.asFlow import io.smallrye.mutiny.coroutines.asMulti import io.smallrye.mutiny.coroutines.asUni import io.smallrye.mutiny.coroutines.awaitSuspending // end::importStatements[] import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf suspend fun uniAwaitSuspending() { // tag::uniAwaitSuspending[] val uni: Uni<String> = Uni.createFrom().item("Mutiny ❤ Kotlin") try { // Available within suspend function and CoroutineScope val item: String = uni.awaitSuspending() } catch (failure: Throwable) { // onFailure event happened } // end::uniAwaitSuspending[] } @ExperimentalCoroutinesApi suspend fun deferredAsUni() { // tag::deferredAsUni[] val deferred: Deferred<String> = GlobalScope.async { "Kotlin ❤ Mutiny" } val uni: Uni<String> = deferred.asUni() // end::deferredAsUni[] } @ExperimentalCoroutinesApi suspend fun multiAsFlow() { // tag::multiAsFlow[] val multi: Multi<String> = Multi.createFrom().items("Mutiny", "❤", "Kotlin") val flow: Flow<String> = multi.asFlow() // end::multiAsFlow[] } suspend fun flowAsMulti() { // tag::flowAsMulti[] val flow: Flow<String> = flowOf("Kotlin", "❤", "Mutiny") val multi: Multi<String> = flow.asMulti() // end::flowAsMulti[] }
16
Java
78
436
6bd0c1ce8929e9ef53364870a60dd5f4a75fb5b0
1,565
smallrye-mutiny
Apache License 2.0
data/slack-jackson-dto-test-extensions/src/main/kotlin/io/olaph/slack/dto/jackson/group/channels/ChannelsListExtension.kt
gitter-badger
181,514,383
true
{"Kotlin": 338538}
package io.olaph.slack.dto.jackson.group.channels import io.olaph.slack.dto.jackson.common.types.Channel import io.olaph.slack.dto.jackson.group.chat.Message import io.olaph.slack.dto.jackson.group.chat.sample fun SuccessfulGetChannelListResponse.Companion.sample(): SuccessfulGetChannelListResponse = SuccessfulGetChannelListResponse(true, listOf()) fun ErrorGetChannelListResponse.Companion.sample(): ErrorGetChannelListResponse = ErrorGetChannelListResponse(false, "") fun Channel.Companion.sample(): Channel = Channel( id = "", name = "", isChannel = true, created = 0, isArchived = false, isGeneral = true, unlinked = 0, createdBy = "userID", nameNormalized = "", isShared = false, isOrgShared = false, isMember = false, isPrivate = false, isMpim = false, lastRead = "", latest = Message.sample(), unreadCount = 0, unreadCountDisplay = 0, members = listOf(), topic = Channel.Topic.sample(), purpose = Channel.Purpose.sample(), previousNames = listOf(), numMembers = 1 ) fun Channel.Topic.Companion.sample(): Channel.Topic = Channel.Topic("", "", 0) fun Channel.Purpose.Companion.sample(): Channel.Purpose = Channel.Purpose("", "", 0)
0
Kotlin
0
0
429fa4293cb5c5bf67d7d543f92d4cc7a81eea4f
1,330
slack-spring-boot-starter
MIT License
react-query-kotlin/src/jsMain/kotlin/tanstack/react/query/useMutation.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! @file:JsModule("@tanstack/react-query") package tanstack.react.query import tanstack.query.core.QueryClient external fun <TData, TError, TVariables, TContext> useMutation( options: UseMutationOptions<TData, TError, TVariables, TContext>, queryClient: QueryClient = definedExternally, ): UseMutationResult<TData, TError, TVariables, TContext>
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
398
types-kotlin
Apache License 2.0
ui/widget/src/main/kotlin/ru/maksonic/beresta/ui/widget/button/FloatingFabButton.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta.ui.widget.button import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import ru.maksonic.beresta.ui.theme.Theme import ru.maksonic.beresta.ui.theme.color.onTertiaryContainer import ru.maksonic.beresta.ui.theme.color.tertiaryContainer import ru.maksonic.beresta.ui.widget.functional.rippledClick import ru.maksonic.beresta.ui.widget.surface.SurfacePro /** * @Author maksonic on 31.03.2023 */ @Composable fun FloatingFabButton( modifier: Modifier = Modifier, onClick: () -> Unit = {}, enabled: Boolean = true, fabColor: Color = tertiaryContainer, rippleColor: Color = onTertiaryContainer, shape: Shape = ru.maksonic.beresta.ui.theme.component.Shape.cornerBig, shadowElevation: Dp = Theme.elevation.Level3, border: BorderStroke? = null, fabContent: @Composable () -> Unit ) { SurfacePro(color = fabColor, shape = shape, shadowElevation = shadowElevation, border = border, modifier = modifier .semantics { role = Role.Button }) { Box( Modifier .defaultMinSize(Theme.widgetSize.btnFabSize, Theme.widgetSize.btnFabSize) .rippledClick(enabled = enabled, rippleColor = rippleColor, onClick = onClick), contentAlignment = Alignment.Center ) { fabContent() } } }
0
Kotlin
0
0
e4a25c791082df384c4cb380d98a767a75870740
1,829
Beresta
MIT License
shared/src/commonMain/kotlin/com/reidsync/vibepulse/util/LocalDateTimeFormatter.kt
ReidSync
721,997,250
false
{"Kotlin": 73907, "Swift": 42109}
package com.reidsync.vibepulse.util import kotlinx.datetime.LocalDateTime /** * Created by Reid on 2023/12/18. * Copyright (c) 2023 <NAME>. All rights reserved. */ expect fun LocalDateTime.format(format: String): String
0
Kotlin
0
0
0d7bd0eb3131db23294c792228283767e9d92e52
225
VibePulse
The Unlicense
sample/src/main/java/io/constructor/sample/common/BasePresenter.kt
Constructor-io
132,483,938
false
{"Kotlin": 581338}
package io.constructor.sample.common import io.reactivex.disposables.CompositeDisposable /** * @suppress */ open class BasePresenter<V : BaseView>(protected var view: V) { protected val compositeDisposable = CompositeDisposable() fun onDestroy() { if (!compositeDisposable.isDisposed) { compositeDisposable.dispose() } } }
2
Kotlin
1
4
c47a8fea1fa4cc12c8d428aadbea49cbb7353da3
368
constructorio-client-android
MIT License
app/src/main/java/com/gumu/bookwormapp/presentation/component/CustomAsyncImage.kt
Gumu-96
636,874,711
false
{"Kotlin": 192426}
package com.gumu.bookwormapp.presentation.component import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.BrokenImage import androidx.compose.material.icons.filled.Image import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImagePainter import coil.compose.SubcomposeAsyncImage import coil.compose.SubcomposeAsyncImageContent import coil.request.CachePolicy import coil.request.ImageRequest import com.gumu.bookwormapp.presentation.theme.BookwormAppTheme @Composable fun CustomAsyncImage( modifier: Modifier = Modifier, model: Any?, contentDescription: String?, contentScale: ContentScale = ContentScale.Crop ) { SubcomposeAsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(model) .crossfade(true) .diskCachePolicy(CachePolicy.ENABLED) .build(), contentDescription = contentDescription, contentScale = contentScale, modifier = modifier ) { when (painter.state) { is AsyncImagePainter.State.Loading -> Icon( imageVector = Icons.Default.Image, contentDescription = null, modifier = Modifier.size(40.dp) ) is AsyncImagePainter.State.Success -> SubcomposeAsyncImageContent() else -> Icon( imageVector = Icons.Default.BrokenImage, contentDescription = null, modifier = Modifier.size(40.dp) ) } } } @Preview @Composable private fun CustomAsyncImagePreview() { BookwormAppTheme { CustomAsyncImage( model = null, contentDescription = null ) } }
0
Kotlin
0
2
07751f9e2c7b70713938c9049f661cf7810a67c2
2,041
BookwormApp
MIT License
retrofit-metrics/src/main/kotlin/net/niebes/retrofit/metrics/MeasuredCallAdapter.kt
niebes
205,933,166
false
{"Kotlin": 39268, "Shell": 684}
package net.niebes.retrofit.metrics import retrofit2.Call import retrofit2.CallAdapter import java.lang.reflect.Type class MeasuredCallAdapter<OriginalType, TargetType> internal constructor( private val nextCallAdapter: CallAdapter<OriginalType, TargetType>, private val metricsCollector: RetrofitCallMetricsCollector, ) : CallAdapter<OriginalType, TargetType> { override fun responseType(): Type = nextCallAdapter.responseType() override fun adapt(call: Call<OriginalType>): TargetType = nextCallAdapter.adapt( MeasuredCall( call, metricsCollector ) ) }
3
Kotlin
0
5
44755127c7b3392078416ee754ee098475772d2f
618
retrofit-plugins
MIT License
app/src/main/java/io/github/ch8n/compose97/ui/components/Preview.kt
ch8n
403,836,527
false
{"Kotlin": 83109}
package io.github.ch8n.compose97.ui.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import io.github.ch8n.compose97.ui.theme.Compose97Theme @Composable fun Preview(content: @Composable () -> Unit) { Compose97Theme { Box(modifier = Modifier.fillMaxSize()) { content.invoke() } } }
0
Kotlin
1
25
a41af28865814b89cf1519f0a749c1d22f2e4753
460
Compose97
MIT License
core/src/test/kotlin/TestJavaComplexity.kt
cs125-illinois
190,280,127
false
{"YAML": 13, "Gradle Kotlin DSL": 6, "INI": 2, "Shell": 1, "Text": 2, "Ignore List": 12, "Batchfile": 1, "Markdown": 1, "Dockerfile": 3, "XML": 30, "Kotlin": 80, "Java": 1, "ANTLR": 7, "JSON": 10, "JSON with Comments": 6, "TSX": 3, "JavaScript": 3, "CSS": 2, "SCSS": 1, "HTML": 1}
package edu.illinois.cs.cs125.jeed.core import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class TestJavaComplexity : StringSpec({ "should calculate complexity for snippets" { Source.fromSnippet( """ int add(int i, int j) { return i + j; } int i = 0; """.trim() ).complexity().also { it.lookup("").complexity shouldBe 2 } } "should calculate complexity for sources" { Source( mapOf( "Test.java" to """ public class Test { public Test(int first, double second) { if (first > 0) { System.out.println("Here"); } } int add(int i, int j) { return i + j; } } """.trim() ) ).complexity().also { it.lookup("Test.int add(int,int)", "Test.java").complexity shouldBe 1 it.lookup("Test.Test(int,double)", "Test.java").complexity shouldBe 2 } } "should fail properly on parse errors" { shouldThrow<ComplexityFailed> { Source( mapOf( "Test.java" to """ public class Test int add(int i, int j) { return i + j; } } """.trim() ) ).complexity() } } "should calculate complexity for simple conditional statements" { Source( mapOf( "Test.java" to """ public class Test { int chooser(int i, int j) { if (i > j) { return i; } else { return i; } } } """.trim() ) ).complexity().also { it.lookup("Test.int chooser(int,int)", "Test.java").complexity shouldBe 2 } } "should calculate complexity for complex conditional statements" { Source( mapOf( "Test.java" to """ public class Test { int chooser(int i, int j) { if (i > j) { return i; } else if (i < j) { return j; } else if (i == j) { return i + j; } else { return i; } } } """.trim() ) ).complexity().also { it.lookup("Test.int chooser(int,int)", "Test.java").complexity shouldBe 4 } } "should calculate complexity for old switch statements" { Source( mapOf( "Test.java" to """ public class Test { int chooser(int i) { int j = 0; switch (i) { case 0: j = 1; case 1: j = 2; case 2: j = 3; default: j = 0; } } } """.trim() ) ).complexity().also { it.lookup("Test.int chooser(int)", "Test.java").complexity shouldBe 4 } } "should calculate complexity for new switch statements" { Source( mapOf( "Test.java" to """ public class Test { int chooser(int i) { int j = 0; switch (i) { case 0 -> j = 1; case 1 -> j = 2; case 2 -> j = 3; default -> { if (i > 0) { j = 0; } } } } } """.trim() ) ).complexity().also { it.lookup("Test.int chooser(int)", "Test.java").complexity shouldBe 5 } } "should calculate complexity for classes in snippets" { Source.fromSnippet( """ class Example { int value = 0; } """.trim() ).complexity().also { it.lookup("Example", "").complexity shouldBe 0 } } "should not fail on records in snippets" { Source.fromSnippet( """ record Example(int value) { }; """.trim() ).complexity().also { it.lookup("Example", "").complexity shouldBe 0 } } "should not fail on records with contents" { Source.fromSnippet( """ record Example(int value) { public int it() { return value; } }; """.trim() ).complexity().also { it.lookup("Example", "").complexity shouldBe 1 it.lookup("Example.int it()", "").complexity shouldBe 1 } } "should not fail on interfaces" { Source.fromSnippet( """ interface Simple { int simple(int first); } """.trim() ).complexity().also { it.lookup("Simple", "").complexity shouldBe 0 } } "should not fail on anonymous classes" { Source.fromSnippet( """ interface Test { void test(); } Test first = new Test() { @Override public void test() { } }; Test second = new Test() { @Override public void test() { } }; """.trim() ).complexity().also { it.lookup(".", "").complexity shouldBe 3 } } "should not fail on generic methods" { Source.fromSnippet( """ <T> T max(T[] array) { return null; } """.trim() ).complexity().also { it.lookup(".T max(T[])", "").complexity shouldBe 1 } } "should not fail on lambda expressions with body" { Source.fromSnippet( """ Thread thread = new Thread(() -> { System.out.println("Blah"); }); """.trim() ).complexity().also { it.lookup(".", "").complexity shouldBe 2 } } "should not fail on lambda expressions without body" { Source.fromSnippet( """ interface Modify { int modify(int value); } Modify first = (v) -> v + 1; System.out.println(first.getClass()); """.trim() ).complexity().also { it.lookup(".", "").complexity shouldBe 2 } } "should not fail on class declarations" { Source.fromSnippet( """ public class Example { public static void main() { int[] array = new int[] {1, 2, 4}; System.out.println("ran"); } }""".trim() ).complexity().also { it.lookup("Example", "").complexity shouldBe 1 } } "should parse empty constructors properly" { Source.fromSnippet( """ public class Example { public Example() { } }""".trim() ).complexity().also { it.lookup("Example", "").complexity shouldBe 1 } } "should not fail on multiple anonymous objects" { Source.fromSnippet( """ interface Filter { boolean accept(int first, int second); } Filter bothPositive = new Filter() { @Override public boolean accept(int first, int second) { return first > 0 && second > 0; } }; Filter bothNegative = new Filter() { @Override public boolean accept(int first, int second) { return first < 0 && second < 0; } }; """.trim() ).complexity().also { it.lookup(".", "").complexity shouldBe 5 } } "should not fail on class declarations with initializer blocks" { Source.fromSnippet( """ public class Example { { System.out.println("Instance initializer"); } }""".trim() ).complexity() } "should not fail on class declarations with static initializer blocks" { Source.fromSnippet( """ public class Example { static { System.out.println("Static initializer"); } }""".trim() ).complexity() } "!should not overflow on deep nesting" { // Flaky test shouldThrow<SnippetTransformationFailed> { Source.fromSnippet( """ public class Mystery { public static int mystery(int x) { if (x == -1) { return 0; } else if (x == -2147483648) { return 2; } else if (x == 0) { return 0; } else if (x == 2147483647) { return 1; } else if (x == 1) { return 0; } else if (x == 889510) { return 2; } else if (x == 563383) { return 1; } else if (x == 598806) { return 2; } else if (x == 60018) { return 1; } else if (x == 974889) { return 2; } else if (x == 1081509) { return 1; } else if (x == 485818) { return 3; } else if (x == 126897) { return 1; } else if (x == 858845) { return 3; } else if (x == 504487) { return 1; } else if (x == 887182) { return 3; } else if (x == 836611) { return 1; } else if (x == 668881) { return 3; } else if (x == 872299) { return 1; } else if (x == 88180) { return 3; } else if (x == 985087) { return 2; } else if (x == 888447) { return 3; } else if (x == 547149) { return 0; } else if (x == 812617) { return 1; } else if (x == 438786) { return 2; } else if (x == 838822) { return 3; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == -2147483648) { return 2; } else if (x == 0) { return 0; } else if (x == 2147483647) { return 1; } else if (x == 1) { return 0; } else if (x == 889510) { return 2; } else if (x == 563383) { return 1; } else if (x == 598806) { return 2; } else if (x == 60018) { return 1; } else if (x == 974889) { return 2; } else if (x == 1081509) { return 1; } else if (x == 485818) { return 3; } else if (x == 126897) { return 1; } else if (x == 858845) { return 3; } else if (x == 504487) { return 1; } else if (x == 887182) { return 3; } else if (x == 836611) { return 1; } else if (x == 668881) { return 3; } else if (x == 872299) { return 1; } else if (x == 88180) { return 3; } else if (x == 985087) { return 2; } else if (x == 888447) { return 3; } else if (x == 547149) { return 0; } else if (x == 812617) { return 1; } else if (x == 438786) { return 2; } else if (x == 838822) { return 3; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } else if (x == 239056) { return 0; } else if (x == 273870) { return 1; } else if (x == 878818) { return 4; } else if (x == 380227) { return 1; } else if (x == 590759) { return 0; } else if (x == 434896) { return 1; } else if (x == 530766) { return 0; } else if (x == 862595) { return 1; } else if (x == 888353) { return 3; } else if (x == 279984) { return 1; } else if (x == 808668) { return 3; } else if (x == 853053) { return 1; } else if (x == 838474) { return 2; } else if (x == 950185) { return 1; } } } """.trimIndent() ).complexity() } } "should not fail on repeated nested anonmyous classes" { Source.fromJavaSnippet( """ public static IWhichHemisphere create(Position p) { double a = p.getLatitude(); if (a == 0) { return new IWhichHemisphere() { public boolean isNorthern() { return false; } public boolean isSouthern() { return true; } }; } if (a > 0) { return new IWhichHemisphere() { public boolean isNorthern() { return true; } public boolean isSouthern() { return false; } }; } else { return new IWhichHemisphere() { public boolean isNorthern() { return false; } public boolean isSouthern() { return true; } }; } }""".trim() ).complexity() } "should allow top-level lambda methods" { Source.fromJavaSnippet( """ public interface Modify { int modify(int value); } public class Modifier { Modify modify = value -> value + 1; } """.trim() ).complexity() } })
4
Kotlin
9
19
ee0a9296f64f9fc9d3c1f4cc2ddd921fe64c0233
16,274
jeed
MIT License
app/src/main/java/com/ss/universitiesdirectory/ui/splash/SplashScreen.kt
Abdulrahman-AlGhamdi
244,158,788
false
null
package com.ss.universitiesdirectory.ui.splash import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.ss.universitiesdirectory.R import com.ss.universitiesdirectory.ui.main.Screen import com.ss.universitiesdirectory.ui.theme.Black import com.ss.universitiesdirectory.ui.theme.White @Composable fun SplashScreen(navController: NavHostController) { val scale = remember { Animatable(0f) } Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background) ) { Image( painter = painterResource(id = R.drawable.icon_university), contentDescription = null, modifier = Modifier.scale(scale.value), colorFilter = ColorFilter.tint(color = if (isSystemInDarkTheme()) White else Black) ) Text( text = stringResource(id = R.string.app_name), fontSize = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.scale(scale.value), color = if (isSystemInDarkTheme()) White else Black ) } LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 0.8f, animationSpec = tween(durationMillis = 1000) ) navController.popBackStack() navController.navigate(route = Screen.UniversitiesScreen.route) } }
0
Kotlin
0
0
f8a5b376a3bac6368f26696f7c3b120f2a6c47e8
2,400
SaudiUniversitiesDirectory
Apache License 2.0